repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit.circuit import Parameter from qiskit import pulse from qiskit.test.mock.backends.almaden import * phase = Parameter('phase') with pulse.build(FakeAlmaden()) as phase_test_sched: pulse.shift_phase(phase, pulse.drive_channel(0)) phase_test_sched.instructions # ()
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit.circuit import Parameter from qiskit import pulse from qiskit.test.mock.backends.almaden import * phase = Parameter('phase') with pulse.build(FakeAlmaden()) as phase_test_sched: pulse.shift_phase(phase, pulse.drive_channel(0)) phase_test_sched.instructions # ()
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit.circuit import Parameter from qiskit import pulse from qiskit.test.mock.backends.almaden import * phase = Parameter('phase') with pulse.build(FakeAlmaden()) as phase_test_sched: pulse.shift_phase(phase, pulse.drive_channel(0)) phase_test_sched.instructions # ()
https://github.com/Z-928/Bugs4Q
Z-928
# The snipplet above ==== is buggy version; the code below ==== is fixed version. from math import pi,pow from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, BasicAer, execute def IQFT(circuit, qin, n): for i in range (int(n/2)): circuit.swap(qin[i], qin[n -1 -i]) for i in range (n): circuit.h(qin[i]) for j in range (i +1, n, 1): circuit.cu1(-pi/ pow(2, j-i), qin[j], qin[i]) n = 3 qin = QuantumRegister(n) cr = ClassicalRegister(n) circuit = QuantumCircuit(qin, cr, name="Inverse_Quantum_Fourier_Transform") circuit.h(qin) circuit.z(qin[2]) circuit.s(qin[1]) circuit.z(qin[0]) circuit.t(qin[0]) IQFT(circuit, qin, n) circuit.measure (qin, cr) backend = BasicAer.get_backend("qasm_simulator") result = execute(circuit, backend, shots = 500).result() counts = result.get_counts(circuit) print(counts) #============ from math import pi,pow from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, BasicAer, execute def QFT(n, inverse=False): """This function returns a circuit implementing the (inverse) QFT.""" circuit = QuantumCircuit(n, name='IQFT' if inverse else 'QFT') # here's your old code, building the inverse QFT for i in range(int(n/2)): # note that I removed the qin register, since registers are not # really needed and you can just use the qubit indices circuit.swap(i, n - 1 - i) for i in range(n): circuit.h(i) for j in range(i + 1, n, 1): circuit.cu1(-pi / pow(2, j - i), j, i) # now we invert it to get the regular QFT if inverse: circuit = circuit.inverse() return circuit n = 3 qin = QuantumRegister(n) cr = ClassicalRegister(n) circuit = QuantumCircuit(qin, cr) circuit.h(qin) circuit.z(qin[2]) circuit.s(qin[1]) circuit.z(qin[0]) circuit.t(qin[0]) # get the IQFT and add it to your circuit with ``compose`` # if you want the regular QFT, just set inverse=False iqft = QFT(n, inverse=True) circuit.compose(iqft, inplace=True) circuit.measure (qin, cr) backend = BasicAer.get_backend("qasm_simulator") result = execute(circuit, backend, shots = 500).result() counts = result.get_counts(circuit) print(counts)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.wrapper import available_backends, get_backend from qiskit.wrapper import execute as q_execute q = QuantumRegister(2, name='q') c = ClassicalRegister(2, name='c') qc = QuantumCircuit(q,c) qc.h(q[0]) qc.h(q[1]) qc.cx(q[0], q[1]) qc.measure(q, c) z = 0.995004165 + 1j * 0.099833417 z = z / abs(z) u_error = np.array([[1, 0], [0, z]]) noise_params = {'U': {'gate_time': 1, 'p_depol': 0.001, 'p_pauli': [0, 0, 0.01], 'U_error': u_error } } config = {"noise_params": noise_params} ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config) ret = ret.result() print(ret.get_counts())
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.wrapper import available_backends, get_backend from qiskit.wrapper import execute as q_execute q = QuantumRegister(2, name='q') c = ClassicalRegister(2, name='c') qc = QuantumCircuit(q,c) qc.h(q[0]) qc.h(q[1]) qc.cx(q[0], q[1]) qc.measure(q, c) z = 0.995004165 + 1j * 0.099833417 z = z / abs(z) u_error = np.array([[1, 0], [0, z]]) noise_params = {'U': {'gate_time': 1, 'p_depol': 0.001, 'p_pauli': [0, 0, 0.01], 'U_error': u_error } } config = {"noise_params": noise_params} ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config) ret = ret.result() print(ret.get_counts())
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.wrapper import available_backends, get_backend from qiskit.wrapper import execute as q_execute q = QuantumRegister(2, name='q') c = ClassicalRegister(2, name='c') qc = QuantumCircuit(q,c) qc.h(q[0]) qc.h(q[1]) qc.cx(q[0], q[1]) qc.measure(q, c) z = 0.995004165 + 1j * 0.099833417 z = z / abs(z) u_error = np.array([[1, 0], [0, z]]) noise_params = {'U': {'gate_time': 1, 'p_depol': 0.001, 'p_pauli': [0, 0, 0.01], 'U_error': u_error } } config = {"noise_params": noise_params} ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config) ret = ret.result() print(ret.get_counts())
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.wrapper import available_backends, get_backend from qiskit.wrapper import execute as q_execute q = QuantumRegister(2, name='q') c = ClassicalRegister(2, name='c') qc = QuantumCircuit(q,c) qc.h(q[0]) qc.h(q[1]) qc.cx(q[0], q[1]) qc.measure(q, c) z = 0.995004165 + 1j * 0.099833417 z = z / abs(z) u_error = np.array([[1, 0], [0, z]]) noise_params = {'U': {'gate_time': 1, 'p_depol': 0.001, 'p_pauli': [0, 0, 0.01], 'U_error': u_error } } config = {"noise_params": noise_params} ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config) ret = ret.result() print(ret.get_counts())
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.wrapper import available_backends, get_backend from qiskit.wrapper import execute as q_execute q = QuantumRegister(2, name='q') c = ClassicalRegister(2, name='c') qc = QuantumCircuit(q,c) qc.h(q[0]) qc.h(q[1]) qc.cx(q[0], q[1]) qc.measure(q, c) z = 0.995004165 + 1j * 0.099833417 z = z / abs(z) u_error = np.array([[1, 0], [0, z]]) noise_params = {'U': {'gate_time': 1, 'p_depol': 0.001, 'p_pauli': [0, 0, 0.01], 'U_error': u_error } } config = {"noise_params": noise_params} ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config) ret = ret.result() print(ret.get_counts())
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.wrapper import available_backends, get_backend from qiskit.wrapper import execute as q_execute q = QuantumRegister(2, name='q') c = ClassicalRegister(2, name='c') qc = QuantumCircuit(q,c) qc.h(q[0]) qc.h(q[1]) qc.cx(q[0], q[1]) qc.measure(q, c) z = 0.995004165 + 1j * 0.099833417 z = z / abs(z) u_error = np.array([[1, 0], [0, z]]) noise_params = {'U': {'gate_time': 1, 'p_depol': 0.001, 'p_pauli': [0, 0, 0.01], 'U_error': u_error } } config = {"noise_params": noise_params} ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config) ret = ret.result() print(ret.get_counts())
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit.circuit import Parameter from qiskit import pulse from qiskit.test.mock.backends.almaden import * phase = Parameter('phase') with pulse.build(FakeAlmaden()) as phase_test_sched: pulse.shift_phase(phase, pulse.drive_channel(0)) phase_test_sched.instructions # ()
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit.circuit import Parameter from qiskit import pulse from qiskit.test.mock.backends.almaden import * phase = Parameter('phase') with pulse.build(FakeAlmaden()) as phase_test_sched: pulse.shift_phase(phase, pulse.drive_channel(0)) phase_test_sched.instructions # ()
https://github.com/Z-928/Bugs4Q
Z-928
#change from qiskit import QuantumProgram import Qconfig qp = QuantumProgram() qp.set_api(Qconfig.APItoken, Qconfig.config['url']) qr = qp.create_quantum_register('qr', 16) #if i create only 1, the program doesn't run cr = qp.create_classical_register('cr', 16) qc = qp.create_circuit('qc', [qr], [cr]) def pad_QId(circuit,N,qr): for ii in range(N): circuit.barrier(qr) circuit.iden(qr) return circuit qc.x(qr[0]) qc = pad_QId(qc, 1000, qr[0]) qc.measure(qr[0], cr[0]) result = qp.execute('qc', timeout = 1000, backend = 'ibmqx5', shots = 8192, max_credits = 5) result.get_counts('qc') #to from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister from qiskit import * from qiskit.providers.aer import QasmSimulator #qp.set_api(Qconfig.APItoken, Qconfig.config['url']) q = QuantumRegister(16) #if i create only 1, the program doesn't run c = ClassicalRegister(16) qc = QuantumCircuit(q, c) def pad_QId(circuit,N,q): for ii in range(N): circuit.barrier(q) circuit.id(q) return circuit qc.x(q[0]) qc = pad_QId(qc, 1000, q[0]) qc.measure(q[0], c[0]) result = execute(qc, timeout = 1000, backend=QasmSimulator(), shots = 8192, max_credits = 5) counts = result.result().get_counts(qc) print(counts)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.wrapper import available_backends, get_backend from qiskit.wrapper import execute as q_execute q = QuantumRegister(2, name='q') c = ClassicalRegister(2, name='c') qc = QuantumCircuit(q,c) qc.h(q[0]) qc.h(q[1]) qc.cx(q[0], q[1]) qc.measure(q, c) z = 0.995004165 + 1j * 0.099833417 z = z / abs(z) u_error = np.array([[1, 0], [0, z]]) noise_params = {'U': {'gate_time': 1, 'p_depol': 0.001, 'p_pauli': [0, 0, 0.01], 'U_error': u_error } } config = {"noise_params": noise_params} ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config) ret = ret.result() print(ret.get_counts())
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit.circuit import Parameter from qiskit import pulse from qiskit.test.mock.backends.almaden import * phase = Parameter('phase') with pulse.build(FakeAlmaden()) as phase_test_sched: pulse.shift_phase(phase, pulse.drive_channel(0)) phase_test_sched.instructions # ()
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit.circuit import Parameter from qiskit import pulse from qiskit.test.mock.backends.almaden import * phase = Parameter('phase') with pulse.build(FakeAlmaden()) as phase_test_sched: pulse.shift_phase(phase, pulse.drive_channel(0)) phase_test_sched.instructions # ()
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit.circuit import Parameter from qiskit import pulse from qiskit.test.mock.backends.almaden import * phase = Parameter('phase') with pulse.build(FakeAlmaden()) as phase_test_sched: pulse.shift_phase(phase, pulse.drive_channel(0)) phase_test_sched.instructions # ()
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit.circuit import Parameter from qiskit import pulse from qiskit.test.mock.backends.almaden import * phase = Parameter('phase') with pulse.build(FakeAlmaden()) as phase_test_sched: pulse.shift_phase(phase, pulse.drive_channel(0)) phase_test_sched.instructions # ()
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') result = backend.run(qc, shots = 8192).result()
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit, transpile from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') qc_transpiled = transpile(qc, backend) result = backend.run(qc, shots = 8192).result()
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') result = backend.run(qc, shots = 8192).result()
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit, transpile from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') qc_transpiled = transpile(qc, backend) result = backend.run(qc, shots = 8192).result()
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') result = backend.run(qc, shots = 8192).result()
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit, transpile from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') qc_transpiled = transpile(qc, backend) result = backend.run(qc, shots = 8192).result()
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') result = backend.run(qc, shots = 8192).result()
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit, transpile from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') qc_transpiled = transpile(qc, backend) result = backend.run(qc, shots = 8192).result()
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') result = backend.run(qc, shots = 8192).result()
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit, transpile from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') qc_transpiled = transpile(qc, backend) result = backend.run(qc, shots = 8192).result()
https://github.com/Chibikuri/Quantum-Othello
Chibikuri
# -*- coding: utf-8 -*- """ Created on Tue Nov 19 20:45:54 2019 @author: User """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.compiler import transpile import numpy as np import collections import random import matplotlib.pyplot as plt import os plt.ioff() ''' Function to create folder ''' def createFolder(directory): try: if not os.path.exists(directory): os.makedirs(directory) except OSError: print ('Error: Creating directory. ' + directory) ''' Define class ''' class QuantumOthello(): def __init__(self, num, turn): self.num = num self.turn = turn self.qc = QuantumCircuit(num) self.turnA = int(self.turn/2) self.turnB = self.turn - self.turnA self.GateA = self.RandomGate(self.turnA) self.GateB = self.RandomGate(self.turnB) self.MeasurementBasis = self.RandomBasis() def StartTheGame(self): for i in range(self.num): if i % 2 == 0: x = str(input('A, instruction >')) y = int(input('A #qubit >')) self.initial(x, y) else: x = str(input('B, instruction >')) y = int(input('B #qubit >')) self.initial(x, y) self.end_initial() #q.get_cir() print('End of initialization') for i in range(self.turn): if i % 2 == 0: x = str(input('A, instruction >')) if x == 'CX': y1 = int(input('Control qubit #> ')) y2 = int(input('target qubit #> ')) self.operation(x, [y1, y2]) else: y = int(input('A #qubit >')) self.operation(x, y) else: x = str(input('B, instruction >')) if x == 'CX': y1 = int(input('Control qubit #> ')) y2 = int(input('target qubit #> ')) self.operation(x, [y1, y2]) else: y = int(input('B #qubit >')) self.operation(x, y) result = self.RuntheGaame() print(result) def get_cir(self, trans=False): createFolder('./fig') style = { 'showindex': True, 'cregbundle' : True, 'dpi' : 300} if trans == True: return transpile(self.qc, basis_gates = ['x', 'h', 'u3', 'cx']).draw(output='mpl', style = style, fold=100) return self.qc.draw(output='mpl', style = style, fold=100) def initial(self, instruction, num, vector=None): ''' Normal gate version ''' if instruction == '+': self.qc.h(num) elif instruction == '-': self.qc.x(num) self.qc.h(num) elif instruction == '1': self.qc.x(num) elif instruction == '0': None else: print('invalid initialize instruction') def SeqInitial(self, instruction): for i in range(self.num): self.initial(instruction[i], i) def end_initial(self): self.qc.barrier() def operation(self, oper, num): if type(num) == list and len(num) == 2: num_control = num[0] num_target = num[1] if type(num) == list and len(num) == 1: num = num[0] if oper == 'H': self.qc.h(num) if oper == 'CX': self.qc.cx(num_control, num_target) if oper == 'X': self.qc.x(num) if oper == 'Z': self.qc.z(num) if oper == 'HX': self.qc.h(num) self.qc.x(num) if oper == 'CZ': self.qc.cz(num_control, num_target) def RuntheGame(self): self.qc.barrier() for i in range(self.num): if self.MeasurementBasis[i] == 'X': self.qc.h(i) elif self.MeasurementBasis[i] == 'Y': self.qc.sdg(i) self.qc.h(i) else: None self.qc.measure_all() self.get_cir().savefig('fig/Mreasurment.png') backend = Aer.get_backend('qasm_simulator') #qasm_simulator job = execute(self.qc, backend=backend, shots = 8192).result().get_counts() List = {'0': 0, '1': 0} for i in job: if len(collections.Counter(i).most_common()) == 2: t, t_c = collections.Counter(i).most_common(2)[0] d, d_c = collections.Counter(i).most_common(2)[1] if t_c > d_c: List[t] += job[i] elif t_c < d_c: List[d] += job[i] else: None else: t, _ = collections.Counter(i).most_common(1)[0] List[t] += job[i] return List def ReturnResult(self, result, error = 500): if abs(result['0'] - result['1']) < error: return 'tie' elif result['0'] > result['1']: return '0' else: return '1' def RandomBasis(self): Basis = ['X', 'Z'] return random.choices(Basis, k=self.num) def RandomGate(self, numTurn): Gate = ['H', 'HX', 'CX', 'CZ'] return random.choices(Gate, k=numTurn) def RemoveOper(self, player, gate): if player == 'A': self.GateA.remove(gate) else: self.GateB.remove(gate)
https://github.com/Chibikuri/Quantum-Othello
Chibikuri
import kivy from kivy.app import App from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput from kivy.uix.button import Button from kivy.uix.screenmanager import ScreenManager, Screen from kivy.graphics import * from kivy.uix.splitter import Splitter from kivy.uix.widget import Widget from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute kivy.require('1.11.1') class OthelloBoard(GridLayout): def __init__(self, **kwargs): super(OthelloBoard, self).__init__(**kwargs) self.cols = 3 self.add_widget(Label(text='qubit 1'), index=0) self.add_widget(Label(text='qubit 2'), index=1) self.add_widget(Label(text='qubit 3'), index=2) self.add_widget(Label(text='qubit 4'), index=0) self.add_widget(Label(text='qubit 5'), index=1) self.add_widget(Label(text='qubit 6'), index=2) self.add_widget(Label(text='qubit 7'), index=0) self.add_widget(Label(text='qubit 8'), index=1) self.add_widget(Label(text='qubit 9'), index=2) class CircuitLiner(Screen): def __init__(self, **kwargs): self.canvas = Canvas with self.canvas: Line(points=[10, 10, 20, 20, 30, 30], width=10) # class PlayScreen: # def __init__(self, **kwargs): # self.splitter = Splitter(sizable_from='right') # self.splitter.add_widget(OthelloBoard()) # self.splitter.add_widget(CircuitLiner()) class QuantumOthello(App): def build(self): sm = ScreenManager() # sm.add_widget(OthelloBoard) sm.add_widget(CircuitLiner) return OthelloBoard() if __name__ == '__main__': QuantumOthello().run()
https://github.com/Chibikuri/Quantum-Othello
Chibikuri
# -*- coding: utf-8 -*- import warnings # warnings.filterwarnings('ignore') import matplotlib import numpy as np import matplotlib.pyplot as plt import sys import os import np import time import datetime import random import np import pandas as pd import multiprocessing as mul import umap import csv import pandas as pd from scipy.sparse.csgraph import connected_components from notification import Notify from scipy.special import expit from multiprocessing import pool from pprint import pprint from sklearn import datasets from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.manifold import TSNE from qiskit import IBMQ, QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, Aer, compile from numpy import pi from qiskit.tools.visualization import plot_histogram, circuit_drawer from qiskit.tools.visualization import matplotlib_circuit_drawer from numba import jit from matplotlib.colors import ListedColormap as clp class QVC: def __init__(self, qubits, cbits, target, shots, l_iteration, dimension, n_class): ''' This is initial config. qubits, cbits: the instance of qubits, classical bits qc: the name of circuit num_q, num_c: the number of qubits, cbits train, test: the directory of training data, test data ''' self.q = QuantumRegister(qubits) self.c = ClassicalRegister(cbits) self.qc = QuantumCircuit(self.q, self.c) self.num_q = qubits self.num_c = cbits self.target = target self.shots = shots self.l_iter = l_iteration self.dim = dimension self.n_class = n_class def _reduce_dimension(self): pass def _feature_map(self, qc, S, data_angle): ''' Quantum State Mapping apply feature map circuit(fig1 b) using two qubits for making reading feature map 1.applying feature map circuit to 0state. <-- in this part 2.training theta 3.measurement 4.fitting cost function qc : circuit name S : the number of test data set x_angle : the angle for fitting traingin data sets ### In this paper, x_angle is artifitially generated. ''' q = self.q n = self.num_q # TODO understand how to decide theta of u1 for i in range(n): qc.h(q[i]) qc.u1(data_angle[0], q[0]) for j in range(S-1): qc.cx(q[j], q[j+1]) qc.u1(data_angle[j], q[j+1]) qc.cx(q[j], q[j+1]) qc.u1(data_angle[S-1], q[S-1]) for i in range(n): qc.h(q[i]) qc.u1(data_angle[0], q[0]) for j in range(S-1): qc.cx(q[j], q[j+1]) qc.u1(data_angle[j], q[j+1]) qc.cx(q[j], q[j+1]) qc.u1(data_angle[S-1], q[S-1]) return qc def _w_circuit(self, qc, theta_list): ''' repeat this circuit for l times to classify qc: The name of quantum circuit theta : the angle for u3gate ''' q = self.q n = self.num_q # TODO how to tune the theta_list # for ini in range(n): # qc.u3(theta_list[ini], 0, theta_list[ini], q[ini]) # FIXME This part is wrong? should be one time but this part is apply many times. for iter in range(self.l_iter): for j in range(1, n): qc.cz(q[j-1], q[j]) qc.cz(q[n-1], q[0]) # TODO how to decide lambda of u3? for m in range(n): qc.u3(0, 0, theta_list[m], q[m]) return qc def _R_emp(self, distribution, y, bias): ''' this is cost fucntion for optimize theta(lambda) theta: lambda for u3 gate ''' a_1 = (np.sqrt(self.shots)*(1/2-(distribution-y*bias/2))) a_2 = np.sqrt(abs(2*(1-distribution)*distribution)) sig = expit(a_1/a_2) # expit is sigmoid function print(sig) # FIXME 1/T should multiplied by the sum of emps? return 1/self.dim * sig def _multi_emp_cost(self, count, correct_class): binlabel = self._label2binary(correct_class) print(max(count, key=count.get)) n_c = count[binlabel] oth_dict = count.pop(binlabel) at = (np.sqrt(self.shots)*max(count.values())-n_c) bt = np.sqrt(2*(self.shots-n_c)*n_c) return expit(at/bt) # @jit def _multic_cost(self, val_list, correct_class): # print(val_list) n_c = val_list[correct_class] _ = val_list.pop(correct_class) at = (np.sqrt(self.shots)*max(val_list)-n_c) bt = np.sqrt(2*(self.shots-n_c)*n_c) return expit(at/bt) def _label2binary(self, correct_class): ''' maybe no need this function. input: class label ex 3 ------------------------------------- output: binary(String) ex.'0000000100' correct class -> binary label boolean now:10qubit # FIXME fir for any qubits. ''' if correct_class == 0: return '0'*self.dim else: return '0'*(self.dim-correct_class)+'1'+'0'*(correct_class-1) def _aggregate(self, count, labels): ''' input:count output:list(aggregate by number) ''' values = [] for k in labels: rc = 0 for i, j in zip(count.keys(), count.values()): if list(i)[self.dim-1-k] == '1': # FIXME wrong? rc += (j/self.shots) values.append(rc) return values def fit(self, x_data, y_data, labels): ''' training and fitting parameter 1.applying feature map circuit to 0state. 2.training theta <-- in this part 3.measurement 4.fitting cost function ''' initial_theta = [0.01]*self.num_q b = list(np.arange(-1, 1, 0.1)) x_data = zip(*[iter(x_data)]*3) y_data = zip(*[iter(y_data)]*3) while True: count = 0 params = [] emp_cost = [99, 99] theta_l = [initial_theta, initial_theta] for training_data, t_label in zip(x_data, y_data): # like(1, 3, 4) fit_theta = self._fitting_theta(theta_l, emp_cost, count) # print("fit!", fit_theta) count_results = self._circuit(fit_theta, list(training_data)) # array # print(theta_l) theta_l.append(fit_theta) bias = random.choice(b) # print(t_label) for i, j in zip(count_results, t_label): count_vals = self._aggregate(i, labels) empirical = self._multic_cost(count_vals, list(t_label).index(j)) emp_cost.append(empirical) # print(emp_cost) count += 1 print("="*25, count, "="*25) if self.isOptimized(min(emp_cost)): break index = np.array(emp_cost).argmin() # print("min 1", theta_l[-1]) return theta_l[-1] def isOptimized(self, empirical_cost): ''' This fucntion is for checking R_empirical is optimized or not. empirical_cost : the value of R_emp() ''' # return True # if len(empirical_cost) > 3: # if empirical_cost[-1] == min(empirical_cost): # return True # else: # return False # if len(empirical_cost) > 5: # return True return True def _fitting_theta(self, theta_list, Rempirical_cost, count): # print("fit_theta!", theta_list) # print("emps!", Rempirical_cost) theta_range = 2*self.dim*(self.l_iter+1) interval = 2*pi/theta_range index = np.mod(count, self.dim+1) sum_list = [interval if i == index else 0 for i in range(self.dim)] n_thetalist = np.array(theta_list[-2]) + np.array(sum_list) theta_list.append(list(n_thetalist)) if Rempirical_cost[-1] < Rempirical_cost[-2]: return theta_list[-1] else: return theta_list[-2] def _circuit(self, theta_list, training_data): qc = self.qc q = self.q c = self.c # TODO we have to chenge the angle of feature map for each data. # TODO multi circuit mean = np.median(training_data, axis=0) # feature_angle = [((mean - (training_data[i]))**2) for i in range(self.dim)] # feature_angle = [(np.sin(training_data[0]))*(np.sin(training_data[1]))*(np.sin(training_data[2])) for i in range(3)] qc_list = [] for data in training_data: # print(data) feature_angle = [(pi - 1/np.exp(i)) for i in data] self._feature_map(qc, self.dim, feature_angle) self._w_circuit(qc, theta_list) qc.measure(q, c) qc_list.append(qc) backends = ['ibmq_20_tokyo', 'qasm_simulator', 'ibmqx_hpc_qasm_simulator', 'statevector_simulator'] backend_options = {'max_parallel_threads': 0, 'max_parallel_experiments': 0, 'max_parallel_shots': 0, 'statevector_parallel_threshold': 12} backend = Aer.get_backend(backends[1]) qobj_list = [compile(qc, backend) for qc in qc_list] count_list = [] job_list = [backend.run(qobj) for qobj in qobj_list] for job in job_list: counts = job.result().get_counts() # print([(k,v) for k, v in counts.items() if v > 10]) count_list.append(counts) # print(count_list) return count_list def _test_circuit(self, theta_list, test_data): qc = self.qc q = self.q c = self.c # TODO we have to chenge the angle of feature map for each data. # TODO multi circuit # mean = np.median(training_data, axis=0) # feature_angle = [((mean - (training_data[i]))**2) for i in range(self.dim)] # feature_angle = [(np.sin(training_data[0]))*(np.sin(training_data[1]))*(np.sin(training_data[2])) for i in range(3)] feature_angle = [(pi - np.sin(i)) for i in test_data] self._feature_map(qc, self.dim, feature_angle) self._w_circuit(qc, theta_list) qc.measure(q, c) # qc_list.append(qc) backends = ['ibmq_20_tokyo', 'qasm_simulator', 'ibmqx_hpc_qasm_simulator', 'statevector_simulator'] backend_options = {'max_parallel_threads': 0, 'max_parallel_experiments': 0, 'max_parallel_shots': 0, 'statevector_parallel_threshold': 12} backend = Aer.get_backend(backends[1]) exec = execute(qc, backend, shots=self.shots, config=backend_options) result = exec.result() counts = result.get_counts(qc) # print([k for k, v in counts.items() if v > 10]) return counts def predict(self, test_data, theta_list, label): # FIXME have to modify add testdata and # for p in parameter: vals = [] # for theta in theta_list: count_results = self._test_circuit(theta_list, test_data) test_val = self._aggregate(count_results, label) answer = label[np.array(test_val).argmax()] return answer @staticmethod def calc_accuracy(labels, test_y): correct_answer = 0 for i, j in zip(labels, test_y): if i == j: correct_answer += 1 return correct_answer/len(test_y) def visualize(self, x, y, theta, bias, resolution=0.5): # print(x) markers = ('o', 'x') cmap = clp(('red', 'blue')) x1_min, x1_max = x[:, 0].min()-1, x[:, 0].max()+1 x2_min, x2_max = x[:, 1].min()-1, x[:, 1].max()+1 x1_mesh, x2_mesh = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) z = self.predict(np.array([x1_mesh.ravel(), x2_mesh.ravel()]).T, theta, bias) z = np.array(z) z = z.reshape(x1_mesh.shape) # print(z) plt.contourf(x1_mesh, x2_mesh, z, alpha=0.4, cmap=cmap) plt.xlim(x1_mesh.min(), x1_mesh.max()) plt.ylim(x2_mesh.min(), x2_mesh.max()) @staticmethod def _sigmoid(x): return 1/(1+np.exp(-x)) @staticmethod def _ReLU(x): return max(0, x) @staticmethod def _ELU(x): if x > 0: return x else: return np.exp(x) - 1 @staticmethod def circle_data(r): x = np.arange(-r, r, r/100) print(np.sqrt((r**2)-(x**2)), -np.sqrt((r**2)-(x**2))) return x, np.array(np.sqrt((r**2)-(x**2))), np.array(-np.sqrt((r**2)-(x**2))) def wrapper(self, args): return self.fit(*args) def multi_process(self, data_list): p = mul.Pool(8) output = p.map(self.wrapper, data_list) p.close() return output if __name__ == '__main__': print('start') start = time.time() fig = plt.figure() # mnist dataset digits = datasets.load_digits() x_data = digits.data[0:100] y_d = digits.target[0:100] labels = (2, 3, 7) x_list = [] y_list = [] for i, j in zip(x_data, y_d): if j in labels: x_list.append(i) y_list.append(j) x_data = umap.UMAP(n_neighbors=20, n_components=10, min_dist=0.01, metric='correlation').fit_transform(x_list, y=y_list) parameters = [] sc = StandardScaler() sc.fit(x_data) x_data = sc.transform(x_data) # labels = random.sample(range(10), k=3) x_train, x_test, y_train, y_test = train_test_split(x_data, y_list, test_size=0.1, shuffle=False) dim = len(x_data[0]) theta_list = [] test = QVC(dim, dim, ["0"*dim, "1"*dim], 16384, 1, dim, max(y_d)) parameter = test.fit(x_train, y_train, labels) # theta_list.append(parameter) # print("theta", theta_list) count = 1 answers = [] print("param!",parameter) for i in x_test: prob_all = [] print("="*25, "test", count, "="*25) label = test.predict(i, parameter, labels) answers.append(label) count += 1 acc = test.calc_accuracy(answers, y_test) Notify.notify(acc) print(acc) print(answers) print(y_test) print(parameters) # df = pd.DataFrame([[acc], [parameters]]) # print(df) df.to_csv('./data/%sn%s.csv' % ('237', str(sys.argv[1]))) print(time.time() - start)
https://github.com/Chibikuri/Quantum-Othello
Chibikuri
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.compiler import transpile import numpy as np import collections import random import matplotlib.pyplot as plt import os plt.ioff() ''' Function to create folder ''' def createFolder(directory): try: if not os.path.exists(directory): os.makedirs(directory) except OSError: print ('Error: Creating directory. ' + directory) ''' Define class ''' class QuantumOthello(): def __init__(self, num, turn): self.num = num self.turn = turn self.qc = QuantumCircuit(num) self.turnA = int(self.turn/2) self.turnB = self.turn - self.turnA self.GateA = self.RandomGate(self.turnA) self.GateB = self.RandomGate(self.turnB) self.MeasurementBasis = self.RandomBasis() def StartTheGame(self): for i in range(self.num): if i % 2 == 0: x = str(input('A, instruction >')) y = int(input('A #qubit >')) self.initial(x, y) else: x = str(input('B, instruction >')) y = int(input('B #qubit >')) self.initial(x, y) self.end_initial() #q.get_cir() print('End of initialization') for i in range(self.turn): if i % 2 == 0: x = str(input('A, instruction >')) if x == 'CX': y1 = int(input('Control qubit #> ')) y2 = int(input('target qubit #> ')) self.operation(x, [y1, y2]) else: y = int(input('A #qubit >')) self.operation(x, y) else: x = str(input('B, instruction >')) if x == 'CX': y1 = int(input('Control qubit #> ')) y2 = int(input('target qubit #> ')) self.operation(x, [y1, y2]) else: y = int(input('B #qubit >')) self.operation(x, y) result = self.RuntheGaame() print(result) def get_cir(self, trans=False): createFolder('./fig') style = { 'showindex': True, 'cregbundle' : True, 'dpi' : 300} if trans == True: return transpile(self.qc, basis_gates = ['x', 'h', 'u3', 'cx']).draw(output='mpl', style = style, fold=100) return self.qc.draw(output='mpl', style = style, fold=100) def initial(self, instruction, num, vector=None): ''' Normal gate version ''' if instruction == '+': self.qc.h(num) elif instruction == '-': self.qc.x(num) self.qc.h(num) elif instruction == '1': self.qc.x(num) elif instruction == '0': None else: print('invalid initialize instruction') def SeqInitial(self, instruction): for i in range(self.num): self.initial(instruction[i], i) def end_initial(self): self.qc.barrier() def operation(self, oper, num): if type(num) == list and len(num) == 2: num_control = num[0] num_target = num[1] if type(num) == list and len(num) == 1: num = num[0] if oper == 'H': self.qc.h(num) if oper == 'CX': self.qc.cx(num_control, num_target) if oper == 'X': self.qc.x(num) if oper == 'Z': self.qc.z(num) if oper == 'HX': self.qc.h(num) self.qc.x(num) if oper == 'CZ': self.qc.cz(num_control, num_target) def RuntheGame(self): self.qc.barrier() for i in range(self.num): if self.MeasurementBasis[i] == 'X': self.qc.h(i) elif self.MeasurementBasis[i] == 'Y': self.qc.sdg(i) self.qc.h(i) else: None self.qc.measure_all() self.get_cir().savefig('./fig/Measurment.png') backend = Aer.get_backend('qasm_simulator') #qasm_simulator job = execute(self.qc, backend=backend, shots = 8192).result().get_counts() List = {'0': 0, '1': 0} for i in job: if len(collections.Counter(i).most_common()) == 2: t, t_c = collections.Counter(i).most_common(2)[0] d, d_c = collections.Counter(i).most_common(2)[1] if t_c > d_c: List[t] += job[i] elif t_c < d_c: List[d] += job[i] else: None else: t, _ = collections.Counter(i).most_common(1)[0] List[t] += job[i] return List def RandomBasis(self): Basis = ['X', 'Z'] return random.choices(Basis, k=self.num) def RandomGate(self, numTurn): Gate = ['X', 'Z', 'H', 'HX', 'CX', 'CZ'] return random.choices(Gate, k=numTurn) def RemoveOper(self, player, gate): if player == 'A': self.GateA.remove(gate) else: self.GateB.remove(gate)
https://github.com/gustavomirapalheta/Quantum-Computing-with-Qiskit
gustavomirapalheta
import numpy as np D0 = np.array([[1],[0]]); D0 NOT = np.array([[0,1],[1,0]]); NOT NOT.dot(D0) D1 = np.array([[0],[1]]); D1 NOT.dot(D1) AND = np.array([[1,1,1,0],[0,0,0,1]]); AND AND.dot(np.kron(D0,D0)) AND.dot(np.kron(D0,D1)) AND.dot(np.kron(D1,D0)) AND.dot(np.kron(D1,D1)) OR = np.array([[1,0,0,0],[0,1,1,1]]); OR OR.dot(np.kron(D0,D0)) OR.dot(np.kron(D0,D1)) OR.dot(np.kron(D1,D0)) OR.dot(np.kron(D1,D1)) NAND = np.array([[0,0,0,1],[1,1,1,0]]); NAND NOT.dot(AND) NOR = np.array([[0,1,1,1],[1,0,0,0]]);NOR NOT.dot(OR) np.kron(NOT,AND) OR.dot(np.kron(NOT,AND)) NOT.dot(AND).dot(np.kron(NOT,NOT)) OR NOT.dot(OR).dot(np.kron(NOT,NOT)) AND import numpy as np k = np.kron XOR = np.array([[1,0,0,1], [0,1,1,0]]) AND = np.array(([1,1,1,0], [0,0,0,1])) k(XOR,AND) def criaCompat(nbits,nvezes): nlins = 2**(nbits*nvezes) ncols = 2**nbits compat = np.zeros(nlins*ncols).reshape(nlins,ncols) for i in range(ncols): formato = "0" + str(nbits) + "b" binario = format(i,formato)*nvezes decimal = int(binario,2) compat[decimal,i] = 1 return(compat) criaCompat(2,2) k(XOR,AND).dot(criaCompat(2,2)) import numpy as np k = np.kron def criaCompat(nbits,nvezes): nlins = 2**(nbits*nvezes) ncols = 2**nbits compat = np.zeros(nlins*ncols).reshape(nlins,ncols) for i in range(ncols): formato = "0" + str(nbits) + "b" binario = format(i,formato)*nvezes decimal = int(binario,2) compat[decimal,i] = 1 return(compat) criaCompat(2,2) NOT = np.array([[0,1], [1,0]]) AND3 = np.array([[1,1,1,1,1,1,1,0], [0,0,0,0,0,0,0,1]]) OR4 = np.array([[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]]) I2 = np.array([[1,0], [0,1]]) t1z = k(NOT,k(NOT,I2)) t2z = k(NOT,k(I2,NOT)) t3z = k(I2,k(NOT,NOT)) t4z = k(I2,k(I2,I2)) ORz = k(AND3,k(AND3,k(AND3,AND3))) ORz = OR4.dot(ORz).dot(k(t1z,k(t2z,k(t3z,t4z)))) t1c = k(NOT,k(I2,I2)) t2c = k(I2,k(NOT,I2)) t3c = k(I2,k(I2,NOT)) t4c = k(I2,k(I2,I2)) ORc = k(AND3,k(AND3,k(AND3,AND3))) ORc = OR4.dot(ORc).dot(k(t1c,k(t2c,k(t3c,t4c)))) compat = criaCompat(3,8) k(ORz,ORc).dot(compat) import numpy as np TOFFOLI = np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1], [0,0,0,0,0,0,1,0]]) TOFFOLI.dot(TOFFOLI) import numpy as np Z1 = np.array([[0,0,0,0,0,0,0,0], [1,1,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,1,1,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,1,1,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,1,1]]) Z1 Z1I4 = np.array([[0,0,0,0], [1,0,0,0], [0,0,0,0], [0,1,0,0], [0,0,0,0], [0,0,1,0], [0,0,0,0], [0,0,0,1]]) Z1I4 ZpY = np.zeros([8,8]) ZpY[0,0] = 1; ZpY[1,2] = 1; ZpY[2,1] = 1; ZpY[3,3] = 1 ZpY[4,4] = 1; ZpY[5,6] = 1; ZpY[6,5] = 1; ZpY[7,7] = 1 ZpY Zfim = np.array([[1,0,1,0,1,0,1,0], [0,1,0,1,0,1,0,1]]) Zfim.dot(TOFFOLI).dot(ZpY).dot(TOFFOLI).dot(Z1I4) import numpy as np fred = np.identity(8) fred[5,5] = 0; fred[5,6] = 1 fred[6,5] = 1; fred[6,6] = 0 fred fred.dot(fred) import numpy as np Fy0 = np.zeros([8,4]) Fy0[0,0] = 1; Fy0[1,1] = 1; Fy0[4,2] = 1; Fy0[5,3] = 1 Fy0 xYz = np.array([[1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1]]) xYz.dot(fred).dot(Fy0)
https://github.com/gustavomirapalheta/Quantum-Computing-with-Qiskit
gustavomirapalheta
import numpy as np V = np.array([[3+2j],[4-2j]]) modV = np.real(V.T.conjugate().dot(V)[0,0])**0.5 Vn = V/modV; Vn v0 = np.array([[1,0]]).T v1 = np.array([[0,1]]).T Vn[0,0]*v0 + Vn[1,0]*v1 Vn[0,0].conjugate()*Vn[0,0] Vn[1,0].conjugate()*Vn[1,0] import numpy as np CNOT = np.array([[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]]) CNOT.dot(CNOT) import numpy as np H = np.array([[1,1],[1,-1]])/2**0.5 H.dot(H) import numpy as np X = np.array([[0,1], [1,0]]) X X.conj().T.dot(X) Y = np.array([[0,-1j], [1j,0]]) Y Y.conj().T.dot(Y) Z = np.array([[1,0], [0,-1]]) Z Z.conj().T.dot(Z) H = (X+Z)/np.sqrt(2); H H.dot(Z).dot(H) H.dot(X).dot(H) -H.dot(Y).dot(H) import numpy as np S = np.array([[1,0], [0,1j]]) S S.conj().T.dot(S) T = np.array([[1,0], [0,np.exp(1j*np.pi/4)]]) T T.conj().T.dot(T) S = np.array([[1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]]); S v00 = np.array([[1,0,0,0]]).T S.dot(v00) v01 = np.array([[0,1,0,0]]).T S.dot(v01) v10 = np.array([[0,0,1,0]]).T S.dot(v10) v11 = np.array([[0,0,0,1]]).T S.dot(v11) C = np.array([[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]]);C C_ = np.array([[1,0,0,0], [0,0,0,1], [0,0,1,0], [0,1,0,0]]);C_ C.dot(C_).dot(C) v = v0 + v1; v n = np.array([[0,0],[0,1]]); n n.dot(v) n_ = np.array([[1,0],[0,0]]);n_ I2 = np.identity(2); I2 I2 - n n_.dot(v) n.dot(n) n_.dot(n_) n.dot(n_) n_.dot(n) n+n_ n.dot(X) X.dot(n_) import numpy as np n = np.array([[0,0],[0,1]]); n n_ = np.array([[1,0],[0,0]]);n_ # ni nj operam em bits distintos. Como cada operador n atua em um vetor de # 2 dimensรตes, ni nj รฉ um operador de 4 dimensรตes. Sendo assim, fica implรญcito # pelos subscritos que ni nj รฉ um produto tensorial. np.kron(n,n) # O mesmo vale para n'i n'j np.kron(n_,n_) # Para ni n'j np.kron(n,n_) # E para n'i nj np.kron(n_,n) # Xi Xj sรฃo dois operadores 2x2 de inversรฃo, cada um atuando em um bit # distinto. Sendo assim, fazemos o produto tensorial entre ambos # para obter XiXj np.kron(X,X) # No caso da expressรฃo XiXj(ninj' + ni'nj) temos entre parรชnteses duas # matrizes 4x4 (ninj'+ni'nj) e fora dos parรชnteses uma matriz 4x4 (XiXj) # Sendo assim fazemos neste caso o produto matricial normal para # calcular esta expressรฃo. np.kron(X,X).dot(np.kron(n,n_)+np.kron(n_,n)) # E por รบltimo somamos com o resultado inicial de ninj + ni'nj' # Como pode-se ver, esta expressรฃo gera o operador de SWAP np.kron(n,n) + np.kron(n_,n_) + np.kron(X,X).dot(np.kron(n,n_)+np.kron(n_,n)) # ร‰ importante observar que ninj forma um operador que projeta um vetor de # 4 dimensรตes (00, 01, 10, 11) em sua componente 11 np.kron(n,n) # De maneira similar ni'nj' projeta um vetor de 4 dimensรตes em sua componente 00 np.kron(n_,n_) # ni'nj projeta em 01 np.kron(n_,n) # Assim como ninj' projeta em 10 np.kron(n,n_) # E por รบltimo vemos que ni'nj' + ni'nj + ninj' + ninj = I nn = np.kron(n,n) nn_ = np.kron(n,n_) n_n = np.kron(n_,n) n_n_ = np.kron(n_,n_) nn + nn_ + n_n + n_n_ import numpy as np n = np.array([[0,0],[0,1]]); n n_ = np.array([[1,0],[0,0]]);n_ # (n x n).(n_ x n_) np.kron(n,n).dot(np.kron(n_,n_)) # Faz sentido que (ni x nj).(ni_ x nj_) seja o vetor nulo pois: # ni_ x nj_ รฉ um operador que recebe um vetor de 4 dimensรตes e # produz como resultado apenas sua componente |00>. Por sua # vez ni x nj รฉ um operador que recebe um vetor de 4 dimensรตes # e produz como resultado apenas sua componente |11>. Esta # componente foi zerada pelo primeiro operador, logo o resultado # serรก nulo. Isto vai acontecer sempre que a componente nรฃo # zerada do primeiro operador for diferente da do segundo em # outras palavras sempre que ij do primeiro for diferente de ij # do segundo. np.kron(n,n).dot(np.kron(n_,n_)) # Outra forma de entender รฉ transformar (n x n).(n_ x n_) em # (n.n_) x (n.n_). Como n รฉ ortogonal a n_, a projeรงรฃo de n # em n_ darรก zero tambรฉm. np.kron(n.dot(n_),n.dot(n_)) nn.dot(n_n_) # (n_ x n).(n x n_) np.kron(n_,n).dot(np.kron(n,n_)) n_n.dot(nn_) # (n x n_).(n_ x n) np.kron(n, n_).dot(np.kron(n_,n)) nn_.dot(n_n) # (n_ x n_).(n x n) np.kron(n_, n_).dot(np.kron(n, n)) n_n_.dot(nn)
https://github.com/gustavomirapalheta/Quantum-Computing-with-Qiskit
gustavomirapalheta
# Setup bรกsico !pip install qiskit -q !pip install qiskit[visualization] -q import qiskit as qk !pip install qiskit-aer -q import qiskit_aer as qk_aer import numpy as np np.set_printoptions(precision=3, suppress=True) from matplotlib import pyplot as plt %matplotlib inline import pandas as pd import sklearn as sk # Remember that qiskit has to be already installed in the Python environment. # Otherwise the import command will fail import qiskit as qk print("A Qubit (initialized in the state |0> plus one classical bit") qr = qk.QuantumRegister(1,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr, cr) display(qc.draw('mpl', style = 'clifford', scale = 1)) print("A qubit forced initialized in the state |0>") qc.initialize([1,0]) display(qc.draw('mpl', style = 'clifford', scale = 1)) print("A qubit forced initialized in |0> and a measurement") qc.measure([0],[0]) display(qc.draw('mpl', style = 'clifford')) import qiskit as qk import qiskit_aer as qk_aer # A list of possible measurements. qk_aer.Aer.backends()[7:] import qiskit as qk # To simplify the code let's use the function QuantumCircuit(n,m) # which creates n Qubits and m Classical Registers at once qc = qk.QuantumCircuit(1,1) # Also, it is not necessary to force initialize the qubits. Whenever # they are created, they start from |0>. qc.measure([0],[0]) display(qc.draw('mpl', style = 'clifford', scale=1)) # Let's choose a Aer backend with the aer_simulator backend = qk_aer.Aer.get_backend('aer_simulator') # Next we "transpile" the circuit through the backend chosen qc_exe = qk.transpile(qc, backend) # And execute the circuit qc in the simulator backend # getting as final result the counts from 1.000 measures # of the qubit state result = backend.run(qc_exe, shots=1000).result().get_counts() result import qiskit as qk import qiskit_aer as qk_aer backend = qk_aer.Aer.get_backend('aer_simulator') qc_exe = qk.transpile(qc, backend) result = backend.run(qc, shots=1000).result().get_counts() qk.visualization.plot_distribution(result) def show_histogram(qc,shots=1000): display(qc.draw('mpl', style = 'clifford', scale=1)) backend = qk_aer.Aer.get_backend('aer_simulator') qc_exe = qk.transpile(qc, backend) result = backend.run(qc, shots=1000).result().get_counts() print(result) grafico = qk.visualization.plot_distribution(result) display(grafico) return([result, grafico]) show_histogram(qc); import numpy as np v0 = np.array([[1],[0]]);v0 v1 = np.array([[0],[1]]); v1 X = np.array([[0,1],[1,0]]); X X.dot(v0) X.dot(v1) import qiskit as qk # Notice the compact way of creating a circuit. We indicate just the number of # qubits and in the end we make a measurement of all qubits with measure_all() # Also, when using measure_all(), Qiskit inserts a barrier between the Qubits # and the measurements (classical bits) qc = qk.QuantumCircuit(1) qc.x(0) qc.measure_all() show_histogram(qc); import numpy as np # Notice that we are creating the v0 matrix using the transpose operation v0 = np.array([[1,0]]).T; v0 # Here it is created again de X matrix X = np.array([[0,1],[1,0]]); X # Multiplying v0 by the X matrix twice you get again v0 X.dot(X).dot(v0) # Multiplying the X matrix by itself you get the Identity matrix X.dot(X) import qiskit as qk qc = qk.QuantumCircuit(1) qc.x(0) qc.x(0) qc.measure_all() show_histogram(qc); import qiskit as qk qc = qk.QuantumCircuit(1) qc.initialize([2**-0.5,2**-0.5],0) qc.measure_all() show_histogram(qc); import numpy as np v0 = np.array([[1,0]]).T; v0 H = np.array([[1,1],[1,-1]])/np.sqrt(2); H H.dot(v0) import qiskit as qk qc = qk.QuantumCircuit(1) qc.h(0) qc.measure_all() show_histogram(qc); import qiskit as qk qc = qk.QuantumCircuit(1) qc.initialize([2**-0.5,-(2**-0.5)],0) qc.measure_all() show_histogram(qc) import qiskit as qk qc = qk.QuantumCircuit(1) qc.initialize([2**-0.5,-(2**-0.5)],0) qc.h(0) qc.measure_all() show_histogram(qc); import qiskit as qk qc = qk.QuantumCircuit(1) qc.x(0) qc.h(0) qc.h(0) qc.measure_all() show_histogram(qc); import numpy as np # First let's start with the qubit in the state |psi> = (|0> - |1>)/sqrt(2) psi = np.array([[1,-1]]).T/(2**0.5); psi H = np.array([[1,1],[1,-1]])/2**0.5; H # Now let's pass the qubit Psi through an Hadamard gate. # The result is a qubit in the state |1> H.dot(psi) # Let's start with a qubit in the state |1>, pass it through a # a hadamard gate twice and check the result v0 = np.array([[0,1]]).T; v0 H.dot(H).dot(v0) # This means that if we multiply the H gate by itself the result # will be an Identity matrix. Let's check it. H.dot(H) import qiskit as qk qc = qk.QuantumCircuit(2) qc.measure_all() show_histogram(qc); import numpy as np psi1 = np.array([[1,0]]).T; psi1 psi2 = np.array([[1,0]]).T; psi2 # In numpy the tensor product is calculated with the function kron np.kron(psi1,psi2) import qiskit as qk qc = qk.QuantumCircuit(2) qc.h(0) qc.h(1) qc.measure_all() show_histogram(qc); import numpy as np psi1 = np.array([[1,0]]).T;psi1 psi2 = np.array([[1,0]]).T;psi2 H = np.array([[1,1],[1,-1]])/2**0.5;H # When we want to combine two vector states or gate matrices we tensor product them. psi3 = np.kron(psi1,psi2);psi3 H2 = np.kron(H,H);H2 # When we want to pass a vetor through a gate we calculate the dot product # of the total gate matrix with the total vector. # As we have predicted, the resulting vector state has a=b=c=d=1/2 psi4 = H2.dot(psi3); psi4 import qiskit as qk qc = qk.QuantumCircuit(2) qc.x([0,1]) qc.h(0) qc.h(1) qc.measure_all() show_histogram(qc); import numpy as np psi1 = np.array([[0,1]]).T;psi1 psi2 = np.array([[0,1]]).T;psi2 H = np.array([[1,1],[1,-1]])/2**0.5;H # When we want to combine two vector states or gate matrices we tensor product them. psi3 = np.kron(psi1,psi2);psi3 H2 = np.kron(H,H);H2 # When we want to pass a vetor through a gate we calculate the dot product # of the total gate matrix with the total vector. # As we have predicted, the resulting vector state has a=b=c=d=1/2 psi4 = H2.dot(psi3); psi4 import qiskit as qk qc = qk.QuantumCircuit(2) qc.cx(0,1) qc.measure_all() show_histogram(qc); import numpy as np C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C v00 = np.array([[1,0,0,0]]).T;v00 # C.v00 = v00 C.dot(v00) # Please notice that Qiskit's qubits presentation order is reversed. # Therefore 10 in the histogram's x axis should be read as 01 (from # inside out or right to left). This makes sense when pairing a # a circuit with an histogram import qiskit as qk qc = qk.QuantumCircuit(2) qc.x(1) qc.cx(0,1) qc.measure_all() show_histogram(qc) import numpy as np C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C v01 = np.array([[0,1,0,0]]).T;v01 # C.v01 = v01 C.dot(v01) import qiskit as qk qc = qk.QuantumCircuit(2) qc.x(1) qc.cx(0,1) qc.measure_all() show_histogram(qc); import numpy as np C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C v10 = np.array([[0,0,1,0]]).T; v10 # C.v10 = v11 C.dot(v10) # Again remember to read qiskit qubits state presentation order # from right to left. Therefore 01 in the x axis is in fact 10 import qiskit as qk qc = qk.QuantumCircuit(2) qc.x([0,1]) qc.cx(0,1) qc.measure_all() show_histogram(qc); import numpy as np C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C v11 = np.array([[0,0,0,1]]).T; v11 # C.v11 = v10 C.dot(v11) import qiskit as qk qc = qk.QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.measure_all() show_histogram(qc); import numpy as np va = np.array([[1,0]]).T; va vb = np.array([[1,0]]).T; vb H = np.array([[1,1],[1,-1]])/2**0.5;H vaH = H.dot(va); vaH vaHvb = np.kron(vaH,vb); vaHvb C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C vout = C.dot(vaHvb); vout import qiskit as qk qc = qk.QuantumCircuit(2) qc.x(0) qc.h(0) qc.cx(0,1) qc.measure_all() show_histogram(qc); import numpy as np va = np.array([[0,1]]).T; va vb = np.array([[1,0]]).T; vb H = np.array([[1,1],[1,-1]])/2**0.5;H vaH = H.dot(va); vaH vaHvb = np.kron(vaH,vb); vaHvb C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C vout = C.dot(vaHvb); vout import qiskit as qk qc = qk.QuantumCircuit(3,3) for i in range(3): qc.h(i) qc.measure(i,i) show_histogram(qc); from qiskit import QuantumCircuit qc = QuantumCircuit(4,4) qc.x([0,1]) qc.cx([0,1],[2,2]) qc.ccx(0,1,3) qc.measure([0,1,2,3],[0,1,2,3]) show_histogram(qc); import qiskit as qk qc = qk.QuantumCircuit(1) qc.x(0) qc.measure_all() show_histogram(qc); # To avoid modifying the original circuit, let's first copy it qc2 = qc.copy() qc2.remove_final_measurements() qc2.draw('mpl', style='clifford', scale=1) import qiskit as qk sv = qk.quantum_info.Statevector(qc2); sv from qiskit.visualization import plot_bloch_multivector plot_bloch_multivector(sv) from qiskit.quantum_info import Operator Operator(qc2).data
https://github.com/gustavomirapalheta/Quantum-Computing-with-Qiskit
gustavomirapalheta
# Setup bรกsico !pip install qiskit -q !pip install qiskit[visualization] -q import qiskit as qk !pip install qiskit-aer -q import qiskit_aer as qk_aer import numpy as np np.set_printoptions(precision=3, suppress=True) from matplotlib import pyplot as plt %matplotlib inline import pandas as pd import sklearn as sk import qiskit as qk qc = qk.QuantumCircuit(3,3) qc.initialize(1,[0]) qc.barrier() qc.h(1) qc.cx(1,2) qc.barrier() qc.cx(0,1) qc.h(0) qc.barrier() qc.measure([0,1],[0,1]) display(qc.draw('mpl', style='clifford', scale=1)) import sympy as sp a, b = sp.symbols('a b') q0 = sp.Matrix([[a, b]]); display(q0); print(" ") q1 = sp.Matrix([[1, 0]]); display(q1); print(" ") q2 = sp.Matrix([[1, 0]]); display(q2); from sympy import kronecker_product as kron e0 = kron(q0, kron(q1,q2)); e0 I1 = sp.Matrix([[1,0], [0,1]]) H1 = sp.Matrix([[1, 1], [1,-1]]) IHI = kron(I1,kron(H1,I1)) CNOT12 = sp.Matrix([[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]]) IC12 = kron(I1,CNOT12) e1 = e0*IHI*IC12; e1 e2 = e1*kron(CNOT12,I1)*kron(H1,kron(I1,I1)); e2
https://github.com/gustavomirapalheta/Quantum-Computing-with-Qiskit
gustavomirapalheta
import sympy as sp f0, f0L, f1, f1L = sp.symbols('f0 f0L f1, f1L'); Or = sp.Matrix([[f0L, f0, 0, 0], [ f0, f0L, 0, 0], [ 0, 0, f1L, f1], [ 0, 0, f1, f1L]]) Or import sympy as sp from sympy import kronecker_product as kron H = sp.Matrix([[1,1],[1,-1]]) I = sp.Matrix([[1,0],[0,1]]) x=sp.Matrix([[1,0]]) y=sp.Matrix([[0,1]]) #ATENร‡รƒO: |yx> -> <xy| ou |q2q1q0> -> <q0q1q2| (equivalรชncia ket-bra) #Logo se utilizamos "bras" no lugar de "kets", o Qiskit deve ser lido #de cima para baixo e da esquerda para a direita. deustch = kron(x,y)*(kron(H,H))*(Or)*(kron(H,I)) display(deustch.T) deustch.subs({f0:1, f0L:0, f1:1, f1L:0}) deustch.subs({f0:0, f0L:1, f1:0, f1L:1}) deustch.subs({f0:0, f0L:1, f1:1, f1L:0}) deustch.subs({f0:1, f0L:0, f1:0, f1L:1}) import numpy as np x = np.array([[1,0]]) y = np.array([[0,1]]) xy = np.kron(x,y); xy H2 = np.array([[1, 1], [1,-1]]); H2 I2 = np.array([[1,0],[0,1]]); I2 H2H2 = np.kron(H2,H2); H2H2 print(xy.dot(H2H2)) Or1 = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]); Or1 res1 = xy.dot(H2H2).dot(Or1).dot(H2I2); print(res1) Or2 = np.array([[0,1,0,0],[1,0,0,0],[0,0,0,1],[0,0,1,0]]); Or2 res2 = xy.dot(H2H2).dot(Or2).dot(H2I2); print(res2) Or3 = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); Or3 res3 = xy.dot(H2H2).dot(Or3).dot(H2I2); print(res3) Or4 = np.array([[0,1,0,0],[1,0,0,0],[0,0,1,0],[0,0,0,1]]); Or4 res4 = xy.dot(H2H2).dot(Or4).dot(H2I2); print(res4) # Setup bรกsico !pip install qiskit -q !pip install qiskit[visualization] -q import qiskit as qk !pip install qiskit-aer -q import qiskit_aer as qk_aer import numpy as np np.set_printoptions(precision=3, suppress=True) from matplotlib import pyplot as plt %matplotlib inline import pandas as pd import sklearn as sk # IMPORTANT NOTE: The readings in Qiskit should be done from bottom up. # The most significant bit (the leftmost in a table or # matrix is the one at the BOTTOM. To keep compatibility # with the sympy and numpy matrices, x will be placed # BELOW and y on TOP. import numpy as np Or1 = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]); display(Or1) import qiskit as qk from qiskit.quantum_info.operators import Operator qrx = qk.QuantumRegister(1,'x') cr = qk.ClassicalRegister(1,"c") qry = qk.QuantumRegister(1,'y') qc = qk.QuantumCircuit(qry,qrx,cr) qc.barrier() qc.h(qrx) qc.x(qry) qc.h(qry) qc.barrier() oracle = Operator(Or1) qc.append(oracle,[qry,qrx]) qc.barrier() qc.h(qrx) qc.measure(qrx,cr) display(qc.draw('mpl')) simulator = qk_aer.Aer.get_backend("aer_simulator") results = simulator.run(qk.transpile(qc,simulator),shots=10000).result().get_counts() qk.visualization.plot_histogram(results) # IMPORTANT NOTE: The readings in Qiskit should be done from bottom up. # The most significant bit (the leftmost in a table or # matrix is the one at the BOTTOM. To keep compatibility # with the sympy and numpy matrices, x will be placed # BELOW and y on TOP. import numpy as np Or2 = np.array([[0,1,0,0],[1,0,0,0],[0,0,0,1],[0,0,1,0]]); display(Or2) import qiskit as qk from qiskit.quantum_info.operators import Operator qrx = qk.QuantumRegister(1,'x') cr = qk.ClassicalRegister(1,"c") qry = qk.QuantumRegister(1,'y') qc = qk.QuantumCircuit(qry,qrx,cr) qc.barrier() qc.h(qrx) qc.x(qry) qc.h(qry) qc.barrier() oracle = Operator(Or2) qc.append(oracle,[qry,qrx]) qc.barrier() qc.h(qrx) qc.measure(qrx,cr) display(qc.draw('mpl')) simulator = qk_aer.Aer.get_backend("aer_simulator") results = simulator.run(qk.transpile(qc,simulator),shots=10000).result().get_counts() qk.visualization.plot_histogram(results) # IMPORTANT NOTE: The readings in Qiskit should be done from bottom up. # The most significant bit (the leftmost in a table or # matrix is the one at the BOTTOM. To keep compatibility # with the sympy and numpy matrices, x will be placed # BELOW and y on TOP. When the function in balanced this # is essential to get the correct measurement (x=<1|) import numpy as np Or3 = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); display(Or3) import qiskit as qk from qiskit.quantum_info.operators import Operator qrx = qk.QuantumRegister(1,'x') cr = qk.ClassicalRegister(1,"c") qry = qk.QuantumRegister(1,'y') qc = qk.QuantumCircuit(qry,qrx,cr) qc.barrier() qc.h(qrx) qc.x(qry) qc.h(qry) qc.barrier() oracle = Operator(Or3) qc.append(oracle,[qry,qrx]) qc.barrier() qc.h(qrx) qc.measure(qrx,cr) display(qc.draw('mpl')) simulator = qk_aer.Aer.get_backend("aer_simulator") results = simulator.run(qk.transpile(qc,simulator),shots=10000).result().get_counts() qk.visualization.plot_histogram(results) # IMPORTANT NOTE: The readings in Qiskit should be done from bottom up. # The most significant bit (the leftmost in a table or # matrix is the one at the BOTTOM. To keep compatibility # with the sympy and numpy matrices, x will be placed # BELOW and y on TOP. When the function in balanced this # is essential to get the correct measurement (x=<1|) import numpy as np Or4 = np.array([[0,1,0,0],[1,0,0,0],[0,0,1,0],[0,0,0,1]]); display(Or4) import qiskit as qk from qiskit.quantum_info.operators import Operator qrx = qk.QuantumRegister(1,'x') cr = qk.ClassicalRegister(1,"c") qry = qk.QuantumRegister(1,'y') qc = qk.QuantumCircuit(qry,qrx,cr) qc.barrier() qc.h(qrx) qc.x(qry) qc.h(qry) qc.barrier() oracle = Operator(Or4) qc.append(oracle,[qry,qrx]) qc.barrier() qc.h(qrx) qc.measure(qrx,cr) display(qc.draw('mpl')) simulator = qk_aer.Aer.get_backend("aer_simulator") results = simulator.run(qk.transpile(qc,simulator),shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import sympy as sp f00, f00L, f01, f01L, f10, f10L, f11, f11L = \ sp.symbols('f00 f00L f01, f01L f10 f10L f11, f11L'); Or = sp.Matrix([[f00L, f00 , 0, 0, 0, 0, 0, 0], [f00 , f00L, 0, 0, 0, 0, 0, 0], [ 0, 0, f01L, f01 , 0, 0, 0, 0], [ 0, 0, f01 , f01L, 0, 0, 0, 0], [ 0, 0, 0, 0, f10L, f10 , 0, 0], [ 0, 0, 0, 0, f10 , f10L, 0, 0], [ 0, 0, 0, 0, 0, 0, f11L, f11 ], [ 0, 0, 0, 0, 0, 0, f11, f11L]]) Or import sympy as sp from sympy import kronecker_product as kron H = sp.Matrix([[1,1],[1,-1]]) I = sp.Matrix([[1,0],[0,1]]) x0=sp.Matrix([[1,0]]) x1=sp.Matrix([[1,0]]) y=sp.Matrix([[0,1]]) #ATENร‡รƒO: |yx> -> <xy| ou |q2q1q0> -> <q0q1q2| (equivalรชncia ket-bra) #Logo se utilizamos "bras" no lugar de "kets", o Qiskit deve ser lido #de cima para baixo e da esquerda para a direita. josza = kron(x0,kron(x1,y))*(kron(H,kron(H,H)))*(Or)*(kron(H,kron(H,I))) display(josza.T) josza.subs({f00:0, f00L:1, f01:0, f01L:1, f10:1, f10L:0, f11:1, f11L:0}) josza.subs({f00:0, f00L:1, f01:1, f01L:0, f10:1, f10L:0, f11:0, f11L:1}) josza.subs({f00:0, f00L:1, f01:0, f01L:1, f10:0, f10L:1, f11:0, f11L:1}) josza.subs({f00:1, f00L:0, f01:1, f01L:0, f10:1, f10L:0, f11:1, f11L:0}) josza.subs({f00:0, f00L:1, f01:0, f01L:1, f10:0, f10L:1, f11:1, f11L:0})
https://github.com/gustavomirapalheta/Quantum-Computing-with-Qiskit
gustavomirapalheta
# Setup bรกsico !pip install qiskit -q !pip install qiskit[visualization] -q import qiskit as qk !pip install qiskit-aer -q import qiskit_aer as qk_aer import numpy as np np.set_printoptions(precision=3, suppress=True) from matplotlib import pyplot as plt %matplotlib inline import pandas as pd import sklearn as sk import qiskit as qk qrx = qk.QuantumRegister(2,'x') qry = qk.QuantumRegister(2,'y') qc = qk.QuantumCircuit(qrx,qry) qc.barrier() qc.cx(0,2) qc.cx(0,3) qc.cx(1,2) qc.cx(1,3) qc.barrier() qc.draw('mpl') def histograma(qc): simulador = qk_aer.Aer.get_backend('aer_simulator') resultado = simulator.run(qk.transpile(qc,simulator),shots=10000).result() contagens = resultado.get_counts() grafico = qk.visualization.plot_histogram(contagens) return(grafico) def simon(initial_y, initial_x): import qiskit as qk qrx = qk.QuantumRegister(2,'x') crx = qk.ClassicalRegister(4,'c') qry = qk.QuantumRegister(2,'y') qc = qk.QuantumCircuit(qrx,qry,crx) qc.initialize(initial_x,qrx) qc.initialize(initial_y,qry) qc.barrier() qc.cx(0,2) qc.cx(0,3) qc.cx(1,2) qc.cx(1,3) qc.barrier() qc.measure([0,1,2,3],[0,1,2,3]) display(qc.draw('mpl')) grafico = histograma(qc) return(grafico) simon([1,0,0,0],[1,0,0,0]) simon([1,0,0,0],[0,0,0,1]) simon([1,0,0,0],[0,1,0,0]) simon([1,0,0,0],[0,0,1,0]) import qiskit as qk qrx = qk.QuantumRegister(2,'x') crx = qk.ClassicalRegister(2,'c') qry = qk.QuantumRegister(2,'y') qc = qk.QuantumCircuit(qrx,qry,crx) qc.initialize([1,0,0,0],qrx) qc.initialize([1,0,0,0],qry) qc.h([0,1]) qc.barrier() qc.cx(0,2) qc.cx(0,3) qc.cx(1,2) qc.cx(1,3) qc.barrier() qc.h([0,1]) qc.measure([0,1],[0,1]) display(qc.draw('mpl')) histograma(qc) import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T x1x0 = np.kron(x1,x0) y0 = np.array([[1,0]]).T y1 = np.array([[1,0]]).T y1y0 = np.kron(y1,y0) psi0 = np.kron(y1y0,x1x0) psi0.T H = np.array([[1,1],[1,-1]],dtype='int') H2 = np.kron(H,H) I2 = np.eye(4) I2H2 = np.kron(I2,H2) psi1 = I2H2.dot(psi0)/(np.sqrt(2)*np.sqrt(2)) I2H2.dot(psi0).T Tf1_2 = np.eye(16) Tf1_2 = Tf1_2[:,[0,5,2,7,4,1,6,3,8,9,10,11,12,13,14,15]] psi2 = Tf1_2.dot(psi1); psi2.T*2 Tf2_3 = np.eye(16) Tf2_3 = Tf2_3[:,[0,1,2,3,4,13,6,15,8,9,10,11,12,5,14,7]] psi3 = Tf2_3.dot(psi2); psi3.T*2 Tf3_4 = np.eye(16) Tf3_4 = Tf3_4[:,[0,1,6,3,4,5,2,7,8,9,10,15,12,13,14,11]] psi4 = Tf3_4.dot(psi3); psi4.T*2 Tf4_5 = np.eye(16) Tf4_5 = Tf4_5[:,[0,1,2,11,4,5,14,7,8,9,10,3,12,13,6,15]] psi5 = Tf4_5.dot(psi4); psi5.T*2 I2 = np.eye(4) H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) I2H2 = np.kron(I2,H2) psi6 = I2H2.dot(psi5) print(psi6.T*2) import numpy as np I2 = np.eye(4, dtype='int'); H2 = np.array([[1, 1, 1, 1], [1,-1, 1,-1], [1, 1,-1,-1], [1,-1,-1, 1]])/2; I2H2 = np.kron(I2,H2); print(I2H2*2) import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T x2 = np.array([[1,0]]).T x2x1x0 = np.kron(x2,np.kron(x1,x0)) x2x1x0.T y0 = np.array([[1,0]]).T y1 = np.array([[1,0]]).T y2 = np.array([[1,0]]).T y2y1y0 = np.kron(y2,np.kron(y1,y0)) y2y1y0.T psi0 = np.kron(y2y1y0,x2x1x0) psi0.T I3 = np.eye(2**3) H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H3 = np.kron(H,H2) I3H3 = np.kron(I3,H3) psi1 = I3H3.dot(psi0) psi1.T.round(2) n = 2*3 # 2 nรบmeros de 3 digitos cada Uf = np.eye(2**n) # 2^6 = 64 posiรงรตes Uf = Uf[:,[ 0, 9,18,27,12, 5,30,23, 8, 1,10,11, 4,13,14,15, 16,17, 2,19,20,21,22, 7, 24,25,26, 3,28,29, 6,31, 32,33,34,35,36,37,38,39, 40,41,42,43,44,45,46,47, 48,49,50,51,52,53,54,55, 56,57,58,59,60,61,62,63]] psi5 = Uf.dot(psi1) psi5.T.round(2) psi6 = I3H3.dot(psi5) psi6.T np.where(psi6 > 0)[0] [format(i,'#08b')[2:] for i in np.where(psi6 > 0)[0]] import numpy as np CCNOT = np.eye(8) CCNOT = CCNOT[:,[0,1,2,7,4,5,6,3]] CCNOT.dot(CCNOT) import qiskit as qk def qNAND(y0,x0): x = qk.QuantumRegister(1,"x") y = qk.QuantumRegister(1,"y") z = qk.QuantumRegister(1,"z") u = qk.QuantumRegister(1,"u") c = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(x,y,z,u,c) # Put qubits u and z in state |0> qc.initialize([1,0],z) qc.initialize([1,0],u) qc.initialize(y0,y) qc.initialize(x0,x) # Perform computation qc.barrier() qc.ccx(x,y,z) qc.x(z) # Copy CLASSICALY state of z to u qc.cx(z,u) qc.barrier() # Reverse computation qc.x(z) qc.ccx(x,y,z) qc.barrier() # Measure results qc.measure(x,c[0]) qc.measure(y,c[1]) qc.measure(u,c[2]) display(qc.draw('mpl')) simulator = qk_aer.Aer.get_backend("aer_simulator") results = simulator.run(qk.transpile(qc,simulator), shots=10000).result().get_counts() grafico = qk.visualization.plot_histogram(results) return(grafico) print("0 NAND 0 = 1") qNAND([1,0],[1,0]) print("0 NAND 1 = 1") qNAND([1,0],[0,1]) print("1 NAND 0 = 1") qNAND([0,1],[1,0]) print("1 NAND 1 = 0") qNAND([0,1],[0,1]) import qiskit as qk def qOR(y0,x0): x = qk.QuantumRegister(1,"x") y = qk.QuantumRegister(1,"y") z = qk.QuantumRegister(1,"z") u = qk.QuantumRegister(1,"u") c = qk.ClassicalRegister(3,'c') # Initialize qubits qc = qk.QuantumCircuit(x,y,z,u,c) qc.initialize(x0,x) qc.initialize(y0,y) qc.initialize([1,0],z) qc.initialize([1,0],u) # Compute function qc.barrier() qc.x(x) qc.x(y) qc.ccx(x,y,z) qc.x(z) qc.cx(z,u) qc.barrier() # Reverse computation qc.x(z) qc.ccx(x,y,z) qc.x(y) qc.x(x) qc.barrier() # Measure results qc.measure(x,c[0]) qc.measure(y,c[1]) qc.measure(u,c[2]) display(qc.draw('mpl')) # Simulate circuit simulator = qk_aer.Aer.get_backend('aer_simulator') results = simulator.run(qk.transpile(qc,simulator),shots=10000).result().get_counts() grafico = qk.visualization.plot_histogram(results) return(grafico) qOR([1,0],[1,0]) qOR([1,0],[0,1]) qOR([0,1],[1,0]) qOR([0,1],[0,1]) import qiskit as qk def qNXOR(y0,x0,calc=True,show=False): ################################################## # Create registers # ################################################## # Base registers x = qk.QuantumRegister(1,"x") y = qk.QuantumRegister(1,"y") # Auxiliary register (for x and y) z = qk.QuantumRegister(1,"z") # Auxiliary register (to store x AND y) a1 = qk.QuantumRegister(1,"a1") # Auxiliary register (to store NOT(x) AND NOT(y)) a2 = qk.QuantumRegister(1,"a2") # Auxiliary register (for a1 and a2) b1 = qk.QuantumRegister(1,"b1") # Auxiliary register (to store a1 OR a2) b2 = qk.QuantumRegister(1,"b2") # Classical Registers to store x,y and final measurement c = qk.ClassicalRegister(3,"c") ################################################## # Create Circuit # ################################################## qc = qk.QuantumCircuit(x,y,z,a1,a2,b1,b2,c) ################################################## # Initialize registers # ################################################## qc.initialize(x0,x) qc.initialize(y0,y) qc.initialize([1,0],z) qc.initialize([1,0],a1) qc.initialize([1,0],a2) qc.initialize([1,0],b1) qc.initialize([1,0],b2) ################################################### # Calculate x AND y. Copy result to a1. Reverse z # ################################################### qc.barrier() qc.ccx(x,y,z) qc.cx(z,a1) qc.ccx(x,y,z) qc.barrier() ######################################################### # Calc. NOT(x) AND NOT(y). Copy result to a2. Reverse z # ######################################################### qc.barrier() qc.x(x) qc.x(y) qc.ccx(x,y,z) qc.cx(z,a2) qc.ccx(x,y,z) qc.x(y) qc.x(x) qc.barrier() ################################################# # Calc. a1 OR a2. Copy result to b2. Reverse b1 # ################################################# qc.barrier() qc.x(a1) qc.x(a2) qc.ccx(a1,a2,b1) qc.x(b1) qc.cx(b1,b2) qc.x(b1) qc.ccx(a1,a2,b1) qc.barrier() ################################################# # Measure b2 # ################################################# qc.measure(x,c[0]) qc.measure(y,c[1]) qc.measure(b2,c[2]) ################################################# # Draw circuit # ################################################# if show: display(qc.draw("mpl")) ################################################# # Run circuit. Collect results # ################################################# if calc: simulator = qk_aer.Aer.get_backend("aer_simulator") results = simulator.run(qk.transpile(qc,simulator),shots=10000).result().get_counts() grafico = qk.visualization.plot_histogram(results) return(grafico) else: return() qNXOR([1,0],[1,0],False,True) qNXOR([1,0],[1,0]) qNXOR([1,0],[0,1]) qNXOR([0,1],[1,0]) qNXOR([0,1],[0,1]) x0 = np.array([1,1])/np.sqrt(2) y0 = np.array([1,1])/np.sqrt(2) qNXOR(y0,x0) import qiskit as qk from qiskit.quantum_info.operators import Operator qr = qk.QuantumRegister(6,"q") cr = qk.ClassicalRegister(6,"c") qc = qk.QuantumCircuit(qr,cr) for i in range(6): qc.initialize([1,0],i) for i in range(3): qc.h(i) oracle = np.eye(2**6) oracle[:,[ 0, 0]] = oracle[:,[ 0, 0]] oracle[:,[ 1, 9]] = oracle[:,[ 9, 1]] oracle[:,[ 2, 18]] = oracle[:,[ 18, 2]] oracle[:,[ 3, 27]] = oracle[:,[ 27, 3]] oracle[:,[ 4, 12]] = oracle[:,[ 12, 4]] oracle[:,[ 5, 5]] = oracle[:,[ 5, 5]] oracle[:,[ 6, 30]] = oracle[:,[ 30, 6]] oracle[:,[ 7, 23]] = oracle[:,[ 23, 7]] oracle = Operator(oracle) qc.append(oracle,qr) for i in range(3): qc.h(i) qc.barrier() for i in range(3): qc.measure(i,i) display(qc.draw("mpl")) simulator = qk_aer.Aer.get_backend("aer_simulator") results = simulator.run(qk.transpile(qc,simulator),shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np oracle = np.eye(8) oracle[:,[2,6]] = oracle[:,[6,2]] oracle import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T psi0 = np.kron(x1,x0) H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) psi1 = H2.dot(psi0) psi1.T # Initialize a qubit y in state |1> y = np.array([[0,1]]).T # Pass it through a Hadamard gate and obtain state psi2a H = np.array([[1,1],[1,-1]])/np.sqrt(2) psi2a = H.dot(y) psi2a.T psi2 = np.kron(psi2a,psi1) psi2.T oracle = np.eye(8) oracle[:,[2,6]] = oracle[:,[6,2]] oracle psi3 = oracle.dot(psi2) psi3.T v0 = np.array([[10,20,-30,40,50]]).T mu = np.mean(v0) v0.T, mu D = v0 - mu D.T v1 = 2*np.mean(v0)-v0 v1.T import numpy as np A = np.ones(5**2).reshape(5,5) A = A/5 I = np.eye(5) R = 2*A-I R R.dot(R) n = 4 I = np.eye(n) A = np.ones(n**2).reshape(n,n)/n R = 2*A-I R I2 = np.eye(2) I2R = np.kron(I2,R) I2R psi4 = I2R.dot(psi3) psi4.T import qiskit as qk import numpy as np from qiskit.quantum_info.operators import Operator q = qk.QuantumRegister(3,'q') c = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(q,c) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.h(1) qc.initialize([0,1],2) qc.h(2) qc.barrier() oracle = np.eye(8) oracle[:,[2,6]] = oracle[:,[6,2]] oracle = Operator(oracle) qc.append(oracle,q) # n = 2 (two digits number to look for) A = np.ones(4*4).reshape(4,4)/4 I4 = np.eye(4) R = 2*A - I4 I2 = np.eye(2) boost = np.kron(I2,R) boost = Operator(boost) qc.append(boost,q) qc.barrier() qc.measure(q[:2],c[:2]) display(qc.draw('mpl')) simulator = qk_aer.Aer.get_backend('aer_simulator') results = simulator.run(qk.transpile(qc,simulator),shots=1000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T x2 = np.array([[1,0]]).T x2x1x0 = np.kron(x2,np.kron(x1,x0)) x2x1x0.T H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H3 = np.kron(H,H2) x = H3.dot(x2x1x0) x.T y0 = np.array([[0,1]]).T y0.T H = np.array([[1,1],[1,-1]])/np.sqrt(2) y = H.dot(y0) y.T psi0 = np.kron(y,x) psi0.T oracle = np.eye(16) oracle[:,[5,13]] = oracle[:,[13,5]] psi1 = oracle.dot(psi0) psi1.T # n = 8 A = np.ones(8*8).reshape(8,8)/8 I8 = np.eye(8) R = 2*A-I8 R I2 = np.eye(2) I2R = np.kron(I2,R) psi2 = I2R.dot(psi1) psi2.T 0.625**2 + 0.625**2 psi3 = I2R.dot(oracle).dot(psi2) psi3.T 0.687**2 + 0.687**2 I2R.dot(oracle).dot(psi3).T T = I2R.dot(oracle) psi = psi1 prob = [] for i in range(25): prob.append(psi[5,0]**2 + psi[13,0]**2) psi = T.dot(psi) from matplotlib import pyplot as plt plt.plot(list(range(25)), prob); import qiskit as qk import numpy as np from qiskit.quantum_info.operators import Operator q = qk.QuantumRegister(4,'q') c = qk.ClassicalRegister(4,'c') qc = qk.QuantumCircuit(q,c) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([1,0],2) qc.h(0) qc.h(1) qc.h(2) qc.initialize([0,1],3) qc.h(3) qc.barrier() # Create oracle matrix oracle = np.eye(16) oracle[:,[5,13]] = oracle[:,[13,5]] # Create rotation about the mean matrix # n = 3 (three digits number to look for) A = np.ones(8*8).reshape(8,8)/8 I8 = np.eye(8) R = 2*A - I8 # Identity matrix to leave fourth qubit undisturbed I2 = np.eye(2) # Create second transformation matrix boost = np.kron(I2,R) # Combine oracle with second transformation matrix in # an unique operator T = boost.dot(oracle) T = Operator(T) # Apply operator twice (2 phase inversions and # rotations about the mean) qc.append(T,q) qc.append(T,q) qc.barrier() qc.measure(q[:3],c[:3]) display(qc.draw('mpl')) simulator = qk_aer.Aer.get_backend('aer_simulator') results = simulator.run(qk.transpile(qc,simulator),shots=1000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk import numpy as np from qiskit.quantum_info.operators import Operator q = qk.QuantumRegister(5,'q') c = qk.ClassicalRegister(5,'c') qc = qk.QuantumCircuit(q,c) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([1,0],2) qc.initialize([1,0],3) qc.h(0) qc.h(1) qc.h(2) qc.h(3) qc.initialize([0,1],4) qc.h(4) qc.barrier() # Create oracle matrix oracle = np.eye(32) oracle[:,[13,29]] = oracle[:,[29,13]] # Create rotation about the mean matrix # n = 4 (four digits number to look for) A = np.ones(16*16).reshape(16,16)/16 I16 = np.eye(16) R = 2*A - I16 # Identity matrix to leave fifth qubit undisturbed I2 = np.eye(2) # Create second transformation matrix boost = np.kron(I2,R) # Combine oracle with second transformation matrix in # an unique operator T = boost.dot(oracle) # n = 4. Therefore it will be necessary 4 T operations # to get maximum probability. Tn = T.dot(T).dot(T) Tn = Operator(Tn) # Apply operator Tn once (n phase inversions and # rotations about the mean) qc.append(Tn,q) qc.barrier() qc.measure(q[:4],c[:4]) display(qc.draw('mpl')) simulator = qk_aer.Aer.get_backend('aer_simulator') results = simulator.run(qk.transpile(qc,simulator),shots=1000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np import pandas as pd N = 35; a = 6 GCD = pd.DataFrame({'N':[N], 'a':[a], 'N-a':[N-a]}) while GCD.iloc[-1,2] != 0: temp = GCD.iloc[-1].values temp = np.sort(temp); temp[-1] = temp[-2] - temp[-3] temp = pd.DataFrame(data = temp.reshape(-1,3), columns = ['N','a','N-a']) GCD = pd.concat([GCD,temp], ignore_index=True) GCD import numpy as np import pandas as pd N = 15; a = 9 GCD = pd.DataFrame({'N':[N], 'a':[a], 'N-a':[N-a]}) while GCD.iloc[-1,2] != 0: temp = GCD.iloc[-1].values temp = np.sort(temp); temp[-1] = temp[-2] - temp[-3] temp = pd.DataFrame(data = temp.reshape(-1,3), columns = ['N','a','N-a']) GCD = pd.concat([GCD,temp], ignore_index=True) GCD import numpy as np np.gcd(6,35), np.gcd(9,15) import numpy as np np.gcd(215,35), np.gcd(217,35) 20 % 7 import numpy as np f = lambda x,a,N: a**x % N [f(x,2,15) for x in range(10)] import numpy as np (13*35)%11, ((2%11)*(24%11))%11 import numpy as np def f(x,a,N): a0 = 1 for i in range(x): a0 = ((a%N)*(a0))%N return(a0) [f(x,2,371) for x in range(8)] [f(x,2,371) for x in range(154,159)] [f(x,24,371) for x in range(77,81)] import numpy as np def fr(a,N): ax = ((a%N)*(1))%N x = 1 while ax != 1: ax = ((a%N)*(ax))%N x = x+1 return(x) fr(2,371), fr(6,371), fr(24,371) import numpy as np def fr(a,N): a0 = 1 a0 = ((a%N)*a0)%N x = 2 find = False while find==False: a0 = ((a%N)*(a0))%N if a0 == 1: find = True x = x+1 return(x-1) N = 35 a = 2 fr(a,N) 2**(12/2)-1, 2**(12/2)+1 np.gcd(63,35), np.gcd(65,35) import numpy as np # Function to calculate the period of f(x) = a^x MOD N def fr(a,N): a1 = ((a%N)*(1))%N x = 1 while a1 != 1: a1 = ((a%N)*a1)%N x = x+1 return(x) # Function to factor N based on a def factor(N, a=2): r = fr(a,N) g1 = a**(int(r/2)) - 1 g2 = a**(int(r/2)) + 1 f1 = np.gcd(g1,N) f2 = np.gcd(g2,N) return(f1,f2, f1*f2) factor(247) factor(1045)
https://github.com/gustavomirapalheta/Quantum-Computing-with-Qiskit
gustavomirapalheta
def chop(x, tol=1.e-14): r = np.real(x) if abs(r)<tol: r = 0 i = np.imag(x) if abs(i)<tol: i = 0 if i == 0: n = r elif r == 0: n = i*1j else: n = r + i*1j return(n) import numpy as np a = 1e-16 + 1e-16*1j b = 1e-16 + 1j c = 1 + 1e-16*1j chop(a), chop(b), chop(c) n = 4 w4 = np.exp(2*np.pi*1j/n) w4 = chop(w4) w4 F4 = np.zeros([4,4], dtype=complex) for i in range(4): for j in range(4): F4[i,j] = w4**(i*j) F4 I2 = np.array([[1,0],[0,1]]); I2 D2_4 = np.zeros([2,2], dtype=complex) for i in range(2): D2_4[i,i] = w4**(i) D2_4 M1 = np.concatenate([I2,D2_4],axis=1) M2 = np.concatenate([I2,-D2_4],axis=1) M3 = np.concatenate([M1,M2],axis=0); M3 n = 2 w2 = np.exp(2*np.pi*1j/n) w2 = chop(w2) w2 F2 = np.zeros([2,2], dtype=complex) for i in range(2): for j in range(2): F2[i,j] = w2**(i*j) F2 Z2 = np.zeros([2,2], dtype=complex) Z2 K1 = np.concatenate([F2,Z2],axis=1) K2 = np.concatenate([Z2,F2],axis=1) K3 = np.concatenate([K1,K2],axis=0); K3 P4 = np.array([[1,0,0,0], [0,0,1,0], [0,1,0,0], [0,0,0,1]]) P4 M3.dot(K3).dot(P4) F4 np.all(F4 == M3.dot(K3).dot(P4))
https://github.com/gustavomirapalheta/Quantum-Computing-with-Qiskit
gustavomirapalheta
!pip install qutip -q !pip install qiskit -q !pip install qiskit[visualization] -q !pip install git+https://github.com/qiskit-community/qiskit-textbook.git#subdirectory=qiskit-textbook-src -q import numpy as np np.set_printoptions(precision=3, suppress=True) import qutip as qt from matplotlib import pyplot as plt %matplotlib inline import pandas as pd import sklearn as sk import qiskit as qk !pip install qutip -q !pip install qiskit -q !pip install qiskit[visualization] -q !pip install git+https://github.com/qiskit-community/qiskit-textbook.git#subdirectory=qiskit-textbook-src -q import numpy as np np.set_printoptions(precision=3, suppress=True) import qutip as qt from matplotlib import pyplot as plt %matplotlib inline import pandas as pd import sklearn as sk import qiskit as qk # Remember that qiskit has to be already installed in the Python environment. # Otherwise the import command will fail import qiskit as qk # A circuit composed of just one qubit qc = qk.QuantumCircuit(1) qc.draw('mpl') import qiskit as qiskit # A qubit initialized in the state |0> qc = qk.QuantumCircuit(1) qc.initialize([1,0]) qc.draw('mpl') import qiskit as qk # A qubit initialized in |0> and a measurement qc = qk.QuantumCircuit(1) qc.initialize([1,0]) qc.measure_all() qc.draw('mpl') import qiskit as qk # A list of possible measurements. The results of measurements are obtained # by executing an object called backend a = [print(i) for i in qk.Aer.backends()] import qiskit as qk qc = qk.QuantumCircuit(1) qc.initialize([1,0],0) qc.measure_all() # Let's choose the statevector simulator from the Aer backend backend = qk.Aer.get_backend('statevector_simulator') # And execute the circuit qc in the simulator backend # getting as final result the counts from 1.000 measures # of the qubit state result = qk.execute(qc, backend, shots=1000).result().get_counts() result import qiskit as qk qc = qk.QuantumCircuit(1) qc.initialize([1,0],0) qc.measure_all() backend = qk.Aer.get_backend('statevector_simulator') result = qk.execute(qc, backend, shots=1000).result().get_counts() qk.visualization.plot_histogram(result) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) qc.measure(0,0) qc.draw('mpl') backend = qk.Aer.get_backend('statevector_simulator') result = qk.execute(qc, backend, shots=1000).result().get_counts() qk.visualization.plot_histogram(result) import numpy as np v0 = np.array([[1],[0]]);v0 v1 = np.array([[0],[1]]); v1 X = np.array([[0,1],[1,0]]); X X.dot(v0) X.dot(v1) import qiskit as qk qr = qk.QuantumRegister(1,"q0") cr = qk.ClassicalRegister(1,"c0") qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) qc.x(0) qc.measure(qr[0], cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, simulator, shots=1000).result().get_counts() results qk.visualization.plot_histogram(results) import numpy as np # Notice that we are creating the v0 matrix using the transpose operation v0 = np.array([[1,0]]).T; v0 # Here it is created again de X matrix X = np.array([[0,1],[1,0]]); X # Multiplying v0 by the X matrix twice you get again v0 X.dot(X).dot(v0) # Multiplying the X matrix by itself you get the Identity matrix X.dot(X) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) qc.x(0) qc.x(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') # The result of 1000 measures of the qubit above gives the |0> state as result # in all measures simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=1000).result().get_counts() results qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([2**-0.5,2**-0.5],0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np v0 = np.array([[1,0]]).T; v0 H = np.array([[1,1],[1,-1]])/np.sqrt(2); H H.dot(v0) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.h(qr[0]) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, simulator, shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([2**-0.5,-(2**-0.5)],0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([2**-0.5,-(2**-0.5)],0) qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([0,1],0) qc.h(0) qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np # First let's start with the qubit in the state |psi> = (|0> - |1>)/sqrt(2) psi = np.array([[1,-1]]).T/(2**0.5); psi H = np.array([[1,1],[1,-1]])/2**0.5; H # Now let's pass the qubit Psi through an Hadamard gate. # The result is a qubit in the state |1> H.dot(psi) # Let's start with a qubit in the state |1>, pass it through a # a hadamard gate twice and check the result v0 = np.array([[0,1]]).T; v0 H.dot(H).dot(v0) # This means that if we multiply the H gate by itself the result # will be an Identity matrix. Let's check it. H.dot(H) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np psi1 = np.array([[1,0]]).T; psi1 psi2 = np.array([[1,0]]).T; psi2 # In numpy the tensor product is calculated with the function kron np.kron(psi1,psi2) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.h(1) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np psi1 = np.array([[1,0]]).T;psi1 psi2 = np.array([[1,0]]).T;psi2 H = np.array([[1,1],[1,-1]])/2**0.5;H # When we want to combine two vector states or gate matrices we tensor product them. psi3 = np.kron(psi1,psi2);psi3 H2 = np.kron(H,H);H2 # When we want to pass a vetor through a gate we calculate the dot product # of the total gate matrix with the total vector. # As we have predicted, the resulting vector state has a=b=c=d=1/2 psi4 = H2.dot(psi3); psi4 import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([0,1],0) qc.initialize([0,1],1) qc.h(0) qc.h(1) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np psi1 = np.array([[0,1]]).T;psi1 psi2 = np.array([[0,1]]).T;psi2 H = np.array([[1,1],[1,-1]])/2**0.5;H # When we want to combine two vector states or gate matrices we tensor product them. psi3 = np.kron(psi1,psi2);psi3 H2 = np.kron(H,H);H2 # When we want to pass a vetor through a gate we calculate the dot product # of the total gate matrix with the total vector. # As we have predicted, the resulting vector state has a=b=c=d=1/2 psi4 = H2.dot(psi3); psi4 import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.cnot(0,1) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, simulator, shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C v00 = np.array([[1,0,0,0]]).T;v00 # C.v00 = v00 C.dot(v00) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.cnot(0,1) qc.measure(qr,cr) qc.draw('mpl') # Please notice that Qiskit's qubits presentation order is reversed. # Therefore 10 in the histogram's x axis should be read as 01 (from # inside out or right to left). simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, simulator, shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C v01 = np.array([[0,1,0,0]]).T;v01 # C.v01 = v01 C.dot(v01) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([0,1],0) qc.initialize([1,0],1) qc.cnot(0,1) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, simulator, shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C v10 = np.array([[0,0,1,0]]).T; v10 # C.v10 = v11 C.dot(v10) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([0,1],0) qc.initialize([0,1],1) qc.cnot(0,1) qc.measure(qr,cr) qc.draw('mpl') # Again remember to read qiskit qubits state presentation order # from right to left. Therefore 01 in the x axis is in fact 10 simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, simulator, shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C v11 = np.array([[0,0,0,1]]).T; v11 # C.v11 = v10 C.dot(v11) import qiskit as qk qr = qk.QuantumRegister(2, 'q') cr = qk.ClassicalRegister(2, 'c') qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(qr[0]) qc.cx(qr[0],qr[1]) qc.measure(qr, cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np va = np.array([[1,0]]).T; va vb = np.array([[1,0]]).T; vb H = np.array([[1,1],[1,-1]])/2**0.5;H vaH = H.dot(va); vaH vaHvb = np.kron(vaH,vb); vaHvb C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C vout = C.dot(vaHvb); vout import qiskit as qk qr = qk.QuantumRegister(2, 'q') cr = qk.ClassicalRegister(2, 'c') qc = qk.QuantumCircuit(qr, cr) qc.initialize([0,1],0) qc.initialize([1,0],1) qc.h(qr[0]) qc.cx(qr[0],qr[1]) qc.measure(qr, cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np va = np.array([[0,1]]).T; va vb = np.array([[1,0]]).T; vb H = np.array([[1,1],[1,-1]])/2**0.5;H vaH = H.dot(va); vaH vaHvb = np.kron(vaH,vb); vaHvb C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C vout = C.dot(vaHvb); vout # Get the IBM API key in: https://quantum-computing.ibm.com # chave = 'My key is already saved in this environment' # qk.IBMQ.save_account(chave) # Load the account in the active session qk.IBMQ.load_account() # The default provider is รฉ hub='ibm-q', group='open, project='main' # The code below is executed as an example provider_1 = qk.IBMQ.get_provider(hub='ibm-q', group='open', project='main') # In the public provider we will use a cloud simulator. backend_1 = provider_1.get_backend('ibmq_qasm_simulator') # The provider listed below has unlimited jobs provider_2 = qk.IBMQ.get_provider(hub='ibm-q-education', group='fgv-1', project='ml-business-app') # For this provider we will use the ibmq_jakarta machine backend_2 = provider_2.get_backend('ibmq_jakarta') # With n Qubits we can generate a random number from 0 to 2^n - 1 n = 3 qr = qk.QuantumRegister(n,'q') cr = qk.ClassicalRegister(n,'c') qc = qk.QuantumCircuit(qr, cr) # Applying a Hadamard to each of the three qubits for i in range(n): qc.h(q[i]) # Measuring the three qubits qc.measure(q,c) # Visualizing the circuit qc.draw('mpl') # qk.execute envia para o backend. Conferindo no iqmq explorer aparece o job new_job = qk.execute(circ, backend_2, shots=1) # this result is stored on the local machine. However, it will only be available # after the job has been executed. It returns a python dictionary. new_job.result().get_counts() int(list(new_job.result().get_counts().keys())[0],2) from qiskit import QuantumCircuit circuit = QuantumCircuit(2, 2) circuit.h(0) circuit.cx(0,1) circuit.measure([0,1], [0,1]) display(circuit.draw('mpl')) from qiskit.providers.aer import AerSimulator print(AerSimulator().run(circuit, shots=1000).result().get_counts()) print(AerSimulator().run(circuit, shots=1000).result().get_counts()) from qiskit import QuantumCircuit circuito = QuantumCircuit(3,3) for i in range(3): circuito.h(i) circuito.measure(i,i) display(circuito.draw('mpl')) from qiskit.providers.aer import AerSimulator AerSimulator().run(circuito, shots = 1000).result().get_counts() from qiskit import QuantumCircuit qc = QuantumCircuit(4,4) qc.x([0,1]) qc.cx([0,1],[2,2]) qc.ccx(0,1,3) qc.measure([0,1,2,3],[0,1,2,3]) display(qc.draw(output='mpl')) from qiskit.providers.aer import AerSimulator AerSimulator().run(qc, shots = 10000).result().get_counts() import qiskit as qk qr = qk.QuantumRegister(1,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) print("Circuit 1 - Registers Only") display(qc.draw('mpl')) qc.x(qr) print("Circuit 1 - Quantum Register with a Gate X ") display(qc.draw('mpl')) job = qk.execute(experiments = qc, backend = qk.Aer.get_backend('statevector_simulator')) result1 = job.result().get_statevector() print("Quantum Register Vector State") from qiskit.tools.visualization import plot_bloch_multivector display(plot_bloch_multivector(result1)) job = qk.execute(experiments = qc, backend = qk.Aer.get_backend('unitary_simulator')) print("Transformation Matrix (up to this stage)") print(job.result().get_unitary()) qc.measure(qr, cr) print() print("Circuit 1 - Registers, Gate X and Quantum Register Measure") display(qc.draw('mpl')) print("Quantum Register Thousand Measures") job = qk.execute(experiments = qc, backend = qk.Aer.get_backend('statevector_simulator'), shots = 1000) print(job.result().get_counts()) print() print("Result's Histogram") from qiskit.tools.visualization import plot_histogram plot_histogram(data = job.result().get_counts(), figsize=(4,3)) import qiskit as qk from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector qr = qk.QuantumRegister(3,'q') cr = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([1,0],2) display(qc.draw('mpl')) sv = Statevector.from_label('000') state_data = lambda qc,sv: np.round(np.asarray(sv.evolve(qc).data),4) state_bloch = lambda qc,sv: plot_bloch_multivector(sv.evolve(qc).data, reverse_bits=True) print(state_data(qc,sv)) state_bloch(qc,sv) qc.x(0) qc.barrier() display(qc.draw('mpl')) print(state_data(qc,sv)) display(state_bloch(qc,sv)) qc.h(1) display(qc.draw('mpl')) print(state_data(qc,sv)) state_bloch(qc,sv) qc.cnot(1,2) display(qc.draw("mpl")) state_data(qc,sv) state_bloch(qc,sv) qc.cnot(0,1) display(qc.draw('mpl')) state_data(qc,sv) qc.h(0) qc.barrier() display(qc.draw('mpl')) state_data(qc,sv) qc.measure(0,0) qc.measure(1,1) qc.barrier() qc.cnot(1,2) qc.cz(0,2) qc.measure(2,2) display(qc.draw('mpl')) simulador = qk.Aer.get_backend('statevector_simulator') resultado = qk.execute(qc, simulador, shots=10000).result() qk.visualization.plot_histogram(resultado.get_counts()) import numpy as np V = np.array([[3+2j],[4-2j]]) modV = np.real(V.T.conjugate().dot(V)[0,0])**0.5 Vn = V/modV; Vn v0 = np.array([[1,0]]).T v1 = np.array([[0,1]]).T Vn[0,0]*v0 + Vn[1,0]*v1 import qiskit as qk qr = qk.QuantumRegister(1,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([Vn[0,0],Vn[1,0]],0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) Vn[0,0].conjugate()*Vn[0,0] Vn[1,0].conjugate()*Vn[1,0] import numpy as np CNOT = np.array([[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]]) CNOT.dot(CNOT) import numpy as np H = np.array([[1,1],[1,-1]])/2**0.5 H.dot(H) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.cnot(qr[0],qr[1]) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.cnot(qr[0],qr[1]) qc.cnot(qr[0],qr[1]) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.cnot(qr[0],qr[1]) qc.cnot(qr[0],qr[1]) qc.h(0) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np X = np.array([[0,1], [1,0]]) X X.conj().T.dot(X) Y = np.array([[0,-1j], [1j,0]]) Y Y.conj().T.dot(Y) Z = np.array([[1,0], [0,-1]]) Z Z.conj().T.dot(Z) H = (X+Z)/np.sqrt(2); H H.dot(Z).dot(H) H.dot(X).dot(H) -H.dot(Y).dot(H) import numpy as np S = np.array([[1,0], [0,1j]]) S S.conj().T.dot(S) T = np.array([[1,0], [0,np.exp(1j*np.pi/4)]]) T T.conj().T.dot(T) S = np.array([[1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]]); S S.dot(v00) S.dot(v01) S.dot(v10) S.dot(v11) C = np.array([[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]]);C C_ = np.array([[1,0,0,0], [0,0,0,1], [0,0,1,0], [0,1,0,0]]);C_ C.dot(C_).dot(C) v = v0 + v1; v n = np.array([[0,0],[0,1]]); n n.dot(v) n_ = np.array([[1,0],[0,0]]);n_ I2 = np.identity(2); I2 I2 - n n_.dot(v) n.dot(n) n_.dot(n_) n.dot(n_) n_.dot(n) n+n_ n.dot(X) X.dot(n_) import numpy as np n = np.array([[0,0],[0,1]]); n n_ = np.array([[1,0],[0,0]]);n_ # ni nj operam em bits distintos. Como cada operador n atua em um vetor de # 2 dimensรตes, ni nj รฉ um operador de 4 dimensรตes. Sendo assim, fica implรญcito # pelos subscritos que ni nj รฉ um produto tensorial. np.kron(n,n) # O mesmo vale para n'i n'j np.kron(n_,n_) # Para ni n'j np.kron(n,n_) # E para n'i nj np.kron(n_,n) # Xi Xj sรฃo dois operadores 2x2 de inversรฃo, cada um atuando em um bit # distinto. Sendo assim, fazemos o produto tensorial entre ambos # para obter XiXj np.kron(X,X) # No caso da expressรฃo XiXj(ninj' + ni'nj) temos entre parรชnteses duas # matrizes 4x4 (ninj'+ni'nj) e fora dos parรชnteses uma matriz 4x4 (XiXj) # Sendo assim fazemos neste caso o produto matricial normal para # calcular esta expressรฃo. np.kron(X,X).dot(np.kron(n,n_)+np.kron(n_,n)) # E por รบltimo somamos com o resultado inicial de ninj + ni'nj' # Como pode-se ver, esta expressรฃo gera o operador de SWAP np.kron(n,n) + np.kron(n_,n_) + np.kron(X,X).dot(np.kron(n,n_)+np.kron(n_,n)) # ร‰ importante observar que ninj forma um operador que projeta um vetor de # 4 dimensรตes (00, 01, 10, 11) em sua componente 11 np.kron(n,n) # De maneira similar ni'nj' projeta um vetor de 4 dimensรตes em sua componente 00 np.kron(n_,n_) # ni'nj projeta em 01 np.kron(n_,n) # Assim como ninj' projeta em 10 np.kron(n,n_) # E por รบltimo vemos que ni'nj' + ni'nj + ninj' + ninj = I nn = np.kron(n,n) nn_ = np.kron(n,n_) n_n = np.kron(n_,n) n_n_ = np.kron(n_,n_) nn + nn_ + n_n + n_n_ import numpy as np n = np.array([[0,0],[0,1]]); n n_ = np.array([[1,0],[0,0]]);n_ # (n x n).(n_ x n_) np.kron(n,n).dot(np.kron(n_,n_)) # Faz sentido que (ni x nj).(ni_ x nj_) seja o vetor nulo pois: # ni_ x nj_ รฉ um operador que recebe um vetor de 4 dimensรตes e # produz como resultado apenas sua componente |00>. Por sua # vez ni x nj รฉ um operador que recebe um vetor de 4 dimensรตes # e produz como resultado apenas sua componente |11>. Esta # componente foi zerada pelo primeiro operador, logo o resultado # serรก nulo. Isto vai acontecer sempre que a componente nรฃo # zerada do primeiro operador for diferente da do segundo em # outras palavras sempre que ij do primeiro for diferente de ij # do segundo. np.kron(n,n).dot(np.kron(n_,n_)) # Outra forma de entender รฉ transformar (n x n).(n_ x n_) em # (n.n_) x (n.n_). Como n รฉ ortogonal a n_, a projeรงรฃo de n # em n_ darรก zero tambรฉm. np.kron(n.dot(n_),n.dot(n_)) nn.dot(n_n_) # (n_ x n).(n x n_) np.kron(n_,n).dot(np.kron(n,n_)) n_n.dot(nn_) # (n x n_).(n_ x n) np.kron(n, n_).dot(np.kron(n_,n)) nn_.dot(n_n) # (n_ x n_).(n x n) np.kron(n_, n_).dot(np.kron(n, n)) n_n_.dot(nn) NOT = np.array([[0,1],[1,0]]); NOT NOT.dot(D0) NOT.dot(D1) AND = np.array([[1,1,1,0],[0,0,0,1]]); AND AND.dot(np.kron(D0,D0)) AND.dot(np.kron(D0,D1)) AND.dot(np.kron(D1,D0)) AND.dot(np.kron(D1,D1)) OR = np.array([[1,0,0,0],[0,1,1,1]]); OR OR.dot(np.kron(D0,D0)) OR.dot(np.kron(D0,D1)) OR.dot(np.kron(D1,D0)) OR.dot(np.kron(D1,D1)) NAND = np.array([[0,0,0,1],[1,1,1,0]]); NAND NOT.dot(AND) NOR = np.array([[0,1,1,1],[1,0,0,0]]);NOR NOT.dot(OR) np.kron(NOT,AND) OR.dot(np.kron(NOT,AND)) NOT.dot(AND).dot(np.kron(NOT,NOT)) OR NOT.dot(OR).dot(np.kron(NOT,NOT)) AND import numpy as np k = np.kron XOR = np.array([[1,0,0,1], [0,1,1,0]]) AND = np.array(([1,1,1,0], [0,0,0,1])) k(XOR,AND) def criaCompat(nbits,nvezes): nlins = 2**(nbits*nvezes) ncols = 2**nbits compat = np.zeros(nlins*ncols).reshape(nlins,ncols) for i in range(ncols): formato = "0" + str(nbits) + "b" binario = format(i,formato)*nvezes decimal = int(binario,2) compat[decimal,i] = 1 return(compat) criaCompat(2,2) k(XOR,AND).dot(criaCompat(2,2)) import numpy as np k = np.kron def criaCompat(nbits,nvezes): nlins = 2**(nbits*nvezes) ncols = 2**nbits compat = np.zeros(nlins*ncols).reshape(nlins,ncols) for i in range(ncols): formato = "0" + str(nbits) + "b" binario = format(i,formato)*nvezes decimal = int(binario,2) compat[decimal,i] = 1 return(compat) criaCompat(2,2) NOT = np.array([[0,1], [1,0]]) AND3 = np.array([[1,1,1,1,1,1,1,0], [0,0,0,0,0,0,0,1]]) OR4 = np.array([[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]]) I2 = np.array([[1,0], [0,1]]) t1z = k(NOT,k(NOT,I2)) t2z = k(NOT,k(I2,NOT)) t3z = k(I2,k(NOT,NOT)) t4z = k(I2,k(I2,I2)) ORz = k(AND3,k(AND3,k(AND3,AND3))) ORz = OR4.dot(ORz).dot(k(t1z,k(t2z,k(t3z,t4z)))) t1c = k(NOT,k(I2,I2)) t2c = k(I2,k(NOT,I2)) t3c = k(I2,k(I2,NOT)) t4c = k(I2,k(I2,I2)) ORc = k(AND3,k(AND3,k(AND3,AND3))) ORc = OR4.dot(ORc).dot(k(t1c,k(t2c,k(t3c,t4c)))) compat = criaCompat(3,8) k(ORz,ORc).dot(compat) import numpy as np TOFFOLI = np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1], [0,0,0,0,0,0,1,0]]) TOFFOLI.dot(TOFFOLI) Z1 = np.array([[0,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,1]]) Z1 Z1I4 = np.array([[0,0,0,0], [1,0,0,0], [0,0,0,0], [0,1,0,0], [0,0,0,0], [0,0,1,0], [0,0,0,0], [0,0,0,1]]) TOFFOLI.dot(ZpY).dot(TOFFOLI).dot(Z1I4) ZpY = np.zeros([8,8]) ZpY[0,0] = 1; ZpY[1,2] = 1; ZpY[2,1] = 1; ZpY[3,3] = 1 ZpY[4,4] = 1; ZpY[5,6] = 1; ZpY[6,5] = 1; ZpY[7,7] = 1 ZpY Zfim = np.array([[1,0,1,0,1,0,1,0], [0,1,0,1,0,1,0,1]]) Zfim.dot(TOFFOLI).dot(ZpY).dot(TOFFOLI).dot(Z1I4) import numpy as np fred = np.identity(8) fred[5,5] = 0; fred[5,6] = 1 fred[6,5] = 1; fred[6,6] = 0 fred fred.dot(fred) import numpy as np Fy0 = np.zeros([8,4]) Fy0[0,0] = 1; Fy0[1,1] = 1; Fy0[4,2] = 1; Fy0[5,3] = 1 Fy0 xYz = np.array([[1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1]]) xYz.dot(fred).dot(Fy0) import numpy as np q0 = np.array([[1,0]]).T; q0 q1 = np.array([[0,1]]).T; q1 q01 = np.kron(q0,q1); q01 H = np.array([[1,1],[1,-1]])/np.sqrt(2); H H2 = np.kron(H,H); H2 H2.dot(q01) I4 = np.eye(4); I4 I4.dot(H2).dot(q01) I2 = np.eye(2); I2 HI2 = np.kron(H,I2); HI2 HI2.dot(I4).dot(H2).dot(q01) X = np.array([[0,1],[1,0]]); X I2 = np.eye(2); I2 I2X = np.kron(I2,X); I2X HI2.dot(I2X).dot(H2).dot(q01) CNOT = np.array([[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]]) CNOT HI2.dot(CNOT).dot(H2).dot(q01) X = np.array([[0,1],[1,0]]); X I2 = np.eye(2); I2 XI2 = np.kron(X,I2); XI2 CNOT = np.array([[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]]) CNOT CNOT.dot(XI2) HI2.dot(CNOT).dot(XI2).dot(H2).dot(q01) import qiskit as qk import numpy as np qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.h(0) qc.h(1) qc.barrier() qc.barrier() qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc, simulator).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk import numpy as np qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.h(0) qc.h(1) qc.barrier() qc.x(1) qc.barrier() qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc, simulator).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk import numpy as np qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.h(0) qc.h(1) qc.barrier() qc.cx(0,1) qc.barrier() qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc, simulator).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk import numpy as np qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.h(0) qc.h(1) qc.barrier() qc.x(0) qc.cx(0,1) qc.barrier() qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc, simulator).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qc = qk.QuantumCircuit(3,3) qc.barrier() qc.cnot(1,2) qc.barrier() qc.draw('mpl') import qiskit as qk qc = qk.QuantumCircuit(3,3) qc.initialize([0,0,0,0,1,0,0,0],[0,1,2]) qc.h([0,1,2]) qc.barrier() qc.cnot(1,2) qc.barrier() qc.h([0,1]) qc.measure([0,1],[0,1]) qc.draw('mpl') def histograma(qc): import qiskit as qk from qiskit.visualization import plot_histogram simulador = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulador,shots=10000).result().get_counts() grafico = plot_histogram(results) return(grafico) histograma(qc) import numpy as np x1 = np.array([[1,0]]).T x0 = np.array([[1,0]]).T y = np.array([[0,1]]).T psi0 = np.kron(y,np.kron(x1,x0)); psi0.T import numpy as np H = np.array([[1, 1], [1,-1]])/np.sqrt(2) H3 = np.kron(H,np.kron(H,H)); np.round(H3,3) psi0 = np.array([[0,0,0,0,1,0,0,0]]).T psi1 = H3.dot(psi0); psi1.T CNOTsm = np.array([[1,0,0,0], [0,0,0,1], [0,0,1,0], [0,1,0,0]]) I2 = np.array([[1,0], [0,1]]) CNOTsm_I2 = np.kron(CNOTsm,I2) psi0 = np.array([[0,0,0,0,1,0,0,0]]).T CNOTsm_I2.dot(H3).dot(psi0).T psi = np.array([[1,1,-1,-1]]).T/2 H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H2.dot(psi) import qiskit as qk qc = qk.QuantumCircuit(3,3) qc.initialize([0,0,0,0,1,0,0,0],[0,1,2]) qc.h([0,1,2]) qc.barrier() qc.cnot(0,2) qc.barrier() qc.h([0,1]) qc.measure([0,1],[0,1]) display(qc.draw('mpl')) histograma(qc) import numpy as np v0 = np.array([[0,0,0,0,1,0,0,0]]).T; v0.T H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H); H3 = np.kron(H2,H) H3.dot(v0).T CNOTs_I_m = np.array([[1,0,0,0,0,0,0,0], [0,0,0,0,0,1,0,0], [0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1], [0,0,0,0,1,0,0,0], [0,1,0,0,0,0,0,0], [0,0,0,0,0,0,1,0], [0,0,0,1,0,0,0,0]]) v0 = np.array([[0,0,0,0,1,0,0,0]]).T CNOTs_I_m.dot(H3).dot(v0).T psi = np.array([[+1,-1,+1,-1]]).T/2 H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H2.dot(psi) import qiskit as qk qc = qk.QuantumCircuit(3,3) qc.initialize([0,0,0,0,1,0,0,0],[0,1,2]) qc.h([0,1,2]) qc.barrier() qc.cnot(0,1) qc.cnot(1,2) qc.cnot(0,1) qc.barrier() qc.h([0,1]) qc.measure([0,1],[0,1]) display(qc.draw('mpl')) histograma(qc) v0 = np.array([[0,0,0,0,1,0,0,0]]).T H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H); H3 = np.kron(H2,H) H3.dot(v0).T CNOT_CNOT = np.array([[1,0,0,0,0,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1]]) v0 = np.array([[0,0,0,0,1,0,0,0]]).T H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H); H3 = np.kron(H2,H) CNOT_CNOT.dot(H3).dot(v0).T psi = np.array([[+1,-1,-1,+1]]).T/2 H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H2.dot(psi) import numpy as np CNOTsm = np.array([[1,0,0,0], [0,0,0,1], [0,0,1,0], [0,1,0,0]]) I = np.array([[1,0], [0,1]]) ISM = np.kron(I,CNOTsm) SMI = np.kron(CNOTsm,I) H = np.array([[1, 1], [1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H3 = np.kron(H2,H) IH2 = np.kron(I,H2) v0 = np.array([[0,0,0,0,1,0,0,0]]).T IH2.dot(ISM).dot(SMI).dot(ISM).dot(H3).dot(v0).round(3) CNOT_CNOT = np.array([[1,0,0,0,0,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1]]) ISM.dot(SMI).dot(ISM) import qiskit as qk from qiskit.quantum_info import Statevector from qiskit.visualization import plot_histogram qr = qk.QuantumRegister(3,'q') cr = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([0,1],2) qc.h(0) qc.h(1) qc.h(2) qc.barrier() qc.barrier() qc.h(0) qc.h(1) qc.measure(0,0) qc.measure(1,1) display(qc.draw('mpl')) histograma(qc) psi = np.array([[1,1,1,1]]).T/2 H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H2.dot(psi) import qiskit as qk from qiskit.quantum_info import Statevector from qiskit.visualization import plot_histogram qr = qk.QuantumRegister(3,'q') cr = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([0,1],2) qc.h(0) qc.h(1) qc.h(2) qc.barrier() qc.x(2) qc.barrier() qc.h(0) qc.h(1) qc.measure(0,0) qc.measure(1,1) display(qc.draw('mpl')) histograma(qc) psi = np.array([[1,1,1,1]]).T/2 H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H2.dot(psi) import qiskit as qk from qiskit.quantum_info import Statevector from qiskit.visualization import plot_histogram qr = qk.QuantumRegister(3,'q') cr = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([0,1],2) qc.h(0) qc.h(1) qc.h(2) qc.barrier() qc.ccx(0,1,2) qc.barrier() qc.h(0) qc.h(1) qc.measure(0,0) qc.measure(1,1) display(qc.draw('mpl')) histograma(qc) import qiskit as qk qrx = qk.QuantumRegister(2,'x') qry = qk.QuantumRegister(2,'y') qc = qk.QuantumCircuit(qrx,qry) qc.barrier() qc.cx(0,2) qc.cx(0,3) qc.cx(1,2) qc.cx(1,3) qc.barrier() qc.draw('mpl') def histograma(qc): simulador = qk.Aer.get_backend('statevector_simulator') resultado = qk.execute(qc,simulador,shots=10000).result() contagens = resultado.get_counts() grafico = qk.visualization.plot_histogram(contagens) return(grafico) def simon(initial_y, initial_x): import qiskit as qk qrx = qk.QuantumRegister(2,'x') crx = qk.ClassicalRegister(4,'c') qry = qk.QuantumRegister(2,'y') qc = qk.QuantumCircuit(qrx,qry,crx) qc.initialize(initial_x,qrx) qc.initialize(initial_y,qry) qc.barrier() qc.cx(0,2) qc.cx(0,3) qc.cx(1,2) qc.cx(1,3) qc.barrier() qc.measure([0,1,2,3],[0,1,2,3]) display(qc.draw('mpl')) grafico = histograma(qc) return(grafico) simon([1,0,0,0],[1,0,0,0]) simon([1,0,0,0],[0,0,0,1]) simon([1,0,0,0],[0,1,0,0]) simon([1,0,0,0],[0,0,1,0]) import qiskit as qk qrx = qk.QuantumRegister(2,'x') crx = qk.ClassicalRegister(2,'c') qry = qk.QuantumRegister(2,'y') qc = qk.QuantumCircuit(qrx,qry,crx) qc.initialize([1,0,0,0],qrx) qc.initialize([1,0,0,0],qry) qc.h([0,1]) qc.barrier() qc.cx(0,2) qc.cx(0,3) qc.cx(1,2) qc.cx(1,3) qc.barrier() qc.h([0,1]) qc.measure([0,1],[0,1]) display(qc.draw('mpl')) histograma(qc) import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T x1x0 = np.kron(x1,x0) y0 = np.array([[1,0]]).T y1 = np.array([[1,0]]).T y1y0 = np.kron(y1,y0) psi0 = np.kron(y1y0,x1x0) psi0.T H = np.array([[1,1],[1,-1]],dtype='int') H2 = np.kron(H,H) I2 = np.eye(4) I2H2 = np.kron(I2,H2) psi1 = I2H2.dot(psi0)/(np.sqrt(2)*np.sqrt(2)) I2H2.dot(psi0).T Tf1_2 = np.eye(16) Tf1_2 = Tf1_2[:,[0,5,2,7,4,1,6,3,8,9,10,11,12,13,14,15]] psi2 = Tf1_2.dot(psi1); psi2.T*2 Tf2_3 = np.eye(16) Tf2_3 = Tf2_3[:,[0,1,2,3,4,13,6,15,8,9,10,11,12,5,14,7]] psi3 = Tf2_3.dot(psi2); psi3.T*2 Tf3_4 = np.eye(16) Tf3_4 = Tf3_4[:,[0,1,6,3,4,5,2,7,8,9,10,15,12,13,14,11]] psi4 = Tf3_4.dot(psi3); psi4.T*2 Tf4_5 = np.eye(16) Tf4_5 = Tf4_5[:,[0,1,2,11,4,5,14,7,8,9,10,3,12,13,6,15]] psi5 = Tf4_5.dot(psi4); psi5.T*2 I2 = np.eye(4) H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) I2H2 = np.kron(I2,H2) psi6 = I2H2.dot(psi5) print(psi6.T*2) import numpy as np I2 = np.eye(4, dtype='int'); H2 = np.array([[1, 1, 1, 1], [1,-1, 1,-1], [1, 1,-1,-1], [1,-1,-1, 1]])/2; I2H2 = np.kron(I2,H2); print(I2H2*2) import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T x2 = np.array([[1,0]]).T x2x1x0 = np.kron(x2,np.kron(x1,x0)) x2x1x0.T y0 = np.array([[1,0]]).T y1 = np.array([[1,0]]).T y2 = np.array([[1,0]]).T y2y1y0 = np.kron(y2,np.kron(y1,y0)) y2y1y0.T psi0 = np.kron(y2y1y0,x2x1x0) psi0.T I3 = np.eye(2**3) H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H3 = np.kron(H,H2) I3H3 = np.kron(I3,H3) psi1 = I3H3.dot(psi0) psi1.T.round(2) n = 2*3 # 2 nรบmeros de 3 digitos cada Uf = np.eye(2**n) # 2^6 = 64 posiรงรตes Uf = Uf[:,[ 0, 9,18,27,12, 5,30,23, 8, 1,10,11, 4,13,14,15, 16,17, 2,19,20,21,22, 7, 24,25,26, 3,28,29, 6,31, 32,33,34,35,36,37,38,39, 40,41,42,43,44,45,46,47, 48,49,50,51,52,53,54,55, 56,57,58,59,60,61,62,63]] psi5 = Uf.dot(psi1) psi5.T.round(2) psi6 = I3H3.dot(psi5) psi6.T np.where(psi6 > 0)[0] [format(i,'#08b')[2:] for i in np.where(psi6 > 0)[0]] import numpy as np CCNOT = np.eye(8) CCNOT = CCNOT[:,[0,1,2,7,4,5,6,3]] CCNOT.dot(CCNOT) import qiskit as qk def qNAND(y0,x0): x = qk.QuantumRegister(1,"x") y = qk.QuantumRegister(1,"y") z = qk.QuantumRegister(1,"z") u = qk.QuantumRegister(1,"u") c = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(x,y,z,u,c) # Put qubits u and z in state |0> qc.initialize([1,0],z) qc.initialize([1,0],u) qc.initialize(y0,y) qc.initialize(x0,x) # Perform computation qc.barrier() qc.ccx(x,y,z) qc.x(z) # Copy CLASSICALY state of z to u qc.cx(z,u) qc.barrier() # Reverse computation qc.x(z) qc.ccx(x,y,z) qc.barrier() # Measure results qc.measure(x,c[0]) qc.measure(y,c[1]) qc.measure(u,c[2]) display(qc.draw('mpl')) simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc, simulator, shots=10000).result().get_counts() grafico = qk.visualization.plot_histogram(results) return(grafico) print("0 NAND 0 = 1") qNAND([1,0],[1,0]) print("0 NAND 1 = 1") qNAND([1,0],[0,1]) print("1 NAND 0 = 1") qNAND([0,1],[1,0]) print("1 NAND 1 = 0") qNAND([0,1],[0,1]) import qiskit as qk def qOR(y0,x0): x = qk.QuantumRegister(1,"x") y = qk.QuantumRegister(1,"y") z = qk.QuantumRegister(1,"z") u = qk.QuantumRegister(1,"u") c = qk.ClassicalRegister(3,'c') # Initialize qubits qc = qk.QuantumCircuit(x,y,z,u,c) qc.initialize(x0,x) qc.initialize(y0,y) qc.initialize([1,0],z) qc.initialize([1,0],u) # Compute function qc.barrier() qc.x(x) qc.x(y) qc.ccx(x,y,z) qc.x(z) qc.cx(z,u) qc.barrier() # Reverse computation qc.x(z) qc.ccx(x,y,z) qc.x(y) qc.x(x) qc.barrier() # Measure results qc.measure(x,c[0]) qc.measure(y,c[1]) qc.measure(u,c[2]) display(qc.draw('mpl')) # Simulate circuit simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() grafico = qk.visualization.plot_histogram(results) return(grafico) qOR([1,0],[1,0]) qOR([1,0],[0,1]) qOR([0,1],[1,0]) qOR([0,1],[0,1]) import qiskit as qk def qNXOR(y0,x0,calc=True,show=False): ################################################## # Create registers # ################################################## # Base registers x = qk.QuantumRegister(1,"x") y = qk.QuantumRegister(1,"y") # Auxiliary register (for x and y) z = qk.QuantumRegister(1,"z") # Auxiliary register (to store x AND y) a1 = qk.QuantumRegister(1,"a1") # Auxiliary register (to store NOT(x) AND NOT(y)) a2 = qk.QuantumRegister(1,"a2") # Auxiliary register (for a1 and a2) b1 = qk.QuantumRegister(1,"b1") # Auxiliary register (to store a1 OR a2) b2 = qk.QuantumRegister(1,"b2") # Classical Registers to store x,y and final measurement c = qk.ClassicalRegister(3,"c") ################################################## # Create Circuit # ################################################## qc = qk.QuantumCircuit(x,y,z,a1,a2,b1,b2,c) ################################################## # Initialize registers # ################################################## qc.initialize(x0,x) qc.initialize(y0,y) qc.initialize([1,0],z) qc.initialize([1,0],a1) qc.initialize([1,0],a2) qc.initialize([1,0],b1) qc.initialize([1,0],b2) ################################################### # Calculate x AND y. Copy result to a1. Reverse z # ################################################### qc.barrier() qc.ccx(x,y,z) qc.cx(z,a1) qc.ccx(x,y,z) qc.barrier() ######################################################### # Calc. NOT(x) AND NOT(y). Copy result to a2. Reverse z # ######################################################### qc.barrier() qc.x(x) qc.x(y) qc.ccx(x,y,z) qc.cx(z,a2) qc.ccx(x,y,z) qc.x(y) qc.x(x) qc.barrier() ################################################# # Calc. a1 OR a2. Copy result to b2. Reverse b1 # ################################################# qc.barrier() qc.x(a1) qc.x(a2) qc.ccx(a1,a2,b1) qc.x(b1) qc.cx(b1,b2) qc.x(b1) qc.ccx(a1,a2,b1) qc.barrier() ################################################# # Measure b2 # ################################################# qc.measure(x,c[0]) qc.measure(y,c[1]) qc.measure(b2,c[2]) ################################################# # Draw circuit # ################################################# if show: display(qc.draw("mpl")) ################################################# # Run circuit. Collect results # ################################################# if calc: simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc,simulator,shots=10000).result().get_counts() grafico = qk.visualization.plot_histogram(results) return(grafico) else: return() qNXOR([1,0],[1,0],False,True) qNXOR([1,0],[1,0]) qNXOR([1,0],[0,1]) qNXOR([0,1],[1,0]) qNXOR([0,1],[0,1]) x0 = np.array([1,1])/np.sqrt(2) y0 = np.array([1,1])/np.sqrt(2) qNXOR(y0,x0) import qiskit as qk from qiskit.quantum_info.operators import Operator qr = qk.QuantumRegister(6,"q") cr = qk.ClassicalRegister(6,"c") qc = qk.QuantumCircuit(qr,cr) for i in range(6): qc.initialize([1,0],i) for i in range(3): qc.h(i) oracle = np.eye(2**6) oracle[:,[ 0, 0]] = oracle[:,[ 0, 0]] oracle[:,[ 1, 9]] = oracle[:,[ 9, 1]] oracle[:,[ 2, 18]] = oracle[:,[ 18, 2]] oracle[:,[ 3, 27]] = oracle[:,[ 27, 3]] oracle[:,[ 4, 12]] = oracle[:,[ 12, 4]] oracle[:,[ 5, 5]] = oracle[:,[ 5, 5]] oracle[:,[ 6, 30]] = oracle[:,[ 30, 6]] oracle[:,[ 7, 23]] = oracle[:,[ 23, 7]] oracle = Operator(oracle) qc.append(oracle,qr) for i in range(3): qc.h(i) qc.barrier() for i in range(3): qc.measure(i,i) display(qc.draw("mpl")) simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np oracle = np.eye(8) oracle[:,[2,6]] = oracle[:,[6,2]] oracle import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T psi0 = np.kron(x1,x0) H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) psi1 = H2.dot(psi0) psi1.T # Initialize a qubit y in state |1> y = np.array([[0,1]]).T # Pass it through a Hadamard gate and obtain state psi2a H = np.array([[1,1],[1,-1]])/np.sqrt(2) psi2a = H.dot(y) psi2a.T psi2 = np.kron(psi2a,psi1) psi2.T oracle = np.eye(8) oracle[:,[2,6]] = oracle[:,[6,2]] oracle psi3 = oracle.dot(psi2) psi3.T v0 = np.array([[10,20,-30,40,50]]).T mu = np.mean(v0) v0.T, mu D = v0 - mu D.T v1 = 2*np.mean(v0)-v0 v1.T import numpy as np A = np.ones(5**2).reshape(5,5) A = A/5 I = np.eye(5) R = 2*A-I R R.dot(R) n = 4 I = np.eye(n) A = np.ones(n**2).reshape(n,n)/n R = 2*A-I R I2 = np.eye(2) I2R = np.kron(I2,R) I2R psi4 = I2R.dot(psi3) psi4.T import qiskit as qk import numpy as np from qiskit.quantum_info.operators import Operator q = qk.QuantumRegister(3,'q') c = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(q,c) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.h(1) qc.initialize([0,1],2) qc.h(2) qc.barrier() oracle = np.eye(8) oracle[:,[2,6]] = oracle[:,[6,2]] oracle = Operator(oracle) qc.append(oracle,q) # n = 2 (two digits number to look for) A = np.ones(4*4).reshape(4,4)/4 I4 = np.eye(4) R = 2*A - I4 I2 = np.eye(2) boost = np.kron(I2,R) boost = Operator(boost) qc.append(boost,q) qc.barrier() qc.measure(q[:2],c[:2]) display(qc.draw('mpl')) simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=1000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T x2 = np.array([[1,0]]).T x2x1x0 = np.kron(x2,np.kron(x1,x0)) x2x1x0.T H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H3 = np.kron(H,H2) x = H3.dot(x2x1x0) x.T y0 = np.array([[0,1]]).T y0.T H = np.array([[1,1],[1,-1]])/np.sqrt(2) y = H.dot(y0) y.T psi0 = np.kron(y,x) psi0.T oracle = np.eye(16) oracle[:,[5,13]] = oracle[:,[13,5]] psi1 = oracle.dot(psi0) psi1.T # n = 8 A = np.ones(8*8).reshape(8,8)/8 I8 = np.eye(8) R = 2*A-I8 R I2 = np.eye(2) I2R = np.kron(I2,R) psi2 = I2R.dot(psi1) psi2.T 0.625**2 + 0.625**2 psi3 = I2R.dot(oracle).dot(psi2) psi3.T 0.687**2 + 0.687**2 I2R.dot(oracle).dot(psi3).T T = I2R.dot(oracle) psi = psi1 prob = [] for i in range(25): prob.append(psi[5,0]**2 + psi[13,0]**2) psi = T.dot(psi) from matplotlib import pyplot as plt plt.plot(list(range(25)), prob); import qiskit as qk import numpy as np from qiskit.quantum_info.operators import Operator q = qk.QuantumRegister(4,'q') c = qk.ClassicalRegister(4,'c') qc = qk.QuantumCircuit(q,c) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([1,0],2) qc.h(0) qc.h(1) qc.h(2) qc.initialize([0,1],3) qc.h(3) qc.barrier() # Create oracle matrix oracle = np.eye(16) oracle[:,[5,13]] = oracle[:,[13,5]] # Create rotation about the mean matrix # n = 3 (three digits number to look for) A = np.ones(8*8).reshape(8,8)/8 I8 = np.eye(8) R = 2*A - I8 # Identity matrix to leave fourth qubit undisturbed I2 = np.eye(2) # Create second transformation matrix boost = np.kron(I2,R) # Combine oracle with second transformation matrix in # an unique operator T = boost.dot(oracle) T = Operator(T) # Apply operator twice (2 phase inversions and # rotations about the mean) qc.append(T,q) qc.append(T,q) qc.barrier() qc.measure(q[:3],c[:3]) display(qc.draw('mpl')) simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=1000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk import numpy as np from qiskit.quantum_info.operators import Operator q = qk.QuantumRegister(5,'q') c = qk.ClassicalRegister(5,'c') qc = qk.QuantumCircuit(q,c) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([1,0],2) qc.initialize([1,0],3) qc.h(0) qc.h(1) qc.h(2) qc.h(3) qc.initialize([0,1],4) qc.h(4) qc.barrier() # Create oracle matrix oracle = np.eye(32) oracle[:,[13,29]] = oracle[:,[29,13]] # Create rotation about the mean matrix # n = 4 (four digits number to look for) A = np.ones(16*16).reshape(16,16)/16 I16 = np.eye(16) R = 2*A - I16 # Identity matrix to leave fifth qubit undisturbed I2 = np.eye(2) # Create second transformation matrix boost = np.kron(I2,R) # Combine oracle with second transformation matrix in # an unique operator T = boost.dot(oracle) # n = 4. Therefore it will be necessary 4 T operations # to get maximum probability. Tn = T.dot(T).dot(T) Tn = Operator(Tn) # Apply operator Tn once (n phase inversions and # rotations about the mean) qc.append(Tn,q) qc.barrier() qc.measure(q[:4],c[:4]) display(qc.draw('mpl')) simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=1000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np import pandas as pd N = 35; a = 6 GCD = pd.DataFrame({'N':[N], 'a':[a], 'N-a':[N-a]}) while GCD.iloc[-1,2] != 0: temp = GCD.iloc[-1].values temp = np.sort(temp); temp[-1] = temp[-2] - temp[-3] temp = pd.DataFrame(data = temp.reshape(-1,3), columns = ['N','a','N-a']) GCD = GCD.append(temp, ignore_index=True) GCD import numpy as np import pandas as pd N = 15; a = 9 GCD = pd.DataFrame({'N':[N], 'a':[a], 'N-a':[N-a]}) while GCD.iloc[-1,2] != 0: temp = GCD.iloc[-1].values temp = np.sort(temp); temp[-1] = temp[-2] - temp[-3] temp = pd.DataFrame(data = temp.reshape(-1,3), columns = ['N','a','N-a']) GCD = GCD.append(temp, ignore_index=True) GCD import numpy as np np.gcd(6,35), np.gcd(9,15) import numpy as np np.gcd(215,35), np.gcd(217,35) 20 % 7 import numpy as np f = lambda x,a,N: a**x % N [f(x,2,15) for x in range(10)] import numpy as np (13*35)%11, ((2%11)*(24%11))%11 import numpy as np def f(x,a,N): a0 = 1 for i in range(x): a0 = ((a%N)*(a0))%N return(a0) [f(x,2,371) for x in range(8)] [f(x,2,371) for x in range(154,159)] [f(x,24,371) for x in range(77,81)] import numpy as np def fr(a,N): ax = ((a%N)*(1))%N x = 1 while ax != 1: ax = ((a%N)*(ax))%N x = x+1 return(x) fr(2,371), fr(6,371), fr(24,371) import numpy as np def fr(a,N): a0 = 1 a0 = ((a%N)*a0)%N x = 2 find = False while find==False: a0 = ((a%N)*(a0))%N if a0 == 1: find = True x = x+1 return(x-1) N = 35 a = 2 fr(a,N) 2**(12/2)-1, 2**(12/2)+1 np.gcd(63,35), np.gcd(65,35) import numpy as np # Function to calculate the period of f(x) = a^x MOD N def fr(a,N): a1 = ((a%N)*(1))%N x = 1 while a1 != 1: a1 = ((a%N)*a1)%N x = x+1 return(x) # Function to factor N based on a def factor(N, a=2): r = fr(a,N) g1 = a**(int(r/2)) - 1 g2 = a**(int(r/2)) + 1 f1 = np.gcd(g1,N) f2 = np.gcd(g2,N) return(f1,f2, f1*f2) factor(247) factor(1045) import numpy as np N = 15 # number to be factored n = 4 # number of bits necessary to represent N m = 8 # number of bits necessary to represent N^2 x = np.zeros(2**m).reshape(-1,1) x[0,0] = 1 x.shape # since x is a 2^8 = 256 positions vector it will not be showed here y = np.zeros(2**n).reshape(-1,1) y[0,0] = 1; y.T # y is a 2^4 = 16 positions vector shown below psi0 = np.kron(y,x) psi0.shape # psi0 is a 256 x 16 = 4.096 positions vector In = np.eye(2**n); In.shape H = np.array([[1,1],[1,-1]])/np.sqrt(2) Hm = H.copy() for i in range(1,m): Hm = np.kron(Hm,H) Hm.shape psi1 = np.kron(In,Hm).dot(psi0); psi1.shape
https://github.com/gustavomirapalheta/Quantum-Computing-with-Qiskit
gustavomirapalheta
!pip install qutip -q !pip install qiskit -q !pip install qiskit[visualization] -q !pip install git+https://github.com/qiskit-community/qiskit-textbook.git#subdirectory=qiskit-textbook-src -q import numpy as np np.set_printoptions(precision=3, suppress=True) import qutip as qt from matplotlib import pyplot as plt %matplotlib inline import pandas as pd import sklearn as sk import qiskit as qk # Remember that qiskit has to be already installed in the Python environment. # Otherwise the import command will fail import qiskit as qk # A circuit composed of just one qubit qc = qk.QuantumCircuit(1) qc.draw('mpl') import qiskit as qiskit # A qubit initialized in the state |0> qc = qk.QuantumCircuit(1) qc.initialize([1,0]) qc.draw('mpl') import qiskit as qk # A qubit initialized in |0> and a measurement qc = qk.QuantumCircuit(1) qc.initialize([1,0]) qc.measure_all() qc.draw('mpl') import qiskit as qk # A list of possible measurements. The results of measurements are obtained # by executing an object called backend a = [print(i) for i in qk.Aer.backends()] import qiskit as qk qc = qk.QuantumCircuit(1) qc.initialize([1,0],0) qc.measure_all() # Let's choose the statevector simulator from the Aer backend backend = qk.Aer.get_backend('statevector_simulator') # And execute the circuit qc in the simulator backend # getting as final result the counts from 1.000 measures # of the qubit state result = qk.execute(qc, backend, shots=1000).result().get_counts() result import qiskit as qk qc = qk.QuantumCircuit(1) qc.initialize([1,0],0) qc.measure_all() backend = qk.Aer.get_backend('statevector_simulator') result = qk.execute(qc, backend, shots=1000).result().get_counts() qk.visualization.plot_histogram(result) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) qc.measure(0,0) qc.draw('mpl') backend = qk.Aer.get_backend('statevector_simulator') result = qk.execute(qc, backend, shots=1000).result().get_counts() qk.visualization.plot_histogram(result) import numpy as np v0 = np.array([[1],[0]]);v0 v1 = np.array([[0],[1]]); v1 X = np.array([[0,1],[1,0]]); X X.dot(v0) X.dot(v1) import qiskit as qk qr = qk.QuantumRegister(1,"q0") cr = qk.ClassicalRegister(1,"c0") qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) qc.x(0) qc.measure(qr[0], cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, simulator, shots=1000).result().get_counts() results qk.visualization.plot_histogram(results) import numpy as np # Notice that we are creating the v0 matrix using the transpose operation v0 = np.array([[1,0]]).T; v0 # Here it is created again de X matrix X = np.array([[0,1],[1,0]]); X # Multiplying v0 by the X matrix twice you get again v0 X.dot(X).dot(v0) # Multiplying the X matrix by itself you get the Identity matrix X.dot(X) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) qc.x(0) qc.x(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') # The result of 1000 measures of the qubit above gives the |0> state as result # in all measures simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=1000).result().get_counts() results qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([2**-0.5,2**-0.5],0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np v0 = np.array([[1,0]]).T; v0 H = np.array([[1,1],[1,-1]])/np.sqrt(2); H H.dot(v0) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.h(qr[0]) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, simulator, shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([2**-0.5,-(2**-0.5)],0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([2**-0.5,-(2**-0.5)],0) qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([0,1],0) qc.h(0) qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np # First let's start with the qubit in the state |psi> = (|0> - |1>)/sqrt(2) psi = np.array([[1,-1]]).T/(2**0.5); psi H = np.array([[1,1],[1,-1]])/2**0.5; H # Now let's pass the qubit Psi through an Hadamard gate. # The result is a qubit in the state |1> H.dot(psi) # Let's start with a qubit in the state |1>, pass it through a # a hadamard gate twice and check the result v0 = np.array([[0,1]]).T; v0 H.dot(H).dot(v0) # This means that if we multiply the H gate by itself the result # will be an Identity matrix. Let's check it. H.dot(H) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np psi1 = np.array([[1,0]]).T; psi1 psi2 = np.array([[1,0]]).T; psi2 # In numpy the tensor product is calculated with the function kron np.kron(psi1,psi2) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.h(1) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np psi1 = np.array([[1,0]]).T;psi1 psi2 = np.array([[1,0]]).T;psi2 H = np.array([[1,1],[1,-1]])/2**0.5;H # When we want to combine two vector states or gate matrices we tensor product them. psi3 = np.kron(psi1,psi2);psi3 H2 = np.kron(H,H);H2 # When we want to pass a vetor through a gate we calculate the dot product # of the total gate matrix with the total vector. # As we have predicted, the resulting vector state has a=b=c=d=1/2 psi4 = H2.dot(psi3); psi4 import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([0,1],0) qc.initialize([0,1],1) qc.h(0) qc.h(1) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np psi1 = np.array([[0,1]]).T;psi1 psi2 = np.array([[0,1]]).T;psi2 H = np.array([[1,1],[1,-1]])/2**0.5;H # When we want to combine two vector states or gate matrices we tensor product them. psi3 = np.kron(psi1,psi2);psi3 H2 = np.kron(H,H);H2 # When we want to pass a vetor through a gate we calculate the dot product # of the total gate matrix with the total vector. # As we have predicted, the resulting vector state has a=b=c=d=1/2 psi4 = H2.dot(psi3); psi4 import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.cnot(0,1) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, simulator, shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C v00 = np.array([[1,0,0,0]]).T;v00 # C.v00 = v00 C.dot(v00) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.cnot(0,1) qc.measure(qr,cr) qc.draw('mpl') # Please notice that Qiskit's qubits presentation order is reversed. # Therefore 10 in the histogram's x axis should be read as 01 (from # inside out or right to left). simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, simulator, shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C v01 = np.array([[0,1,0,0]]).T;v01 # C.v01 = v01 C.dot(v01) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([0,1],0) qc.initialize([1,0],1) qc.cnot(0,1) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, simulator, shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C v10 = np.array([[0,0,1,0]]).T; v10 # C.v10 = v11 C.dot(v10) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([0,1],0) qc.initialize([0,1],1) qc.cnot(0,1) qc.measure(qr,cr) qc.draw('mpl') # Again remember to read qiskit qubits state presentation order # from right to left. Therefore 01 in the x axis is in fact 10 simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, simulator, shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C v11 = np.array([[0,0,0,1]]).T; v11 # C.v11 = v10 C.dot(v11) import qiskit as qk qr = qk.QuantumRegister(2, 'q') cr = qk.ClassicalRegister(2, 'c') qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(qr[0]) qc.cx(qr[0],qr[1]) qc.measure(qr, cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np va = np.array([[1,0]]).T; va vb = np.array([[1,0]]).T; vb H = np.array([[1,1],[1,-1]])/2**0.5;H vaH = H.dot(va); vaH vaHvb = np.kron(vaH,vb); vaHvb C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C vout = C.dot(vaHvb); vout import qiskit as qk qr = qk.QuantumRegister(2, 'q') cr = qk.ClassicalRegister(2, 'c') qc = qk.QuantumCircuit(qr, cr) qc.initialize([0,1],0) qc.initialize([1,0],1) qc.h(qr[0]) qc.cx(qr[0],qr[1]) qc.measure(qr, cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np va = np.array([[0,1]]).T; va vb = np.array([[1,0]]).T; vb H = np.array([[1,1],[1,-1]])/2**0.5;H vaH = H.dot(va); vaH vaHvb = np.kron(vaH,vb); vaHvb C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C vout = C.dot(vaHvb); vout # Get the IBM API key in: https://quantum-computing.ibm.com # chave = 'My key is already saved in this environment' # qk.IBMQ.save_account(chave) # Load the account in the active session qk.IBMQ.load_account() # The default provider is รฉ hub='ibm-q', group='open, project='main' # The code below is executed as an example provider_1 = qk.IBMQ.get_provider(hub='ibm-q', group='open', project='main') # In the public provider we will use a cloud simulator. backend_1 = provider_1.get_backend('ibmq_qasm_simulator') # The provider listed below has unlimited jobs provider_2 = qk.IBMQ.get_provider(hub='ibm-q-education', group='fgv-1', project='ml-business-app') # For this provider we will use the ibmq_jakarta machine backend_2 = provider_2.get_backend('ibmq_jakarta') # With n Qubits we can generate a random number from 0 to 2^n - 1 n = 3 qr = qk.QuantumRegister(n,'q') cr = qk.ClassicalRegister(n,'c') qc = qk.QuantumCircuit(qr, cr) # Applying a Hadamard to each of the three qubits for i in range(n): qc.h(q[i]) # Measuring the three qubits qc.measure(q,c) # Visualizing the circuit qc.draw('mpl') # qk.execute envia para o backend. Conferindo no iqmq explorer aparece o job new_job = qk.execute(circ, backend_2, shots=1) # this result is stored on the local machine. However, it will only be available # after the job has been executed. It returns a python dictionary. new_job.result().get_counts() int(list(new_job.result().get_counts().keys())[0],2) from qiskit import QuantumCircuit circuit = QuantumCircuit(2, 2) circuit.h(0) circuit.cx(0,1) circuit.measure([0,1], [0,1]) display(circuit.draw('mpl')) from qiskit.providers.aer import AerSimulator print(AerSimulator().run(circuit, shots=1000).result().get_counts()) print(AerSimulator().run(circuit, shots=1000).result().get_counts()) from qiskit import QuantumCircuit circuito = QuantumCircuit(3,3) for i in range(3): circuito.h(i) circuito.measure(i,i) display(circuito.draw('mpl')) from qiskit.providers.aer import AerSimulator AerSimulator().run(circuito, shots = 1000).result().get_counts() from qiskit import QuantumCircuit qc = QuantumCircuit(4,4) qc.x([0,1]) qc.cx([0,1],[2,2]) qc.ccx(0,1,3) qc.measure([0,1,2,3],[0,1,2,3]) display(qc.draw(output='mpl')) from qiskit.providers.aer import AerSimulator AerSimulator().run(qc, shots = 10000).result().get_counts() import qiskit as qk qr = qk.QuantumRegister(1,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) print("Circuit 1 - Registers Only") display(qc.draw('mpl')) qc.x(qr) print("Circuit 1 - Quantum Register with a Gate X ") display(qc.draw('mpl')) job = qk.execute(experiments = qc, backend = qk.Aer.get_backend('statevector_simulator')) result1 = job.result().get_statevector() print("Quantum Register Vector State") from qiskit.tools.visualization import plot_bloch_multivector display(plot_bloch_multivector(result1)) job = qk.execute(experiments = qc, backend = qk.Aer.get_backend('unitary_simulator')) print("Transformation Matrix (up to this stage)") print(job.result().get_unitary()) qc.measure(qr, cr) print() print("Circuit 1 - Registers, Gate X and Quantum Register Measure") display(qc.draw('mpl')) print("Quantum Register Thousand Measures") job = qk.execute(experiments = qc, backend = qk.Aer.get_backend('statevector_simulator'), shots = 1000) print(job.result().get_counts()) print() print("Result's Histogram") from qiskit.tools.visualization import plot_histogram plot_histogram(data = job.result().get_counts(), figsize=(4,3)) import qiskit as qk from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector qr = qk.QuantumRegister(3,'q') cr = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([1,0],2) display(qc.draw('mpl')) sv = Statevector.from_label('000') state_data = lambda qc,sv: np.round(np.asarray(sv.evolve(qc).data),4) state_bloch = lambda qc,sv: plot_bloch_multivector(sv.evolve(qc).data, reverse_bits=True) print(state_data(qc,sv)) state_bloch(qc,sv) qc.x(0) qc.barrier() display(qc.draw('mpl')) print(state_data(qc,sv)) display(state_bloch(qc,sv)) qc.h(1) display(qc.draw('mpl')) print(state_data(qc,sv)) state_bloch(qc,sv) qc.cnot(1,2) display(qc.draw("mpl")) state_data(qc,sv) state_bloch(qc,sv) qc.cnot(0,1) display(qc.draw('mpl')) state_data(qc,sv) qc.h(0) qc.barrier() display(qc.draw('mpl')) state_data(qc,sv) qc.measure(0,0) qc.measure(1,1) qc.barrier() qc.cnot(1,2) qc.cz(0,2) qc.measure(2,2) display(qc.draw('mpl')) simulador = qk.Aer.get_backend('statevector_simulator') resultado = qk.execute(qc, simulador, shots=10000).result() qk.visualization.plot_histogram(resultado.get_counts()) import numpy as np V = np.array([[3+2j],[4-2j]]) modV = np.real(V.T.conjugate().dot(V)[0,0])**0.5 Vn = V/modV; Vn v0 = np.array([[1,0]]).T v1 = np.array([[0,1]]).T Vn[0,0]*v0 + Vn[1,0]*v1 import qiskit as qk qr = qk.QuantumRegister(1,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([Vn[0,0],Vn[1,0]],0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) Vn[0,0].conjugate()*Vn[0,0] Vn[1,0].conjugate()*Vn[1,0] import numpy as np CNOT = np.array([[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]]) CNOT.dot(CNOT) import numpy as np H = np.array([[1,1],[1,-1]])/2**0.5 H.dot(H) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.cnot(qr[0],qr[1]) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.cnot(qr[0],qr[1]) qc.cnot(qr[0],qr[1]) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.cnot(qr[0],qr[1]) qc.cnot(qr[0],qr[1]) qc.h(0) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np X = np.array([[0,1], [1,0]]) X X.conj().T.dot(X) Y = np.array([[0,-1j], [1j,0]]) Y Y.conj().T.dot(Y) Z = np.array([[1,0], [0,-1]]) Z Z.conj().T.dot(Z) H = (X+Z)/np.sqrt(2); H H.dot(Z).dot(H) H.dot(X).dot(H) -H.dot(Y).dot(H) import numpy as np S = np.array([[1,0], [0,1j]]) S S.conj().T.dot(S) T = np.array([[1,0], [0,np.exp(1j*np.pi/4)]]) T T.conj().T.dot(T) S = np.array([[1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]]); S S.dot(v00) S.dot(v01) S.dot(v10) S.dot(v11) C = np.array([[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]]);C C_ = np.array([[1,0,0,0], [0,0,0,1], [0,0,1,0], [0,1,0,0]]);C_ C.dot(C_).dot(C) v = v0 + v1; v n = np.array([[0,0],[0,1]]); n n.dot(v) n_ = np.array([[1,0],[0,0]]);n_ I2 = np.identity(2); I2 I2 - n n_.dot(v) n.dot(n) n_.dot(n_) n.dot(n_) n_.dot(n) n+n_ n.dot(X) X.dot(n_) import numpy as np n = np.array([[0,0],[0,1]]); n n_ = np.array([[1,0],[0,0]]);n_ # ni nj operam em bits distintos. Como cada operador n atua em um vetor de # 2 dimensรตes, ni nj รฉ um operador de 4 dimensรตes. Sendo assim, fica implรญcito # pelos subscritos que ni nj รฉ um produto tensorial. np.kron(n,n) # O mesmo vale para n'i n'j np.kron(n_,n_) # Para ni n'j np.kron(n,n_) # E para n'i nj np.kron(n_,n) # Xi Xj sรฃo dois operadores 2x2 de inversรฃo, cada um atuando em um bit # distinto. Sendo assim, fazemos o produto tensorial entre ambos # para obter XiXj np.kron(X,X) # No caso da expressรฃo XiXj(ninj' + ni'nj) temos entre parรชnteses duas # matrizes 4x4 (ninj'+ni'nj) e fora dos parรชnteses uma matriz 4x4 (XiXj) # Sendo assim fazemos neste caso o produto matricial normal para # calcular esta expressรฃo. np.kron(X,X).dot(np.kron(n,n_)+np.kron(n_,n)) # E por รบltimo somamos com o resultado inicial de ninj + ni'nj' # Como pode-se ver, esta expressรฃo gera o operador de SWAP np.kron(n,n) + np.kron(n_,n_) + np.kron(X,X).dot(np.kron(n,n_)+np.kron(n_,n)) # ร‰ importante observar que ninj forma um operador que projeta um vetor de # 4 dimensรตes (00, 01, 10, 11) em sua componente 11 np.kron(n,n) # De maneira similar ni'nj' projeta um vetor de 4 dimensรตes em sua componente 00 np.kron(n_,n_) # ni'nj projeta em 01 np.kron(n_,n) # Assim como ninj' projeta em 10 np.kron(n,n_) # E por รบltimo vemos que ni'nj' + ni'nj + ninj' + ninj = I nn = np.kron(n,n) nn_ = np.kron(n,n_) n_n = np.kron(n_,n) n_n_ = np.kron(n_,n_) nn + nn_ + n_n + n_n_ import numpy as np n = np.array([[0,0],[0,1]]); n n_ = np.array([[1,0],[0,0]]);n_ # (n x n).(n_ x n_) np.kron(n,n).dot(np.kron(n_,n_)) # Faz sentido que (ni x nj).(ni_ x nj_) seja o vetor nulo pois: # ni_ x nj_ รฉ um operador que recebe um vetor de 4 dimensรตes e # produz como resultado apenas sua componente |00>. Por sua # vez ni x nj รฉ um operador que recebe um vetor de 4 dimensรตes # e produz como resultado apenas sua componente |11>. Esta # componente foi zerada pelo primeiro operador, logo o resultado # serรก nulo. Isto vai acontecer sempre que a componente nรฃo # zerada do primeiro operador for diferente da do segundo em # outras palavras sempre que ij do primeiro for diferente de ij # do segundo. np.kron(n,n).dot(np.kron(n_,n_)) # Outra forma de entender รฉ transformar (n x n).(n_ x n_) em # (n.n_) x (n.n_). Como n รฉ ortogonal a n_, a projeรงรฃo de n # em n_ darรก zero tambรฉm. np.kron(n.dot(n_),n.dot(n_)) nn.dot(n_n_) # (n_ x n).(n x n_) np.kron(n_,n).dot(np.kron(n,n_)) n_n.dot(nn_) # (n x n_).(n_ x n) np.kron(n, n_).dot(np.kron(n_,n)) nn_.dot(n_n) # (n_ x n_).(n x n) np.kron(n_, n_).dot(np.kron(n, n)) n_n_.dot(nn) NOT = np.array([[0,1],[1,0]]); NOT NOT.dot(D0) NOT.dot(D1) AND = np.array([[1,1,1,0],[0,0,0,1]]); AND AND.dot(np.kron(D0,D0)) AND.dot(np.kron(D0,D1)) AND.dot(np.kron(D1,D0)) AND.dot(np.kron(D1,D1)) OR = np.array([[1,0,0,0],[0,1,1,1]]); OR OR.dot(np.kron(D0,D0)) OR.dot(np.kron(D0,D1)) OR.dot(np.kron(D1,D0)) OR.dot(np.kron(D1,D1)) NAND = np.array([[0,0,0,1],[1,1,1,0]]); NAND NOT.dot(AND) NOR = np.array([[0,1,1,1],[1,0,0,0]]);NOR NOT.dot(OR) np.kron(NOT,AND) OR.dot(np.kron(NOT,AND)) NOT.dot(AND).dot(np.kron(NOT,NOT)) OR NOT.dot(OR).dot(np.kron(NOT,NOT)) AND import numpy as np k = np.kron XOR = np.array([[1,0,0,1], [0,1,1,0]]) AND = np.array(([1,1,1,0], [0,0,0,1])) k(XOR,AND) def criaCompat(nbits,nvezes): nlins = 2**(nbits*nvezes) ncols = 2**nbits compat = np.zeros(nlins*ncols).reshape(nlins,ncols) for i in range(ncols): formato = "0" + str(nbits) + "b" binario = format(i,formato)*nvezes decimal = int(binario,2) compat[decimal,i] = 1 return(compat) criaCompat(2,2) k(XOR,AND).dot(criaCompat(2,2)) import numpy as np k = np.kron def criaCompat(nbits,nvezes): nlins = 2**(nbits*nvezes) ncols = 2**nbits compat = np.zeros(nlins*ncols).reshape(nlins,ncols) for i in range(ncols): formato = "0" + str(nbits) + "b" binario = format(i,formato)*nvezes decimal = int(binario,2) compat[decimal,i] = 1 return(compat) criaCompat(2,2) NOT = np.array([[0,1], [1,0]]) AND3 = np.array([[1,1,1,1,1,1,1,0], [0,0,0,0,0,0,0,1]]) OR4 = np.array([[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]]) I2 = np.array([[1,0], [0,1]]) t1z = k(NOT,k(NOT,I2)) t2z = k(NOT,k(I2,NOT)) t3z = k(I2,k(NOT,NOT)) t4z = k(I2,k(I2,I2)) ORz = k(AND3,k(AND3,k(AND3,AND3))) ORz = OR4.dot(ORz).dot(k(t1z,k(t2z,k(t3z,t4z)))) t1c = k(NOT,k(I2,I2)) t2c = k(I2,k(NOT,I2)) t3c = k(I2,k(I2,NOT)) t4c = k(I2,k(I2,I2)) ORc = k(AND3,k(AND3,k(AND3,AND3))) ORc = OR4.dot(ORc).dot(k(t1c,k(t2c,k(t3c,t4c)))) compat = criaCompat(3,8) k(ORz,ORc).dot(compat) import numpy as np TOFFOLI = np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1], [0,0,0,0,0,0,1,0]]) TOFFOLI.dot(TOFFOLI) Z1 = np.array([[0,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,1]]) Z1 Z1I4 = np.array([[0,0,0,0], [1,0,0,0], [0,0,0,0], [0,1,0,0], [0,0,0,0], [0,0,1,0], [0,0,0,0], [0,0,0,1]]) TOFFOLI.dot(ZpY).dot(TOFFOLI).dot(Z1I4) ZpY = np.zeros([8,8]) ZpY[0,0] = 1; ZpY[1,2] = 1; ZpY[2,1] = 1; ZpY[3,3] = 1 ZpY[4,4] = 1; ZpY[5,6] = 1; ZpY[6,5] = 1; ZpY[7,7] = 1 ZpY Zfim = np.array([[1,0,1,0,1,0,1,0], [0,1,0,1,0,1,0,1]]) Zfim.dot(TOFFOLI).dot(ZpY).dot(TOFFOLI).dot(Z1I4) import numpy as np fred = np.identity(8) fred[5,5] = 0; fred[5,6] = 1 fred[6,5] = 1; fred[6,6] = 0 fred fred.dot(fred) import numpy as np Fy0 = np.zeros([8,4]) Fy0[0,0] = 1; Fy0[1,1] = 1; Fy0[4,2] = 1; Fy0[5,3] = 1 Fy0 xYz = np.array([[1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1]]) xYz.dot(fred).dot(Fy0) import numpy as np q0 = np.array([[1,0]]).T; q0 q1 = np.array([[0,1]]).T; q1 q01 = np.kron(q0,q1); q01 H = np.array([[1,1],[1,-1]])/np.sqrt(2); H H2 = np.kron(H,H); H2 H2.dot(q01) I4 = np.eye(4); I4 I4.dot(H2).dot(q01) I2 = np.eye(2); I2 HI2 = np.kron(H,I2); HI2 HI2.dot(I4).dot(H2).dot(q01) X = np.array([[0,1],[1,0]]); X I2 = np.eye(2); I2 I2X = np.kron(I2,X); I2X HI2.dot(I2X).dot(H2).dot(q01) CNOT = np.array([[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]]) CNOT HI2.dot(CNOT).dot(H2).dot(q01) X = np.array([[0,1],[1,0]]); X I2 = np.eye(2); I2 XI2 = np.kron(X,I2); XI2 CNOT = np.array([[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]]) CNOT CNOT.dot(XI2) HI2.dot(CNOT).dot(XI2).dot(H2).dot(q01) import qiskit as qk import numpy as np qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.h(0) qc.h(1) qc.barrier() qc.barrier() qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc, simulator).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk import numpy as np qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.h(0) qc.h(1) qc.barrier() qc.x(1) qc.barrier() qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc, simulator).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk import numpy as np qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.h(0) qc.h(1) qc.barrier() qc.cx(0,1) qc.barrier() qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc, simulator).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk import numpy as np qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.h(0) qc.h(1) qc.barrier() qc.x(0) qc.cx(0,1) qc.barrier() qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc, simulator).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qc = qk.QuantumCircuit(3,3) qc.barrier() qc.cnot(1,2) qc.barrier() qc.draw('mpl') import qiskit as qk qc = qk.QuantumCircuit(3,3) qc.initialize([0,0,0,0,1,0,0,0],[0,1,2]) qc.h([0,1,2]) qc.barrier() qc.cnot(1,2) qc.barrier() qc.h([0,1]) qc.measure([0,1],[0,1]) qc.draw('mpl') def histograma(qc): import qiskit as qk from qiskit.visualization import plot_histogram simulador = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulador,shots=10000).result().get_counts() grafico = plot_histogram(results) return(grafico) histograma(qc) import numpy as np x1 = np.array([[1,0]]).T x0 = np.array([[1,0]]).T y = np.array([[0,1]]).T psi0 = np.kron(y,np.kron(x1,x0)); psi0.T import numpy as np H = np.array([[1, 1], [1,-1]])/np.sqrt(2) H3 = np.kron(H,np.kron(H,H)); np.round(H3,3) psi0 = np.array([[0,0,0,0,1,0,0,0]]).T psi1 = H3.dot(psi0); psi1.T CNOTsm = np.array([[1,0,0,0], [0,0,0,1], [0,0,1,0], [0,1,0,0]]) I2 = np.array([[1,0], [0,1]]) CNOTsm_I2 = np.kron(CNOTsm,I2) psi0 = np.array([[0,0,0,0,1,0,0,0]]).T CNOTsm_I2.dot(H3).dot(psi0).T psi = np.array([[1,1,-1,-1]]).T/2 H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H2.dot(psi) import qiskit as qk qc = qk.QuantumCircuit(3,3) qc.initialize([0,0,0,0,1,0,0,0],[0,1,2]) qc.h([0,1,2]) qc.barrier() qc.cnot(0,2) qc.barrier() qc.h([0,1]) qc.measure([0,1],[0,1]) display(qc.draw('mpl')) histograma(qc) import numpy as np v0 = np.array([[0,0,0,0,1,0,0,0]]).T; v0.T H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H); H3 = np.kron(H2,H) H3.dot(v0).T CNOTs_I_m = np.array([[1,0,0,0,0,0,0,0], [0,0,0,0,0,1,0,0], [0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1], [0,0,0,0,1,0,0,0], [0,1,0,0,0,0,0,0], [0,0,0,0,0,0,1,0], [0,0,0,1,0,0,0,0]]) v0 = np.array([[0,0,0,0,1,0,0,0]]).T CNOTs_I_m.dot(H3).dot(v0).T psi = np.array([[+1,-1,+1,-1]]).T/2 H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H2.dot(psi) import qiskit as qk qc = qk.QuantumCircuit(3,3) qc.initialize([0,0,0,0,1,0,0,0],[0,1,2]) qc.h([0,1,2]) qc.barrier() qc.cnot(0,1) qc.cnot(1,2) qc.cnot(0,1) qc.barrier() qc.h([0,1]) qc.measure([0,1],[0,1]) display(qc.draw('mpl')) histograma(qc) v0 = np.array([[0,0,0,0,1,0,0,0]]).T H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H); H3 = np.kron(H2,H) H3.dot(v0).T CNOT_CNOT = np.array([[1,0,0,0,0,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1]]) v0 = np.array([[0,0,0,0,1,0,0,0]]).T H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H); H3 = np.kron(H2,H) CNOT_CNOT.dot(H3).dot(v0).T psi = np.array([[+1,-1,-1,+1]]).T/2 H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H2.dot(psi) import numpy as np CNOTsm = np.array([[1,0,0,0], [0,0,0,1], [0,0,1,0], [0,1,0,0]]) I = np.array([[1,0], [0,1]]) ISM = np.kron(I,CNOTsm) SMI = np.kron(CNOTsm,I) H = np.array([[1, 1], [1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H3 = np.kron(H2,H) IH2 = np.kron(I,H2) v0 = np.array([[0,0,0,0,1,0,0,0]]).T IH2.dot(ISM).dot(SMI).dot(ISM).dot(H3).dot(v0).round(3) CNOT_CNOT = np.array([[1,0,0,0,0,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1]]) ISM.dot(SMI).dot(ISM) import qiskit as qk from qiskit.quantum_info import Statevector from qiskit.visualization import plot_histogram qr = qk.QuantumRegister(3,'q') cr = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([0,1],2) qc.h(0) qc.h(1) qc.h(2) qc.barrier() qc.barrier() qc.h(0) qc.h(1) qc.measure(0,0) qc.measure(1,1) display(qc.draw('mpl')) histograma(qc) psi = np.array([[1,1,1,1]]).T/2 H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H2.dot(psi) import qiskit as qk from qiskit.quantum_info import Statevector from qiskit.visualization import plot_histogram qr = qk.QuantumRegister(3,'q') cr = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([0,1],2) qc.h(0) qc.h(1) qc.h(2) qc.barrier() qc.x(2) qc.barrier() qc.h(0) qc.h(1) qc.measure(0,0) qc.measure(1,1) display(qc.draw('mpl')) histograma(qc) psi = np.array([[1,1,1,1]]).T/2 H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H2.dot(psi) import qiskit as qk from qiskit.quantum_info import Statevector from qiskit.visualization import plot_histogram qr = qk.QuantumRegister(3,'q') cr = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([0,1],2) qc.h(0) qc.h(1) qc.h(2) qc.barrier() qc.ccx(0,1,2) qc.barrier() qc.h(0) qc.h(1) qc.measure(0,0) qc.measure(1,1) display(qc.draw('mpl')) histograma(qc) import qiskit as qk qrx = qk.QuantumRegister(2,'x') qry = qk.QuantumRegister(2,'y') qc = qk.QuantumCircuit(qrx,qry) qc.barrier() qc.cx(0,2) qc.cx(0,3) qc.cx(1,2) qc.cx(1,3) qc.barrier() qc.draw('mpl') def histograma(qc): simulador = qk.Aer.get_backend('statevector_simulator') resultado = qk.execute(qc,simulador,shots=10000).result() contagens = resultado.get_counts() grafico = qk.visualization.plot_histogram(contagens) return(grafico) def simon(initial_y, initial_x): import qiskit as qk qrx = qk.QuantumRegister(2,'x') crx = qk.ClassicalRegister(4,'c') qry = qk.QuantumRegister(2,'y') qc = qk.QuantumCircuit(qrx,qry,crx) qc.initialize(initial_x,qrx) qc.initialize(initial_y,qry) qc.barrier() qc.cx(0,2) qc.cx(0,3) qc.cx(1,2) qc.cx(1,3) qc.barrier() qc.measure([0,1,2,3],[0,1,2,3]) display(qc.draw('mpl')) grafico = histograma(qc) return(grafico) simon([1,0,0,0],[1,0,0,0]) simon([1,0,0,0],[0,0,0,1]) simon([1,0,0,0],[0,1,0,0]) simon([1,0,0,0],[0,0,1,0]) import qiskit as qk qrx = qk.QuantumRegister(2,'x') crx = qk.ClassicalRegister(2,'c') qry = qk.QuantumRegister(2,'y') qc = qk.QuantumCircuit(qrx,qry,crx) qc.initialize([1,0,0,0],qrx) qc.initialize([1,0,0,0],qry) qc.h([0,1]) qc.barrier() qc.cx(0,2) qc.cx(0,3) qc.cx(1,2) qc.cx(1,3) qc.barrier() qc.h([0,1]) qc.measure([0,1],[0,1]) display(qc.draw('mpl')) histograma(qc) import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T x1x0 = np.kron(x1,x0) y0 = np.array([[1,0]]).T y1 = np.array([[1,0]]).T y1y0 = np.kron(y1,y0) psi0 = np.kron(y1y0,x1x0) psi0.T H = np.array([[1,1],[1,-1]],dtype='int') H2 = np.kron(H,H) I2 = np.eye(4) I2H2 = np.kron(I2,H2) psi1 = I2H2.dot(psi0)/(np.sqrt(2)*np.sqrt(2)) I2H2.dot(psi0).T Tf1_2 = np.eye(16) Tf1_2 = Tf1_2[:,[0,5,2,7,4,1,6,3,8,9,10,11,12,13,14,15]] psi2 = Tf1_2.dot(psi1); psi2.T*2 Tf2_3 = np.eye(16) Tf2_3 = Tf2_3[:,[0,1,2,3,4,13,6,15,8,9,10,11,12,5,14,7]] psi3 = Tf2_3.dot(psi2); psi3.T*2 Tf3_4 = np.eye(16) Tf3_4 = Tf3_4[:,[0,1,6,3,4,5,2,7,8,9,10,15,12,13,14,11]] psi4 = Tf3_4.dot(psi3); psi4.T*2 Tf4_5 = np.eye(16) Tf4_5 = Tf4_5[:,[0,1,2,11,4,5,14,7,8,9,10,3,12,13,6,15]] psi5 = Tf4_5.dot(psi4); psi5.T*2 I2 = np.eye(4) H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) I2H2 = np.kron(I2,H2) psi6 = I2H2.dot(psi5) print(psi6.T*2) import numpy as np I2 = np.eye(4, dtype='int'); H2 = np.array([[1, 1, 1, 1], [1,-1, 1,-1], [1, 1,-1,-1], [1,-1,-1, 1]])/2; I2H2 = np.kron(I2,H2); print(I2H2*2) import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T x2 = np.array([[1,0]]).T x2x1x0 = np.kron(x2,np.kron(x1,x0)) x2x1x0.T y0 = np.array([[1,0]]).T y1 = np.array([[1,0]]).T y2 = np.array([[1,0]]).T y2y1y0 = np.kron(y2,np.kron(y1,y0)) y2y1y0.T psi0 = np.kron(y2y1y0,x2x1x0) psi0.T I3 = np.eye(2**3) H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H3 = np.kron(H,H2) I3H3 = np.kron(I3,H3) psi1 = I3H3.dot(psi0) psi1.T.round(2) n = 2*3 # 2 nรบmeros de 3 digitos cada Uf = np.eye(2**n) # 2^6 = 64 posiรงรตes Uf = Uf[:,[ 0, 9,18,27,12, 5,30,23, 8, 1,10,11, 4,13,14,15, 16,17, 2,19,20,21,22, 7, 24,25,26, 3,28,29, 6,31, 32,33,34,35,36,37,38,39, 40,41,42,43,44,45,46,47, 48,49,50,51,52,53,54,55, 56,57,58,59,60,61,62,63]] psi5 = Uf.dot(psi1) psi5.T.round(2) psi6 = I3H3.dot(psi5) psi6.T np.where(psi6 > 0)[0] [format(i,'#08b')[2:] for i in np.where(psi6 > 0)[0]] import numpy as np CCNOT = np.eye(8) CCNOT = CCNOT[:,[0,1,2,7,4,5,6,3]] CCNOT.dot(CCNOT) import qiskit as qk def qNAND(y0,x0): x = qk.QuantumRegister(1,"x") y = qk.QuantumRegister(1,"y") z = qk.QuantumRegister(1,"z") u = qk.QuantumRegister(1,"u") c = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(x,y,z,u,c) # Put qubits u and z in state |0> qc.initialize([1,0],z) qc.initialize([1,0],u) qc.initialize(y0,y) qc.initialize(x0,x) # Perform computation qc.barrier() qc.ccx(x,y,z) qc.x(z) # Copy CLASSICALY state of z to u qc.cx(z,u) qc.barrier() # Reverse computation qc.x(z) qc.ccx(x,y,z) qc.barrier() # Measure results qc.measure(x,c[0]) qc.measure(y,c[1]) qc.measure(u,c[2]) display(qc.draw('mpl')) simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc, simulator, shots=10000).result().get_counts() grafico = qk.visualization.plot_histogram(results) return(grafico) print("0 NAND 0 = 1") qNAND([1,0],[1,0]) print("0 NAND 1 = 1") qNAND([1,0],[0,1]) print("1 NAND 0 = 1") qNAND([0,1],[1,0]) print("1 NAND 1 = 0") qNAND([0,1],[0,1]) import qiskit as qk def qOR(y0,x0): x = qk.QuantumRegister(1,"x") y = qk.QuantumRegister(1,"y") z = qk.QuantumRegister(1,"z") u = qk.QuantumRegister(1,"u") c = qk.ClassicalRegister(3,'c') # Initialize qubits qc = qk.QuantumCircuit(x,y,z,u,c) qc.initialize(x0,x) qc.initialize(y0,y) qc.initialize([1,0],z) qc.initialize([1,0],u) # Compute function qc.barrier() qc.x(x) qc.x(y) qc.ccx(x,y,z) qc.x(z) qc.cx(z,u) qc.barrier() # Reverse computation qc.x(z) qc.ccx(x,y,z) qc.x(y) qc.x(x) qc.barrier() # Measure results qc.measure(x,c[0]) qc.measure(y,c[1]) qc.measure(u,c[2]) display(qc.draw('mpl')) # Simulate circuit simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() grafico = qk.visualization.plot_histogram(results) return(grafico) qOR([1,0],[1,0]) qOR([1,0],[0,1]) qOR([0,1],[1,0]) qOR([0,1],[0,1]) import qiskit as qk def qNXOR(y0,x0,calc=True,show=False): ################################################## # Create registers # ################################################## # Base registers x = qk.QuantumRegister(1,"x") y = qk.QuantumRegister(1,"y") # Auxiliary register (for x and y) z = qk.QuantumRegister(1,"z") # Auxiliary register (to store x AND y) a1 = qk.QuantumRegister(1,"a1") # Auxiliary register (to store NOT(x) AND NOT(y)) a2 = qk.QuantumRegister(1,"a2") # Auxiliary register (for a1 and a2) b1 = qk.QuantumRegister(1,"b1") # Auxiliary register (to store a1 OR a2) b2 = qk.QuantumRegister(1,"b2") # Classical Registers to store x,y and final measurement c = qk.ClassicalRegister(3,"c") ################################################## # Create Circuit # ################################################## qc = qk.QuantumCircuit(x,y,z,a1,a2,b1,b2,c) ################################################## # Initialize registers # ################################################## qc.initialize(x0,x) qc.initialize(y0,y) qc.initialize([1,0],z) qc.initialize([1,0],a1) qc.initialize([1,0],a2) qc.initialize([1,0],b1) qc.initialize([1,0],b2) ################################################### # Calculate x AND y. Copy result to a1. Reverse z # ################################################### qc.barrier() qc.ccx(x,y,z) qc.cx(z,a1) qc.ccx(x,y,z) qc.barrier() ######################################################### # Calc. NOT(x) AND NOT(y). Copy result to a2. Reverse z # ######################################################### qc.barrier() qc.x(x) qc.x(y) qc.ccx(x,y,z) qc.cx(z,a2) qc.ccx(x,y,z) qc.x(y) qc.x(x) qc.barrier() ################################################# # Calc. a1 OR a2. Copy result to b2. Reverse b1 # ################################################# qc.barrier() qc.x(a1) qc.x(a2) qc.ccx(a1,a2,b1) qc.x(b1) qc.cx(b1,b2) qc.x(b1) qc.ccx(a1,a2,b1) qc.barrier() ################################################# # Measure b2 # ################################################# qc.measure(x,c[0]) qc.measure(y,c[1]) qc.measure(b2,c[2]) ################################################# # Draw circuit # ################################################# if show: display(qc.draw("mpl")) ################################################# # Run circuit. Collect results # ################################################# if calc: simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc,simulator,shots=10000).result().get_counts() grafico = qk.visualization.plot_histogram(results) return(grafico) else: return() qNXOR([1,0],[1,0],False,True) qNXOR([1,0],[1,0]) qNXOR([1,0],[0,1]) qNXOR([0,1],[1,0]) qNXOR([0,1],[0,1]) x0 = np.array([1,1])/np.sqrt(2) y0 = np.array([1,1])/np.sqrt(2) qNXOR(y0,x0) import qiskit as qk from qiskit.quantum_info.operators import Operator qr = qk.QuantumRegister(6,"q") cr = qk.ClassicalRegister(6,"c") qc = qk.QuantumCircuit(qr,cr) for i in range(6): qc.initialize([1,0],i) for i in range(3): qc.h(i) oracle = np.eye(2**6) oracle[:,[ 0, 0]] = oracle[:,[ 0, 0]] oracle[:,[ 1, 9]] = oracle[:,[ 9, 1]] oracle[:,[ 2, 18]] = oracle[:,[ 18, 2]] oracle[:,[ 3, 27]] = oracle[:,[ 27, 3]] oracle[:,[ 4, 12]] = oracle[:,[ 12, 4]] oracle[:,[ 5, 5]] = oracle[:,[ 5, 5]] oracle[:,[ 6, 30]] = oracle[:,[ 30, 6]] oracle[:,[ 7, 23]] = oracle[:,[ 23, 7]] oracle = Operator(oracle) qc.append(oracle,qr) for i in range(3): qc.h(i) qc.barrier() for i in range(3): qc.measure(i,i) display(qc.draw("mpl")) simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np oracle = np.eye(8) oracle[:,[2,6]] = oracle[:,[6,2]] oracle import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T psi0 = np.kron(x1,x0) H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) psi1 = H2.dot(psi0) psi1.T # Initialize a qubit y in state |1> y = np.array([[0,1]]).T # Pass it through a Hadamard gate and obtain state psi2a H = np.array([[1,1],[1,-1]])/np.sqrt(2) psi2a = H.dot(y) psi2a.T psi2 = np.kron(psi2a,psi1) psi2.T oracle = np.eye(8) oracle[:,[2,6]] = oracle[:,[6,2]] oracle psi3 = oracle.dot(psi2) psi3.T v0 = np.array([[10,20,-30,40,50]]).T mu = np.mean(v0) v0.T, mu D = v0 - mu D.T v1 = 2*np.mean(v0)-v0 v1.T import numpy as np A = np.ones(5**2).reshape(5,5) A = A/5 I = np.eye(5) R = 2*A-I R R.dot(R) n = 4 I = np.eye(n) A = np.ones(n**2).reshape(n,n)/n R = 2*A-I R I2 = np.eye(2) I2R = np.kron(I2,R) I2R psi4 = I2R.dot(psi3) psi4.T import qiskit as qk import numpy as np from qiskit.quantum_info.operators import Operator q = qk.QuantumRegister(3,'q') c = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(q,c) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.h(1) qc.initialize([0,1],2) qc.h(2) qc.barrier() oracle = np.eye(8) oracle[:,[2,6]] = oracle[:,[6,2]] oracle = Operator(oracle) qc.append(oracle,q) # n = 2 (two digits number to look for) A = np.ones(4*4).reshape(4,4)/4 I4 = np.eye(4) R = 2*A - I4 I2 = np.eye(2) boost = np.kron(I2,R) boost = Operator(boost) qc.append(boost,q) qc.barrier() qc.measure(q[:2],c[:2]) display(qc.draw('mpl')) simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=1000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T x2 = np.array([[1,0]]).T x2x1x0 = np.kron(x2,np.kron(x1,x0)) x2x1x0.T H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H3 = np.kron(H,H2) x = H3.dot(x2x1x0) x.T y0 = np.array([[0,1]]).T y0.T H = np.array([[1,1],[1,-1]])/np.sqrt(2) y = H.dot(y0) y.T psi0 = np.kron(y,x) psi0.T oracle = np.eye(16) oracle[:,[5,13]] = oracle[:,[13,5]] psi1 = oracle.dot(psi0) psi1.T # n = 8 A = np.ones(8*8).reshape(8,8)/8 I8 = np.eye(8) R = 2*A-I8 R I2 = np.eye(2) I2R = np.kron(I2,R) psi2 = I2R.dot(psi1) psi2.T 0.625**2 + 0.625**2 psi3 = I2R.dot(oracle).dot(psi2) psi3.T 0.687**2 + 0.687**2 I2R.dot(oracle).dot(psi3).T T = I2R.dot(oracle) psi = psi1 prob = [] for i in range(25): prob.append(psi[5,0]**2 + psi[13,0]**2) psi = T.dot(psi) from matplotlib import pyplot as plt plt.plot(list(range(25)), prob); import qiskit as qk import numpy as np from qiskit.quantum_info.operators import Operator q = qk.QuantumRegister(4,'q') c = qk.ClassicalRegister(4,'c') qc = qk.QuantumCircuit(q,c) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([1,0],2) qc.h(0) qc.h(1) qc.h(2) qc.initialize([0,1],3) qc.h(3) qc.barrier() # Create oracle matrix oracle = np.eye(16) oracle[:,[5,13]] = oracle[:,[13,5]] # Create rotation about the mean matrix # n = 3 (three digits number to look for) A = np.ones(8*8).reshape(8,8)/8 I8 = np.eye(8) R = 2*A - I8 # Identity matrix to leave fourth qubit undisturbed I2 = np.eye(2) # Create second transformation matrix boost = np.kron(I2,R) # Combine oracle with second transformation matrix in # an unique operator T = boost.dot(oracle) T = Operator(T) # Apply operator twice (2 phase inversions and # rotations about the mean) qc.append(T,q) qc.append(T,q) qc.barrier() qc.measure(q[:3],c[:3]) display(qc.draw('mpl')) simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=1000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk import numpy as np from qiskit.quantum_info.operators import Operator q = qk.QuantumRegister(5,'q') c = qk.ClassicalRegister(5,'c') qc = qk.QuantumCircuit(q,c) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([1,0],2) qc.initialize([1,0],3) qc.h(0) qc.h(1) qc.h(2) qc.h(3) qc.initialize([0,1],4) qc.h(4) qc.barrier() # Create oracle matrix oracle = np.eye(32) oracle[:,[13,29]] = oracle[:,[29,13]] # Create rotation about the mean matrix # n = 4 (four digits number to look for) A = np.ones(16*16).reshape(16,16)/16 I16 = np.eye(16) R = 2*A - I16 # Identity matrix to leave fifth qubit undisturbed I2 = np.eye(2) # Create second transformation matrix boost = np.kron(I2,R) # Combine oracle with second transformation matrix in # an unique operator T = boost.dot(oracle) # n = 4. Therefore it will be necessary 4 T operations # to get maximum probability. Tn = T.dot(T).dot(T) Tn = Operator(Tn) # Apply operator Tn once (n phase inversions and # rotations about the mean) qc.append(Tn,q) qc.barrier() qc.measure(q[:4],c[:4]) display(qc.draw('mpl')) simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=1000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np import pandas as pd N = 35; a = 6 GCD = pd.DataFrame({'N':[N], 'a':[a], 'N-a':[N-a]}) while GCD.iloc[-1,2] != 0: temp = GCD.iloc[-1].values temp = np.sort(temp); temp[-1] = temp[-2] - temp[-3] temp = pd.DataFrame(data = temp.reshape(-1,3), columns = ['N','a','N-a']) GCD = GCD.append(temp, ignore_index=True) GCD import numpy as np import pandas as pd N = 15; a = 9 GCD = pd.DataFrame({'N':[N], 'a':[a], 'N-a':[N-a]}) while GCD.iloc[-1,2] != 0: temp = GCD.iloc[-1].values temp = np.sort(temp); temp[-1] = temp[-2] - temp[-3] temp = pd.DataFrame(data = temp.reshape(-1,3), columns = ['N','a','N-a']) GCD = GCD.append(temp, ignore_index=True) GCD import numpy as np np.gcd(6,35), np.gcd(9,15) import numpy as np np.gcd(215,35), np.gcd(217,35) 20 % 7 import numpy as np f = lambda x,a,N: a**x % N [f(x,2,15) for x in range(10)] import numpy as np (13*35)%11, ((2%11)*(24%11))%11 import numpy as np def f(x,a,N): a0 = 1 for i in range(x): a0 = ((a%N)*(a0))%N return(a0) [f(x,2,371) for x in range(8)] [f(x,2,371) for x in range(154,159)] [f(x,24,371) for x in range(77,81)] import numpy as np def fr(a,N): ax = ((a%N)*(1))%N x = 1 while ax != 1: ax = ((a%N)*(ax))%N x = x+1 return(x) fr(2,371), fr(6,371), fr(24,371) import numpy as np def fr(a,N): a0 = 1 a0 = ((a%N)*a0)%N x = 2 find = False while find==False: a0 = ((a%N)*(a0))%N if a0 == 1: find = True x = x+1 return(x-1) N = 35 a = 2 fr(a,N) 2**(12/2)-1, 2**(12/2)+1 np.gcd(63,35), np.gcd(65,35) import numpy as np # Function to calculate the period of f(x) = a^x MOD N def fr(a,N): a1 = ((a%N)*(1))%N x = 1 while a1 != 1: a1 = ((a%N)*a1)%N x = x+1 return(x) # Function to factor N based on a def factor(N, a=2): r = fr(a,N) g1 = a**(int(r/2)) - 1 g2 = a**(int(r/2)) + 1 f1 = np.gcd(g1,N) f2 = np.gcd(g2,N) return(f1,f2, f1*f2) factor(247) factor(1045) import numpy as np N = 15 # number to be factored n = 4 # number of bits necessary to represent N m = 8 # number of bits necessary to represent N^2 x = np.zeros(2**m).reshape(-1,1) x[0,0] = 1 x.shape # since x is a 2^8 = 256 positions vector it will not be showed here y = np.zeros(2**n).reshape(-1,1) y[0,0] = 1; y.T # y is a 2^4 = 16 positions vector shown below psi0 = np.kron(y,x) psi0.shape # psi0 is a 256 x 16 = 4.096 positions vector In = np.eye(2**n); In.shape H = np.array([[1,1],[1,-1]])/np.sqrt(2) Hm = H.copy() for i in range(1,m): Hm = np.kron(Hm,H) Hm.shape psi1 = np.kron(In,Hm).dot(psi0); psi1.shape
https://github.com/gustavomirapalheta/Quantum-Computing-with-Qiskit
gustavomirapalheta
# Setup Acesso do Google Colab aos sistemas IBM Quantum from google.colab import userdata ibm_token = userdata.get("IBM_TOKEN") # As of 2024/01/25 it is not necessary to install qutip anymore for qiskit # graphical circuit display to function properly. !pip install qiskit-ibm-provider -q !pip install qiskit -q !pip install qiskit[visualization] -q !pip install qiskit-aer !pip install git+https://github.com/qiskit-community/qiskit-textbook.git#subdirectory=qiskit-textbook-src -q import numpy as np np.set_printoptions(precision=3, suppress=True) from matplotlib import pyplot as plt %matplotlib inline import pandas as pd import sklearn as sk import qiskit as qk # Remember that qiskit has to be already installed in the Python environment. # Otherwise the import command will fail import qiskit as qk # A circuit composed of just one qubit qc = qk.QuantumCircuit(1) qc.draw('mpl', style = 'clifford', scale = 1) import qiskit as qiskit # A qubit initialized in the state |0> qc = qk.QuantumCircuit(1) qc.initialize([1,0]) qc.draw('mpl', style = 'clifford', scale = 1) import qiskit as qk # A qubit initialized in |0> and a measurement qc = qk.QuantumCircuit(1) qc.initialize([1,0]) qc.measure_all() qc.draw('mpl', style = 'clifford') import qiskit as qk import qiskit_aer # A list of possible measurements. The results of measurements are obtained # by executing an object called backend - As of 16/02/2024 the line below # was giving an error. Need to understand how to list possible backends in # qiskit now. a = [print(i) for i in qk.aer.backends()] import qiskit as qk qc = qk.QuantumCircuit(1) qc.initialize([1,0],0) qc.measure_all() # Let's choose a Aer backend with the statevector simulator backend = qk.Aer.get_backend('statevector_simulator') # And execute the circuit qc in the simulator backend # getting as final result the counts from 1.000 measures # of the qubit state result = qk.execute(qc, backend, shots=1000).result().get_counts() result import qiskit as qk qc = qk.QuantumCircuit(1) qc.initialize([1,0],0) qc.measure_all() backend = qk.Aer.get_backend('statevector_simulator') result = qk.execute(qc, backend, shots=1000).result().get_counts() qk.visualization.plot_distribution(result) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) qc.measure(0,0) qc.draw('mpl', style = 'clifford') backend = qk.Aer.get_backend('statevector_simulator') result = qk.execute(qc, backend, shots=1000).result().get_counts() qk.visualization.plot_distribution(result) import numpy as np v0 = np.array([[1],[0]]);v0 v1 = np.array([[0],[1]]); v1 X = np.array([[0,1],[1,0]]); X X.dot(v0) X.dot(v1) import qiskit as qk qr = qk.QuantumRegister(1,"q0") cr = qk.ClassicalRegister(1,"c0") qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) qc.x(0) qc.measure(qr[0], cr[0]) qc.draw('mpl', style = "clifford") backend = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, backend, shots=1000).result().get_counts() results qk.visualization.plot_distribution(results) import numpy as np # Notice that we are creating the v0 matrix using the transpose operation v0 = np.array([[1,0]]).T; v0 # Here it is created again de X matrix X = np.array([[0,1],[1,0]]); X # Multiplying v0 by the X matrix twice you get again v0 X.dot(X).dot(v0) # Multiplying the X matrix by itself you get the Identity matrix X.dot(X) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) qc.x(0) qc.x(0) qc.measure(qr[0],cr[0]) qc.draw('mpl', style = "clifford") # The result of 1000 measures of the qubit above gives the |0> state as result # in all measures simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=1000).result().get_counts() results qk.visualization.plot_distribution(results) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([2**-0.5,2**-0.5],0) qc.measure(qr[0],cr[0]) qc.draw('mpl', style = "clifford") backend = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,backend,shots=10000).result().get_counts() qk.visualization.plot_distribution(results) import numpy as np v0 = np.array([[1,0]]).T; v0 H = np.array([[1,1],[1,-1]])/np.sqrt(2); H H.dot(v0) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.h(qr[0]) qc.measure(qr[0],cr[0]) qc.draw('mpl', style = "clifford") backend = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, backend, shots=10000).result().get_counts() qk.visualization.plot_distribution(results) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([2**-0.5,-(2**-0.5)],0) qc.measure(qr[0],cr[0]) qc.draw('mpl', style = "clifford") backend = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,backend,shots=10000).result().get_counts() qk.visualization.plot_distribution(results) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([2**-0.5,-(2**-0.5)],0) qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl', style = 'clifford') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_distribution(results) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([0,1],0) qc.h(0) qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl', style = 'clifford') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_distribution(results) import numpy as np # First let's start with the qubit in the state |psi> = (|0> - |1>)/sqrt(2) psi = np.array([[1,-1]]).T/(2**0.5); psi H = np.array([[1,1],[1,-1]])/2**0.5; H # Now let's pass the qubit Psi through an Hadamard gate. # The result is a qubit in the state |1> H.dot(psi) # Let's start with a qubit in the state |1>, pass it through a # a hadamard gate twice and check the result v0 = np.array([[0,1]]).T; v0 H.dot(H).dot(v0) # This means that if we multiply the H gate by itself the result # will be an Identity matrix. Let's check it. H.dot(H) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.measure(qr,cr) qc.draw('mpl', style = "clifford") backend = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,backend,shots=10000).result().get_counts() qk.visualization.plot_distribution(results) import numpy as np psi1 = np.array([[1,0]]).T; psi1 psi2 = np.array([[1,0]]).T; psi2 # In numpy the tensor product is calculated with the function kron np.kron(psi1,psi2) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.h(1) qc.measure(qr,cr) qc.draw('mpl', style = "clifford") backend = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,backend,shots=10000).result().get_counts() qk.visualization.plot_distribution(results) import numpy as np psi1 = np.array([[1,0]]).T;psi1 psi2 = np.array([[1,0]]).T;psi2 H = np.array([[1,1],[1,-1]])/2**0.5;H # When we want to combine two vector states or gate matrices we tensor product them. psi3 = np.kron(psi1,psi2);psi3 H2 = np.kron(H,H);H2 # When we want to pass a vetor through a gate we calculate the dot product # of the total gate matrix with the total vector. # As we have predicted, the resulting vector state has a=b=c=d=1/2 psi4 = H2.dot(psi3); psi4 import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([0,1],0) qc.initialize([0,1],1) qc.h(0) qc.h(1) qc.measure(qr,cr) qc.draw('mpl', style = "clifford") backend = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,backend,shots=10000).result().get_counts() qk.visualization.plot_distribution(results) import numpy as np psi1 = np.array([[0,1]]).T;psi1 psi2 = np.array([[0,1]]).T;psi2 H = np.array([[1,1],[1,-1]])/2**0.5;H # When we want to combine two vector states or gate matrices we tensor product them. psi3 = np.kron(psi1,psi2);psi3 H2 = np.kron(H,H);H2 # When we want to pass a vetor through a gate we calculate the dot product # of the total gate matrix with the total vector. # As we have predicted, the resulting vector state has a=b=c=d=1/2 psi4 = H2.dot(psi3); psi4 import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.cx(0,1) qc.measure(qr,cr) qc.draw('mpl', style = "clifford") backend = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, backend, shots=10000).result().get_counts() qk.visualization.plot_distribution(results) import numpy as np C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C v00 = np.array([[1,0,0,0]]).T;v00 # C.v00 = v00 C.dot(v00) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.cx(0,1) qc.measure(qr,cr) qc.draw('mpl', style = 'clifford') # Please notice that Qiskit's qubits presentation order is reversed. # Therefore 10 in the histogram's x axis should be read as 01 (from # inside out or right to left). backend = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, backend, shots=10000).result().get_counts() qk.visualization.plot_distribution(results) import numpy as np C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C v01 = np.array([[0,1,0,0]]).T;v01 # C.v01 = v01 C.dot(v01) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([0,1],0) qc.initialize([1,0],1) qc.cx(0,1) qc.measure(qr,cr) qc.draw('mpl', style = 'clifford') backend = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, backend, shots=10000).result().get_counts() qk.visualization.plot_distribution(results) import numpy as np C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C v10 = np.array([[0,0,1,0]]).T; v10 # C.v10 = v11 C.dot(v10) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([0,1],0) qc.initialize([0,1],1) qc.cx(0,1) qc.measure(qr,cr) qc.draw('mpl', style = 'clifford') # Again remember to read qiskit qubits state presentation order # from right to left. Therefore 01 in the x axis is in fact 10 backend = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, backend, shots=10000).result().get_counts() qk.visualization.plot_distribution(results) import numpy as np C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C v11 = np.array([[0,0,0,1]]).T; v11 # C.v11 = v10 C.dot(v11) import qiskit as qk qr = qk.QuantumRegister(2, 'q') cr = qk.ClassicalRegister(2, 'c') qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(qr[0]) qc.cx(qr[0],qr[1]) qc.measure(qr, cr) qc.draw('mpl', style = 'clifford') backend = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,backend,shots=10000).result().get_counts() qk.visualization.plot_distribution(results) import numpy as np va = np.array([[1,0]]).T; va vb = np.array([[1,0]]).T; vb H = np.array([[1,1],[1,-1]])/2**0.5;H vaH = H.dot(va); vaH vaHvb = np.kron(vaH,vb); vaHvb C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C vout = C.dot(vaHvb); vout import qiskit as qk qr = qk.QuantumRegister(2, 'q') cr = qk.ClassicalRegister(2, 'c') qc = qk.QuantumCircuit(qr, cr) qc.initialize([0,1],0) qc.initialize([1,0],1) qc.h(qr[0]) qc.cx(qr[0],qr[1]) qc.measure(qr, cr) qc.draw('mpl', style = 'clifford') backend = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,backend,shots=10000).result().get_counts() qk.visualization.plot_distribution(results) import numpy as np va = np.array([[0,1]]).T; va vb = np.array([[1,0]]).T; vb H = np.array([[1,1],[1,-1]])/2**0.5;H vaH = H.dot(va); vaH vaHvb = np.kron(vaH,vb); vaHvb C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C vout = C.dot(vaHvb); vout # Get the IBM API key in: https://quantum-computing.ibm.com # ibm_token is saved as a Google Secret in this notebook from qiskit_ibm_provider import IBMProvider IBMProvider.save_account(token=ibm_token, overwrite=True) # Load the account in the active session provider = IBMProvider(token=ibm_token, instance='ibm-q-education/fgv-1/ml-business-app') provider.backends() backend = provider.get_backend("ibmq_qasm_simulator") backend # With n Qubits we can generate a random number from 0 to 2^n - 1 n = 3 qr = qk.QuantumRegister(n,'q') cr = qk.ClassicalRegister(n,'c') qc = qk.QuantumCircuit(qr, cr) # Applying a Hadamard to each of the three qubits for i in range(n): qc.h(qr[i]) # Measuring the three qubits qc.measure(qr,cr) # Visualizing the circuit qc.draw('mpl', style='clifford') # qk.execute envia para o backend. Conferindo no iqmq explorer aparece o job new_job = qk.execute(qc, backend, shots=1) # this result is stored on the local machine. However, it will only be available # after the job has been executed. It returns a python dictionary. new_job.result().get_counts() int(list(new_job.result().get_counts().keys())[0],2) from qiskit import QuantumCircuit circuit = QuantumCircuit(2, 2) circuit.h(0) circuit.cx(0,1) circuit.measure([0,1], [0,1]) display(circuit.draw('mpl', style='clifford')) backend = qk.Aer.get_backend('aer_simulator') print(backend.run(circuit, shots=1000).result().get_counts()) print(backend.run(circuit, shots=1000).result().get_counts()) from qiskit import QuantumCircuit circuito = QuantumCircuit(3,3) for i in range(3): circuito.h(i) circuito.measure(i,i) display(circuito.draw('mpl', style='clifford')) backend = qk.Aer.get_backend('aer_simulator') backend.run(circuito, shots = 1000).result().get_counts() from qiskit import QuantumCircuit qc = QuantumCircuit(4,4) qc.x([0,1]) qc.cx([0,1],[2,2]) qc.ccx(0,1,3) qc.measure([0,1,2,3],[0,1,2,3]) display(qc.draw(output='mpl', style="clifford")) backend = qk.Aer.get_backend('aer_simulator') qk.execute(qc, backend, shots = 10000).result().get_counts() import qiskit as qk qr = qk.QuantumRegister(1,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) print("Circuit 1 - Registers Only") display(qc.draw('mpl', style="clifford")) qc.x(qr) print("Circuit 1 - Quantum Register with a Gate X ") display(qc.draw('mpl', style="clifford")) job = qk.execute(experiments = qc, backend = qk.Aer.get_backend('statevector_simulator')) result = job.result().get_statevector() print("Quantum Register Vector State") from qiskit.tools.visualization import plot_bloch_multivector display(plot_bloch_multivector(result)) job = qk.execute(experiments = qc, backend = qk.Aer.get_backend('unitary_simulator')) #WARNING:qiskit_aer.backends.aerbackend:Simulation failed and returned the # following error message: #ERROR: [Experiment 0] Circuit circuit-293 contains invalid instructions # {"instructions": {save_unitary}} for "statevector" method.Circuit # circuit-293 contains invalid parameters for "statevector" method. #result = job.result().get_unitary() print("Transformation Matrix (up to this stage)") print(result) qc.measure(qr, cr) print() print("Circuit 1 - Registers, Gate X and Quantum Register Measure") display(qc.draw('mpl', style="clifford")) print("Quantum Register Thousand Measures") job = qk.execute(experiments = qc, backend = qk.Aer.get_backend('statevector_simulator'), shots = 1000) print(job.result().get_counts()) print() print("Result's Histogram") from qiskit.tools.visualization import plot_distribution plot_distribution(data = job.result().get_counts()) import qiskit as qk from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector qr = qk.QuantumRegister(3,'q') cr = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([1,0],2) display(qc.draw('mpl', style="clifford")) sv = Statevector.from_label('000') state_data = lambda qc,sv: np.round(np.asarray(sv.evolve(qc).data),4) state_bloch = lambda qc,sv: plot_bloch_multivector(sv.evolve(qc).data, reverse_bits=True) print(state_data(qc,sv)) state_bloch(qc,sv) qc.x(0) qc.barrier() display(qc.draw('mpl', style="clifford")) print(state_data(qc,sv)) display(state_bloch(qc,sv)) qc.h(1) display(qc.draw('mpl', style="clifford")) print(state_data(qc,sv)) state_bloch(qc,sv) qc.cx(1,2) display(qc.draw("mpl", style="clifford")) state_data(qc,sv) state_bloch(qc,sv) qc.cx(0,1) display(qc.draw('mpl', style="clifford")) state_data(qc,sv) qc.h(0) qc.barrier() display(qc.draw('mpl', style="clifford")) state_data(qc,sv) qc.measure(0,0) qc.measure(1,1) qc.barrier() qc.cx(1,2) qc.cz(0,2) qc.measure(2,2) display(qc.draw('mpl', style='clifford')) simulador = qk.Aer.get_backend('statevector_simulator') resultado = qk.execute(qc, simulador, shots=10000).result() qk.visualization.plot_distribution(resultado.get_counts()) import numpy as np V = np.array([[3+2j],[4-2j]]) modV = np.real(V.T.conjugate().dot(V)[0,0])**0.5 Vn = V/modV; Vn v0 = np.array([[1,0]]).T v1 = np.array([[0,1]]).T Vn[0,0]*v0 + Vn[1,0]*v1 import qiskit as qk qr = qk.QuantumRegister(1,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([Vn[0,0],Vn[1,0]],0) qc.measure(qr[0],cr[0]) qc.draw('mpl', style="clifford") backend = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,backend,shots=10000).result().get_counts() qk.visualization.plot_distribution(results) Vn[0,0].conjugate()*Vn[0,0] Vn[1,0].conjugate()*Vn[1,0] import numpy as np CNOT = np.array([[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]]) CNOT.dot(CNOT) import numpy as np H = np.array([[1,1],[1,-1]])/2**0.5 H.dot(H) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.cnot(qr[0],qr[1]) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.cnot(qr[0],qr[1]) qc.cnot(qr[0],qr[1]) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.cnot(qr[0],qr[1]) qc.cnot(qr[0],qr[1]) qc.h(0) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np X = np.array([[0,1], [1,0]]) X X.conj().T.dot(X) Y = np.array([[0,-1j], [1j,0]]) Y Y.conj().T.dot(Y) Z = np.array([[1,0], [0,-1]]) Z Z.conj().T.dot(Z) H = (X+Z)/np.sqrt(2); H H.dot(Z).dot(H) H.dot(X).dot(H) -H.dot(Y).dot(H) import numpy as np S = np.array([[1,0], [0,1j]]) S S.conj().T.dot(S) T = np.array([[1,0], [0,np.exp(1j*np.pi/4)]]) T T.conj().T.dot(T) S = np.array([[1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]]); S S.dot(v00) S.dot(v01) S.dot(v10) S.dot(v11) C = np.array([[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]]);C C_ = np.array([[1,0,0,0], [0,0,0,1], [0,0,1,0], [0,1,0,0]]);C_ C.dot(C_).dot(C) v = v0 + v1; v n = np.array([[0,0],[0,1]]); n n.dot(v) n_ = np.array([[1,0],[0,0]]);n_ I2 = np.identity(2); I2 I2 - n n_.dot(v) n.dot(n) n_.dot(n_) n.dot(n_) n_.dot(n) n+n_ n.dot(X) X.dot(n_) import numpy as np n = np.array([[0,0],[0,1]]); n n_ = np.array([[1,0],[0,0]]);n_ # ni nj operam em bits distintos. Como cada operador n atua em um vetor de # 2 dimensรตes, ni nj รฉ um operador de 4 dimensรตes. Sendo assim, fica implรญcito # pelos subscritos que ni nj รฉ um produto tensorial. np.kron(n,n) # O mesmo vale para n'i n'j np.kron(n_,n_) # Para ni n'j np.kron(n,n_) # E para n'i nj np.kron(n_,n) # Xi Xj sรฃo dois operadores 2x2 de inversรฃo, cada um atuando em um bit # distinto. Sendo assim, fazemos o produto tensorial entre ambos # para obter XiXj np.kron(X,X) # No caso da expressรฃo XiXj(ninj' + ni'nj) temos entre parรชnteses duas # matrizes 4x4 (ninj'+ni'nj) e fora dos parรชnteses uma matriz 4x4 (XiXj) # Sendo assim fazemos neste caso o produto matricial normal para # calcular esta expressรฃo. np.kron(X,X).dot(np.kron(n,n_)+np.kron(n_,n)) # E por รบltimo somamos com o resultado inicial de ninj + ni'nj' # Como pode-se ver, esta expressรฃo gera o operador de SWAP np.kron(n,n) + np.kron(n_,n_) + np.kron(X,X).dot(np.kron(n,n_)+np.kron(n_,n)) # ร‰ importante observar que ninj forma um operador que projeta um vetor de # 4 dimensรตes (00, 01, 10, 11) em sua componente 11 np.kron(n,n) # De maneira similar ni'nj' projeta um vetor de 4 dimensรตes em sua componente 00 np.kron(n_,n_) # ni'nj projeta em 01 np.kron(n_,n) # Assim como ninj' projeta em 10 np.kron(n,n_) # E por รบltimo vemos que ni'nj' + ni'nj + ninj' + ninj = I nn = np.kron(n,n) nn_ = np.kron(n,n_) n_n = np.kron(n_,n) n_n_ = np.kron(n_,n_) nn + nn_ + n_n + n_n_ import numpy as np n = np.array([[0,0],[0,1]]); n n_ = np.array([[1,0],[0,0]]);n_ # (n x n).(n_ x n_) np.kron(n,n).dot(np.kron(n_,n_)) # Faz sentido que (ni x nj).(ni_ x nj_) seja o vetor nulo pois: # ni_ x nj_ รฉ um operador que recebe um vetor de 4 dimensรตes e # produz como resultado apenas sua componente |00>. Por sua # vez ni x nj รฉ um operador que recebe um vetor de 4 dimensรตes # e produz como resultado apenas sua componente |11>. Esta # componente foi zerada pelo primeiro operador, logo o resultado # serรก nulo. Isto vai acontecer sempre que a componente nรฃo # zerada do primeiro operador for diferente da do segundo em # outras palavras sempre que ij do primeiro for diferente de ij # do segundo. np.kron(n,n).dot(np.kron(n_,n_)) # Outra forma de entender รฉ transformar (n x n).(n_ x n_) em # (n.n_) x (n.n_). Como n รฉ ortogonal a n_, a projeรงรฃo de n # em n_ darรก zero tambรฉm. np.kron(n.dot(n_),n.dot(n_)) nn.dot(n_n_) # (n_ x n).(n x n_) np.kron(n_,n).dot(np.kron(n,n_)) n_n.dot(nn_) # (n x n_).(n_ x n) np.kron(n, n_).dot(np.kron(n_,n)) nn_.dot(n_n) # (n_ x n_).(n x n) np.kron(n_, n_).dot(np.kron(n, n)) n_n_.dot(nn) NOT = np.array([[0,1],[1,0]]); NOT NOT.dot(D0) NOT.dot(D1) AND = np.array([[1,1,1,0],[0,0,0,1]]); AND AND.dot(np.kron(D0,D0)) AND.dot(np.kron(D0,D1)) AND.dot(np.kron(D1,D0)) AND.dot(np.kron(D1,D1)) OR = np.array([[1,0,0,0],[0,1,1,1]]); OR OR.dot(np.kron(D0,D0)) OR.dot(np.kron(D0,D1)) OR.dot(np.kron(D1,D0)) OR.dot(np.kron(D1,D1)) NAND = np.array([[0,0,0,1],[1,1,1,0]]); NAND NOT.dot(AND) NOR = np.array([[0,1,1,1],[1,0,0,0]]);NOR NOT.dot(OR) np.kron(NOT,AND) OR.dot(np.kron(NOT,AND)) NOT.dot(AND).dot(np.kron(NOT,NOT)) OR NOT.dot(OR).dot(np.kron(NOT,NOT)) AND import numpy as np k = np.kron XOR = np.array([[1,0,0,1], [0,1,1,0]]) AND = np.array(([1,1,1,0], [0,0,0,1])) k(XOR,AND) def criaCompat(nbits,nvezes): nlins = 2**(nbits*nvezes) ncols = 2**nbits compat = np.zeros(nlins*ncols).reshape(nlins,ncols) for i in range(ncols): formato = "0" + str(nbits) + "b" binario = format(i,formato)*nvezes decimal = int(binario,2) compat[decimal,i] = 1 return(compat) criaCompat(2,2) k(XOR,AND).dot(criaCompat(2,2)) import numpy as np k = np.kron def criaCompat(nbits,nvezes): nlins = 2**(nbits*nvezes) ncols = 2**nbits compat = np.zeros(nlins*ncols).reshape(nlins,ncols) for i in range(ncols): formato = "0" + str(nbits) + "b" binario = format(i,formato)*nvezes decimal = int(binario,2) compat[decimal,i] = 1 return(compat) criaCompat(2,2) NOT = np.array([[0,1], [1,0]]) AND3 = np.array([[1,1,1,1,1,1,1,0], [0,0,0,0,0,0,0,1]]) OR4 = np.array([[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]]) I2 = np.array([[1,0], [0,1]]) t1z = k(NOT,k(NOT,I2)) t2z = k(NOT,k(I2,NOT)) t3z = k(I2,k(NOT,NOT)) t4z = k(I2,k(I2,I2)) ORz = k(AND3,k(AND3,k(AND3,AND3))) ORz = OR4.dot(ORz).dot(k(t1z,k(t2z,k(t3z,t4z)))) t1c = k(NOT,k(I2,I2)) t2c = k(I2,k(NOT,I2)) t3c = k(I2,k(I2,NOT)) t4c = k(I2,k(I2,I2)) ORc = k(AND3,k(AND3,k(AND3,AND3))) ORc = OR4.dot(ORc).dot(k(t1c,k(t2c,k(t3c,t4c)))) compat = criaCompat(3,8) k(ORz,ORc).dot(compat) import numpy as np TOFFOLI = np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1], [0,0,0,0,0,0,1,0]]) TOFFOLI.dot(TOFFOLI) Z1 = np.array([[0,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,1]]) Z1 Z1I4 = np.array([[0,0,0,0], [1,0,0,0], [0,0,0,0], [0,1,0,0], [0,0,0,0], [0,0,1,0], [0,0,0,0], [0,0,0,1]]) TOFFOLI.dot(ZpY).dot(TOFFOLI).dot(Z1I4) ZpY = np.zeros([8,8]) ZpY[0,0] = 1; ZpY[1,2] = 1; ZpY[2,1] = 1; ZpY[3,3] = 1 ZpY[4,4] = 1; ZpY[5,6] = 1; ZpY[6,5] = 1; ZpY[7,7] = 1 ZpY Zfim = np.array([[1,0,1,0,1,0,1,0], [0,1,0,1,0,1,0,1]]) Zfim.dot(TOFFOLI).dot(ZpY).dot(TOFFOLI).dot(Z1I4) import numpy as np fred = np.identity(8) fred[5,5] = 0; fred[5,6] = 1 fred[6,5] = 1; fred[6,6] = 0 fred fred.dot(fred) import numpy as np Fy0 = np.zeros([8,4]) Fy0[0,0] = 1; Fy0[1,1] = 1; Fy0[4,2] = 1; Fy0[5,3] = 1 Fy0 xYz = np.array([[1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1]]) xYz.dot(fred).dot(Fy0) import numpy as np q0 = np.array([[1,0]]).T; q0 q1 = np.array([[0,1]]).T; q1 q01 = np.kron(q0,q1); q01 H = np.array([[1,1],[1,-1]])/np.sqrt(2); H H2 = np.kron(H,H); H2 H2.dot(q01) I4 = np.eye(4); I4 I4.dot(H2).dot(q01) I2 = np.eye(2); I2 HI2 = np.kron(H,I2); HI2 HI2.dot(I4).dot(H2).dot(q01) X = np.array([[0,1],[1,0]]); X I2 = np.eye(2); I2 I2X = np.kron(I2,X); I2X HI2.dot(I2X).dot(H2).dot(q01) CNOT = np.array([[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]]) CNOT HI2.dot(CNOT).dot(H2).dot(q01) X = np.array([[0,1],[1,0]]); X I2 = np.eye(2); I2 XI2 = np.kron(X,I2); XI2 CNOT = np.array([[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]]) CNOT CNOT.dot(XI2) HI2.dot(CNOT).dot(XI2).dot(H2).dot(q01) import qiskit as qk import numpy as np qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.h(0) qc.h(1) qc.barrier() qc.barrier() qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc, simulator).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk import numpy as np qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.h(0) qc.h(1) qc.barrier() qc.x(1) qc.barrier() qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc, simulator).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk import numpy as np qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.h(0) qc.h(1) qc.barrier() qc.cx(0,1) qc.barrier() qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc, simulator).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk import numpy as np qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.h(0) qc.h(1) qc.barrier() qc.x(0) qc.cx(0,1) qc.barrier() qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc, simulator).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qc = qk.QuantumCircuit(3,3) qc.barrier() qc.cnot(1,2) qc.barrier() qc.draw('mpl') import qiskit as qk qc = qk.QuantumCircuit(3,3) qc.initialize([0,0,0,0,1,0,0,0],[0,1,2]) qc.h([0,1,2]) qc.barrier() qc.cnot(1,2) qc.barrier() qc.h([0,1]) qc.measure([0,1],[0,1]) qc.draw('mpl') def histograma(qc): import qiskit as qk from qiskit.visualization import plot_histogram simulador = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulador,shots=10000).result().get_counts() grafico = plot_histogram(results) return(grafico) histograma(qc) import numpy as np x1 = np.array([[1,0]]).T x0 = np.array([[1,0]]).T y = np.array([[0,1]]).T psi0 = np.kron(y,np.kron(x1,x0)); psi0.T import numpy as np H = np.array([[1, 1], [1,-1]])/np.sqrt(2) H3 = np.kron(H,np.kron(H,H)); np.round(H3,3) psi0 = np.array([[0,0,0,0,1,0,0,0]]).T psi1 = H3.dot(psi0); psi1.T CNOTsm = np.array([[1,0,0,0], [0,0,0,1], [0,0,1,0], [0,1,0,0]]) I2 = np.array([[1,0], [0,1]]) CNOTsm_I2 = np.kron(CNOTsm,I2) psi0 = np.array([[0,0,0,0,1,0,0,0]]).T CNOTsm_I2.dot(H3).dot(psi0).T psi = np.array([[1,1,-1,-1]]).T/2 H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H2.dot(psi) import qiskit as qk qc = qk.QuantumCircuit(3,3) qc.initialize([0,0,0,0,1,0,0,0],[0,1,2]) qc.h([0,1,2]) qc.barrier() qc.cnot(0,2) qc.barrier() qc.h([0,1]) qc.measure([0,1],[0,1]) display(qc.draw('mpl')) histograma(qc) import numpy as np v0 = np.array([[0,0,0,0,1,0,0,0]]).T; v0.T H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H); H3 = np.kron(H2,H) H3.dot(v0).T CNOTs_I_m = np.array([[1,0,0,0,0,0,0,0], [0,0,0,0,0,1,0,0], [0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1], [0,0,0,0,1,0,0,0], [0,1,0,0,0,0,0,0], [0,0,0,0,0,0,1,0], [0,0,0,1,0,0,0,0]]) v0 = np.array([[0,0,0,0,1,0,0,0]]).T CNOTs_I_m.dot(H3).dot(v0).T psi = np.array([[+1,-1,+1,-1]]).T/2 H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H2.dot(psi) import qiskit as qk qc = qk.QuantumCircuit(3,3) qc.initialize([0,0,0,0,1,0,0,0],[0,1,2]) qc.h([0,1,2]) qc.barrier() qc.cnot(0,1) qc.cnot(1,2) qc.cnot(0,1) qc.barrier() qc.h([0,1]) qc.measure([0,1],[0,1]) display(qc.draw('mpl')) histograma(qc) v0 = np.array([[0,0,0,0,1,0,0,0]]).T H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H); H3 = np.kron(H2,H) H3.dot(v0).T CNOT_CNOT = np.array([[1,0,0,0,0,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1]]) v0 = np.array([[0,0,0,0,1,0,0,0]]).T H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H); H3 = np.kron(H2,H) CNOT_CNOT.dot(H3).dot(v0).T psi = np.array([[+1,-1,-1,+1]]).T/2 H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H2.dot(psi) import numpy as np CNOTsm = np.array([[1,0,0,0], [0,0,0,1], [0,0,1,0], [0,1,0,0]]) I = np.array([[1,0], [0,1]]) ISM = np.kron(I,CNOTsm) SMI = np.kron(CNOTsm,I) H = np.array([[1, 1], [1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H3 = np.kron(H2,H) IH2 = np.kron(I,H2) v0 = np.array([[0,0,0,0,1,0,0,0]]).T IH2.dot(ISM).dot(SMI).dot(ISM).dot(H3).dot(v0).round(3) CNOT_CNOT = np.array([[1,0,0,0,0,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1]]) ISM.dot(SMI).dot(ISM) import qiskit as qk from qiskit.quantum_info import Statevector from qiskit.visualization import plot_histogram qr = qk.QuantumRegister(3,'q') cr = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([0,1],2) qc.h(0) qc.h(1) qc.h(2) qc.barrier() qc.barrier() qc.h(0) qc.h(1) qc.measure(0,0) qc.measure(1,1) display(qc.draw('mpl')) histograma(qc) psi = np.array([[1,1,1,1]]).T/2 H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H2.dot(psi) import qiskit as qk from qiskit.quantum_info import Statevector from qiskit.visualization import plot_histogram qr = qk.QuantumRegister(3,'q') cr = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([0,1],2) qc.h(0) qc.h(1) qc.h(2) qc.barrier() qc.x(2) qc.barrier() qc.h(0) qc.h(1) qc.measure(0,0) qc.measure(1,1) display(qc.draw('mpl')) histograma(qc) psi = np.array([[1,1,1,1]]).T/2 H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H2.dot(psi) import qiskit as qk from qiskit.quantum_info import Statevector from qiskit.visualization import plot_histogram qr = qk.QuantumRegister(3,'q') cr = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([0,1],2) qc.h(0) qc.h(1) qc.h(2) qc.barrier() qc.ccx(0,1,2) qc.barrier() qc.h(0) qc.h(1) qc.measure(0,0) qc.measure(1,1) display(qc.draw('mpl')) histograma(qc) import qiskit as qk qrx = qk.QuantumRegister(2,'x') qry = qk.QuantumRegister(2,'y') qc = qk.QuantumCircuit(qrx,qry) qc.barrier() qc.cx(0,2) qc.cx(0,3) qc.cx(1,2) qc.cx(1,3) qc.barrier() qc.draw('mpl') def histograma(qc): simulador = qk.Aer.get_backend('statevector_simulator') resultado = qk.execute(qc,simulador,shots=10000).result() contagens = resultado.get_counts() grafico = qk.visualization.plot_histogram(contagens) return(grafico) def simon(initial_y, initial_x): import qiskit as qk qrx = qk.QuantumRegister(2,'x') crx = qk.ClassicalRegister(4,'c') qry = qk.QuantumRegister(2,'y') qc = qk.QuantumCircuit(qrx,qry,crx) qc.initialize(initial_x,qrx) qc.initialize(initial_y,qry) qc.barrier() qc.cx(0,2) qc.cx(0,3) qc.cx(1,2) qc.cx(1,3) qc.barrier() qc.measure([0,1,2,3],[0,1,2,3]) display(qc.draw('mpl')) grafico = histograma(qc) return(grafico) simon([1,0,0,0],[1,0,0,0]) simon([1,0,0,0],[0,0,0,1]) simon([1,0,0,0],[0,1,0,0]) simon([1,0,0,0],[0,0,1,0]) import qiskit as qk qrx = qk.QuantumRegister(2,'x') crx = qk.ClassicalRegister(2,'c') qry = qk.QuantumRegister(2,'y') qc = qk.QuantumCircuit(qrx,qry,crx) qc.initialize([1,0,0,0],qrx) qc.initialize([1,0,0,0],qry) qc.h([0,1]) qc.barrier() qc.cx(0,2) qc.cx(0,3) qc.cx(1,2) qc.cx(1,3) qc.barrier() qc.h([0,1]) qc.measure([0,1],[0,1]) display(qc.draw('mpl')) histograma(qc) import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T x1x0 = np.kron(x1,x0) y0 = np.array([[1,0]]).T y1 = np.array([[1,0]]).T y1y0 = np.kron(y1,y0) psi0 = np.kron(y1y0,x1x0) psi0.T H = np.array([[1,1],[1,-1]],dtype='int') H2 = np.kron(H,H) I2 = np.eye(4) I2H2 = np.kron(I2,H2) psi1 = I2H2.dot(psi0)/(np.sqrt(2)*np.sqrt(2)) I2H2.dot(psi0).T Tf1_2 = np.eye(16) Tf1_2 = Tf1_2[:,[0,5,2,7,4,1,6,3,8,9,10,11,12,13,14,15]] psi2 = Tf1_2.dot(psi1); psi2.T*2 Tf2_3 = np.eye(16) Tf2_3 = Tf2_3[:,[0,1,2,3,4,13,6,15,8,9,10,11,12,5,14,7]] psi3 = Tf2_3.dot(psi2); psi3.T*2 Tf3_4 = np.eye(16) Tf3_4 = Tf3_4[:,[0,1,6,3,4,5,2,7,8,9,10,15,12,13,14,11]] psi4 = Tf3_4.dot(psi3); psi4.T*2 Tf4_5 = np.eye(16) Tf4_5 = Tf4_5[:,[0,1,2,11,4,5,14,7,8,9,10,3,12,13,6,15]] psi5 = Tf4_5.dot(psi4); psi5.T*2 I2 = np.eye(4) H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) I2H2 = np.kron(I2,H2) psi6 = I2H2.dot(psi5) print(psi6.T*2) import numpy as np I2 = np.eye(4, dtype='int'); H2 = np.array([[1, 1, 1, 1], [1,-1, 1,-1], [1, 1,-1,-1], [1,-1,-1, 1]])/2; I2H2 = np.kron(I2,H2); print(I2H2*2) import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T x2 = np.array([[1,0]]).T x2x1x0 = np.kron(x2,np.kron(x1,x0)) x2x1x0.T y0 = np.array([[1,0]]).T y1 = np.array([[1,0]]).T y2 = np.array([[1,0]]).T y2y1y0 = np.kron(y2,np.kron(y1,y0)) y2y1y0.T psi0 = np.kron(y2y1y0,x2x1x0) psi0.T I3 = np.eye(2**3) H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H3 = np.kron(H,H2) I3H3 = np.kron(I3,H3) psi1 = I3H3.dot(psi0) psi1.T.round(2) n = 2*3 # 2 nรบmeros de 3 digitos cada Uf = np.eye(2**n) # 2^6 = 64 posiรงรตes Uf = Uf[:,[ 0, 9,18,27,12, 5,30,23, 8, 1,10,11, 4,13,14,15, 16,17, 2,19,20,21,22, 7, 24,25,26, 3,28,29, 6,31, 32,33,34,35,36,37,38,39, 40,41,42,43,44,45,46,47, 48,49,50,51,52,53,54,55, 56,57,58,59,60,61,62,63]] psi5 = Uf.dot(psi1) psi5.T.round(2) psi6 = I3H3.dot(psi5) psi6.T np.where(psi6 > 0)[0] [format(i,'#08b')[2:] for i in np.where(psi6 > 0)[0]] import numpy as np CCNOT = np.eye(8) CCNOT = CCNOT[:,[0,1,2,7,4,5,6,3]] CCNOT.dot(CCNOT) import qiskit as qk def qNAND(y0,x0): x = qk.QuantumRegister(1,"x") y = qk.QuantumRegister(1,"y") z = qk.QuantumRegister(1,"z") u = qk.QuantumRegister(1,"u") c = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(x,y,z,u,c) # Put qubits u and z in state |0> qc.initialize([1,0],z) qc.initialize([1,0],u) qc.initialize(y0,y) qc.initialize(x0,x) # Perform computation qc.barrier() qc.ccx(x,y,z) qc.x(z) # Copy CLASSICALY state of z to u qc.cx(z,u) qc.barrier() # Reverse computation qc.x(z) qc.ccx(x,y,z) qc.barrier() # Measure results qc.measure(x,c[0]) qc.measure(y,c[1]) qc.measure(u,c[2]) display(qc.draw('mpl')) simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc, simulator, shots=10000).result().get_counts() grafico = qk.visualization.plot_histogram(results) return(grafico) print("0 NAND 0 = 1") qNAND([1,0],[1,0]) print("0 NAND 1 = 1") qNAND([1,0],[0,1]) print("1 NAND 0 = 1") qNAND([0,1],[1,0]) print("1 NAND 1 = 0") qNAND([0,1],[0,1]) import qiskit as qk def qOR(y0,x0): x = qk.QuantumRegister(1,"x") y = qk.QuantumRegister(1,"y") z = qk.QuantumRegister(1,"z") u = qk.QuantumRegister(1,"u") c = qk.ClassicalRegister(3,'c') # Initialize qubits qc = qk.QuantumCircuit(x,y,z,u,c) qc.initialize(x0,x) qc.initialize(y0,y) qc.initialize([1,0],z) qc.initialize([1,0],u) # Compute function qc.barrier() qc.x(x) qc.x(y) qc.ccx(x,y,z) qc.x(z) qc.cx(z,u) qc.barrier() # Reverse computation qc.x(z) qc.ccx(x,y,z) qc.x(y) qc.x(x) qc.barrier() # Measure results qc.measure(x,c[0]) qc.measure(y,c[1]) qc.measure(u,c[2]) display(qc.draw('mpl')) # Simulate circuit simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() grafico = qk.visualization.plot_histogram(results) return(grafico) qOR([1,0],[1,0]) qOR([1,0],[0,1]) qOR([0,1],[1,0]) qOR([0,1],[0,1]) import qiskit as qk def qNXOR(y0,x0,calc=True,show=False): ################################################## # Create registers # ################################################## # Base registers x = qk.QuantumRegister(1,"x") y = qk.QuantumRegister(1,"y") # Auxiliary register (for x and y) z = qk.QuantumRegister(1,"z") # Auxiliary register (to store x AND y) a1 = qk.QuantumRegister(1,"a1") # Auxiliary register (to store NOT(x) AND NOT(y)) a2 = qk.QuantumRegister(1,"a2") # Auxiliary register (for a1 and a2) b1 = qk.QuantumRegister(1,"b1") # Auxiliary register (to store a1 OR a2) b2 = qk.QuantumRegister(1,"b2") # Classical Registers to store x,y and final measurement c = qk.ClassicalRegister(3,"c") ################################################## # Create Circuit # ################################################## qc = qk.QuantumCircuit(x,y,z,a1,a2,b1,b2,c) ################################################## # Initialize registers # ################################################## qc.initialize(x0,x) qc.initialize(y0,y) qc.initialize([1,0],z) qc.initialize([1,0],a1) qc.initialize([1,0],a2) qc.initialize([1,0],b1) qc.initialize([1,0],b2) ################################################### # Calculate x AND y. Copy result to a1. Reverse z # ################################################### qc.barrier() qc.ccx(x,y,z) qc.cx(z,a1) qc.ccx(x,y,z) qc.barrier() ######################################################### # Calc. NOT(x) AND NOT(y). Copy result to a2. Reverse z # ######################################################### qc.barrier() qc.x(x) qc.x(y) qc.ccx(x,y,z) qc.cx(z,a2) qc.ccx(x,y,z) qc.x(y) qc.x(x) qc.barrier() ################################################# # Calc. a1 OR a2. Copy result to b2. Reverse b1 # ################################################# qc.barrier() qc.x(a1) qc.x(a2) qc.ccx(a1,a2,b1) qc.x(b1) qc.cx(b1,b2) qc.x(b1) qc.ccx(a1,a2,b1) qc.barrier() ################################################# # Measure b2 # ################################################# qc.measure(x,c[0]) qc.measure(y,c[1]) qc.measure(b2,c[2]) ################################################# # Draw circuit # ################################################# if show: display(qc.draw("mpl")) ################################################# # Run circuit. Collect results # ################################################# if calc: simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc,simulator,shots=10000).result().get_counts() grafico = qk.visualization.plot_histogram(results) return(grafico) else: return() qNXOR([1,0],[1,0],False,True) qNXOR([1,0],[1,0]) qNXOR([1,0],[0,1]) qNXOR([0,1],[1,0]) qNXOR([0,1],[0,1]) x0 = np.array([1,1])/np.sqrt(2) y0 = np.array([1,1])/np.sqrt(2) qNXOR(y0,x0) import qiskit as qk from qiskit.quantum_info.operators import Operator qr = qk.QuantumRegister(6,"q") cr = qk.ClassicalRegister(6,"c") qc = qk.QuantumCircuit(qr,cr) for i in range(6): qc.initialize([1,0],i) for i in range(3): qc.h(i) oracle = np.eye(2**6) oracle[:,[ 0, 0]] = oracle[:,[ 0, 0]] oracle[:,[ 1, 9]] = oracle[:,[ 9, 1]] oracle[:,[ 2, 18]] = oracle[:,[ 18, 2]] oracle[:,[ 3, 27]] = oracle[:,[ 27, 3]] oracle[:,[ 4, 12]] = oracle[:,[ 12, 4]] oracle[:,[ 5, 5]] = oracle[:,[ 5, 5]] oracle[:,[ 6, 30]] = oracle[:,[ 30, 6]] oracle[:,[ 7, 23]] = oracle[:,[ 23, 7]] oracle = Operator(oracle) qc.append(oracle,qr) for i in range(3): qc.h(i) qc.barrier() for i in range(3): qc.measure(i,i) display(qc.draw("mpl")) simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np oracle = np.eye(8) oracle[:,[2,6]] = oracle[:,[6,2]] oracle import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T psi0 = np.kron(x1,x0) H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) psi1 = H2.dot(psi0) psi1.T # Initialize a qubit y in state |1> y = np.array([[0,1]]).T # Pass it through a Hadamard gate and obtain state psi2a H = np.array([[1,1],[1,-1]])/np.sqrt(2) psi2a = H.dot(y) psi2a.T psi2 = np.kron(psi2a,psi1) psi2.T oracle = np.eye(8) oracle[:,[2,6]] = oracle[:,[6,2]] oracle psi3 = oracle.dot(psi2) psi3.T v0 = np.array([[10,20,-30,40,50]]).T mu = np.mean(v0) v0.T, mu D = v0 - mu D.T v1 = 2*np.mean(v0)-v0 v1.T import numpy as np A = np.ones(5**2).reshape(5,5) A = A/5 I = np.eye(5) R = 2*A-I R R.dot(R) n = 4 I = np.eye(n) A = np.ones(n**2).reshape(n,n)/n R = 2*A-I R I2 = np.eye(2) I2R = np.kron(I2,R) I2R psi4 = I2R.dot(psi3) psi4.T import qiskit as qk import numpy as np from qiskit.quantum_info.operators import Operator q = qk.QuantumRegister(3,'q') c = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(q,c) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.h(1) qc.initialize([0,1],2) qc.h(2) qc.barrier() oracle = np.eye(8) oracle[:,[2,6]] = oracle[:,[6,2]] oracle = Operator(oracle) qc.append(oracle,q) # n = 2 (two digits number to look for) A = np.ones(4*4).reshape(4,4)/4 I4 = np.eye(4) R = 2*A - I4 I2 = np.eye(2) boost = np.kron(I2,R) boost = Operator(boost) qc.append(boost,q) qc.barrier() qc.measure(q[:2],c[:2]) display(qc.draw('mpl')) simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=1000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T x2 = np.array([[1,0]]).T x2x1x0 = np.kron(x2,np.kron(x1,x0)) x2x1x0.T H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H3 = np.kron(H,H2) x = H3.dot(x2x1x0) x.T y0 = np.array([[0,1]]).T y0.T H = np.array([[1,1],[1,-1]])/np.sqrt(2) y = H.dot(y0) y.T psi0 = np.kron(y,x) psi0.T oracle = np.eye(16) oracle[:,[5,13]] = oracle[:,[13,5]] psi1 = oracle.dot(psi0) psi1.T # n = 8 A = np.ones(8*8).reshape(8,8)/8 I8 = np.eye(8) R = 2*A-I8 R I2 = np.eye(2) I2R = np.kron(I2,R) psi2 = I2R.dot(psi1) psi2.T 0.625**2 + 0.625**2 psi3 = I2R.dot(oracle).dot(psi2) psi3.T 0.687**2 + 0.687**2 I2R.dot(oracle).dot(psi3).T T = I2R.dot(oracle) psi = psi1 prob = [] for i in range(25): prob.append(psi[5,0]**2 + psi[13,0]**2) psi = T.dot(psi) from matplotlib import pyplot as plt plt.plot(list(range(25)), prob); import qiskit as qk import numpy as np from qiskit.quantum_info.operators import Operator q = qk.QuantumRegister(4,'q') c = qk.ClassicalRegister(4,'c') qc = qk.QuantumCircuit(q,c) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([1,0],2) qc.h(0) qc.h(1) qc.h(2) qc.initialize([0,1],3) qc.h(3) qc.barrier() # Create oracle matrix oracle = np.eye(16) oracle[:,[5,13]] = oracle[:,[13,5]] # Create rotation about the mean matrix # n = 3 (three digits number to look for) A = np.ones(8*8).reshape(8,8)/8 I8 = np.eye(8) R = 2*A - I8 # Identity matrix to leave fourth qubit undisturbed I2 = np.eye(2) # Create second transformation matrix boost = np.kron(I2,R) # Combine oracle with second transformation matrix in # an unique operator T = boost.dot(oracle) T = Operator(T) # Apply operator twice (2 phase inversions and # rotations about the mean) qc.append(T,q) qc.append(T,q) qc.barrier() qc.measure(q[:3],c[:3]) display(qc.draw('mpl')) simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=1000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk import numpy as np from qiskit.quantum_info.operators import Operator q = qk.QuantumRegister(5,'q') c = qk.ClassicalRegister(5,'c') qc = qk.QuantumCircuit(q,c) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([1,0],2) qc.initialize([1,0],3) qc.h(0) qc.h(1) qc.h(2) qc.h(3) qc.initialize([0,1],4) qc.h(4) qc.barrier() # Create oracle matrix oracle = np.eye(32) oracle[:,[13,29]] = oracle[:,[29,13]] # Create rotation about the mean matrix # n = 4 (four digits number to look for) A = np.ones(16*16).reshape(16,16)/16 I16 = np.eye(16) R = 2*A - I16 # Identity matrix to leave fifth qubit undisturbed I2 = np.eye(2) # Create second transformation matrix boost = np.kron(I2,R) # Combine oracle with second transformation matrix in # an unique operator T = boost.dot(oracle) # n = 4. Therefore it will be necessary 4 T operations # to get maximum probability. Tn = T.dot(T).dot(T) Tn = Operator(Tn) # Apply operator Tn once (n phase inversions and # rotations about the mean) qc.append(Tn,q) qc.barrier() qc.measure(q[:4],c[:4]) display(qc.draw('mpl')) simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=1000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np import pandas as pd N = 35; a = 6 GCD = pd.DataFrame({'N':[N], 'a':[a], 'N-a':[N-a]}) while GCD.iloc[-1,2] != 0: temp = GCD.iloc[-1].values temp = np.sort(temp); temp[-1] = temp[-2] - temp[-3] temp = pd.DataFrame(data = temp.reshape(-1,3), columns = ['N','a','N-a']) GCD = GCD.append(temp, ignore_index=True) GCD import numpy as np import pandas as pd N = 15; a = 9 GCD = pd.DataFrame({'N':[N], 'a':[a], 'N-a':[N-a]}) while GCD.iloc[-1,2] != 0: temp = GCD.iloc[-1].values temp = np.sort(temp); temp[-1] = temp[-2] - temp[-3] temp = pd.DataFrame(data = temp.reshape(-1,3), columns = ['N','a','N-a']) GCD = GCD.append(temp, ignore_index=True) GCD import numpy as np np.gcd(6,35), np.gcd(9,15) import numpy as np np.gcd(215,35), np.gcd(217,35) 20 % 7 import numpy as np f = lambda x,a,N: a**x % N [f(x,2,15) for x in range(10)] import numpy as np (13*35)%11, ((2%11)*(24%11))%11 import numpy as np def f(x,a,N): a0 = 1 for i in range(x): a0 = ((a%N)*(a0))%N return(a0) [f(x,2,371) for x in range(8)] [f(x,2,371) for x in range(154,159)] [f(x,24,371) for x in range(77,81)] import numpy as np def fr(a,N): ax = ((a%N)*(1))%N x = 1 while ax != 1: ax = ((a%N)*(ax))%N x = x+1 return(x) fr(2,371), fr(6,371), fr(24,371) import numpy as np def fr(a,N): a0 = 1 a0 = ((a%N)*a0)%N x = 2 find = False while find==False: a0 = ((a%N)*(a0))%N if a0 == 1: find = True x = x+1 return(x-1) N = 35 a = 2 fr(a,N) 2**(12/2)-1, 2**(12/2)+1 np.gcd(63,35), np.gcd(65,35) import numpy as np # Function to calculate the period of f(x) = a^x MOD N def fr(a,N): a1 = ((a%N)*(1))%N x = 1 while a1 != 1: a1 = ((a%N)*a1)%N x = x+1 return(x) # Function to factor N based on a def factor(N, a=2): r = fr(a,N) g1 = a**(int(r/2)) - 1 g2 = a**(int(r/2)) + 1 f1 = np.gcd(g1,N) f2 = np.gcd(g2,N) return(f1,f2, f1*f2) factor(247) factor(1045) import numpy as np N = 15 # number to be factored n = 4 # number of bits necessary to represent N m = 8 # number of bits necessary to represent N^2 x = np.zeros(2**m).reshape(-1,1) x[0,0] = 1 x.shape # since x is a 2^8 = 256 positions vector it will not be showed here y = np.zeros(2**n).reshape(-1,1) y[0,0] = 1; y.T # y is a 2^4 = 16 positions vector shown below psi0 = np.kron(y,x) psi0.shape # psi0 is a 256 x 16 = 4.096 positions vector In = np.eye(2**n); In.shape H = np.array([[1,1],[1,-1]])/np.sqrt(2) Hm = H.copy() for i in range(1,m): Hm = np.kron(Hm,H) Hm.shape psi1 = np.kron(In,Hm).dot(psi0); psi1.shape
https://github.com/Heisenbug-s-Dog/qnn_visualization
Heisenbug-s-Dog
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. pip install tensorflow==1.5.1 !pip -q install lucid>=0.3.8 !pip -q install umap-learn>=0.3.7 # General support import math import tensorflow as tf import numpy as np # For plots import matplotlib.pyplot as plt # Dimensionality reduction import umap from sklearn.manifold import TSNE # General lucid code from lucid.misc.io import save, show, load import lucid.modelzoo.vision_models as models # For rendering feature visualizations import lucid.optvis.objectives as objectives import lucid.optvis.param as param import lucid.optvis.render as render import lucid.optvis.transform as transform model = models.InceptionV1() model.load_graphdef() # model.layers[7] is "mixed4c" layer = "mixed4c" print(model.layers[7]) raw_activations = model.layers[7].activations activations = raw_activations[:100000] print(activations.shape) def whiten(full_activations): correl = np.matmul(full_activations.T, full_activations) / len(full_activations) correl = correl.astype("float32") S = np.linalg.inv(correl) S = S.astype("float32") return S S = whiten(raw_activations) def normalize_layout(layout, min_percentile=1, max_percentile=99, relative_margin=0.1): """Removes outliers and scales layout to between [0,1].""" # compute percentiles mins = np.percentile(layout, min_percentile, axis=(0)) maxs = np.percentile(layout, max_percentile, axis=(0)) # add margins mins -= relative_margin * (maxs - mins) maxs += relative_margin * (maxs - mins) # `clip` broadcasts, `[None]`s added only for readability clipped = np.clip(layout, mins, maxs) # embed within [0,1] along both axes clipped -= clipped.min(axis=0) clipped /= clipped.max(axis=0) return clipped layout = umap.UMAP(n_components=2, verbose=True, n_neighbors=20, min_dist=0.01, metric="cosine").fit_transform(activations) ## You can optionally use TSNE as well # layout = TSNE(n_components=2, verbose=True, metric="cosine", learning_rate=10, perplexity=50).fit_transform(d) layout = normalize_layout(layout) plt.figure(figsize=(10, 10)) plt.scatter(x=layout[:,0],y=layout[:,1], s=2) plt.show() # # Whitened, euclidean neuron objective # @objectives.wrap_objective def direction_neuron_S(layer_name, vec, batch=None, x=None, y=None, S=None): def inner(T): layer = T(layer_name) shape = tf.shape(layer) x_ = shape[1] // 2 if x is None else x y_ = shape[2] // 2 if y is None else y if batch is None: raise RuntimeError("requires batch") acts = layer[batch, x_, y_] vec_ = vec if S is not None: vec_ = tf.matmul(vec_[None], S)[0] # mag = tf.sqrt(tf.reduce_sum(acts**2)) dot = tf.reduce_mean(acts * vec_) # cossim = dot/(1e-4 + mag) return dot return inner # # Whitened, cosine similarity objective # @objectives.wrap_objective def direction_neuron_cossim_S(layer_name, vec, batch=None, x=None, y=None, cossim_pow=1, S=None): def inner(T): layer = T(layer_name) shape = tf.shape(layer) x_ = shape[1] // 2 if x is None else x y_ = shape[2] // 2 if y is None else y if batch is None: raise RuntimeError("requires batch") acts = layer[batch, x_, y_] vec_ = vec if S is not None: vec_ = tf.matmul(vec_[None], S)[0] mag = tf.sqrt(tf.reduce_sum(acts**2)) dot = tf.reduce_mean(acts * vec_) cossim = dot/(1e-4 + mag) cossim = tf.maximum(0.1, cossim) return dot * cossim ** cossim_pow return inner # # Renders a batch of activations as icons # def render_icons(directions, model, layer, size=80, n_steps=128, verbose=False, S=None, num_attempts=2, cossim=True, alpha=True): image_attempts = [] loss_attempts = [] # Render multiple attempts, and pull the one with the lowest loss score. for attempt in range(num_attempts): # Render an image for each activation vector param_f = lambda: param.image(size, batch=directions.shape[0], fft=True, decorrelate=True, alpha=alpha) if(S is not None): if(cossim is True): obj_list = ([ direction_neuron_cossim_S(layer, v, batch=n, S=S, cossim_pow=4) for n,v in enumerate(directions) ]) else: obj_list = ([ direction_neuron_S(layer, v, batch=n, S=S) for n,v in enumerate(directions) ]) else: obj_list = ([ objectives.direction_neuron(layer, v, batch=n) for n,v in enumerate(directions) ]) obj = objectives.Objective.sum(obj_list) transforms = [] if alpha: transforms.append(transform.collapse_alpha_random()) transforms.append(transform.pad(2, mode='constant', constant_value=1)) transforms.append(transform.jitter(4)) transforms.append(transform.jitter(4)) transforms.append(transform.jitter(8)) transforms.append(transform.jitter(8)) transforms.append(transform.jitter(8)) transforms.append(transform.random_scale([0.995**n for n in range(-5,80)] + [0.998**n for n in 2*list(range(20,40))])) transforms.append(transform.random_rotate(list(range(-20,20))+list(range(-10,10))+list(range(-5,5))+5*[0])) transforms.append(transform.jitter(2)) # This is the tensorflow optimization process. # We can't use the lucid helpers here because we need to know the loss. print("attempt: ", attempt) with tf.Graph().as_default(), tf.Session() as sess: learning_rate = 0.05 losses = [] trainer = tf.train.AdamOptimizer(learning_rate) T = render.make_vis_T(model, obj, param_f, trainer, transforms) loss_t, vis_op, t_image = T("loss"), T("vis_op"), T("input") losses_ = [obj_part(T) for obj_part in obj_list] tf.global_variables_initializer().run() for i in range(n_steps): loss, _ = sess.run([losses_, vis_op]) losses.append(loss) if (i % 100 == 0): print(i) img = t_image.eval() img_rgb = img[:,:,:,:3] if alpha: print("alpha true") k = 0.8 bg_color = 0.0 img_a = img[:,:,:,3:] img_merged = img_rgb*((1-k)+k*img_a) + bg_color * k*(1-img_a) image_attempts.append(img_merged) else: print("alpha false") image_attempts.append(img_rgb) loss_attempts.append(losses[-1]) # Use the icon with the lowest loss loss_attempts = np.asarray(loss_attempts) loss_final = [] image_final = [] print("Merging best scores from attempts...") for i, d in enumerate(directions): # note, this should be max, it is not a traditional loss mi = np.argmax(loss_attempts[:,i]) image_final.append(image_attempts[mi][i]) return (image_final, loss_final) # # Takes a list of x,y layout and bins them into grid cells # def grid(xpts=None, ypts=None, grid_size=(8,8), x_extent=(0., 1.), y_extent=(0., 1.)): xpx_length = grid_size[0] ypx_length = grid_size[1] xpt_extent = x_extent ypt_extent = y_extent xpt_length = xpt_extent[1] - xpt_extent[0] ypt_length = ypt_extent[1] - ypt_extent[0] xpxs = ((xpts - xpt_extent[0]) / xpt_length) * xpx_length ypxs = ((ypts - ypt_extent[0]) / ypt_length) * ypx_length ix_s = range(grid_size[0]) iy_s = range(grid_size[1]) xs = [] for xi in ix_s: ys = [] for yi in iy_s: xpx_extent = (xi, (xi + 1)) ypx_extent = (yi, (yi + 1)) in_bounds_x = np.logical_and(xpx_extent[0] <= xpxs, xpxs <= xpx_extent[1]) in_bounds_y = np.logical_and(ypx_extent[0] <= ypxs, ypxs <= ypx_extent[1]) in_bounds = np.logical_and(in_bounds_x, in_bounds_y) in_bounds_indices = np.where(in_bounds)[0] ys.append(in_bounds_indices) xs.append(ys) return np.asarray(xs) def render_layout(model, layer, S, xs, ys, activ, n_steps=512, n_attempts=2, min_density=10, grid_size=(10, 10), icon_size=80, x_extent=(0., 1.0), y_extent=(0., 1.0)): grid_layout = grid(xpts=xs, ypts=ys, grid_size=grid_size, x_extent=x_extent, y_extent=y_extent) icons = [] for x in range(grid_size[0]): for y in range(grid_size[1]): indices = grid_layout[x, y] if len(indices) > min_density: average_activation = np.average(activ[indices], axis=0) icons.append((average_activation, x, y)) icons = np.asarray(icons) icon_batch, losses = render_icons(icons[:,0], model, alpha=False, layer=layer, S=S, n_steps=n_steps, size=icon_size, num_attempts=n_attempts) canvas = np.ones((icon_size * grid_size[0], icon_size * grid_size[1], 3)) for i, icon in enumerate(icon_batch): y = int(icons[i, 1]) x = int(icons[i, 2]) canvas[(grid_size[0] - x - 1) * icon_size:(grid_size[0] - x) * icon_size, (y) * icon_size:(y + 1) * icon_size] = icon return canvas # # Given a layout, renders an icon for the average of all the activations in each grid cell. # xs = layout[:, 0] ys = layout[:, 1] canvas = render_layout(model, layer, S, xs, ys, raw_activations, n_steps=512, grid_size=(20, 20), n_attempts=1) show(canvas)
https://github.com/Heisenbug-s-Dog/qnn_visualization
Heisenbug-s-Dog
from google.colab import drive drive.mount('/content/drive') !pip install torch==1.3.1 !pip install torchvision==0.4.2 !pip install Pillow==6.2.1 !pip install pennylane==0.7.0 # OpenMP: number of parallel threads. %env OMP_NUM_THREADS=1 # Plotting %matplotlib inline import matplotlib.pyplot as plt # PyTorch import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import torchvision from torchvision import datasets, models, transforms # Pennylane import pennylane as qml from pennylane import numpy as np # Other tools import time import copy filtered_classes = ['cat', 'dog'] # Subset of CIFAR ('plane', 'car', 'bird', 'cat','deer', 'dog', 'frog', 'horse', 'ship', 'truck') n_qubits = 4 # Number of qubits quantum = False # If set to "False", the dressed quantum circuit is replaced by # An enterily classical net (defined by the next parameter). classical_model = '512_nq_n' # Possible choices: '512_n','512_nq_n','551_512_n'. [nq=n_qubits, n=num_filtered_classes] step = 0.001 # Learning rate batch_size = 8 # Number of samples for each training step num_epochs = 3 # Number of training epochs q_depth = 5 # Depth of the quantum circuit (number of variational layers) gamma_lr_scheduler = 1 # Learning rate reduction applied every 10 epochs. max_layers = 15 # Keep 15 even if not all are used. q_delta = 0.01 # Initial spread of random quantum weights rng_seed = 0 # Seed for random number generator start_time = time.time() # start of the computation timer ''' filtered_classes = ['plane', 'car'] # Subset of CIFAR ('plane', 'car', 'bird', 'cat','deer', 'dog', 'frog', 'horse', 'ship', 'truck') n_qubits = 4 # Number of qubits quantum = True # If set to "False", the dressed quantum circuit is replaced by # An enterily classical net (defined by the next parameter). classical_model = '512_n' # Possible choices: '512_n','512_nq_n','551_512_n'. [nq=n_qubits, n=num_filtered_classes] step = 0.0007 # Learning rate batch_size = 8 # Number of samples for each training step num_epochs = 3 # Number of training epochs q_depth = 4 # Depth of the quantum circuit (number of variational layers) gamma_lr_scheduler = 0.1 # Learning rate reduction applied every 3 epochs. max_layers = 15 # Keep 15 even if not all are used. q_delta = 0.01 # Initial spread of random quantum weights rng_seed = 0 # Seed for random number generator start_time = time.time() # Start of the computation timer ''' dev = qml.device('default.qubit', wires=n_qubits) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Fixed pre-processing operations data_transforms = { 'train': transforms.Compose([ #transforms.RandomResizedCrop(224), # uncomment for data augmentation #transforms.RandomHorizontalFlip(), # uncomment for data augmentation transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), # Normalize input channels using mean values and standard deviations of ImageNet. transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]), 'val': transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]), } # =================== begin CIFAR dataset loading =================== trainset_full = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=data_transforms['train']) testset_full = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=data_transforms['val']) image_datasets_full={'train': trainset_full, 'val': testset_full} # CIFAR classes class_names = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') # Get indices of samples associated to filtered_classes filtered_labels=[class_names.index(cl) for cl in filtered_classes] sub_indices={'train': [], 'val': []} for phase in ['train', 'val']: for idx, label in enumerate(image_datasets_full[phase].targets): if label in filtered_labels: sub_indices[phase].append(idx) # Initialize sub-datasets according to filtered indices image_datasets = {x: torch.utils.data.Subset(image_datasets_full[x], sub_indices[x]) for x in ['train', 'val']} def labels_to_filtered(labels): """Maps CIFAR labels (0,1,2,3,4,5,6,7,8,9) to the index of filtered_labels""" return [filtered_labels.index(label) for label in labels] # =================== end CIFAR dataset loading ========================== # Number of samples dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']} # Initialize dataloader dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=batch_size, shuffle=True, num_workers=0) for x in ['train', 'val']} # Function to plot images from tensors def imshow(inp, title=None): """Imshow for Tensor.""" inp = inp.numpy().transpose((1, 2, 0)) # We apply the inverse of the initial normalization operation. mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) inp = std * inp + mean inp = np.clip(inp, 0, 1) plt.imshow(inp) if title is not None: plt.title(title) # Get a batch of training data inputs, classes = next(iter(dataloaders['val'])) # Make a grid from batch out = torchvision.utils.make_grid(inputs) imshow(out, title=[class_names[x] for x in classes]) torch.manual_seed(rng_seed) dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=batch_size, shuffle=True, num_workers=0) for x in ['train', 'val']} def H_layer(nqubits): """Layer of single-qubit Hadamard gates. """ for idx in range(nqubits): qml.Hadamard(wires=idx) def RY_layer(w): """Layer of parametrized qubit rotations around the y axis. """ for idx, element in enumerate(w): qml.RY(element, wires=idx) def entangling_layer(nqubits): """Layer of CNOTs followed by another shifted layer of CNOT. """ # In other words it should apply something like : # CNOT CNOT CNOT CNOT... CNOT # CNOT CNOT CNOT... CNOT for i in range(0, nqubits - 1, 2): # Loop over even indices: i=0,2,...N-2 qml.CNOT(wires=[i, i + 1]) for i in range(1, nqubits - 1,2): # Loop over odd indices: i=1,3,...N-3 qml.CNOT(wires=[i, i + 1]) @qml.qnode(dev, interface='torch') def q_net(q_in, q_weights_flat): # Reshape weights q_weights = q_weights_flat.reshape(max_layers, n_qubits) # Start from state |+> , unbiased w.r.t. |0> and |1> H_layer(n_qubits) # Embed features in the quantum node RY_layer(q_in) # Sequence of trainable variational layers for k in range(q_depth): entangling_layer(n_qubits) RY_layer(q_weights[k+1]) # Expectation values in the Z basis return [qml.expval(qml.PauliZ(j)) for j in range(n_qubits)] class Quantumnet(nn.Module): def __init__(self): super().__init__() self.pre_net = nn.Linear(512, n_qubits) self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits)) self.post_net = nn.Linear(n_qubits, len(filtered_classes)) def forward(self, input_features): pre_out = self.pre_net(input_features) q_in = torch.tanh(pre_out) * np.pi / 2.0 # Apply the quantum circuit to each element of the batch, and append to q_out q_out = torch.Tensor(0, n_qubits) q_out = q_out.to(device) for elem in q_in: q_out_elem = q_net(elem,self.q_params).float().unsqueeze(0) q_out = torch.cat((q_out, q_out_elem)) return self.post_net(q_out) model_hybrid = torchvision.models.resnet18(pretrained=True) for param in model_hybrid.parameters(): param.requires_grad = False if quantum: model_hybrid.fc = Quantumnet() elif classical_model == '512_n': model_hybrid.fc = nn.Linear(512,len(filtered_classes)) elif classical_model == '512_nq_n': model_hybrid.fc = nn.Sequential(nn.Linear(512, n_qubits),torch.nn.ReLU(),nn.Linear(n_qubits, len(filtered_classes))) elif classical_model == '551_512_n': model_hybrid.fc = nn.Sequential(nn.Linear(512, 512), torch.nn.ReLU(), nn.Linear(512, len(filtered_classes))) # Use CUDA or CPU according to the "device" object. model_hybrid = model_hybrid.to(device) criterion = nn.CrossEntropyLoss() optimizer_hybrid = optim.Adam(model_hybrid.fc.parameters(), lr=step) exp_lr_scheduler = lr_scheduler.StepLR(optimizer_hybrid, step_size=3, gamma=gamma_lr_scheduler) def train_model(model, criterion, optimizer, scheduler, num_epochs): since = time.time() best_model_wts = copy.deepcopy(model.state_dict()) best_acc = 0.0 best_loss = 10000.0 # Large arbitrary number best_acc_train = 0.0 best_loss_train = 10000.0 # Large arbitrary number print('Training started:') for epoch in range(num_epochs): # Each epoch has a training and validation phase for phase in ['train', 'val']: if phase == 'train': # Set model to training mode scheduler.step() model.train() else: # Set model to evaluate mode model.eval() # Iteration loop running_loss = 0.0 running_corrects = 0 n_batches = dataset_sizes[phase] // batch_size it = 0 for inputs, cifar_labels in dataloaders[phase]: since_batch = time.time() batch_size_ = len(inputs) inputs = inputs.to(device) labels = torch.tensor(labels_to_filtered(cifar_labels)) labels = labels.to(device) optimizer.zero_grad() # Track/compute gradient and make an optimization step only when training with torch.set_grad_enabled(phase == 'train'): outputs = model(inputs) _, preds = torch.max(outputs, 1) loss = criterion(outputs, labels) if phase == 'train': loss.backward() optimizer.step() # Print iteration results running_loss += loss.item() * batch_size_ batch_corrects = torch.sum(preds == labels.data).item() running_corrects += batch_corrects print('Phase: {} Epoch: {}/{} Iter: {}/{} Batch time: {:.4f}'.format(phase, epoch + 1, num_epochs, it + 1, n_batches + 1, time.time() - since_batch), end='\r', flush=True) it += 1 # Print epoch results epoch_loss = running_loss / dataset_sizes[phase] epoch_acc = running_corrects / dataset_sizes[phase] print('Phase: {} Epoch: {}/{} Loss: {:.4f} Acc: {:.4f} '.format('train' if phase == 'train' else 'val ', epoch + 1, num_epochs, epoch_loss, epoch_acc)) # Check if this is the best model wrt previous epochs if phase == 'val' and epoch_acc > best_acc: best_acc = epoch_acc best_model_wts = copy.deepcopy(model.state_dict()) if phase == 'val' and epoch_loss < best_loss: best_loss = epoch_loss if phase == 'train' and epoch_acc > best_acc_train: best_acc_train = epoch_acc if phase == 'train' and epoch_loss < best_loss_train: best_loss_train = epoch_loss # Print final results model.load_state_dict(best_model_wts) time_elapsed = time.time() - since print('Training completed in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60)) print('Best test loss: {:.4f} | Best test accuracy: {:.4f}'.format(best_loss, best_acc)) return model model_hybrid = train_model(model_hybrid, criterion, optimizer_hybrid, exp_lr_scheduler, num_epochs=num_epochs) path = '/content/drive/MyDrive/Qiskit-Hackathon-Korea/qnn-visualization/' if quantum: torch.save(model_hybrid.state_dict(), path+'quantum_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt' ) else: torch.save(model_hybrid.state_dict(), path+'classical_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt' ) print("Model state_dict saved.") if quantum: model_hybrid.load_state_dict(torch.load( path+'quantum_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt' ) ) else: model_hybrid.load_state_dict(torch.load( path+'classical_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt' ) ) criterion = nn.CrossEntropyLoss() running_loss = 0.0 running_corrects = 0 n_batches = dataset_sizes['val'] // batch_size it = 0 model_hybrid.eval() # Testing loop for inputs, cifar_labels in dataloaders['val']: inputs = inputs.to(device) labels = torch.tensor(labels_to_filtered(cifar_labels)) labels = labels.to(device) batch_size_ = len(inputs) with torch.set_grad_enabled(False): outputs = model_hybrid(inputs) _, preds = torch.max(outputs, 1) loss = criterion(outputs, labels) running_loss += loss.item() * batch_size_ batch_corrects = torch.sum(preds == labels.data).item() running_corrects += batch_corrects print('Iter: {}/{}'.format(it+1,n_batches+1), end='\r', flush=True) it += 1 # Print final results epoch_loss = running_loss / dataset_sizes['val'] epoch_acc = running_corrects / dataset_sizes['val'] print('\nTest Loss: {:.4f} Test Acc: {:.4f} '.format(epoch_loss, epoch_acc)) def visualize_model(model, num_images=6, fig_name='Predictions'): images_so_far = 0 fig = plt.figure(fig_name) model.eval() with torch.no_grad(): for i, (inputs, cifar_labels) in enumerate(dataloaders['val']): inputs = inputs.to(device) labels = torch.tensor(labels_to_filtered(cifar_labels)) labels = labels.to(device) outputs = model(inputs) _, preds = torch.max(outputs, 1) for j in range(inputs.size()[0]): images_so_far += 1 ax = plt.subplot(num_images // 2, 2, images_so_far) ax.axis('off') ax.set_title('[{}]'.format(filtered_classes[preds[j]])) imshow(inputs.cpu().data[j]) if images_so_far == num_images: return visualize_model(model_hybrid, num_images=4)
https://github.com/Heisenbug-s-Dog/qnn_visualization
Heisenbug-s-Dog
from google.colab import drive drive.mount('/content/drive') !pip install torch==1.3.1 !pip install torchvision==0.4.2 !pip install Pillow==6.2.1 !pip install pennylane==0.7.0 # OpenMP: number of parallel threads. %env OMP_NUM_THREADS=1 # Plotting %matplotlib inline import matplotlib.pyplot as plt # PyTorch import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import torchvision from torchvision import datasets, models, transforms # Pennylane import pennylane as qml from pennylane import numpy as np # Other tools import time import copy filtered_classes = ['cat', 'dog'] # Subset of CIFAR ('plane', 'car', 'bird', 'cat','deer', 'dog', 'frog', 'horse', 'ship', 'truck') n_qubits = 4 # Number of qubits quantum = True # If set to "False", the dressed quantum circuit is replaced by # An enterily classical net (defined by the next parameter). classical_model = '512_n' # Possible choices: '512_n','512_nq_n','551_512_n'. [nq=n_qubits, n=num_filtered_classes] step = 0.001 # Learning rate batch_size = 8 # Number of samples for each training step num_epochs = 3 # Number of training epochs q_depth = 5 # Depth of the quantum circuit (number of variational layers) gamma_lr_scheduler = 1 # Learning rate reduction applied every 10 epochs. max_layers = 15 # Keep 15 even if not all are used. q_delta = 0.01 # Initial spread of random quantum weights rng_seed = 0 # Seed for random number generator start_time = time.time() # start of the computation timer torch.manual_seed(rng_seed) dev = qml.device('default.qubit', wires=n_qubits) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") def H_layer(nqubits): """Layer of single-qubit Hadamard gates. """ for idx in range(nqubits): qml.Hadamard(wires=idx) def RY_layer(w): """Layer of parametrized qubit rotations around the y axis. """ for idx, element in enumerate(w): qml.RY(element, wires=idx) def entangling_layer(nqubits): """Layer of CNOTs followed by another shifted layer of CNOT. """ # In other words it should apply something like : # CNOT CNOT CNOT CNOT... CNOT # CNOT CNOT CNOT... CNOT for i in range(0, nqubits - 1, 2): # Loop over even indices: i=0,2,...N-2 qml.CNOT(wires=[i, i + 1]) for i in range(1, nqubits - 1,2): # Loop over odd indices: i=1,3,...N-3 qml.CNOT(wires=[i, i + 1]) @qml.qnode(dev, interface='torch') def q_net(q_in, q_weights_flat): # Reshape weights q_weights = q_weights_flat.reshape(max_layers, n_qubits) # Start from state |+> , unbiased w.r.t. |0> and |1> H_layer(n_qubits) # Embed features in the quantum node RY_layer(q_in) # Sequence of trainable variational layers for k in range(q_depth): entangling_layer(n_qubits) RY_layer(q_weights[k+1]) # Expectation values in the Z basis return [qml.expval(qml.PauliZ(j)) for j in range(n_qubits)] class Quantumnet(nn.Module): def __init__(self): super().__init__() self.pre_net = nn.Linear(512, n_qubits) self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits)) self.post_net = nn.Linear(n_qubits, len(filtered_classes)) def forward(self, input_features): pre_out = self.pre_net(input_features) q_in = torch.tanh(pre_out) * np.pi / 2.0 # Apply the quantum circuit to each element of the batch, and append to q_out q_out = torch.Tensor(0, n_qubits) q_out = q_out.to(device) for elem in q_in: q_out_elem = q_net(elem,self.q_params).float().unsqueeze(0) q_out = torch.cat((q_out, q_out_elem)) return self.post_net(q_out) class Quantumnet_Cut(nn.Module): def __init__(self): super().__init__() self.pre_net = nn.Linear(512, n_qubits) self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits)) def forward(self, input_features): pre_out = self.pre_net(input_features) q_in = torch.tanh(pre_out) * np.pi / 2.0 # Apply the quantum circuit to each element of the batch, and append to q_out q_out = torch.Tensor(0, n_qubits) q_out = q_out.to(device) for elem in q_in: q_out_elem = q_net(elem,self.q_params).float().unsqueeze(0) q_out = torch.cat((q_out, q_out_elem)) return q_out class Quantumnet_Classical_Cut(nn.Module): def __init__(self): super().__init__() self.pre_net = nn.Linear(512, n_qubits) self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits)) def forward(self, input_features): pre_out = self.pre_net(input_features) q_in = torch.tanh(pre_out) * np.pi / 2.0 return q_in model = torchvision.models.resnet18(pretrained=True) model.fc = Quantumnet() for param in model.parameters(): param.requires_grad = False # Use CUDA or CPU according to the "device" object. model = model.to(device) model_cut = torchvision.models.resnet18(pretrained=True) model_cut.fc = Quantumnet_Cut() for param in model_cut.parameters(): param.requires_grad = False # Use CUDA or CPU according to the "device" object. model_cut = model_cut.to(device) model_classical_cut = torchvision.models.resnet18(pretrained=True) model_classical_cut.fc = Quantumnet_Classical_Cut() for param in model_classical_cut.parameters(): param.requires_grad = False # Use CUDA or CPU according to the "device" object. model_classical_cut = model_classical_cut.to(device) # Load model from file path = '/content/drive/MyDrive/Qiskit-Hackathon-Korea/qnn-visualization/' if quantum: model.load_state_dict(torch.load( path+'quantum_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt' ) ) else: model.load_state_dict(torch.load( path+'classical_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt' ) ) model_dict = model.state_dict() model_cut_dict = model_cut.state_dict() model_cut_dict = {k: v for k, v in model_dict.items() if k in model_cut_dict} model_cut.load_state_dict(model_cut_dict) model_classical_cut_dict = model_classical_cut.state_dict() model_classical_cut_dict = {k: v for k, v in model_dict.items() if k in model_classical_cut_dict} model_classical_cut.load_state_dict(model_classical_cut_dict) def dream(image, model, iterations, lr): """ Updates the image to maximize outputs for n iterations """ Tensor = torch.cuda.FloatTensor if torch.cuda.is_available else torch.FloatTensor image = preprocess(image).unsqueeze(0).cpu().data.numpy() image = Variable(Tensor(image), requires_grad=True) for i in range(iterations): model.zero_grad() out = model(image) loss = out.norm() if i % 10 == 0: print('iter: {}/{}, loss: {}'.format(i+1, iterations, loss.item())) loss.backward() avg_grad = np.abs(image.grad.data.cpu().numpy()).mean() norm_lr = lr / avg_grad image.data += norm_lr * image.grad.data image.data = clip(image.data) image.grad.data.zero_() return image.cpu().data.numpy() def diff_dream(image, model1, model2, iterations, lr): """ Updates the image to maximize outputs for n iterations """ Tensor = torch.cuda.FloatTensor if torch.cuda.is_available else torch.FloatTensor image = preprocess(image).unsqueeze(0).cpu().data.numpy() image = Variable(Tensor(image), requires_grad=True) for i in range(iterations): model1.zero_grad() model2.zero_grad() out1 = model1(image) out2 = model2(image) loss = out1.norm() / np.sqrt(np.prod(out1.shape)) - out2.norm() / np.sqrt(np.prod(out2.shape)) if i % 10 == 0: print('iter: {}/{}, loss: {}'.format(i+1, iterations, loss.item())) loss.backward() avg_grad = np.abs(image.grad.data.cpu().numpy()).mean() norm_lr = lr / avg_grad image.data += norm_lr * image.grad.data image.data = clip(image.data) image.grad.data.zero_() return image.cpu().data.numpy() def deep_dream(image, model, iterations, lr, octave_scale, num_octaves): """ Main deep dream method """ image = preprocess(image).unsqueeze(0).cpu().data.numpy() # Extract image representations for each octave octaves = [image] for _ in range(num_octaves - 1): octaves.append(nd.zoom(octaves[-1], (1, 1, 1 / octave_scale, 1 / octave_scale), order=1)) detail = np.zeros_like(octaves[-1]) for octave, octave_base in enumerate(tqdm.tqdm(octaves[::-1], desc="Dreaming")): if octave > 0: # Upsample detail to new octave dimension detail = nd.zoom(detail, np.array(octave_base.shape) / np.array(detail.shape), order=1) # Add deep dream detail from previous octave to new base input_image = octave_base + detail # Get new deep dream image dreamed_image = dream(input_image, model, iterations, lr) # Extract deep dream details detail = dreamed_image - octave_base return deprocess(dreamed_image) mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) #preprocess = transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean, std)]) preprocess = transforms.Compose([transforms.ToTensor()]) def deprocess(image_np): image_np = image_np.squeeze().transpose(1, 2, 0) image_np = image_np * std.reshape((1, 1, 3)) + mean.reshape((1, 1, 3)) image_np = np.clip(image_np, 0.0, 255.0) return image_np def clip(image_tensor): for c in range(3): m, s = mean[c], std[c] image_tensor[0, c] = torch.clamp(image_tensor[0, c], -m / s, (1 - m) / s) return image_tensor from PIL import Image import scipy.ndimage as nd from torch.autograd import Variable import tqdm, os # Load image image = Image.open("/content/drive/MyDrive/Qiskit-Hackathon-Korea/qnn-visualization/images/dog.jpg") # Set Models #network = model #layers = list(network.children()) #classical_model = nn.Sequential(*layers[: 9]) #Max: 9 classical_model = model_classical_cut quantum_model = model_cut # Extract deep dream image dreamed_image = dream( image, quantum_model, iterations=1000, lr=0.01 ) dreamed_image = np.transpose(dreamed_image, (0,2,3,1)) dreamed_image = dreamed_image[0] # Save and plot image #os.makedirs("outputs", exist_ok=True) #filename = 'test' plt.figure(figsize=(20, 20)) plt.imshow(dreamed_image) #plt.imsave(f"outputs/output_{filename}", dreamed_image) plt.show() quantum_dreamed_image = diff_dream( image, quantum_model, classical_model, iterations=1000, lr=0.01 ) dreamed_image = quantum_dreamed_image dreamed_image = np.transpose(dreamed_image, (0,2,3,1)) dreamed_image = dreamed_image[0] # Save and plot image #os.makedirs("outputs", exist_ok=True) #filename = 'test' plt.figure(figsize=(20, 20)) plt.imshow(dreamed_image) #plt.imsave(f"outputs/output_{filename}", dreamed_image) plt.show() classical_dreamed_image = diff_dream( image, classical_model, quantum_model, iterations=1000, lr=0.01 ) dreamed_image = classical_dreamed_image dreamed_image = np.transpose(dreamed_image, (0,2,3,1)) dreamed_image = dreamed_image[0] # Save and plot image #os.makedirs("outputs", exist_ok=True) #filename = 'test' plt.figure(figsize=(20, 20)) plt.imshow(dreamed_image) #plt.imsave(f"outputs/output_{filename}", dreamed_image) plt.show()
https://github.com/Heisenbug-s-Dog/qnn_visualization
Heisenbug-s-Dog
# OpenMP: number of parallel threads. %env OMP_NUM_THREADS=1 # Plotting %matplotlib inline import matplotlib.pyplot as plt # PyTorch import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import torchvision from torchvision import datasets, models, transforms # Pennylane import pennylane as qml from pennylane import numpy as np # Other tools import time import copy filtered_classes = ['cat', 'dog'] # Subset of CIFAR ('plane', 'car', 'bird', 'cat','deer', 'dog', 'frog', 'horse', 'ship', 'truck') n_qubits = 4 # Number of qubits # An enterily classical net (defined by the next parameter). classical_model = '512_nq_n' # Possible choices: '512_n','512_nq_n','551_512_n'. [nq=n_qubits, n=num_filtered_classes] step = 0.001 # Learning rate batch_size = 256 # Number of samples for each training step num_epochs = 3 # Number of training epochs q_depth = 5 # Depth of the quantum circuit (number of variational layers) gamma_lr_scheduler = 1 # Learning rate reduction applied every 10 epochs. max_layers = 15 # Keep 15 even if not all are used. q_delta = 0.01 # Initial spread of random quantum weights rng_seed = 0 # Seed for random number generator start_time = time.time() # start of the computation timer torch.manual_seed(rng_seed) dev = qml.device('default.qubit', wires=n_qubits) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") #device = torch.device("cpu") def H_layer(nqubits): """Layer of single-qubit Hadamard gates. """ for idx in range(nqubits): qml.Hadamard(wires=idx) def RY_layer(w): """Layer of parametrized qubit rotations around the y axis. """ for idx, element in enumerate(w): qml.RY(element, wires=idx) def entangling_layer(nqubits): """Layer of CNOTs followed by another shifted layer of CNOT. """ # In other words it should apply something like : # CNOT CNOT CNOT CNOT... CNOT # CNOT CNOT CNOT... CNOT for i in range(0, nqubits - 1, 2): # Loop over even indices: i=0,2,...N-2 qml.CNOT(wires=[i, i + 1]) for i in range(1, nqubits - 1,2): # Loop over odd indices: i=1,3,...N-3 qml.CNOT(wires=[i, i + 1]) @qml.qnode(dev, interface='torch') def q_net(q_in, q_weights_flat): # Reshape weights q_weights = q_weights_flat.reshape(max_layers, n_qubits) # Start from state |+> , unbiased w.r.t. |0> and |1> H_layer(n_qubits) # Embed features in the quantum node RY_layer(q_in) # Sequence of trainable variational layers for k in range(q_depth): entangling_layer(n_qubits) RY_layer(q_weights[k+1]) # Expectation values in the Z basis return [qml.expval(qml.PauliZ(j)) for j in range(n_qubits)] class Quantumnet(nn.Module): def __init__(self): super().__init__() self.pre_net = nn.Linear(512, n_qubits) self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits)) self.post_net = nn.Linear(n_qubits, len(filtered_classes)) def forward(self, input_features): pre_out = self.pre_net(input_features) q_in = torch.tanh(pre_out) * np.pi / 2.0 # Apply the quantum circuit to each element of the batch, and append to q_out q_out = torch.Tensor(0, n_qubits) q_out = q_out.to(device) for elem in q_in: q_out_elem = q_net(elem,self.q_params).float().unsqueeze(0) q_out = torch.cat((q_out, q_out_elem)) return self.post_net(q_out) class Quantumnet_Cut(nn.Module): def __init__(self): super().__init__() self.pre_net = nn.Linear(512, n_qubits) self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits)) def forward(self, input_features): pre_out = self.pre_net(input_features) q_in = torch.tanh(pre_out) * np.pi / 2.0 # Apply the quantum circuit to each element of the batch, and append to q_out q_out = torch.Tensor(0, n_qubits) q_out = q_out.to(device) for elem in q_in: q_out_elem = q_net(elem,self.q_params).float().unsqueeze(0) q_out = torch.cat((q_out, q_out_elem)) return q_out class Quantumnet_Classical_Cut(nn.Module): def __init__(self): super().__init__() self.pre_net = nn.Linear(512, n_qubits) self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits)) def forward(self, input_features): pre_out = self.pre_net(input_features) q_in = torch.tanh(pre_out) * np.pi / 2.0 return q_in # Build Hybrid Model model_hybrid = torchvision.models.resnet18(pretrained=True) for param in model_hybrid.parameters(): param.requires_grad = False model_hybrid.fc = Quantumnet() # Use CUDA or CPU according to the "device" object. model_hybrid = model_hybrid.to(device) model_classical_cut = torchvision.models.resnet18(pretrained=True) model_classical_cut.fc = Quantumnet_Classical_Cut() for param in model_classical_cut.parameters(): param.requires_grad = False # Use CUDA or CPU according to the "device" object. model_classical_cut = model_classical_cut.to(device) model_cut = torchvision.models.resnet18(pretrained=True) model_cut.fc = Quantumnet_Cut() for param in model_cut.parameters(): param.requires_grad = False # Use CUDA or CPU according to the "device" object. model_cut = model_cut.to(device) # Load model from file path = './' model_hybrid.load_state_dict(torch.load(path+'quantum_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt')) model_dict = model_hybrid.state_dict() model_cut_dict = model_cut.state_dict() model_cut_dict = {k: v for k, v in model_dict.items() if k in model_cut_dict} model_cut.load_state_dict(model_cut_dict) model_classical_cut_dict = model_classical_cut.state_dict() model_classical_cut_dict = {k: v for k, v in model_dict.items() if k in model_classical_cut_dict} model_classical_cut.load_state_dict(model_classical_cut_dict) # Fixed pre-processing operations data_transforms = { 'train': transforms.Compose([ #transforms.RandomResizedCrop(224), # uncomment for data augmentation #transforms.RandomHorizontalFlip(), # uncomment for data augmentation transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), # Normalize input channels using mean values and standard deviations of ImageNet. transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]), 'val': transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]), } # =================== begin CIFAR dataset loading =================== trainset_full = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=data_transforms['train']) testset_full = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=data_transforms['val']) image_datasets_full={'train': trainset_full, 'val': testset_full} # CIFAR classes class_names = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') # Get indices of samples associated to filtered_classes filtered_labels=[class_names.index(cl) for cl in filtered_classes] sub_indices={'train': [], 'val': []} for phase in ['train', 'val']: for idx, label in enumerate(image_datasets_full[phase].targets): if label in filtered_labels: sub_indices[phase].append(idx) # Initialize sub-datasets according to filtered indices image_datasets = {x: torch.utils.data.Subset(image_datasets_full[x], sub_indices[x]) for x in ['train', 'val']} def labels_to_filtered(labels): """Maps CIFAR labels (0,1,2,3,4,5,6,7,8,9) to the index of filtered_labels""" return [filtered_labels.index(label) for label in labels] # =================== end CIFAR dataset loading ========================== # Number of samples dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']} # Initialize dataloader dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=batch_size, shuffle=True, num_workers=0) for x in ['train', 'val']} # Function to plot images from tensors def imshow(inp, title=None): """Imshow for Tensor.""" inp = inp.numpy().transpose((1, 2, 0)) # We apply the inverse of the initial normalization operation. mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) inp = std * inp + mean inp = np.clip(inp, 0, 1) plt.imshow(inp) if title is not None: plt.title(title) # Get a batch of training data X, y_cifar = next(iter(dataloaders['val'])) y = torch.tensor(labels_to_filtered(y_cifar)) X, y = X.to(device), y.to(device) # Slice Models network = model_hybrid layers = list(network.children()) hybrid_feats = [] for i in range(9): model_sliced = nn.Sequential(*layers[: i]) #Max: 9 hybrid_feats.append(torch.flatten(model_sliced(X), 1, 3).detach().cpu().numpy()) hybrid_feats.append(model_classical_cut(X).detach().cpu().numpy()) hybrid_feats.append(model_cut(X).detach().cpu().numpy()) import umap.umap_ as umap def normalize_layout(layout, min_percentile=1, max_percentile=99, relative_margin=0.1): """Removes outliers and scales layout to between [0,1].""" # compute percentiles mins = np.percentile(layout, min_percentile, axis=(0)) maxs = np.percentile(layout, max_percentile, axis=(0)) # add margins mins -= relative_margin * (maxs - mins) maxs += relative_margin * (maxs - mins) # `clip` broadcasts, `[None]`s added only for readability clipped = np.clip(layout, mins, maxs) # embed within [0,1] along both axes clipped -= clipped.min(axis=0) clipped /= clipped.max(axis=0) return clipped layout = umap.UMAP(n_components=2, verbose=True, n_neighbors=20, min_dist=0.01, metric="cosine").fit_transform(result) ## You can optionally use TSNE as well # layout = TSNE(n_components=2, verbose=True, metric="cosine", learning_rate=10, perplexity=50).fit_transform(d) layout = normalize_layout(layout) plt.figure(figsize=(10, 10)) plt.scatter(x=layout[:,0],y=layout[:,1], s=2) plt.savefig('quantum_activation_result.png') def whiten(full_activations): correl = np.matmul(full_activations.T, full_activations) / len(full_activations) correl = correl.astype("float32") S = np.linalg.inv(correl) S = S.astype("float32") return S S = whiten(result) plt.imshow(S, cmap='gray') plt.savefig('quantum_activation_whitening.png')
https://github.com/Heisenbug-s-Dog/qnn_visualization
Heisenbug-s-Dog
from google.colab import drive drive.mount('/content/drive') !pip install torch==1.3.1 !pip install torchvision==0.4.2 !pip install Pillow==6.2.1 !pip install pennylane==0.7.0 # OpenMP: number of parallel threads. %env OMP_NUM_THREADS=1 # Plotting %matplotlib inline import matplotlib.pyplot as plt # PyTorch import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import torchvision from torchvision import datasets, models, transforms # Pennylane import pennylane as qml from pennylane import numpy as np # Other tools import time import copy filtered_classes = ['cat', 'dog'] # Subset of CIFAR ('plane', 'car', 'bird', 'cat','deer', 'dog', 'frog', 'horse', 'ship', 'truck') n_qubits = 4 # Number of qubits quantum = True # If set to "False", the dressed quantum circuit is replaced by # An enterily classical net (defined by the next parameter). classical_model = '512_n' # Possible choices: '512_n','512_nq_n','551_512_n'. [nq=n_qubits, n=num_filtered_classes] step = 0.001 # Learning rate batch_size = 8 # Number of samples for each training step num_epochs = 3 # Number of training epochs q_depth = 5 # Depth of the quantum circuit (number of variational layers) gamma_lr_scheduler = 1 # Learning rate reduction applied every 10 epochs. max_layers = 15 # Keep 15 even if not all are used. q_delta = 0.01 # Initial spread of random quantum weights rng_seed = 0 # Seed for random number generator start_time = time.time() # start of the computation timer torch.manual_seed(rng_seed) dev = qml.device('default.qubit', wires=n_qubits) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") def H_layer(nqubits): """Layer of single-qubit Hadamard gates. """ for idx in range(nqubits): qml.Hadamard(wires=idx) def RY_layer(w): """Layer of parametrized qubit rotations around the y axis. """ for idx, element in enumerate(w): qml.RY(element, wires=idx) def entangling_layer(nqubits): """Layer of CNOTs followed by another shifted layer of CNOT. """ # In other words it should apply something like : # CNOT CNOT CNOT CNOT... CNOT # CNOT CNOT CNOT... CNOT for i in range(0, nqubits - 1, 2): # Loop over even indices: i=0,2,...N-2 qml.CNOT(wires=[i, i + 1]) for i in range(1, nqubits - 1,2): # Loop over odd indices: i=1,3,...N-3 qml.CNOT(wires=[i, i + 1]) @qml.qnode(dev, interface='torch') def q_net(q_in, q_weights_flat): # Reshape weights q_weights = q_weights_flat.reshape(max_layers, n_qubits) # Start from state |+> , unbiased w.r.t. |0> and |1> H_layer(n_qubits) # Embed features in the quantum node RY_layer(q_in) # Sequence of trainable variational layers for k in range(q_depth): entangling_layer(n_qubits) RY_layer(q_weights[k+1]) # Expectation values in the Z basis return [qml.expval(qml.PauliZ(j)) for j in range(n_qubits)] class Quantumnet(nn.Module): def __init__(self): super().__init__() self.pre_net = nn.Linear(512, n_qubits) self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits)) self.post_net = nn.Linear(n_qubits, len(filtered_classes)) def forward(self, input_features): pre_out = self.pre_net(input_features) q_in = torch.tanh(pre_out) * np.pi / 2.0 # Apply the quantum circuit to each element of the batch, and append to q_out q_out = torch.Tensor(0, n_qubits) q_out = q_out.to(device) for elem in q_in: q_out_elem = q_net(elem,self.q_params).float().unsqueeze(0) q_out = torch.cat((q_out, q_out_elem)) return self.post_net(q_out) class Quantumnet_Cut(nn.Module): def __init__(self): super().__init__() self.pre_net = nn.Linear(512, n_qubits) self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits)) def forward(self, input_features): pre_out = self.pre_net(input_features) q_in = torch.tanh(pre_out) * np.pi / 2.0 # Apply the quantum circuit to each element of the batch, and append to q_out q_out = torch.Tensor(0, n_qubits) q_out = q_out.to(device) for elem in q_in: q_out_elem = q_net(elem,self.q_params).float().unsqueeze(0) q_out = torch.cat((q_out, q_out_elem)) return q_out class Quantumnet_Classical_Cut(nn.Module): def __init__(self): super().__init__() self.pre_net = nn.Linear(512, n_qubits) self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits)) def forward(self, input_features): pre_out = self.pre_net(input_features) q_in = torch.tanh(pre_out) * np.pi / 2.0 return q_in model = torchvision.models.resnet18(pretrained=True) model.fc = Quantumnet() for param in model.parameters(): param.requires_grad = False # Use CUDA or CPU according to the "device" object. model = model.to(device) model_cut = torchvision.models.resnet18(pretrained=True) model_cut.fc = Quantumnet_Cut() for param in model_cut.parameters(): param.requires_grad = False # Use CUDA or CPU according to the "device" object. model_cut = model_cut.to(device) model_classical_cut = torchvision.models.resnet18(pretrained=True) model_classical_cut.fc = Quantumnet_Classical_Cut() for param in model_cut.parameters(): param.requires_grad = False # Use CUDA or CPU according to the "device" object. model_classical_cut = model_classical_cut.to(device) # Load model from file path = 'drive/MyDrive/' if quantum: model.load_state_dict(torch.load( path+'quantum_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt' ) ) else: model.load_state_dict(torch.load( path+'classical_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt' ) ) model_dict = model.state_dict() model_cut_dict = model_cut.state_dict() model_cut_dict = {k: v for k, v in model_dict.items() if k in model_cut_dict} model_cut.load_state_dict(model_cut_dict) model_classical_cut_dict = model_classical_cut.state_dict() model_classical_cut_dict = {k: v for k, v in model_dict.items() if k in model_classical_cut_dict} model_classical_cut.load_state_dict(model_classical_cut_dict) import sys sys.path.append('drive/My Drive/') from torchvis import util vis_param_dict, reset_state, remove_handles = util.augment_module(model) from PIL import Image # so, this woorks better than skimage, as torchvision transforms work best with PIL and Tensor. from torchvision import transforms img_to_use = Image.open(path + 'dog.jpg') print(img_to_use.size) transform_1 = transforms.Compose([ transforms.Scale(256), transforms.CenterCrop(224), ]) # since it's 0-255 range. transform_2 = transforms.Compose([ transforms.ToTensor(), # convert RGB to BGR # from <https://github.com/mrzhu-cool/pix2pix-pytorch/blob/master/util.py> transforms.Lambda(lambda x: torch.index_select(x, 0, torch.LongTensor([2, 1, 0]))), transforms.Lambda(lambda x: x*255), transforms.Normalize(mean = [103.939, 116.779, 123.68], std = [ 1, 1, 1 ]), ]) img_to_use_cropped = transform_1(img_to_use) img_to_use_cropped_tensor = transform_2(img_to_use_cropped)[np.newaxis] # add first column for batching img_to_use_cropped_tensor.min(), img_to_use_cropped_tensor.max() img_to_use_cropped # this is same as Lasagne example. from torchsummary import summary summary(model, (3, 224, 224)) from torch.nn import Parameter input_img = Parameter(img_to_use_cropped_tensor.cuda(), requires_grad=True) if input_img.grad is not None: input_img.grad.data.zero_() model.zero_grad() # wrap input in Parameter, so that gradients will be computed. raw_score = model(input_img) raw_score_numpy = raw_score.data.cpu().numpy() print(raw_score_numpy.shape, np.argmax(raw_score_numpy.ravel())) loss = raw_score.sum() print('loss', loss) # second time, there's no output anymore, due to lack of hook # I didn't call it, as maybe zero_grad may have some interaction with it. Not sure. Just for safety. # _ = alexnet(Variable(img_to_use_cropped_tensor.cuda())) # so, forward one time, and backward multiple times. vis_param_dict['layer'] = 'classifier.6' vis_param_dict['method'] = util.GradType.NAIVE # which one coresponds # this is the max one. I assume it's the correct one. # indeed, it's correct. # 55 is n01729977, corresponding to "green snake, grass snake". vis_param_dict['index'] = 55 # alexnet gives 64, which is n01749939, or green mamba. not sure which one is correct. loss.backward(retain_graph=True) # adapted from <https://github.com/Lasagne/Recipes/blob/master/examples/Saliency%20Maps%20and%20Guided%20Backpropagation.ipynb> def show_images(img_original, saliency, title): # convert from c01 to 01c print(saliency.min(), saliency.max(), saliency.mean(), saliency.std()) saliency = saliency[::-1] # to BGR saliency = saliency.transpose(1, 2, 0) # # put back std fixing. # saliency = saliency * np.array([ 0.229, 0.224, 0.225 ]) # plot the original image and the three saliency map variants plt.figure(figsize=(10, 10), facecolor='w') plt.subplot(2, 2, 1) plt.title('input') plt.imshow(np.asarray(img_original)) plt.subplot(2, 2, 2) plt.title('abs. saliency') plt.imshow(np.abs(saliency).max(axis=-1), cmap='gray') plt.subplot(2, 2, 3) plt.title('pos. saliency') plt.imshow((np.maximum(0, saliency) / saliency.max())) plt.subplot(2, 2, 4) plt.title('neg. saliency') plt.imshow((np.maximum(0, -saliency) / -saliency.min())) plt.suptitle(title) plt.show() show_images(img_to_use_cropped, input_img.grad.data.cpu().numpy()[0], '') # so, forward one time, and backward multiple times. vis_param_dict['method'] = util.GradType.GUIDED # alexnet gives 64, which is n01749939, or green mamba. not sure which one is correct. if input_img.grad is not None: input_img.grad.data.zero_() model.zero_grad() loss.backward(retain_graph=True) show_images(img_to_use_cropped, input_img.grad.data.cpu().numpy()[0], 'guided') # so, forward one time, and backward multiple times. vis_param_dict['method'] = util.GradType.DECONV # alexnet gives 64, which is n01749939, or green mamba. not sure which one is correct. if input_img.grad is not None: input_img.grad.data.zero_() model.zero_grad() loss.backward(retain_graph=True) show_images(img_to_use_cropped, input_img.grad.data.cpu().numpy()[0], 'deconv') def dream(image, model, iterations, lr): """ Updates the image to maximize outputs for n iterations """ Tensor = torch.cuda.FloatTensor if torch.cuda.is_available else torch.FloatTensor image = preprocess(image).unsqueeze(0).cpu().data.numpy() image = Variable(Tensor(image), requires_grad=True) for i in range(iterations): model.zero_grad() out = model(image) loss = out.norm() if i % 10 == 0: print('iter: {}/{}, loss: {}'.format(i+1, iterations, loss.item())) loss.backward() avg_grad = np.abs(image.grad.data.cpu().numpy()).mean() norm_lr = lr / avg_grad image.data += norm_lr * image.grad.data image.data = clip(image.data) image.grad.data.zero_() return image.cpu().data.numpy() def diff_dream(image, model1, model2, iterations, lr): """ Updates the image to maximize outputs for n iterations """ Tensor = torch.cuda.FloatTensor if torch.cuda.is_available else torch.FloatTensor image = preprocess(image).unsqueeze(0).cpu().data.numpy() image = Variable(Tensor(image), requires_grad=True) for i in range(iterations): model1.zero_grad() model2.zero_grad() out1 = model1(image) out2 = model2(image) loss = out1.norm() / np.sqrt(np.prod(out1.shape)) - out2.norm() / np.sqrt(np.prod(out2.shape)) if i % 10 == 0: print('iter: {}/{}, loss: {}'.format(i+1, iterations, loss.item())) loss.backward() avg_grad = np.abs(image.grad.data.cpu().numpy()).mean() norm_lr = lr / avg_grad image.data += norm_lr * image.grad.data image.data = clip(image.data) image.grad.data.zero_() return image.cpu().data.numpy() def deep_dream(image, model, iterations, lr, octave_scale, num_octaves): """ Main deep dream method """ image = preprocess(image).unsqueeze(0).cpu().data.numpy() # Extract image representations for each octave octaves = [image] for _ in range(num_octaves - 1): octaves.append(nd.zoom(octaves[-1], (1, 1, 1 / octave_scale, 1 / octave_scale), order=1)) detail = np.zeros_like(octaves[-1]) for octave, octave_base in enumerate(tqdm.tqdm(octaves[::-1], desc="Dreaming")): if octave > 0: # Upsample detail to new octave dimension detail = nd.zoom(detail, np.array(octave_base.shape) / np.array(detail.shape), order=1) # Add deep dream detail from previous octave to new base input_image = octave_base + detail # Get new deep dream image dreamed_image = dream(input_image, model, iterations, lr) # Extract deep dream details detail = dreamed_image - octave_base return deprocess(dreamed_image) mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) #preprocess = transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean, std)]) preprocess = transforms.Compose([transforms.ToTensor()]) def deprocess(image_np): image_np = image_np.squeeze().transpose(1, 2, 0) image_np = image_np * std.reshape((1, 1, 3)) + mean.reshape((1, 1, 3)) image_np = np.clip(image_np, 0.0, 255.0) return image_np def clip(image_tensor): for c in range(3): m, s = mean[c], std[c] image_tensor[0, c] = torch.clamp(image_tensor[0, c], -m / s, (1 - m) / s) return image_tensor from PIL import Image import scipy.ndimage as nd from torch.autograd import Variable import tqdm, os # Load image image = Image.open("/content/drive/MyDrive/Qiskit-Hackathon-Korea/qnn-visualization/images/dog.jpg") # Set Models #network = model #layers = list(network.children()) #classical_model = nn.Sequential(*layers[: 9]) #Max: 9 classical_model = model_classical_cut quantum_model = model # Extract deep dream image dreamed_image = dream( image, quantum_model, iterations=1000, lr=0.01 ) dreamed_image = np.transpose(dreamed_image, (0,2,3,1)) dreamed_image = dreamed_image[0] # Save and plot image #os.makedirs("outputs", exist_ok=True) #filename = 'test' plt.figure(figsize=(20, 20)) plt.imshow(dreamed_image) #plt.imsave(f"outputs/output_{filename}", dreamed_image) plt.show() quantum_dreamed_image = diff_dream( image, quantum_model, classical_model, iterations=500, lr=0.01 ) dreamed_image = quantum_dreamed_image dreamed_image = np.transpose(dreamed_image, (0,2,3,1)) dreamed_image = dreamed_image[0] # Save and plot image #os.makedirs("outputs", exist_ok=True) #filename = 'test' plt.figure(figsize=(20, 20)) plt.imshow(dreamed_image) #plt.imsave(f"outputs/output_{filename}", dreamed_image) plt.show() classical_dreamed_image = diff_dream( image, classical_model, quantum_model, iterations=500, lr=0.01 ) dreamed_image = classical_dreamed_image dreamed_image = np.transpose(dreamed_image, (0,2,3,1)) dreamed_image = dreamed_image[0] # Save and plot image #os.makedirs("outputs", exist_ok=True) #filename = 'test' plt.figure(figsize=(20, 20)) plt.imshow(dreamed_image) #plt.imsave(f"outputs/output_{filename}", dreamed_image) plt.show()
https://github.com/Heisenbug-s-Dog/qnn_visualization
Heisenbug-s-Dog
# OpenMP: number of parallel threads. %env OMP_NUM_THREADS=1 # Plotting %matplotlib inline import matplotlib.pyplot as plt # PyTorch import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import torchvision from torchvision import datasets, models, transforms # Pennylane import pennylane as qml from pennylane import numpy as np # Other tools import time import copy filtered_classes = ['cat', 'dog'] # Subset of CIFAR ('plane', 'car', 'bird', 'cat','deer', 'dog', 'frog', 'horse', 'ship', 'truck') n_qubits = 4 # Number of qubits quantum = False # If set to "False", the dressed quantum circuit is replaced by # An enterily classical net (defined by the next parameter). classical_model = '512_nq_n' # Possible choices: '512_n','512_nq_n','551_512_n'. [nq=n_qubits, n=num_filtered_classes] step = 0.001 # Learning rate num_epochs = 3 # Number of training epochs q_depth = 5 # Depth of the quantum circuit (number of variational layers) gamma_lr_scheduler = 1 # Learning rate reduction applied every 10 epochs. max_layers = 15 # Keep 15 even if not all are used. q_delta = 0.01 # Initial spread of random quantum weights rng_seed = 0 # Seed for random number generator start_time = time.time() # start of the computation timer batch_size = 16 # or 8 # Number of samples for each training step STEPS = 40 # or 20 if quantum: figname = 'cq' else: figname = 'cc' torch.manual_seed(rng_seed) dev = qml.device('default.qubit', wires=n_qubits) # device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") device = torch.device("cpu") def H_layer(nqubits): """Layer of single-qubit Hadamard gates. """ for idx in range(nqubits): qml.Hadamard(wires=idx) def RY_layer(w): """Layer of parametrized qubit rotations around the y axis. """ for idx, element in enumerate(w): qml.RY(element, wires=idx) def entangling_layer(nqubits): """Layer of CNOTs followed by another shifted layer of CNOT. """ # In other words it should apply something like : # CNOT CNOT CNOT CNOT... CNOT # CNOT CNOT CNOT... CNOT for i in range(0, nqubits - 1, 2): # Loop over even indices: i=0,2,...N-2 qml.CNOT(wires=[i, i + 1]) for i in range(1, nqubits - 1,2): # Loop over odd indices: i=1,3,...N-3 qml.CNOT(wires=[i, i + 1]) @qml.qnode(dev, interface='torch') def q_net(q_in, q_weights_flat): # Reshape weights q_weights = q_weights_flat.reshape(max_layers, n_qubits) # Start from state |+> , unbiased w.r.t. |0> and |1> H_layer(n_qubits) # Embed features in the quantum node RY_layer(q_in) # Sequence of trainable variational layers for k in range(q_depth): entangling_layer(n_qubits) RY_layer(q_weights[k+1]) # Expectation values in the Z basis return [qml.expval(qml.PauliZ(j)) for j in range(n_qubits)] class Quantumnet(nn.Module): def __init__(self): super().__init__() self.pre_net = nn.Linear(512, n_qubits) self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits)) self.post_net = nn.Linear(n_qubits, len(filtered_classes)) def forward(self, input_features): pre_out = self.pre_net(input_features) q_in = torch.tanh(pre_out) * np.pi / 2.0 # Apply the quantum circuit to each element of the batch, and append to q_out q_out = torch.Tensor(0, n_qubits) q_out = q_out.to(device) for elem in q_in: q_out_elem = q_net(elem,self.q_params).float().unsqueeze(0) q_out = torch.cat((q_out, q_out_elem)) return self.post_net(q_out) # Build Model model_hybrid = torchvision.models.resnet18(pretrained=True) for param in model_hybrid.parameters(): param.requires_grad = False if quantum: model_hybrid.fc = Quantumnet() elif classical_model == '512_n': model_hybrid.fc = nn.Linear(512,len(filtered_classes)) elif classical_model == '512_nq_n': model_hybrid.fc = nn.Sequential(nn.Linear(512, n_qubits),torch.nn.ReLU(),nn.Linear(n_qubits, len(filtered_classes))) elif classical_model == '551_512_n': model_hybrid.fc = nn.Sequential(nn.Linear(512, 512), torch.nn.ReLU(), nn.Linear(512, len(filtered_classes))) # Use CUDA or CPU according to the "device" object. model_hybrid = model_hybrid.to(device) # Load model from file path = './' if quantum: model_hybrid.load_state_dict(torch.load( path+'quantum_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt' ) ) else: model_hybrid.load_state_dict(torch.load( path+'classical_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt' ) ) # Fixed pre-processing operations data_transforms = { 'train': transforms.Compose([ #transforms.RandomResizedCrop(224), # uncomment for data augmentation #transforms.RandomHorizontalFlip(), # uncomment for data augmentation transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), # Normalize input channels using mean values and standard deviations of ImageNet. transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]), 'val': transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]), } # =================== begin CIFAR dataset loading =================== trainset_full = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=data_transforms['train']) testset_full = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=data_transforms['val']) image_datasets_full={'train': trainset_full, 'val': testset_full} # CIFAR classes class_names = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') # Get indices of samples associated to filtered_classes filtered_labels=[class_names.index(cl) for cl in filtered_classes] sub_indices={'train': [], 'val': []} for phase in ['train', 'val']: for idx, label in enumerate(image_datasets_full[phase].targets): if label in filtered_labels: sub_indices[phase].append(idx) # Initialize sub-datasets according to filtered indices image_datasets = {x: torch.utils.data.Subset(image_datasets_full[x], sub_indices[x]) for x in ['train', 'val']} def labels_to_filtered(labels): """Maps CIFAR labels (0,1,2,3,4,5,6,7,8,9) to the index of filtered_labels""" return [filtered_labels.index(label) for label in labels] # =================== end CIFAR dataset loading ========================== # Number of samples dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']} # Initialize dataloader dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=batch_size, shuffle=False, num_workers=0) for x in ['train', 'val']} # shuffle False # Function to plot images from tensors def imshow(inp, title=None): """Imshow for Tensor.""" inp = inp.numpy().transpose((1, 2, 0)) # We apply the inverse of the initial normalization operation. mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) inp = std * inp + mean inp = np.clip(inp, 0, 1) plt.imshow(inp) if title is not None: plt.title(title) from loss_landscapes import random_plane from loss_landscapes.metrics import Loss import matplotlib matplotlib.rcParams['figure.figsize'] = [18, 12] data_iter = iter(dataloaders['train']) # Get a batch of training data X, y_cifar = next(data_iter) y = torch.tensor(labels_to_filtered(y_cifar)) X, y = X.to(device), y.to(device) print(y) loss_func = nn.CrossEntropyLoss() #loss_func = nn.MSELoss(reduce='false') metric = Loss(loss_func, X, y) landscape = random_plane(model_hybrid, metric, distance=10, steps=STEPS, normalization='filter') fig = plt.figure() plt.contour(landscape, levels=50) plt.title('Loss Contours around Trained Model') fig.show() plt.savefig('./landscape/contours_{}_{}_{}_batch1.png'.format(figname, batch_size, STEPS), dpi=300) fig = plt.figure() ax = plt.axes(projection='3d') X = np.array([[j for j in range(STEPS)] for i in range(STEPS)]) Y = np.array([[i for _ in range(STEPS)] for i in range(STEPS)]) ax.plot_surface(X, Y, landscape, rstride=1, cstride=1, cmap='viridis', edgecolor='none') ax.set_title('Surface Plot of Loss Landscape') fig.show() ax.set_zlim([0, 1.5]) plt.savefig('./landscape/surface_{}_{}_{}_batch1.png'.format(figname, batch_size, STEPS), dpi=300) with open('./landscape/landscape_{}_{}_{}_batch1.npy'.format(figname, batch_size, STEPS), 'wb') as f: np.save(f, landscape)
https://github.com/Heisenbug-s-Dog/qnn_visualization
Heisenbug-s-Dog
# OpenMP: number of parallel threads. %env OMP_NUM_THREADS=1 # Plotting %matplotlib inline import matplotlib.pyplot as plt # PyTorch import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import torchvision from torchvision import datasets, models, transforms # Pennylane import pennylane as qml from pennylane import numpy as np # Other tools import time import copy filtered_classes = ['cat', 'dog'] # Subset of CIFAR ('plane', 'car', 'bird', 'cat','deer', 'dog', 'frog', 'horse', 'ship', 'truck') n_qubits = 4 # Number of qubits quantum = True # If set to "False", the dressed quantum circuit is replaced by # An enterily classical net (defined by the next parameter). classical_model = '512_n' # Possible choices: '512_n','512_nq_n','551_512_n'. [nq=n_qubits, n=num_filtered_classes] step = 0.001 # Learning rate batch_size = 8 # Number of samples for each training step num_epochs = 3 # Number of training epochs q_depth = 5 # Depth of the quantum circuit (number of variational layers) gamma_lr_scheduler = 1 # Learning rate reduction applied every 10 epochs. max_layers = 15 # Keep 15 even if not all are used. q_delta = 0.01 # Initial spread of random quantum weights rng_seed = 0 # Seed for random number generator start_time = time.time() # start of the computation timer torch.manual_seed(rng_seed) dev = qml.device('default.qubit', wires=n_qubits) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") def H_layer(nqubits): """Layer of single-qubit Hadamard gates. """ for idx in range(nqubits): qml.Hadamard(wires=idx) def RY_layer(w): """Layer of parametrized qubit rotations around the y axis. """ for idx, element in enumerate(w): qml.RY(element, wires=idx) def entangling_layer(nqubits): """Layer of CNOTs followed by another shifted layer of CNOT. """ # In other words it should apply something like : # CNOT CNOT CNOT CNOT... CNOT # CNOT CNOT CNOT... CNOT for i in range(0, nqubits - 1, 2): # Loop over even indices: i=0,2,...N-2 qml.CNOT(wires=[i, i + 1]) for i in range(1, nqubits - 1,2): # Loop over odd indices: i=1,3,...N-3 qml.CNOT(wires=[i, i + 1]) @qml.qnode(dev, interface='torch') def q_net(q_in, q_weights_flat): # Reshape weights q_weights = q_weights_flat.reshape(max_layers, n_qubits) # Start from state |+> , unbiased w.r.t. |0> and |1> H_layer(n_qubits) # Embed features in the quantum node RY_layer(q_in) # Sequence of trainable variational layers for k in range(q_depth): entangling_layer(n_qubits) RY_layer(q_weights[k+1]) # Expectation values in the Z basis return [qml.expval(qml.PauliZ(j)) for j in range(n_qubits)] class Quantumnet(nn.Module): def __init__(self): super().__init__() self.pre_net = nn.Linear(512, n_qubits) self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits)) self.post_net = nn.Linear(n_qubits, len(filtered_classes)) def forward(self, input_features): pre_out = self.pre_net(input_features) q_in = torch.tanh(pre_out) * np.pi / 2.0 # Apply the quantum circuit to each element of the batch, and append to q_out q_out = torch.Tensor(0, n_qubits) q_out = q_out.to(device) for elem in q_in: q_out_elem = q_net(elem,self.q_params).float().unsqueeze(0) q_out = torch.cat((q_out, q_out_elem)) return self.post_net(q_out) class Quantumnet_Cut(nn.Module): def __init__(self): super().__init__() self.pre_net = nn.Linear(512, n_qubits) self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits)) def forward(self, input_features): pre_out = self.pre_net(input_features) q_in = torch.tanh(pre_out) * np.pi / 2.0 # Apply the quantum circuit to each element of the batch, and append to q_out q_out = torch.Tensor(0, n_qubits) q_out = q_out.to(device) for elem in q_in: q_out_elem = q_net(elem,self.q_params).float().unsqueeze(0) q_out = torch.cat((q_out, q_out_elem)) return q_out class Quantumnet_Classical_Cut(nn.Module): def __init__(self): super().__init__() self.pre_net = nn.Linear(512, n_qubits) self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits)) def forward(self, input_features): pre_out = self.pre_net(input_features) q_in = torch.tanh(pre_out) * np.pi / 2.0 return q_in model = torchvision.models.resnet18(pretrained=True) model.fc = Quantumnet() for param in model.parameters(): param.requires_grad = False # Use CUDA or CPU according to the "device" object. model = model.to(device) model_cut = torchvision.models.resnet18(pretrained=True) model_cut.fc = Quantumnet_Cut() for param in model_cut.parameters(): param.requires_grad = False # Use CUDA or CPU according to the "device" object. model_cut = model_cut.to(device) model_classical_cut = torchvision.models.resnet18(pretrained=True) model_classical_cut.fc = Quantumnet_Classical_Cut() for param in model_cut.parameters(): param.requires_grad = False # Use CUDA or CPU according to the "device" object. model_classical_cut = model_classical_cut.to(device) # Load model from file path = 'drive/MyDrive/' if quantum: model.load_state_dict(torch.load( path+'quantum_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt' ) ) else: model.load_state_dict(torch.load( path+'classical_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt' ) ) model_dict = model.state_dict() model_cut_dict = model_cut.state_dict() model_cut_dict = {k: v for k, v in model_dict.items() if k in model_cut_dict} model_cut.load_state_dict(model_cut_dict) model_classical_cut_dict = model_classical_cut.state_dict() model_classical_cut_dict = {k: v for k, v in model_dict.items() if k in model_classical_cut_dict} model_classical_cut.load_state_dict(model_classical_cut_dict) import sys sys.path.append('drive/My Drive/') from torchvis import util vis_param_dict, reset_state, remove_handles = util.augment_module(model) from PIL import Image # so, this woorks better than skimage, as torchvision transforms work best with PIL and Tensor. from torchvision import transforms img_to_use = Image.open(path + 'dog.jpg') print(img_to_use.size) transform_1 = transforms.Compose([ transforms.Scale(256), transforms.CenterCrop(224), ]) # since it's 0-255 range. transform_2 = transforms.Compose([ transforms.ToTensor(), # convert RGB to BGR # from <https://github.com/mrzhu-cool/pix2pix-pytorch/blob/master/util.py> transforms.Lambda(lambda x: torch.index_select(x, 0, torch.LongTensor([2, 1, 0]))), transforms.Lambda(lambda x: x*255), transforms.Normalize(mean = [103.939, 116.779, 123.68], std = [ 1, 1, 1 ]), ]) img_to_use_cropped = transform_1(img_to_use) # so, forward one time, and backward multiple times. vis_param_dict['layer'] = 'classifier.6' vis_param_dict['method'] = util.GradType.NAIVE # which one coresponds # this is the max one. I assume it's the correct one. # indeed, it's correct. # 55 is n01729977, corresponding to "green snake, grass snake". vis_param_dict['index'] = 55 # alexnet gives 64, which is n01749939, or green mamba. not sure which one is correct. loss.backward(retain_graph=True) # adapted from <https://github.com/Lasagne/Recipes/blob/master/examples/Saliency%20Maps%20and%20Guided%20Backpropagation.ipynb> def show_images(img_original, saliency, title): # convert from c01 to 01c print(saliency.min(), saliency.max(), saliency.mean(), saliency.std()) saliency = saliency[::-1] # to BGR saliency = saliency.transpose(1, 2, 0) # # put back std fixing. # saliency = saliency * np.array([ 0.229, 0.224, 0.225 ]) # plot the original image and the three saliency map variants plt.figure(figsize=(10, 10), facecolor='w') plt.subplot(2, 2, 1) plt.title('input') plt.imshow(np.asarray(img_original)) plt.subplot(2, 2, 2) plt.title('abs. saliency') plt.imshow(np.abs(saliency).max(axis=-1), cmap='gray') plt.subplot(2, 2, 3) plt.title('pos. saliency') plt.imshow((np.maximum(0, saliency) / saliency.max())) plt.subplot(2, 2, 4) plt.title('neg. saliency') plt.imshow((np.maximum(0, -saliency) / -saliency.min())) plt.suptitle(title) plt.show() show_images(img_to_use_cropped, input_img.grad.data.cpu().numpy()[0], '') # so, forward one time, and backward multiple times. vis_param_dict['method'] = util.GradType.GUIDED # alexnet gives 64, which is n01749939, or green mamba. not sure which one is correct. if input_img.grad is not None: input_img.grad.data.zero_() model.zero_grad() loss.backward(retain_graph=True) show_images(img_to_use_cropped, input_img.grad.data.cpu().numpy()[0], 'guided') # so, forward one time, and backward multiple times. vis_param_dict['method'] = util.GradType.DECONV # alexnet gives 64, which is n01749939, or green mamba. not sure which one is correct. if input_img.grad is not None: input_img.grad.data.zero_() model.zero_grad() loss.backward(retain_graph=True) show_images(img_to_use_cropped, input_img.grad.data.cpu().numpy()[0], 'deconv')
https://github.com/Heisenbug-s-Dog/qnn_visualization
Heisenbug-s-Dog
# OpenMP: number of parallel threads. %env OMP_NUM_THREADS=1 # Plotting %matplotlib inline import matplotlib.pyplot as plt # PyTorch import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import torchvision from torchvision import datasets, models, transforms # Pennylane import pennylane as qml from pennylane import numpy as np # Other tools import time import copy filtered_classes = ['cat', 'dog'] # Subset of CIFAR ('plane', 'car', 'bird', 'cat','deer', 'dog', 'frog', 'horse', 'ship', 'truck') n_qubits = 4 # Number of qubits # An enterily classical net (defined by the next parameter). classical_model = '512_nq_n' # Possible choices: '512_n','512_nq_n','551_512_n'. [nq=n_qubits, n=num_filtered_classes] step = 0.001 # Learning rate batch_size = 256 # Number of samples for each training step num_epochs = 3 # Number of training epochs q_depth = 5 # Depth of the quantum circuit (number of variational layers) gamma_lr_scheduler = 1 # Learning rate reduction applied every 10 epochs. max_layers = 15 # Keep 15 even if not all are used. q_delta = 0.01 # Initial spread of random quantum weights rng_seed = 0 # Seed for random number generator start_time = time.time() # start of the computation timer torch.manual_seed(rng_seed) dev = qml.device('default.qubit', wires=n_qubits) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") #device = torch.device("cpu") def H_layer(nqubits): """Layer of single-qubit Hadamard gates. """ for idx in range(nqubits): qml.Hadamard(wires=idx) def RY_layer(w): """Layer of parametrized qubit rotations around the y axis. """ for idx, element in enumerate(w): qml.RY(element, wires=idx) def entangling_layer(nqubits): """Layer of CNOTs followed by another shifted layer of CNOT. """ # In other words it should apply something like : # CNOT CNOT CNOT CNOT... CNOT # CNOT CNOT CNOT... CNOT for i in range(0, nqubits - 1, 2): # Loop over even indices: i=0,2,...N-2 qml.CNOT(wires=[i, i + 1]) for i in range(1, nqubits - 1,2): # Loop over odd indices: i=1,3,...N-3 qml.CNOT(wires=[i, i + 1]) @qml.qnode(dev, interface='torch') def q_net(q_in, q_weights_flat): # Reshape weights q_weights = q_weights_flat.reshape(max_layers, n_qubits) # Start from state |+> , unbiased w.r.t. |0> and |1> H_layer(n_qubits) # Embed features in the quantum node RY_layer(q_in) # Sequence of trainable variational layers for k in range(q_depth): entangling_layer(n_qubits) RY_layer(q_weights[k+1]) # Expectation values in the Z basis return [qml.expval(qml.PauliZ(j)) for j in range(n_qubits)] class Quantumnet(nn.Module): def __init__(self): super().__init__() self.pre_net = nn.Linear(512, n_qubits) self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits)) self.post_net = nn.Linear(n_qubits, len(filtered_classes)) def forward(self, input_features): pre_out = self.pre_net(input_features) q_in = torch.tanh(pre_out) * np.pi / 2.0 # Apply the quantum circuit to each element of the batch, and append to q_out q_out = torch.Tensor(0, n_qubits) q_out = q_out.to(device) for elem in q_in: q_out_elem = q_net(elem,self.q_params).float().unsqueeze(0) q_out = torch.cat((q_out, q_out_elem)) return self.post_net(q_out) class Quantumnet_Cut(nn.Module): def __init__(self): super().__init__() self.pre_net = nn.Linear(512, n_qubits) self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits)) def forward(self, input_features): pre_out = self.pre_net(input_features) q_in = torch.tanh(pre_out) * np.pi / 2.0 # Apply the quantum circuit to each element of the batch, and append to q_out q_out = torch.Tensor(0, n_qubits) q_out = q_out.to(device) for elem in q_in: q_out_elem = q_net(elem,self.q_params).float().unsqueeze(0) q_out = torch.cat((q_out, q_out_elem)) return q_out class Quantumnet_Classical_Cut(nn.Module): def __init__(self): super().__init__() self.pre_net = nn.Linear(512, n_qubits) self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits)) def forward(self, input_features): pre_out = self.pre_net(input_features) q_in = torch.tanh(pre_out) * np.pi / 2.0 return q_in # Build Hybrid Model model_hybrid = torchvision.models.resnet18(pretrained=True) for param in model_hybrid.parameters(): param.requires_grad = False model_hybrid.fc = Quantumnet() # Use CUDA or CPU according to the "device" object. model_hybrid = model_hybrid.to(device) model_classical_cut = torchvision.models.resnet18(pretrained=True) model_classical_cut.fc = Quantumnet_Classical_Cut() for param in model_classical_cut.parameters(): param.requires_grad = False # Use CUDA or CPU according to the "device" object. model_classical_cut = model_classical_cut.to(device) model_cut = torchvision.models.resnet18(pretrained=True) model_cut.fc = Quantumnet_Cut() for param in model_cut.parameters(): param.requires_grad = False # Use CUDA or CPU according to the "device" object. model_cut = model_cut.to(device) # Load model from file path = './' model_hybrid.load_state_dict(torch.load(path+'quantum_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt')) model_dict = model_hybrid.state_dict() model_cut_dict = model_cut.state_dict() model_cut_dict = {k: v for k, v in model_dict.items() if k in model_cut_dict} model_cut.load_state_dict(model_cut_dict) model_classical_cut_dict = model_classical_cut.state_dict() model_classical_cut_dict = {k: v for k, v in model_dict.items() if k in model_classical_cut_dict} model_classical_cut.load_state_dict(model_classical_cut_dict) # Fixed pre-processing operations data_transforms = { 'train': transforms.Compose([ #transforms.RandomResizedCrop(224), # uncomment for data augmentation #transforms.RandomHorizontalFlip(), # uncomment for data augmentation transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), # Normalize input channels using mean values and standard deviations of ImageNet. transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]), 'val': transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]), } # =================== begin CIFAR dataset loading =================== trainset_full = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=data_transforms['train']) testset_full = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=data_transforms['val']) image_datasets_full={'train': trainset_full, 'val': testset_full} # CIFAR classes class_names = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') # Get indices of samples associated to filtered_classes filtered_labels=[class_names.index(cl) for cl in filtered_classes] sub_indices={'train': [], 'val': []} for phase in ['train', 'val']: for idx, label in enumerate(image_datasets_full[phase].targets): if label in filtered_labels: sub_indices[phase].append(idx) # Initialize sub-datasets according to filtered indices image_datasets = {x: torch.utils.data.Subset(image_datasets_full[x], sub_indices[x]) for x in ['train', 'val']} def labels_to_filtered(labels): """Maps CIFAR labels (0,1,2,3,4,5,6,7,8,9) to the index of filtered_labels""" return [filtered_labels.index(label) for label in labels] # =================== end CIFAR dataset loading ========================== # Number of samples dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']} # Initialize dataloader dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=batch_size, shuffle=True, num_workers=0) for x in ['train', 'val']} # Function to plot images from tensors def imshow(inp, title=None): """Imshow for Tensor.""" inp = inp.numpy().transpose((1, 2, 0)) # We apply the inverse of the initial normalization operation. mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) inp = std * inp + mean inp = np.clip(inp, 0, 1) plt.imshow(inp) if title is not None: plt.title(title) # Get a batch of training data X, y_cifar = next(iter(dataloaders['val'])) y = torch.tensor(labels_to_filtered(y_cifar)) X, y = X.to(device), y.to(device) # Slice Models network = model_hybrid layers = list(network.children()) hybrid_feats = [] for i in range(9): model_sliced = nn.Sequential(*layers[: i]) #Max: 9 hybrid_feats.append(torch.flatten(model_sliced(X), 1, 3).detach().cpu().numpy()) hybrid_feats.append(model_classical_cut(X).detach().cpu().numpy()) hybrid_feats.append(model_cut(X).detach().cpu().numpy()) from sklearn.manifold import TSNE from tqdm import tqdm import pickle import matplotlib.pyplot as plt import matplotlib matplotlib.rcParams['figure.figsize'] = [18, 12] hybrid_feats_embedded = [] for feat in tqdm(hybrid_feats): hybrid_feats_embedded.append(TSNE(n_components=2).fit_transform(feat)) with open("./tsne/hybrid.txt", "wb") as fp: #Pickling pickle.dump(hybrid_feats_embedded, fp) tsneNDArray = hybrid_feats_embedded[0] labelNDArray = y.cpu().numpy() def plot_layer(tsneNDArray, labelNDArray, num): figure, axesSubplot = plt.subplots() axesSubplot.scatter(tsneNDArray[:, 0], tsneNDArray[:, 1], c = labelNDArray, s=130) axesSubplot.set_xticks(()) axesSubplot.set_yticks(()) plt.show() figure.savefig('./tsne/tsne_layer_{}.png'.format(num), dpi=300) for i, tsnearray in enumerate(hybrid_feats_embedded): plot_layer(tsnearray, labelNDArray, i)
https://github.com/tanjinadnanabir/qbosons-qiskit-hackathon
tanjinadnanabir
import pandas as pd import numpy as np import os import matplotlib.pyplot as plt import seaborn as sns from google.colab import drive drive.mount('/content/drive') import warnings warnings.filterwarnings('ignore') df = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/iris/Iris.csv') df.head() # delete a column df = df.drop(columns = ['Id']) df.head() # to display stats about data df.describe() # to basic info about datatype df.info() # to display no. of samples on each class df['Species'].value_counts() # check for null values df.isnull().sum() # histograms df['SepalLengthCm'].hist() df['SepalWidthCm'].hist() df['PetalLengthCm'].hist() df['PetalWidthCm'].hist() # scatterplot colors = ['red', 'orange', 'blue'] species = ['Iris-virginica','Iris-versicolor','Iris-setosa'] for i in range(3): x = df[df['Species'] == species[i]] plt.scatter(x['SepalLengthCm'], x['SepalWidthCm'], c = colors[i], label=species[i]) plt.xlabel("Sepal Length") plt.ylabel("Sepal Width") plt.legend() for i in range(3): x = df[df['Species'] == species[i]] plt.scatter(x['PetalLengthCm'], x['PetalWidthCm'], c = colors[i], label=species[i]) plt.xlabel("Petal Length") plt.ylabel("Petal Width") plt.legend() for i in range(3): x = df[df['Species'] == species[i]] plt.scatter(x['SepalLengthCm'], x['PetalLengthCm'], c = colors[i], label=species[i]) plt.xlabel("Sepal Length") plt.ylabel("Petal Length") plt.legend() for i in range(3): x = df[df['Species'] == species[i]] plt.scatter(x['SepalWidthCm'], x['PetalWidthCm'], c = colors[i], label=species[i]) plt.xlabel("Sepal Width") plt.ylabel("Petal Width") plt.legend() df.corr() corr = df.corr() fig, ax = plt.subplots(figsize=(5,4)) sns.heatmap(corr, annot=True, ax=ax, cmap = 'coolwarm') # Feature correlation def featureCorrelation(s): import seaborn as sn import matplotlib.pyplot as plt sn.set(font_scale=1.3) sn.set_style("darkgrid") fig_dims = (10, 4) fig, ax = plt.subplots(figsize=fig_dims) sn.heatmap(s.corr(), annot=True, ax=ax) plt.show() featureCorrelation(df) from sklearn.preprocessing import LabelEncoder le = LabelEncoder() df['Species'] = le.fit_transform(df['Species']) df.head() featureCorrelation(df) # Splitting the dataset from sklearn.model_selection import train_test_split X = df.drop(columns=['Species']) Y = df['Species'] x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.30) # logistic regression from sklearn.linear_model import LogisticRegression model = LogisticRegression() # model training model.fit(x_train, y_train) # print metric to get performance print("Accuracy: ",model.score(x_test, y_test) * 100) # knn - k-nearest neighbours from sklearn.neighbors import KNeighborsClassifier model = KNeighborsClassifier() model.fit(x_train, y_train) # print metric to get performance print("Accuracy: ",model.score(x_test, y_test) * 100) # decision tree from sklearn.tree import DecisionTreeClassifier model = DecisionTreeClassifier() model.fit(x_train, y_train) # print metric to get performance print("Accuracy: ",model.score(x_test, y_test) * 100) from sklearn.svm import SVC model = SVC() model.fit(x_train, y_train) # print metric to get performance print("Accuracy: ",model.score(x_test, y_test) * 100) from sklearn.ensemble import RandomForestClassifier model = RandomForestClassifier() model.fit(x_train, y_train) # print metric to get performance print("Accuracy: ",model.score(x_test, y_test) * 100)
https://github.com/tanjinadnanabir/qbosons-qiskit-hackathon
tanjinadnanabir
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() !pip install mlxtend !pip install lightgbm !pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git import pandas as pd import warnings warnings.filterwarnings('ignore') import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.patches import Patch from matplotlib.lines import Line2D from mlxtend.plotting import plot_decision_regions import seaborn as sns import networkx as nx from IPython.display import clear_output import plotly.graph_objects as go from plotly.subplots import make_subplots from sklearn import datasets from sklearn.datasets import make_hastie_10_2 from sklearn.ensemble import GradientBoostingClassifier, AdaBoostClassifier, RandomForestClassifier from sklearn import metrics from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score, classification_report from sklearn.preprocessing import LabelEncoder, StandardScaler, MinMaxScaler from sklearn.decomposition import PCA from sklearn.pipeline import make_pipeline from sklearn import svm from sklearn.svm import SVC from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.neural_network import MLPClassifier import lightgbm as lgbm from qiskit import Aer, execute from qiskit.opflow import Z, I, PauliExpectation, CircuitSampler, StateFn from qiskit.utils import QuantumInstance from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2 from qiskit.algorithms.optimizers import GradientDescent, COBYLA, SLSQP, ADAM from qiskit.visualization import plot_state_city from qiskit_machine_learning.kernels import QuantumKernel from qiskit_machine_learning.algorithms import QSVC from qc_grader.utilities.graph_util import display_maxcut_widget, QAOA_widget from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors import pauli_error, depolarizing_error from qiskit.utils.mitigation import complete_meas_cal, CompleteMeasFitter from qiskit.opflow.gradients import Gradient, NaturalGradient, QFI, Hessian #from qiskit.algorithms.MulticlassExtension import AllPairs iris = datasets.load_iris() print(iris) iris.feature_names iris.target_names iris_df_data = pd.DataFrame(iris.data, columns = iris.feature_names) iris_df_target = pd.DataFrame(iris.target, columns = ['Iris Label']) iris_df_data # printing iris.data iris_df_target # printing iris.target; 0 : Setosa, 1: Versicolour, 2 : Virginica iris_df_data.describe() # standard decription of data iris_df_data.info() # standard info about data iris_df_data.columns # listing out column names of data iris_df_data['sepal length (cm)'].hist() # histogram plotting of data iris_df_data['sepal width (cm)'].hist() iris_df_data['petal length (cm)'].hist() iris_df_data['petal width (cm)'].hist() iris_df_target['Iris Label'].hist() # This means all flowers have equal number of samples # scatterplot of data irisSB = sns.load_dataset('iris') sns.set_style("darkgrid") sns.FacetGrid(irisSB, hue = "species", height = 6).map(plt.scatter, 'sepal_length', 'sepal_width').add_legend() sns.FacetGrid(irisSB, hue = "species", height = 6).map(plt.scatter, 'petal_length', 'petal_width').add_legend() sns.FacetGrid(irisSB, hue = "species", height = 6).map(plt.scatter, 'sepal_length', 'petal_length').add_legend() sns.FacetGrid(irisSB, hue = "species", height = 6).map(plt.scatter, 'sepal_width', 'petal_width').add_legend() # Pair Plot sns.pairplot(irisSB, hue = 'species') # Distplot for data plot = sns.FacetGrid(irisSB, hue = "species") plot.map(sns.distplot, "sepal_length").add_legend() plot = sns.FacetGrid(irisSB, hue = "species") plot.map(sns.distplot, "sepal_width").add_legend() plot = sns.FacetGrid(irisSB, hue = "species") plot.map(sns.distplot, "petal_length").add_legend() plot = sns.FacetGrid(irisSB, hue = "species") plot.map(sns.distplot, "petal_width").add_legend() plt.show() # Boxplot graph of features VS flower types def graph(y): sns.boxplot(x = "species", y = y, data = irisSB) plt.figure(figsize=(10,10)) # Adding the subplot at the specified # grid position plt.subplot(221) graph('sepal_length') plt.subplot(222) graph('sepal_width') plt.subplot(223) graph('petal_length') plt.subplot(224) graph('petal_width') plt.show() # Outliers for the features sns.boxplot(x = 'sepal_length', data = irisSB) sns.boxplot(x = 'sepal_width', data = irisSB) ## To remove Sepal Width Outliers using IQR(Interquartile Range) ## Code is contained in Single Hashes!! ## IQR #Q1 = np.percentile(irisSB['sepal_width'], 25, interpolation = 'midpoint') #Q3 = np.percentile(irisSB['sepal_width'], 75, interpolation = 'midpoint') #IQR = Q3 - Q1 #print("Old Shape: ", irisSB.shape) ## Upper bound #upper = np.where(irisSB['sepal_width'] >= (Q3+1.5*IQR)) ## Lower bound #lower = np.where(irisSB['sepal_width'] <= (Q1-1.5*IQR)) ## Removing the Outliers #irisSB.drop(upper[0], inplace = True) #irisSB.drop(lower[0], inplace = True) #print("New Shape: ", irisSB.shape) #sns.boxplot(x = 'sepal_width', data = irisSB) sns.boxplot(x = 'petal_length', data = irisSB) sns.boxplot(x = 'petal_width', data = irisSB) # Correlation Matrix iris_df_data.corr() # Petal Length and Petal Width have high correlation # Correlation Matrix Heatmap corr = iris_df_data.corr() fig, ax = plt.subplots(figsize=(5,4)) sns.heatmap(corr, annot=True, ax=ax, cmap = 'coolwarm') # cmap = 'darkgrid' for light colours sepal_length = iris['data'][:, 0] sepal_width = iris['data'][:, 1] petal_length = iris['data'][:, 2] petal_width = iris['data'][:, 3] target = iris['target'] #X = np.column_stack((sepal_length, sepal_width, petal_length, petal_width)) X = np.column_stack((sepal_length, sepal_width, petal_length, petal_width)) x = np.column_stack((sepal_length, sepal_width, petal_length)) # correlation of petal width and petal length is high, hence reducing variable Y = target x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2, random_state = 345) # Reduce dimensions n_dim = 4 pca = PCA(n_components = n_dim).fit(x_train) x_train = pca.transform(x_train) x_test = pca.transform(x_test) # Normalise std_scale = StandardScaler().fit(x_train) x_train = std_scale.transform(x_train) x_test = std_scale.transform(x_test) # Scale samples = np.append(x_train, x_test, axis = 0) minmax_scale = MinMaxScaler((-1, 1)).fit(samples) x_train = minmax_scale.transform(x_train) x_test = minmax_scale.transform(x_test) C = 1 # Regularlization Parameter clf_CSVC = make_pipeline(SVC(C = C, decision_function_shape = 'ovo')) # default kernel is ' RBF ' model_CSVC = clf_CSVC.fit(x_train, y_train) # CSVC Model Creation model_CSVC.score(x_test, y_test) # CSVC Model score against test data # Plotting Decision regions # The dimension should be 2 for plotting purposes # Also choose 2 features of the dataset #plot_decision_regions(X = x_test, y = y_test, clf = model_CSVC, legend = 1) # Split dataset sample_train, sample_test, label_train, label_test = train_test_split( x, Y, test_size = 0.2, random_state = 345) # Reduce dimensions n_dim = 3 pca = PCA(n_components = n_dim).fit(sample_train) sample_train = pca.transform(sample_train) sample_test = pca.transform(sample_test) # Normalise std_scale = StandardScaler().fit(sample_train) sample_train = std_scale.transform(sample_train) sample_test = std_scale.transform(sample_test) # Scale samples = np.append(sample_train, sample_test, axis=0) minmax_scale = MinMaxScaler((-1, 1)).fit(samples) sample_train = minmax_scale.transform(sample_train) sample_test = minmax_scale.transform(sample_test) # Select train_size = 120 sample_train = sample_train[:train_size] label_train = label_train[:train_size] test_size = 30 sample_test = sample_test[:test_size] label_test = label_test[:test_size] # Backend and Quantum Instance backend = Aer.get_backend('statevector_simulator') q_instance = QuantumInstance(backend, shots = 8192, seed_simulator = 345, seed_transpiler = 345) # Feature Map to convert classical data to quantum data, basically a parameterized Quantum Circuit # Can be used to map seemingly unseparable data to separable form, with respect to hyperplanes, in some higher dimension # This is achieved by e.g. rotation gate parameters depend on data features, etc. dim = 3 # Feature Dimension = number of qubits feature_map = ZZFeatureMap(feature_dimension = dim, reps = 1, entanglement = 'linear', insert_barriers = True, parameter_prefix = 'x').decompose() feature_map.draw('mpl', style = 'iqx') # Quantum Kernel q_kernel = QuantumKernel(feature_map = feature_map, quantum_instance = q_instance) q_circuit = q_kernel.construct_circuit(sample_train[0], sample_train[1]) q_circuit.decompose().decompose().draw(output = 'mpl') # Noise Model : Measurement error def get_noise(pm,pg): error_meas = pauli_error([('X',pm), ('I', 1 - pm)]) error_gate1 = depolarizing_error(pg,1) error_gate2 = error_gate1.tensor(error_gate1) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error_meas, "measure") # measurement error is applied to measurements noise_model.add_all_qubit_quantum_error(error_gate1, ["h"]) # single qubit gate error is applied to H gates noise_model.add_all_qubit_quantum_error(error_gate1, ["p"]) # single qubit gate error is applied to P gates noise_model.add_all_qubit_quantum_error(error_gate2, ["cx"]) # two qubit gate error is applied to CX gates return noise_model noise_model = get_noise(0.01,0.01) # Without Noise job = execute(q_circuit, backend = backend, shots = 10000, seed_simulator = 345, seed_transpiler = 345) counts = job.result().get_counts(q_circuit) plot_histogram(counts) # With Noise Noisy_job = execute(q_circuit, backend = backend, shots = 10000, seed_simulator = 345, seed_transpiler = 345, noise_model = noise_model) Noisy_counts = Noisy_job.result().get_counts(q_circuit) plot_histogram(Noisy_counts) # Error mitigation meas_calibs, state_labels = complete_meas_cal(qr = 3, circlabel =' mcal') cal_results = execute(meas_calibs, backend = backend, shots = 10000, seed_simulator = 345, seed_transpiler = 345, noise_model=noise_model).result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') meas_filter = meas_fitter.filter mitigated_results = meas_filter.apply(Noisy_job.result()) mitigated_counts = mitigated_results.get_counts(q_circuit) plot_histogram(mitigated_counts) plot_histogram([counts, Noisy_counts, mitigated_counts], legend = ['Without Noisy','Noisy', 'Mitigated']) # As we can see from the plot, the noise will not affect the score a lot, as the plots are similar in nature # Kernel Matrix Evaluation matrix_train = q_kernel.evaluate(x_vec = sample_train) matrix_test = q_kernel.evaluate(x_vec = sample_test, y_vec = sample_train) fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].imshow(np.asmatrix(matrix_train), interpolation = 'nearest', origin = 'upper', cmap = 'Blues') axs[0].set_title("training kernel matrix") axs[1].imshow(np.asmatrix(matrix_test), interpolation = 'nearest', origin = 'upper', cmap = 'Reds') axs[1].set_title("testing kernel matrix") plt.show() qpc_svc = make_pipeline(SVC(kernel='precomputed', C = 100)) # QSVC precomputed qpc_svc.fit(matrix_train, label_train) qpc_score = qpc_svc.score(matrix_test, label_test) print(f'Precomputed kernel classification test score: {qpc_score}') # best possible score we got after after trying many combinations """ NOTE : On using the multiclass extension function = " AllPairs " on a previous version of Qiskit, we get score of 1! Hope they introduce it back! """ """ This work of ours is a result of 'Qiskit Fall Fest Kolkata Chapter Hackathon', hosted by Mr. Ritajit Majumdar and Ms. Debasmita Bhowmik from Indian Statistical Institute, in collaboration with IBM Quantum""" # Authors # Vismay Joshi, National Institute Of Technology, Agartala # Tanjin Adnan Abir, Jahangirnagar University # Abhishek Rawat, TCG CREST # Suprabhat Sinha, D Y Patil International University # Rajat Lakhera, Sri Dev Suman Uttarakhand University import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/tanjinadnanabir/qbosons-qiskit-hackathon
tanjinadnanabir
from qiskit import BasicAer from qiskit.utils import QuantumInstance, algorithm_globals from qiskit.algorithms.optimizers import COBYLA, SLSQP from qiskit.circuit.library import TwoLocal, ZZFeatureMap,RealAmplitudes from qiskit_machine_learning.algorithms import VQC from qiskit_machine_learning.datasets import ad_hoc_data seed = 1376 algorithm_globals.random_seed = seed import pandas as pd import numpy as np Iris_data=pd.read_csv('Iris.csv') Iris_data.drop(['Id'], axis=1) # print(Iris_data) # Iris_data.head() # import numpy as np # d = np.loadtxt("Iris.csv", delimiter=",") feature_cols = [ 'SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm' ] target_col = ['Species'] from sklearn.model_selection import train_test_split xtrain = Iris_data[feature_cols] ytrain = Iris_data[target_col]#.astype(int) # ytrain = pd.get_dummies(Iris_data, columns = ['Species']) # print(ytrain) ytrain_new = pd.get_dummies(ytrain, columns=["Species"]) # print("The transform data using get_dummies") # print(ytrain_new) x_train, x_test, y_train, y_test = train_test_split(xtrain, ytrain_new, test_size=0.25, random_state=42) x_train.shape, x_test.shape, y_train.shape, y_test.shape # sv = Statevector.from_label('0' * n) # feature_map = ZZFeatureMap(feature_dimension=len(feature_cols), reps=2, entanglement="linear") feature_map = ZZFeatureMap(feature_dimension=4, reps=3, entanglement='linear', insert_barriers=True) # ansatz = RealAmplitudes(4, reps=1) ansatz = TwoLocal(num_qubits=4, reps=3, rotation_blocks=['ry','rz'], entanglement_blocks='cx', entanglement='circular', insert_barriers=True) # ansatz = TwoLocal(feature_map.num_qubits, ['ry', 'rz'], 'cz', reps=3) circuit = feature_map.combine(ansatz) circuit.decompose().draw(output='mpl') import numpy as np import matplotlib.pyplot as plt from IPython.display import clear_output # callback function that draws a live plot when the .fit() method is called def callback_graph(weights, obj_func_eval): clear_output(wait=True) objective_func_vals.append(obj_func_eval) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() vqc = VQC(feature_map=feature_map, ansatz=ansatz, optimizer=COBYLA(maxiter=250), quantum_instance=QuantumInstance(BasicAer.get_backend('statevector_simulator'), shots=1024, seed_simulator=seed, seed_transpiler=seed),callback=callback_graph ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data vqc.fit(x_train, y_train.to_numpy()) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier vqc.score(x_test, y_test.to_numpy()) print(f"Testing accuracy: {score:0.2f}") import os from qiskit import QuantumCircuit, transpile, Aer from qiskit.providers.aer import QasmSimulator from qiskit.providers.aer.noise import NoiseModel import numpy as np from qiskit import QuantumCircuit, transpile from qiskit.quantum_info import Kraus, SuperOp from qiskit.providers.aer import AerSimulator from qiskit.tools.visualization import plot_histogram from qiskit.test.mock import FakeVigo device_backend = FakeVigo() backend = Aer.get_backend('aer_simulator') counts1 = [] values1 = [] noise_model = None device = QasmSimulator.from_backend(device_backend) coupling_map = device.configuration().coupling_map noise_model = NoiseModel.from_backend(device) basis_gates = noise_model.basis_gates print(noise_model) print() algorithm_globals.random_seed = seed qi = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed, coupling_map=coupling_map, noise_model=noise_model,) vqc = VQC(feature_map=feature_map, ansatz=ansatz, optimizer=COBYLA(maxiter=250), quantum_instance=qi,callback=callback_graph ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data vqc.fit(x_train, y_train.to_numpy()) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier vqc.score(x_test, y_test.to_numpy()) print(f"Testing accuracy: {score:0.2f}") from qiskit.utils.mitigation import CompleteMeasFitter counts2 = [] values2 = [] if noise_model is not None: algorithm_globals.random_seed = seed qi2 = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed, coupling_map=coupling_map, noise_model=noise_model, measurement_error_mitigation_cls=CompleteMeasFitter, cals_matrix_refresh_period=30) vqc = VQC(feature_map=feature_map, ansatz=ansatz, optimizer=COBYLA(maxiter=250), quantum_instance=qi2,callback=callback_graph ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data vqc.fit(x_train, y_train.to_numpy()) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier vqc.score(x_test, y_test.to_numpy()) print(f"Testing accuracy: {score:0.2f}") from qiskit.algorithms.optimizers import SPSA vqc = VQC(feature_map=feature_map, ansatz=ansatz, optimizer=SPSA(maxiter=100), quantum_instance=QuantumInstance(BasicAer.get_backend('statevector_simulator'), shots=1024, seed_simulator=seed, seed_transpiler=seed),callback=callback_graph ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data vqc.fit(x_train, y_train.to_numpy()) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier vqc.score(x_test, y_test.to_numpy()) print(f"Testing accuracy: {score:0.2f}") vqc = VQC(feature_map=feature_map, ansatz=ansatz, optimizer=SPSA(maxiter=250), quantum_instance=qi,callback=callback_graph ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data vqc.fit(x_train, y_train.to_numpy()) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier vqc.score(x_test, y_test.to_numpy()) print(f"Testing accuracy: {score:0.2f}") vqc = VQC(feature_map=feature_map, ansatz=ansatz, optimizer=SPSA(maxiter=250), quantum_instance=qi2,callback=callback_graph ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data vqc.fit(x_train, y_train.to_numpy()) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier vqc.score(x_test, y_test.to_numpy()) print(f"Testing accuracy: {score:0.2f}")
https://github.com/avkhadiev/schwinger-vqe
avkhadiev
#Assign these values as per your requirements. global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion min_qubits=1 max_qubits=3 skip_qubits=1 max_circuits=3 num_shots=1000 use_XX_YY_ZZ_gates = True Noise_Inclusion = False saveplots = False Memory_utilization_plot = True Type_of_Simulator = "built_in" #Inputs are "built_in" or "FAKE" or "FAKEV2" backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends gate_counts_plots = True #Change your Specification of Simulator in Declaring Backend Section #By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2() import numpy as np import os,json from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute import time import matplotlib.pyplot as plt # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error) # Benchmark Name benchmark_name = "Hamiltonian Simulation" # Selection of basis gate set for transpilation # Note: selector 1 is a hardware agnostic gate set basis_selector = 1 basis_gates_array = [ [], ['rx', 'ry', 'rz', 'cx'], # a common basis set, default ['cx', 'rz', 'sx', 'x'], # IBM default basis set ['rx', 'ry', 'rxx'], # IonQ default basis set ['h', 'p', 'cx'], # another common basis set ['u', 'cx'] # general unitaries basis gates ] np.random.seed(0) num_gates = 0 depth = 0 def get_QV(backend): import json # Assuming backend.conf_filename is the filename and backend.dirname is the directory path conf_filename = backend.dirname + "/" + backend.conf_filename # Open the JSON file with open(conf_filename, 'r') as file: # Load the JSON data data = json.load(file) # Extract the quantum_volume parameter QV = data.get('quantum_volume', None) return QV def checkbackend(backend_name,Type_of_Simulator): if Type_of_Simulator == "built_in": available_backends = [] for i in Aer.backends(): available_backends.append(i.name) if backend_name in available_backends: platform = backend_name return platform else: print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!") print(f"available backends are : {available_backends}") platform = "qasm_simulator" return platform elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2": import qiskit.providers.fake_provider as fake_backends if hasattr(fake_backends,backend_name) is True: print(f"Backend {backend_name} is available for type {Type_of_Simulator}.") backend_class = getattr(fake_backends,backend_name) backend_instance = backend_class() return backend_instance else: print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!") if Type_of_Simulator == "FAKEV2": backend_class = getattr(fake_backends,"FakeSantiagoV2") else: backend_class = getattr(fake_backends,"FakeSantiago") backend_instance = backend_class() return backend_instance if Type_of_Simulator == "built_in": platform = checkbackend(backend_name,Type_of_Simulator) #By default using "Qasm Simulator" backend = Aer.get_backend(platform) QV_=None print(f"{platform} device is capable of running {backend.num_qubits}") print(f"backend version is {backend.backend_version}") elif Type_of_Simulator == "FAKE": basis_selector = 0 backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting. max_qubits=backend.configuration().n_qubits print(f"{platform} device is capable of running {backend.configuration().n_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") elif Type_of_Simulator == "FAKEV2": basis_selector = 0 if "V2" not in backend_name: backend_name = backend_name+"V2" backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.name +"-" +backend.backend_version max_qubits=backend.num_qubits print(f"{platform} device is capable of running {backend.num_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") else: print("Enter valid Simulator.....") # saved circuits and subcircuits for display QC_ = None XX_ = None YY_ = None ZZ_ = None XXYYZZ_ = None # import precalculated data to compare against filename = os.path.join("precalculated_data.json") with open(filename, 'r') as file: data = file.read() precalculated_data = json.loads(data) ############### Circuit Definition def HamiltonianSimulation(n_spins, K, t, w, h_x, h_z): ''' Construct a Qiskit circuit for Hamiltonian Simulation :param n_spins:The number of spins to simulate :param K: The Trotterization order :param t: duration of simulation :return: return a Qiskit circuit for this Hamiltonian ''' num_qubits = n_spins secret_int = f"{K}-{t}" # allocate qubits qr = QuantumRegister(n_spins); cr = ClassicalRegister(n_spins); qc = QuantumCircuit(qr, cr, name=f"hamsim-{num_qubits}-{secret_int}") tau = t / K # start with initial state of 1010101... for k in range(0, n_spins, 2): qc.x(qr[k]) qc.barrier() # loop over each trotter step, adding gates to the circuit defining the hamiltonian for k in range(K): # the Pauli spin vector product [qc.rx(2 * tau * w * h_x[i], qr[i]) for i in range(n_spins)] [qc.rz(2 * tau * w * h_z[i], qr[i]) for i in range(n_spins)] qc.barrier() # Basic implementation of exp(i * t * (XX + YY + ZZ)) if _use_XX_YY_ZZ_gates: # XX operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(xx_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # YY operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(yy_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # ZZ operation on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(zz_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # Use an optimal XXYYZZ combined operator # See equation 1 and Figure 6 in https://arxiv.org/pdf/quant-ph/0308006.pdf else: # optimized XX + YY + ZZ operator on each pair of qubits in linear chain for j in range(2): for i in range(j % 2, n_spins - 1, 2): qc.append(xxyyzz_opt_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) qc.barrier() # measure all the qubits used in the circuit for i_qubit in range(n_spins): qc.measure(qr[i_qubit], cr[i_qubit]) # save smaller circuit example for display global QC_ if QC_ == None or n_spins <= 6: if n_spins < 9: QC_ = qc return qc ############### XX, YY, ZZ Gate Implementations # Simple XX gate on q0 and q1 with angle 'tau' def xx_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xx_gate") qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) # save circuit example for display global XX_ XX_ = qc return qc # Simple YY gate on q0 and q1 with angle 'tau' def yy_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="yy_gate") qc.s(qr[0]) qc.s(qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.sdg(qr[0]) qc.sdg(qr[1]) # save circuit example for display global YY_ YY_ = qc return qc # Simple ZZ gate on q0 and q1 with angle 'tau' def zz_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="zz_gate") qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) # save circuit example for display global ZZ_ ZZ_ = qc return qc # Optimal combined XXYYZZ gate (with double coupling) on q0 and q1 with angle 'tau' def xxyyzz_opt_gate(tau): alpha = tau; beta = tau; gamma = tau qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xxyyzz_opt") qc.rz(3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(3.1416*gamma - 3.1416/2, qr[0]) qc.ry(3.1416/2 - 3.1416*alpha, qr[1]) qc.cx(qr[0], qr[1]) qc.ry(3.1416*beta - 3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(-3.1416/2, qr[0]) # save circuit example for display global XXYYZZ_ XXYYZZ_ = qc return qc # Create an empty noise model noise_parameters = NoiseModel() if Type_of_Simulator == "built_in": # Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5% depol_one_qb_error = 0.05 depol_two_qb_error = 0.005 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx']) # Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0% amp_damp_one_qb_error = 0.0 amp_damp_two_qb_error = 0.0 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx']) # Add reset noise to all single qubit resets reset_to_zero_error = 0.005 reset_to_one_error = 0.005 noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"]) # Add readout error p0given1_error = 0.000 p1given0_error = 0.000 error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]]) noise_parameters.add_all_qubit_readout_error(error_meas) #print(noise_parameters) elif Type_of_Simulator == "FAKE"or"FAKEV2": noise_parameters = NoiseModel.from_backend(backend) #print(noise_parameters) ### Analysis methods to be expanded and eventually compiled into a separate analysis.py file import math, functools def hellinger_fidelity_with_expected(p, q): """ p: result distribution, may be passed as a counts distribution q: the expected distribution to be compared against References: `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ Qiskit Hellinger Fidelity Function """ p_sum = sum(p.values()) q_sum = sum(q.values()) if q_sum == 0: print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0") return 0 p_normed = {} for key, val in p.items(): p_normed[key] = val/p_sum # if p_sum != 0: # p_normed[key] = val/p_sum # else: # p_normed[key] = 0 q_normed = {} for key, val in q.items(): q_normed[key] = val/q_sum total = 0 for key, val in p_normed.items(): if key in q_normed.keys(): total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2 del q_normed[key] else: total += val total += sum(q_normed.values()) # in some situations (error mitigation) this can go negative, use abs value if total < 0: print(f"WARNING: using absolute value in fidelity calculation") total = abs(total) dist = np.sqrt(total)/np.sqrt(2) fidelity = (1-dist**2)**2 return fidelity def polarization_fidelity(counts, correct_dist, thermal_dist=None): """ Combines Hellinger fidelity and polarization rescaling into fidelity calculation used in every benchmark counts: the measurement outcomes after `num_shots` algorithm runs correct_dist: the distribution we expect to get for the algorithm running perfectly thermal_dist: optional distribution to pass in distribution from a uniform superposition over all states. If `None`: generated as `uniform_dist` with the same qubits as in `counts` returns both polarization fidelity and the hellinger fidelity Polarization from: `https://arxiv.org/abs/2008.11294v1` """ num_measured_qubits = len(list(correct_dist.keys())[0]) #print(num_measured_qubits) counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()} # calculate hellinger fidelity between measured expectation values and correct distribution hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist) # to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits if num_measured_qubits > 16: return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity } # if not provided, generate thermal dist based on number of qubits if thermal_dist == None: thermal_dist = uniform_dist(num_measured_qubits) # set our fidelity rescaling value as the hellinger fidelity for a depolarized state floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist) # rescale fidelity result so uniform superposition (random guessing) returns fidelity # rescaled to 0 to provide a better measure of success of the algorithm (polarization) new_floor_fidelity = 0 fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity) return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity } ## Uniform distribution function commonly used def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity): """ Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks fidelity: raw fidelity to rescale floor_fidelity: threshold fidelity which is equivalent to random guessing new_floor_fidelity: what we rescale the floor_fidelity to Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0: 1 -> 1; 0.25 -> 0; 0.5 -> 0.3333; """ rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1 # ensure fidelity is within bounds (0, 1) if rescaled_fidelity < 0: rescaled_fidelity = 0.0 if rescaled_fidelity > 1: rescaled_fidelity = 1.0 return rescaled_fidelity def uniform_dist(num_state_qubits): dist = {} for i in range(2**num_state_qubits): key = bin(i)[2:].zfill(num_state_qubits) dist[key] = 1/(2**num_state_qubits) return dist from matplotlib.patches import Rectangle import matplotlib.cm as cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize from matplotlib.patches import Circle ############### Color Map functions # Create a selection of colormaps from which to choose; default to custom_spectral cmap_spectral = plt.get_cmap('Spectral') cmap_greys = plt.get_cmap('Greys') cmap_blues = plt.get_cmap('Blues') cmap_custom_spectral = None # the default colormap is the spectral map cmap = cmap_spectral cmap_orig = cmap_spectral # current cmap normalization function (default None) cmap_norm = None default_fade_low_fidelity_level = 0.16 default_fade_rate = 0.7 # Specify a normalization function here (default None) def set_custom_cmap_norm(vmin, vmax): global cmap_norm if vmin == vmax or (vmin == 0.0 and vmax == 1.0): print("... setting cmap norm to None") cmap_norm = None else: print(f"... setting cmap norm to [{vmin}, {vmax}]") cmap_norm = Normalize(vmin=vmin, vmax=vmax) # Remake the custom spectral colormap with user settings def set_custom_cmap_style( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): #print("... set custom map style") global cmap, cmap_custom_spectral, cmap_orig cmap_custom_spectral = create_custom_spectral_cmap( fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate) cmap = cmap_custom_spectral cmap_orig = cmap_custom_spectral # Create the custom spectral colormap from the base spectral def create_custom_spectral_cmap( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): # determine the breakpoint from the fade level num_colors = 100 breakpoint = round(fade_low_fidelity_level * num_colors) # get color list for spectral map spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)] #print(fade_rate) # create a list of colors to replace those below the breakpoint # and fill with "faded" color entries (in reverse) low_colors = [0] * breakpoint #for i in reversed(range(breakpoint)): for i in range(breakpoint): # x is index of low colors, normalized 0 -> 1 x = i / breakpoint # get color at this index bc = spectral_colors[i] r0 = bc[0] g0 = bc[1] b0 = bc[2] z0 = bc[3] r_delta = 0.92 - r0 #print(f"{x} {bc} {r_delta}") # compute saturation and greyness ratio sat_ratio = 1 - x #grey_ratio = 1 - x ''' attempt at a reflective gradient if i >= breakpoint/2: xf = 2*(x - 0.5) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (yf + 0.5) else: xf = 2*(0.5 - x) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (0.5 - yf) ''' grey_ratio = 1 - math.pow(x, 1/fade_rate) #print(f" {xf} {yf} ") #print(f" {sat_ratio} {grey_ratio}") r = r0 + r_delta * sat_ratio g_delta = r - g0 b_delta = r - b0 g = g0 + g_delta * grey_ratio b = b0 + b_delta * grey_ratio #print(f"{r} {g} {b}\n") low_colors[i] = (r,g,b,z0) #print(low_colors) # combine the faded low colors with the regular spectral cmap to make a custom version cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:]) #spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)] #for i in range(10): print(spectral_colors[i]) #print("") return cmap_custom_spectral # Make the custom spectral color map the default on module init set_custom_cmap_style() # Arrange the stored annotations optimally and add to plot def anno_volumetric_data(ax, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True): # sort all arrays by the x point of the text (anno_offs) global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos)) x_anno_offs = [a for a,b,c,d,e in all_annos] y_anno_offs = [b for a,b,c,d,e in all_annos] anno_labels = [c for a,b,c,d,e in all_annos] x_annos = [d for a,b,c,d,e in all_annos] y_annos = [e for a,b,c,d,e in all_annos] #print(f"{x_anno_offs}") #print(f"{y_anno_offs}") #print(f"{anno_labels}") for i in range(len(anno_labels)): x_anno = x_annos[i] y_anno = y_annos[i] x_anno_off = x_anno_offs[i] y_anno_off = y_anno_offs[i] label = anno_labels[i] if i > 0: x_delta = abs(x_anno_off - x_anno_offs[i - 1]) y_delta = abs(y_anno_off - y_anno_offs[i - 1]) if y_delta < 0.7 and x_delta < 2: y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6 #x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1 ax.annotate(label, xy=(x_anno+0.0, y_anno+0.1), arrowprops=dict(facecolor='black', shrink=0.0, width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)), xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='baseline', color=(0.2,0.2,0.2), clip_on=True) if saveplots == True: plt.savefig("VolumetricPlotSample.jpg") # Plot one group of data for volumetric presentation def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True, x_size=1.0, y_size=1.0, zorder=1, offset_flag=False, max_depth=0, suppress_low_fidelity=False): # since data may come back out of order, save point at max y for annotation i_anno = 0 x_anno = 0 y_anno = 0 # plot data rectangles low_fidelity_count = True last_y = -1 k = 0 # determine y-axis dimension for one pixel to use for offset of bars that start at 0 (_, dy) = get_pixel_dims(ax) # do this loop in reverse to handle the case where earlier cells are overlapped by later cells for i in reversed(range(len(d_data))): x = depth_index(d_data[i], depth_base) y = float(w_data[i]) f = f_data[i] # each time we star a new row, reset the offset counter # DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars # that represent time starting from 0 secs. We offset by one pixel each and center the group if y != last_y: last_y = y; k = 3 # hardcoded for 8 cells, offset by 3 #print(f"{i = } {x = } {y = }") if max_depth > 0 and d_data[i] > max_depth: #print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}") break; # reject cells with low fidelity if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True # the only time this is False is when doing merged gradation plots if do_border == True: # this case is for an array of x_sizes, i.e. each box has different width if isinstance(x_size, list): # draw each of the cells, with no offset if not offset_flag: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder)) # use an offset for y value, AND account for x and width to draw starting at 0 else: ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder)) # this case is for only a single cell else: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size)) # save the annotation point with the largest y value if y >= y_anno: x_anno = x y_anno = y i_anno = i # move the next bar down (if using offset) k -= 1 # if no data rectangles plotted, no need for a label if x_anno == 0 or y_anno == 0: return x_annos.append(x_anno) y_annos.append(y_anno) anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 ) # adjust radius of annotation circle based on maximum width of apps anno_max = 10 if w_max > 10: anno_max = 14 if w_max > 14: anno_max = 18 scale = anno_max / anno_dist # offset of text from end of arrow if scale > 1: x_anno_off = scale * x_anno - x_anno - 0.5 y_anno_off = scale * y_anno - y_anno else: x_anno_off = 0.7 y_anno_off = 0.5 x_anno_off += x_anno y_anno_off += y_anno # print(f"... {xx} {yy} {anno_dist}") x_anno_offs.append(x_anno_off) y_anno_offs.append(y_anno_off) anno_labels.append(label) if do_label: ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2)) x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # init arrays to hold annotation points for label spreading def vplot_anno_init (): global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # Number of ticks on volumetric depth axis max_depth_log = 22 # average transpile factor between base QV depth and our depth based on results from QV notebook QV_transpile_factor = 12.7 # format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1 # (sign handling may be incorrect) def format_number(num, digits=0): if isinstance(num, str): num = float(num) num = float('{:.3g}'.format(abs(num))) sign = '' metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1} for index in metric: num_check = num / metric[index] if num_check >= 1: num = round(num_check, digits) sign = index break numstr = f"{str(num)}" if '.' in numstr: numstr = numstr.rstrip('0').rstrip('.') return f"{numstr}{sign}" # Return the color associated with the spcific value, using color map norm def get_color(value): # if there is a normalize function installed, scale the data if cmap_norm: value = float(cmap_norm(value)) if cmap == cmap_spectral: value = 0.05 + value*0.9 elif cmap == cmap_blues: value = 0.00 + value*1.0 else: value = 0.0 + value*0.95 return cmap(value) # Return the x and y equivalent to a single pixel for the given plot axis def get_pixel_dims(ax): # transform 0 -> 1 to pixel dimensions pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0)) xpix = pixdims[1][0] ypix = pixdims[0][1] #determine x- and y-axis dimension for one pixel dx = (1 / xpix) dy = (1 / ypix) return (dx, dy) ############### Helper functions # return the base index for a circuit depth value # take the log in the depth base, and add 1 def depth_index(d, depth_base): if depth_base <= 1: return d if d == 0: return 0 return math.log(d, depth_base) + 1 # draw a box at x,y with various attributes def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1): value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.5*y_size, zorder=zorder) # draw a circle at x,y with various attributes def circle_at(x, y, value, type=1, fill=True): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Circle((x, y), size/2, alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell edgecolor = ec, facecolor = fc, fill=fill, lw=0.5) def box4_at(x, y, value, type=1, fill=True, alpha=1.0): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.3,0.3,0.3) ec = fc return Rectangle((x - size/8, y - size/2), size/4, size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.1) # Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value def qv_box_at(x, y, qv_width, qv_depth, value, depth_base): #print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}") return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width, edgecolor = (value,value,value), facecolor = (value,value,value), fill=True, lw=1) def bkg_box_at(x, y, value=0.9): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (value,value,value), fill=True, lw=0.5) def bkg_empty_box_at(x, y): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (1.0,1.0,1.0), fill=True, lw=0.5) # Plot the background for the volumetric analysis def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"): if suptitle == None: suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}" QV0 = QV qv_estimate = False est_str = "" if QV == 0: # QV = 0 indicates "do not draw QV background or label" QV = 2048 elif QV < 0: # QV < 0 indicates "add est. to label" QV = -QV qv_estimate = True est_str = " (est.)" if avail_qubits > 0 and max_qubits > avail_qubits: max_qubits = avail_qubits max_width = 13 if max_qubits > 11: max_width = 18 if max_qubits > 14: max_width = 20 if max_qubits > 16: max_width = 24 if max_qubits > 24: max_width = 33 #print(f"... {avail_qubits} {max_qubits} {max_width}") plot_width = 6.8 plot_height = 0.5 + plot_width * (max_width / max_depth_log) #print(f"... {plot_width} {plot_height}") # define matplotlib figure and axis; use constrained layout to fit colorbar to right fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True) plt.suptitle(suptitle) plt.xlim(0, max_depth_log) plt.ylim(0, max_width) # circuit depth axis (x axis) xbasis = [x for x in range(1,max_depth_log)] xround = [depth_base**(x-1) for x in xbasis] xlabels = [format_number(x) for x in xround] ax.set_xlabel('Circuit Depth') ax.set_xticks(xbasis) plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor") # other label options #plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left') #plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor") # circuit width axis (y axis) ybasis = [y for y in range(1,max_width)] yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now ylabels = [str(y) for y in yround] # not used now #ax.set_ylabel('Circuit Width (Number of Qubits)') ax.set_ylabel('Circuit Width') ax.set_yticks(ybasis) #create simple line plot (not used right now) #ax.plot([0, 10],[0, 10]) log2QV = math.log2(QV) QV_width = log2QV QV_depth = log2QV * QV_transpile_factor # show a quantum volume rectangle of QV = 64 e.g. (6 x 6) if QV0 != 0: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base)) else: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base)) # the untranspiled version is commented out - we do not show this by default # also show a quantum volume rectangle un-transpiled # ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base)) # show 2D array of volumetric cells based on this QV_transpiled # DEVNOTE: we use +1 only to make the visuals work; s/b without # Also, the second arg of the min( below seems incorrect, needs correction maxprod = (QV_width + 1) * (QV_depth + 1) for w in range(1, min(max_width, round(QV) + 1)): # don't show VB squares if width greater than known available qubits if avail_qubits != 0 and w > avail_qubits: continue i_success = 0 for d in xround: # polarization factor for low circuit widths maxtest = maxprod / ( 1 - 1 / (2**w) ) # if circuit would fail here, don't draw box if d > maxtest: continue if w * d > maxtest: continue # guess for how to capture how hardware decays with width, not entirely correct # # reduce maxtext by a factor of number of qubits > QV_width # # just an approximation to account for qubit distances # if w > QV_width: # over = w - QV_width # maxtest = maxtest / (1 + (over/QV_width)) # draw a box at this width and depth id = depth_index(d, depth_base) # show vb rectangles; if not showing QV, make all hollow (or less dark) if QV0 == 0: #ax.add_patch(bkg_empty_box_at(id, w)) ax.add_patch(bkg_box_at(id, w, 0.95)) else: ax.add_patch(bkg_box_at(id, w, 0.9)) # save index of last successful depth i_success += 1 # plot empty rectangle after others d = xround[i_success] id = depth_index(d, depth_base) ax.add_patch(bkg_empty_box_at(id, w)) # Add annotation showing quantum volume if QV0 != 0: t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12, horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2), bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1)) # add colorbar to right of plot plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax, shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7)) return ax # Function to calculate circuit depth def calculate_circuit_depth(qc): # Calculate the depth of the circuit depth = qc.depth() return depth def calculate_transpiled_depth(qc,basis_selector): # use either the backend or one of the basis gate sets if basis_selector == 0: qc = transpile(qc, backend) else: basis_gates = basis_gates_array[basis_selector] qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0) transpiled_depth = qc.depth() return transpiled_depth,qc def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title): avg_fidelity_means = [] avg_Hf_fidelity_means = [] avg_num_qubits_values = list(fidelity_data.keys()) # Calculate the average fidelity and Hamming fidelity for each unique number of qubits for num_qubits in avg_num_qubits_values: avg_fidelity = np.average(fidelity_data[num_qubits]) avg_fidelity_means.append(avg_fidelity) avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits]) avg_Hf_fidelity_means.append(avg_Hf_fidelity) return avg_fidelity_means,avg_Hf_fidelity_means list_of_gates = [] def list_of_standardgates(): import qiskit.circuit.library as lib from qiskit.circuit import Gate import inspect # List all the attributes of the library module gate_list = dir(lib) # Filter out non-gate classes (like functions, variables, etc.) gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)] # Get method names from QuantumCircuit circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction) method_names = [name for name, _ in circuit_methods] # Map gate class names to method names gate_to_method = {} for gate in gates: gate_class = getattr(lib, gate) class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name for method in method_names: if method == class_name or method == class_name.replace('cr', 'c-r'): gate_to_method[gate] = method break # Add common operations that are not strictly gates additional_operations = { 'Measure': 'measure', 'Barrier': 'barrier', } gate_to_method.update(additional_operations) for k,v in gate_to_method.items(): list_of_gates.append(v) def update_counts(gates,custom_gates): operations = {} for key, value in gates.items(): operations[key] = value for key, value in custom_gates.items(): if key in operations: operations[key] += value else: operations[key] = value return operations def get_gate_counts(gates,custom_gate_defs): result = gates.copy() # Iterate over the gate counts in the quantum circuit for gate, count in gates.items(): if gate in custom_gate_defs: custom_gate_ops = custom_gate_defs[gate] # Multiply custom gate operations by the count of the custom gate in the circuit for _ in range(count): result = update_counts(result, custom_gate_ops) # Remove the custom gate entry as we have expanded it del result[gate] return result dict_of_qc = dict() custom_gates_defs = dict() # Function to count operations recursively def count_operations(qc): dict_of_qc.clear() circuit_traverser(qc) operations = dict() operations = dict_of_qc[qc.name] del dict_of_qc[qc.name] # print("operations :",operations) # print("dict_of_qc :",dict_of_qc) for keys in operations.keys(): if keys not in list_of_gates: for k,v in dict_of_qc.items(): if k in operations.keys(): custom_gates_defs[k] = v operations=get_gate_counts(operations,custom_gates_defs) custom_gates_defs.clear() return operations def circuit_traverser(qc): dict_of_qc[qc.name]=dict(qc.count_ops()) for i in qc.data: if str(i.operation.name) not in list_of_gates: qc_1 = i.operation.definition circuit_traverser(qc_1) def get_memory(): import resource usage = resource.getrusage(resource.RUSAGE_SELF) max_mem = usage.ru_maxrss/1024 #in MB return max_mem def analyzer(num_qubits): # we have precalculated the correct distribution that a perfect quantum computer will return # it is stored in the json file we import at the top of the code correct_dist = precalculated_data[f"Qubits - {num_qubits}"] return correct_dist num_state_qubits=1 #(default) not exposed to users def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, use_XX_YY_ZZ_gates = use_XX_YY_ZZ_gates): creation_times = [] elapsed_times = [] quantum_times = [] circuit_depths = [] transpiled_depths = [] fidelity_data = {} Hf_fidelity_data = {} numckts = [] mem_usage = [] algorithmic_1Q_gate_counts = [] algorithmic_2Q_gate_counts = [] transpiled_1Q_gate_counts = [] transpiled_2Q_gate_counts = [] print(f"{benchmark_name} Benchmark Program - {platform}") #defining all the standard gates supported by qiskit in a list if gate_counts_plots == True: list_of_standardgates() # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even skip_qubits = max(1, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") global _use_XX_YY_ZZ_gates _use_XX_YY_ZZ_gates = use_XX_YY_ZZ_gates if _use_XX_YY_ZZ_gates: print("... using unoptimized XX YY ZZ gates") global max_ckts max_ckts = max_circuits global min_qbits,max_qbits,skp_qubits min_qbits = min_qubits max_qbits = max_qubits skp_qubits = skip_qubits print(f"min, max qubits = {min_qubits} {max_qubits}") # Execute Benchmark Program N times for multiple circuit sizes for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): fidelity_data[num_qubits] = [] Hf_fidelity_data[num_qubits] = [] # reset random seed np.random.seed(0) # determine number of circuits to execute for this group num_circuits = max(1, max_circuits) print(f"Executing [{num_circuits}] circuits with num_qubits = {num_qubits}") numckts.append(num_circuits) # parameters of simulation #### CANNOT BE MODIFIED W/O ALSO MODIFYING PRECALCULATED DATA ######### w = precalculated_data['w'] # strength of disorder k = precalculated_data['k'] # Trotter error. # A large Trotter order approximates the Hamiltonian evolution better. # But a large Trotter order also means the circuit is deeper. # For ideal or noise-less quantum circuits, k >> 1 gives perfect hamiltonian simulation. t = precalculated_data['t'] # time of simulation ####################################################################### for circuit_id in range(num_circuits): print("*********************************************") print(f"qc of {num_qubits} qubits for circuit_id: {circuit_id}") #creation of Quantum Circuit. ts = time.time() h_x = precalculated_data['h_x'][:num_qubits] # precalculated random numbers between [-1, 1] h_z = precalculated_data['h_z'][:num_qubits] qc = HamiltonianSimulation(num_qubits, K=k, t=t, w=w, h_x= h_x, h_z=h_z) #creation time creation_time = time.time() - ts creation_times.append(creation_time) print(f"creation time = {creation_time*1000} ms") # Calculate gate count for the algorithmic circuit (excluding barriers and measurements) if gate_counts_plots == True: operations = count_operations(qc) n1q = 0; n2q = 0 if operations != None: for key, value in operations.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c") or key.startswith("mc"): n2q += value else: n1q += value algorithmic_1Q_gate_counts.append(n1q) algorithmic_2Q_gate_counts.append(n2q) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc=qc.decompose() #print(qc) # Calculate circuit depth depth = calculate_circuit_depth(qc) circuit_depths.append(depth) # Calculate transpiled circuit depth transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector) transpiled_depths.append(transpiled_depth) #print(qc) print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}") if gate_counts_plots == True: # Calculate gate count for the transpiled circuit (excluding barriers and measurements) tr_ops = qc.count_ops() #print("tr_ops = ",tr_ops) tr_n1q = 0; tr_n2q = 0 if tr_ops != None: for key, value in tr_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c"): tr_n2q += value else: tr_n1q += value transpiled_1Q_gate_counts.append(tr_n1q) transpiled_2Q_gate_counts.append(tr_n2q) print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}") print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}") #execution if Type_of_Simulator == "built_in": #To check if Noise is required if Noise_Inclusion == True: noise_model = noise_parameters else: noise_model = None ts = time.time() job = execute(qc, backend, shots=num_shots, noise_model=noise_model) elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" : ts = time.time() job = backend.run(qc,shots=num_shots, noise_model=noise_parameters) #retrieving the result result = job.result() #print(result) #calculating elapsed time elapsed_time = time.time() - ts elapsed_times.append(elapsed_time) # Calculate quantum processing time quantum_time = result.time_taken quantum_times.append(quantum_time) print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms") #counts in result object counts = result.get_counts() #Correct distribution to compare with counts correct_dist = analyzer(num_qubits) #fidelity calculation comparision of counts and correct_dist fidelity_dict = polarization_fidelity(counts, correct_dist) fidelity_data[num_qubits].append(fidelity_dict['fidelity']) Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity']) #maximum memory utilization (if required) if Memory_utilization_plot == True: max_mem = get_memory() print(f"Maximum Memory Utilized: {max_mem} MB") mem_usage.append(max_mem) print("*********************************************") ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if _use_XX_YY_ZZ_gates: print("\nXX, YY, ZZ =") print(XX_); print(YY_); print(ZZ_) else: print("\nXXYYZZ_opt =") print(XXYYZZ_) return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths, fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) # Execute the benchmark program, accumulate metrics, and calculate circuit depths (creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts, algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run() # Define the range of qubits for the x-axis num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits) print("num_qubits_range =",num_qubits_range) # Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits avg_creation_times = [] avg_elapsed_times = [] avg_quantum_times = [] avg_circuit_depths = [] avg_transpiled_depths = [] avg_1Q_algorithmic_gate_counts = [] avg_2Q_algorithmic_gate_counts = [] avg_1Q_Transpiled_gate_counts = [] avg_2Q_Transpiled_gate_counts = [] max_memory = [] start = 0 for num in numckts: avg_creation_times.append(np.mean(creation_times[start:start+num])) avg_elapsed_times.append(np.mean(elapsed_times[start:start+num])) avg_quantum_times.append(np.mean(quantum_times[start:start+num])) avg_circuit_depths.append(np.mean(circuit_depths[start:start+num])) avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num])) if gate_counts_plots == True: avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num]))) avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num]))) avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num]))) avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num]))) if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num])) start += num # Calculate the fidelity data avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison") # Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits # Add labels to the bars def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"): for rect in rects: height = rect.get_height() ax.annotate(str.format(height), # Formatting to two decimal places xy=(rect.get_x() + rect.get_width() / 2, height / 2), xytext=(0, 0), textcoords="offset points", ha='center', va=va,color=text_color,rotation=90) bar_width = 0.3 # Determine the number of subplots and their arrangement if Memory_utilization_plot and gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30)) # Plotting for both memory utilization and gate counts # ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available elif Memory_utilization_plot: fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30)) # Plotting for memory utilization only # ax1, ax2, ax3, ax6, ax7 are available elif gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30)) # Plotting for gate counts only # ax1, ax2, ax3, ax4, ax5, ax6 are available else: fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30)) # Default plotting # ax1, ax2, ax3, ax6 are available fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16) for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000 avg_creation_times[i] *= 1000 ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue') autolabel(ax1.patches, ax1) ax1.set_xlabel('Number of Qubits') ax1.set_ylabel('Average Creation Time (ms)') ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14) ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000 avg_elapsed_times[i] *= 1000 for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000 avg_quantum_times[i] *= 1000 Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time') Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time') autolabel(Elapsed,ax2,str='{:.1f}') autolabel(Quantum,ax2,str='{:.1f}') ax2.set_xlabel('Number of Qubits') ax2.set_ylabel('Average Time (ms)') ax2.set_title('Average Time vs Number of Qubits') ax2.legend() ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here autolabel(Normalized,ax3,str='{:.2f}') autolabel(Algorithmic,ax3,str='{:.2f}') ax3.set_xlabel('Number of Qubits') ax3.set_ylabel('Average Circuit Depth') ax3.set_title('Average Circuit Depth vs Number of Qubits') ax3.legend() if gate_counts_plots == True: ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_1Q_counts,ax4,str='{}') autolabel(Algorithmic_1Q_counts,ax4,str='{}') ax4.set_xlabel('Number of Qubits') ax4.set_ylabel('Average 1-Qubit Gate Counts') ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits') ax4.legend() ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_2Q_counts,ax5,str='{}') autolabel(Algorithmic_2Q_counts,ax5,str='{}') ax5.set_xlabel('Number of Qubits') ax5.set_ylabel('Average 2-Qubit Gate Counts') ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits') ax5.legend() ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here autolabel(Hellinger,ax6,str='{:.2f}') autolabel(Normalized,ax6,str='{:.2f}') ax6.set_xlabel('Number of Qubits') ax6.set_ylabel('Average Value') ax6.set_title("Fidelity Comparison") ax6.legend() if Memory_utilization_plot == True: ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations") autolabel(ax7.patches, ax7) ax7.set_xlabel('Number of Qubits') ax7.set_ylabel('Maximum Memory Utilized (MB)') ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14) plt.tight_layout(rect=[0, 0, 1, 0.96]) if saveplots == True: plt.savefig("ParameterPlotsSample.jpg") plt.show() # Quantum Volume Plot Suptitle = f"Volumetric Positioning - {platform}" appname=benchmark_name if QV_ == None: QV=2048 else: QV=QV_ depth_base =2 ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity") w_data = num_qubits_range # determine width for circuit w_max = 0 for i in range(len(w_data)): y = float(w_data[i]) w_max = max(w_max, y) d_tr_data = avg_transpiled_depths f_data = avg_f plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
https://github.com/avkhadiev/schwinger-vqe
avkhadiev
Energy evaluation 1 returned -0.314419 +/- 0.038533 Energy evaluation 2 returned -0.034149 +/- 0.036455 Energy evaluation 3 returned -0.252537 +/- 0.036098 Energy evaluation 4 returned -0.015569 +/- 0.041661 Energy evaluation 5 returned -0.284201 +/- 0.035386 Energy evaluation 6 returned -0.004501 +/- 0.042106 Energy evaluation 7 returned -0.004931 +/- 0.037232 Energy evaluation 8 returned -0.277657 +/- 0.038728 Energy evaluation 9 returned -0.285717 +/- 0.038541 Energy evaluation 10 returned -0.076791 +/- 0.036352 Energy evaluation 11 returned -0.061213 +/- 0.036020 Energy evaluation 12 returned -0.306550 +/- 0.038751 Energy evaluation 13 returned -0.222509 +/- 0.038363 Energy evaluation 14 returned -0.070618 +/- 0.036528 Energy evaluation 15 returned -0.039417 +/- 0.041066 Energy evaluation 16 returned -0.306513 +/- 0.035928 Energy evaluation 17 returned -0.296036 +/- 0.036557 Energy evaluation 18 returned -0.034967 +/- 0.038903 Energy evaluation 19 returned -0.014590 +/- 0.042304 Energy evaluation 20 returned -0.255674 +/- 0.036446 Energy evaluation 21 returned -0.360293 +/- 0.039284 Energy evaluation 22 returned -0.100509 +/- 0.036138 Energy evaluation 23 returned -0.340962 +/- 0.042083 Energy evaluation 24 returned -0.010969 +/- 0.036061 Energy evaluation 25 returned -0.274148 +/- 0.038141 Energy evaluation 26 returned -0.051694 +/- 0.036584 Energy evaluation 27 returned -0.026856 +/- 0.041999 Energy evaluation 28 returned -0.238935 +/- 0.035605 Energy evaluation 29 returned -0.007813 +/- 0.036288 Energy evaluation 30 returned -0.245291 +/- 0.042334 Energy evaluation 31 returned -0.077277 +/- 0.036349 Energy evaluation 32 returned -0.299390 +/- 0.038325 Energy evaluation 33 returned -0.244863 +/- 0.036762 Energy evaluation 34 returned -0.123679 +/- 0.038950 Energy evaluation 35 returned -0.304524 +/- 0.036613 Energy evaluation 36 returned -0.030690 +/- 0.039158 Energy evaluation 37 returned -0.096245 +/- 0.036339 Energy evaluation 38 returned -0.322952 +/- 0.038412 Energy evaluation 39 returned -0.227033 +/- 0.034959 Energy evaluation 40 returned -0.042812 +/- 0.042150 Energy evaluation 41 returned -0.050591 +/- 0.034910 Energy evaluation 42 returned -0.233218 +/- 0.042512 Energy evaluation 43 returned -0.089703 +/- 0.038503 Energy evaluation 44 returned -0.326966 +/- 0.036690 Energy evaluation 45 returned -0.262048 +/- 0.042559 Energy evaluation 46 returned -0.026316 +/- 0.035945 Energy evaluation 47 returned -0.204359 +/- 0.036694 Energy evaluation 48 returned 0.020287 +/- 0.042867 Energy evaluation 49 returned -0.289152 +/- 0.038433 Energy evaluation 50 returned -0.094473 +/- 0.036482 Energy evaluation 51 returned -0.048750 +/- 0.038764 Energy evaluation 52 returned -0.340434 +/- 0.036239 Energy evaluation 53 returned 0.241486 +/- 0.040902 Energy evaluation 54 returned -0.396109 +/- 0.036407 Energy evaluation 55 returned 2.755252 +/- 0.034989 Energy evaluation 56 returned 2.451752 +/- 0.046300 Energy evaluation 57 returned 0.617239 +/- 0.058144 Energy evaluation 58 returned 0.954188 +/- 0.060074 Energy evaluation 59 returned 0.447600 +/- 0.036744 Energy evaluation 60 returned 0.258387 +/- 0.039346 Energy evaluation 61 returned 0.037581 +/- 0.047261 Energy evaluation 62 returned 0.169163 +/- 0.037793 Energy evaluation 63 returned -0.017572 +/- 0.049549 Energy evaluation 64 returned 0.333352 +/- 0.052784 Energy evaluation 65 returned -0.537248 +/- 0.039097 Energy evaluation 66 returned -0.203030 +/- 0.048513 Energy evaluation 67 returned -0.501960 +/- 0.035612 Energy evaluation 68 returned -0.026316 +/- 0.038832 Energy evaluation 69 returned -0.497420 +/- 0.045825 Energy evaluation 70 returned -0.509203 +/- 0.044074 Energy evaluation 71 returned -0.425120 +/- 0.044529 Energy evaluation 72 returned -0.666494 +/- 0.042247 Energy evaluation 73 returned -0.588548 +/- 0.037761 Energy evaluation 74 returned -0.689551 +/- 0.041281 Energy evaluation 75 returned -0.565480 +/- 0.042151 Energy evaluation 76 returned -0.709236 +/- 0.041800 Energy evaluation 77 returned -0.749831 +/- 0.041553 Energy evaluation 78 returned -0.692665 +/- 0.040703 Energy evaluation 79 returned -0.777060 +/- 0.041852 Energy evaluation 80 returned -0.726131 +/- 0.040768 Energy evaluation 81 returned -0.706200 +/- 0.042219 Energy evaluation 82 returned -0.697409 +/- 0.043357 Energy evaluation 83 returned -0.555009 +/- 0.045526 Energy evaluation 84 returned -0.756471 +/- 0.039474 Energy evaluation 85 returned -0.641371 +/- 0.036647 Energy evaluation 86 returned -0.708978 +/- 0.040471 Energy evaluation 87 returned -0.759841 +/- 0.039266 Energy evaluation 88 returned -0.714643 +/- 0.038788 Energy evaluation 89 returned -0.777053 +/- 0.039972 Energy evaluation 90 returned -0.662277 +/- 0.040555 Energy evaluation 91 returned -0.741532 +/- 0.041389 Energy evaluation 92 returned -0.709092 +/- 0.039435 Energy evaluation 93 returned -0.803988 +/- 0.035729 Energy evaluation 94 returned -0.750954 +/- 0.043295 Energy evaluation 95 returned -0.801802 +/- 0.036859 Energy evaluation 96 returned -0.796823 +/- 0.038786 Energy evaluation 97 returned -0.781198 +/- 0.038059 Energy evaluation 98 returned -0.836939 +/- 0.038834 Energy evaluation 99 returned -0.896372 +/- 0.037187 Energy evaluation 100 returned -0.769736 +/- 0.037996 Energy evaluation 101 returned -0.884862 +/- 0.037113 Energy evaluation 102 returned -0.855735 +/- 0.037939 Energy evaluation 103 returned -0.796620 +/- 0.040837 Energy evaluation 104 returned -0.844414 +/- 0.035505 Energy evaluation 105 returned -0.790673 +/- 0.035822 Energy evaluation 106 returned -0.836877 +/- 0.039194 Energy evaluation 107 returned -0.845762 +/- 0.035188 Energy evaluation 108 returned -0.759944 +/- 0.041047 Energy evaluation 109 returned -0.896422 +/- 0.035738 Energy evaluation 110 returned -0.814654 +/- 0.035935 Energy evaluation 111 returned -0.849734 +/- 0.035598 Energy evaluation 112 returned -0.930865 +/- 0.035603 Energy evaluation 113 returned -0.878019 +/- 0.032635 Energy evaluation 114 returned -0.837757 +/- 0.039473 Energy evaluation 115 returned -0.930090 +/- 0.033083 Energy evaluation 116 returned -0.918484 +/- 0.035569 Energy evaluation 117 returned -0.870833 +/- 0.033283 Energy evaluation 118 returned -0.884911 +/- 0.037352 Energy evaluation 119 returned -0.798788 +/- 0.038355 Energy evaluation 120 returned -0.866350 +/- 0.033119 Energy evaluation 121 returned -0.826328 +/- 0.035390 Energy evaluation 122 returned -0.986659 +/- 0.032752 Energy evaluation 123 returned -0.887663 +/- 0.032878 Energy evaluation 124 returned -0.872651 +/- 0.036840 Energy evaluation 125 returned -0.882326 +/- 0.033825 Energy evaluation 126 returned -0.929125 +/- 0.033515 Energy evaluation 127 returned -1.001759 +/- 0.033453 Energy evaluation 128 returned -0.908909 +/- 0.033250 Energy evaluation 129 returned -0.972004 +/- 0.034969 Energy evaluation 130 returned -0.950699 +/- 0.031468 Energy evaluation 131 returned -0.937912 +/- 0.035330 Energy evaluation 132 returned -0.916773 +/- 0.032410 Energy evaluation 133 returned -0.923081 +/- 0.032368 Energy evaluation 134 returned -0.979786 +/- 0.034977 Energy evaluation 135 returned -0.842778 +/- 0.039373 Energy evaluation 136 returned -0.980387 +/- 0.031376 Energy evaluation 137 returned -0.931943 +/- 0.031225 Energy evaluation 138 returned -0.961333 +/- 0.033090 Energy evaluation 139 returned -0.893452 +/- 0.031355 Energy evaluation 140 returned -0.982632 +/- 0.032894 Energy evaluation 141 returned -0.993145 +/- 0.032234 Energy evaluation 142 returned -0.923592 +/- 0.033731 Energy evaluation 143 returned -0.907517 +/- 0.034382 Energy evaluation 144 returned -0.972998 +/- 0.030526 Energy evaluation 145 returned -0.964261 +/- 0.032776 Energy evaluation 146 returned -1.010649 +/- 0.029539 Energy evaluation 147 returned -1.033455 +/- 0.030128 Energy evaluation 148 returned -1.029202 +/- 0.032279 Energy evaluation 149 returned -0.895641 +/- 0.030169 Energy evaluation 150 returned -0.947901 +/- 0.034433 Energy evaluation 151 returned -0.950785 +/- 0.033793 Energy evaluation 152 returned -1.000621 +/- 0.032060 Energy evaluation 153 returned -0.912934 +/- 0.030065 Energy evaluation 154 returned -0.949362 +/- 0.036167 Energy evaluation 155 returned -0.935753 +/- 0.032433 Energy evaluation 156 returned -0.973807 +/- 0.033926 Energy evaluation 157 returned -0.965741 +/- 0.032311 Energy evaluation 158 returned -0.986501 +/- 0.034828 Energy evaluation 159 returned -1.002078 +/- 0.031970 Energy evaluation 160 returned -0.963456 +/- 0.035203 Energy evaluation 161 returned -0.981760 +/- 0.036019 Energy evaluation 162 returned -0.893087 +/- 0.030171 Energy evaluation 163 returned -1.016767 +/- 0.033179 Energy evaluation 164 returned -0.930183 +/- 0.035200 Energy evaluation 165 returned -0.913683 +/- 0.036609 Energy evaluation 166 returned -0.961411 +/- 0.033617 Energy evaluation 167 returned -0.848942 +/- 0.038371 Energy evaluation 168 returned -0.959859 +/- 0.030518 Energy evaluation 169 returned -0.972236 +/- 0.029401 Energy evaluation 170 returned -0.944359 +/- 0.035231 Energy evaluation 171 returned -0.926911 +/- 0.029834 Energy evaluation 172 returned -0.942219 +/- 0.034955 Energy evaluation 173 returned -0.938858 +/- 0.030810 Energy evaluation 174 returned -0.965214 +/- 0.035725 Energy evaluation 175 returned -0.985691 +/- 0.031211 Energy evaluation 176 returned -0.970937 +/- 0.032578 Energy evaluation 177 returned -1.037661 +/- 0.032930 Energy evaluation 178 returned -0.954307 +/- 0.031281 Energy evaluation 179 returned -0.986713 +/- 0.030774 Energy evaluation 180 returned -0.931088 +/- 0.035303 Energy evaluation 181 returned -0.960684 +/- 0.033088 Energy evaluation 182 returned -0.996380 +/- 0.031083 Energy evaluation 183 returned -0.972511 +/- 0.030284 Energy evaluation 184 returned -0.944405 +/- 0.034428 Energy evaluation 185 returned -0.971349 +/- 0.033983 Energy evaluation 186 returned -0.931737 +/- 0.032552 Energy evaluation 187 returned -1.017673 +/- 0.032189 Energy evaluation 188 returned -0.993811 +/- 0.032376 Energy evaluation 189 returned -1.021794 +/- 0.031756 Energy evaluation 190 returned -0.979901 +/- 0.032631 Energy evaluation 191 returned -0.986764 +/- 0.032344 Energy evaluation 192 returned -0.981282 +/- 0.032125 Energy evaluation 193 returned -0.933521 +/- 0.035778 Energy evaluation 194 returned -0.945435 +/- 0.030417 Energy evaluation 195 returned -0.975347 +/- 0.029266 Energy evaluation 196 returned -0.974304 +/- 0.035900 Energy evaluation 197 returned -1.008231 +/- 0.033745 Energy evaluation 198 returned -0.930056 +/- 0.032316 Energy evaluation 199 returned -0.961197 +/- 0.034382 Energy evaluation 200 returned -0.966274 +/- 0.032741 Energy evaluation 201 returned -0.950879 +/- 0.031305 Energy evaluation 202 returned -0.959500 +/- 0.034598 Energy evaluation 203 returned -0.976293 +/- 0.032974 Energy evaluation 204 returned -0.982877 +/- 0.033685 Energy evaluation 205 returned -0.964974 +/- 0.033429 Energy evaluation 206 returned -1.025090 +/- 0.032110 Energy evaluation 207 returned -0.916041 +/- 0.036830 Energy evaluation 208 returned -0.932845 +/- 0.030836 Energy evaluation 209 returned -0.929876 +/- 0.030874 Energy evaluation 210 returned -0.960441 +/- 0.035735 Energy evaluation 211 returned -1.002527 +/- 0.033479 Energy evaluation 212 returned -0.961805 +/- 0.033020 Energy evaluation 213 returned -0.992272 +/- 0.030848 Energy evaluation 214 returned -1.007284 +/- 0.034102 Energy evaluation 215 returned -0.981967 +/- 0.029777 Energy evaluation 216 returned -0.936929 +/- 0.036198 Energy evaluation 217 returned -0.973293 +/- 0.035213 Energy evaluation 218 returned -0.939441 +/- 0.030462 Energy evaluation 219 returned -0.967215 +/- 0.035747 Energy evaluation 220 returned -0.999228 +/- 0.030963 Energy evaluation 221 returned -1.023688 +/- 0.034020 Energy evaluation 222 returned -0.963705 +/- 0.030884 Energy evaluation 223 returned -0.939745 +/- 0.031560 Energy evaluation 224 returned -0.892028 +/- 0.037064 Energy evaluation 225 returned -0.880389 +/- 0.038096 Energy evaluation 226 returned -0.973223 +/- 0.029987 Energy evaluation 227 returned -0.965879 +/- 0.029503 Energy evaluation 228 returned -1.007509 +/- 0.032544 Energy evaluation 229 returned -1.016328 +/- 0.031103 Energy evaluation 230 returned -1.042828 +/- 0.030372 Energy evaluation 231 returned -0.983961 +/- 0.032488 Energy evaluation 232 returned -0.989788 +/- 0.030779 Energy evaluation 233 returned -0.991819 +/- 0.031338 Energy evaluation 234 returned -0.981511 +/- 0.031787 Energy evaluation 235 returned -0.984419 +/- 0.029837 Energy evaluation 236 returned -1.011387 +/- 0.032164 Energy evaluation 237 returned -0.990560 +/- 0.032270 Energy evaluation 238 returned -1.017317 +/- 0.029765 Energy evaluation 239 returned -0.969015 +/- 0.031655 Energy evaluation 240 returned -0.989907 +/- 0.030564 Energy evaluation 241 returned -0.965055 +/- 0.029232 Energy evaluation 242 returned -0.892362 +/- 0.035967 Energy evaluation 243 returned -0.968725 +/- 0.030035 Energy evaluation 244 returned -1.023148 +/- 0.031765 Energy evaluation 245 returned -0.960270 +/- 0.030299 Energy evaluation 246 returned -1.019015 +/- 0.033144 Energy evaluation 247 returned -0.970927 +/- 0.031626 Energy evaluation 248 returned -0.993521 +/- 0.030745 Energy evaluation 249 returned -0.975590 +/- 0.032999 Energy evaluation 250 returned -1.012290 +/- 0.029461 Energy evaluation 251 returned -1.008661 +/- 0.033915 Energy evaluation 252 returned -0.942275 +/- 0.028185 Energy evaluation 253 returned -0.977620 +/- 0.035437 Energy evaluation 254 returned -1.020543 +/- 0.028695 Energy evaluation 255 returned -0.946430 +/- 0.029240 Energy evaluation 256 returned -0.978012 +/- 0.035111 Energy evaluation 257 returned -0.974300 +/- 0.032797 Energy evaluation 258 returned -1.009957 +/- 0.028860 Energy evaluation 259 returned -1.025348 +/- 0.033198 Energy evaluation 260 returned -0.997949 +/- 0.030080 Energy evaluation 261 returned -1.023380 +/- 0.034890 Energy evaluation 262 returned -0.986950 +/- 0.028785 Energy evaluation 263 returned -1.017399 +/- 0.031175 Energy evaluation 264 returned -0.987522 +/- 0.031239 Energy evaluation 265 returned -1.011958 +/- 0.033280 Energy evaluation 266 returned -1.013210 +/- 0.030774 Energy evaluation 267 returned -0.990175 +/- 0.030109 Energy evaluation 268 returned -0.989369 +/- 0.034477 Energy evaluation 269 returned -0.939258 +/- 0.029811 Energy evaluation 270 returned -0.925432 +/- 0.036554 Energy evaluation 271 returned -0.976931 +/- 0.034468 Energy evaluation 272 returned -0.989865 +/- 0.030288 Energy evaluation 273 returned -0.994962 +/- 0.032813 Energy evaluation 274 returned -0.936370 +/- 0.030540 Energy evaluation 275 returned -0.954380 +/- 0.035355 Energy evaluation 276 returned -0.982644 +/- 0.029184 Energy evaluation 277 returned -1.034801 +/- 0.031721 Energy evaluation 278 returned -0.976806 +/- 0.030472 Energy evaluation 279 returned -0.905336 +/- 0.036010 Energy evaluation 280 returned -0.978917 +/- 0.029414 Energy evaluation 281 returned -0.990523 +/- 0.033888 Energy evaluation 282 returned -0.974197 +/- 0.029001 Energy evaluation 283 returned -1.019514 +/- 0.031819 Energy evaluation 284 returned -0.986109 +/- 0.029892 Energy evaluation 285 returned -1.038095 +/- 0.031488 Energy evaluation 286 returned -0.989012 +/- 0.032727 Energy evaluation 287 returned -0.991693 +/- 0.031039 Energy evaluation 288 returned -0.991788 +/- 0.031443 Energy evaluation 289 returned -0.966597 +/- 0.032483 Energy evaluation 290 returned -1.012247 +/- 0.029887 Energy evaluation 291 returned -0.977269 +/- 0.029577 Energy evaluation 292 returned -1.013340 +/- 0.033126 Energy evaluation 293 returned -1.003906 +/- 0.031146 Energy evaluation 294 returned -1.002292 +/- 0.032231 Energy evaluation 295 returned -1.038868 +/- 0.031098 Energy evaluation 296 returned -1.042260 +/- 0.031038 Energy evaluation 297 returned -0.984846 +/- 0.035439 Energy evaluation 298 returned -0.996117 +/- 0.028658 Energy evaluation 299 returned -0.992387 +/- 0.030391 Energy evaluation 300 returned -1.090005 +/- 0.030371 Energy evaluation 301 returned -0.969032 +/- 0.033259 Energy evaluation 302 returned -0.993847 +/- 0.029276 Energy evaluation 303 returned -0.980092 +/- 0.029920 Energy evaluation 304 returned -0.934418 +/- 0.032683 Energy evaluation 305 returned -0.978137 +/- 0.029191 Energy evaluation 306 returned -1.010691 +/- 0.033322 Energy evaluation 307 returned -0.978313 +/- 0.030963 Energy evaluation 308 returned -0.984335 +/- 0.032698 Energy evaluation 309 returned -0.974643 +/- 0.035178 Energy evaluation 310 returned -1.002443 +/- 0.028646 Energy evaluation 311 returned -0.975769 +/- 0.029122 Energy evaluation 312 returned -0.969579 +/- 0.031847 Energy evaluation 313 returned -0.992971 +/- 0.028803 Energy evaluation 314 returned -0.972081 +/- 0.034370 Energy evaluation 315 returned -0.967637 +/- 0.032781 Energy evaluation 316 returned -0.977754 +/- 0.029631 Energy evaluation 317 returned -0.982747 +/- 0.029460 Energy evaluation 318 returned -1.059103 +/- 0.031870 Energy evaluation 319 returned -0.986167 +/- 0.033370 Energy evaluation 320 returned -0.933559 +/- 0.031090 Energy evaluation 321 returned -1.040134 +/- 0.029543 Energy evaluation 322 returned -1.050525 +/- 0.032291 Energy evaluation 323 returned -1.044234 +/- 0.028190 Energy evaluation 324 returned -1.022210 +/- 0.034596 Energy evaluation 325 returned -0.955185 +/- 0.029623 Energy evaluation 326 returned -0.957992 +/- 0.033132 Energy evaluation 327 returned -0.914438 +/- 0.030901 Energy evaluation 328 returned -0.962628 +/- 0.033450 Energy evaluation 329 returned -1.046471 +/- 0.032636 Energy evaluation 330 returned -0.958410 +/- 0.030376 Energy evaluation 331 returned -0.966327 +/- 0.035549 Energy evaluation 332 returned -0.964599 +/- 0.029960 Energy evaluation 333 returned -0.979234 +/- 0.029194 Energy evaluation 334 returned -1.005067 +/- 0.034639 Energy evaluation 335 returned -0.962701 +/- 0.031089 Energy evaluation 336 returned -1.038116 +/- 0.032001 Energy evaluation 337 returned -1.001709 +/- 0.029983 Energy evaluation 338 returned -1.036319 +/- 0.034661 Energy evaluation 339 returned -1.023273 +/- 0.034908 Energy evaluation 340 returned -1.002423 +/- 0.031209 Energy evaluation 341 returned -0.983429 +/- 0.036064 Energy evaluation 342 returned -0.992937 +/- 0.030883 Energy evaluation 343 returned -0.924520 +/- 0.035950 Energy evaluation 344 returned -0.965919 +/- 0.031982 Energy evaluation 345 returned -0.915517 +/- 0.036566 Energy evaluation 346 returned -0.984700 +/- 0.029966 Energy evaluation 347 returned -0.902882 +/- 0.036939 Energy evaluation 348 returned -1.040770 +/- 0.029299 Energy evaluation 349 returned -0.940645 +/- 0.029890 Energy evaluation 350 returned -0.995147 +/- 0.032542 Energy evaluation 351 returned -0.995874 +/- 0.031939 Energy evaluation 352 returned -0.973731 +/- 0.030407 Energy evaluation 353 returned -1.046024 +/- 0.030832 Energy evaluation 354 returned -1.018609 +/- 0.031002 Energy evaluation 355 returned -0.965663 +/- 0.030782 Energy evaluation 356 returned -1.023519 +/- 0.030212 Energy evaluation 357 returned -1.008912 +/- 0.028315 Energy evaluation 358 returned -0.970109 +/- 0.034566 Energy evaluation 359 returned -0.985041 +/- 0.034438 Energy evaluation 360 returned -1.011831 +/- 0.028795 Energy evaluation 361 returned -1.012877 +/- 0.032924 Energy evaluation 362 returned -1.028021 +/- 0.027528 Energy evaluation 363 returned -0.973566 +/- 0.032376 Energy evaluation 364 returned -0.995673 +/- 0.028795 Energy evaluation 365 returned -0.984455 +/- 0.032977 Energy evaluation 366 returned -0.986222 +/- 0.028958 Energy evaluation 367 returned -1.006734 +/- 0.031021 Energy evaluation 368 returned -0.992785 +/- 0.029153 Energy evaluation 369 returned -1.015728 +/- 0.029072 Energy evaluation 370 returned -1.021096 +/- 0.032105 Energy evaluation 371 returned -1.006909 +/- 0.029965 Energy evaluation 372 returned -1.005781 +/- 0.030206 Energy evaluation 373 returned -1.054606 +/- 0.029743 Energy evaluation 374 returned -1.010810 +/- 0.030485 Energy evaluation 375 returned -0.932473 +/- 0.033166 Energy evaluation 376 returned -0.981597 +/- 0.029141 Energy evaluation 377 returned -1.027567 +/- 0.031684 Energy evaluation 378 returned -0.989801 +/- 0.027801 Energy evaluation 379 returned -1.032312 +/- 0.029860 Energy evaluation 380 returned -1.000099 +/- 0.029224 Energy evaluation 381 returned -1.010365 +/- 0.031103 Energy evaluation 382 returned -0.946082 +/- 0.030083 Energy evaluation 383 returned -1.019525 +/- 0.030242 Energy evaluation 384 returned -0.976086 +/- 0.031397 Energy evaluation 385 returned -1.003141 +/- 0.028965 Energy evaluation 386 returned -1.034498 +/- 0.032193 Energy evaluation 387 returned -1.020009 +/- 0.033092 Energy evaluation 388 returned -1.024942 +/- 0.027733 Energy evaluation 389 returned -1.041128 +/- 0.031350 Energy evaluation 390 returned -0.980532 +/- 0.030055 Energy evaluation 391 returned -0.975529 +/- 0.030025 Energy evaluation 392 returned -1.044269 +/- 0.032214 Energy evaluation 393 returned -0.964225 +/- 0.031401 Energy evaluation 394 returned -1.055833 +/- 0.030284 Energy evaluation 395 returned -1.071592 +/- 0.033151 Energy evaluation 396 returned -0.984460 +/- 0.028675 Energy evaluation 397 returned -0.944889 +/- 0.030351 Energy evaluation 398 returned -1.000204 +/- 0.034567 Energy evaluation 399 returned -1.072046 +/- 0.033391 Energy evaluation 400 returned -1.010406 +/- 0.031249 Energy evaluation 401 returned -1.013944 +/- 0.033792 Energy evaluation 402 returned -0.967404 +/- 0.031813 Energy evaluation 403 returned -0.964138 +/- 0.034261 Energy evaluation 404 returned -1.089823 +/- 0.030496 Energy evaluation 405 returned -0.925980 +/- 0.036125 Energy evaluation 406 returned -1.017361 +/- 0.029648 Energy evaluation 407 returned -1.032020 +/- 0.028656 Energy evaluation 408 returned -0.948430 +/- 0.034790 Energy evaluation 409 returned -0.996406 +/- 0.034668 Energy evaluation 410 returned -0.945592 +/- 0.028796 Energy evaluation 411 returned -1.029799 +/- 0.033047 Energy evaluation 412 returned -0.992684 +/- 0.030930 Energy evaluation 413 returned -1.002690 +/- 0.033667 Energy evaluation 414 returned -0.969467 +/- 0.031150 Energy evaluation 415 returned -1.044256 +/- 0.029752 Energy evaluation 416 returned -0.989328 +/- 0.033298 Energy evaluation 417 returned -0.993618 +/- 0.035052 Energy evaluation 418 returned -0.988272 +/- 0.029111 Energy evaluation 419 returned -0.976979 +/- 0.030490 Energy evaluation 420 returned -0.971057 +/- 0.033926 Energy evaluation 421 returned -0.986030 +/- 0.031548 Energy evaluation 422 returned -1.001391 +/- 0.031195 Energy evaluation 423 returned -0.963039 +/- 0.029232 Energy evaluation 424 returned -1.021754 +/- 0.034420 Energy evaluation 425 returned -1.013567 +/- 0.031970 Energy evaluation 426 returned -0.969036 +/- 0.032961 Energy evaluation 427 returned -0.966730 +/- 0.033462 Energy evaluation 428 returned -0.966388 +/- 0.031023 Energy evaluation 429 returned -1.005050 +/- 0.031340 Energy evaluation 430 returned -0.997072 +/- 0.032413 Energy evaluation 431 returned -1.047329 +/- 0.030640 Energy evaluation 432 returned -1.040273 +/- 0.031596 Energy evaluation 433 returned -1.036418 +/- 0.033234 Energy evaluation 434 returned -0.973810 +/- 0.031930 Energy evaluation 435 returned -0.987738 +/- 0.033974 Energy evaluation 436 returned -1.041633 +/- 0.030800 Energy evaluation 437 returned -1.003653 +/- 0.029542 Energy evaluation 438 returned -1.039195 +/- 0.033755 Energy evaluation 439 returned -1.033529 +/- 0.032045 Energy evaluation 440 returned -1.044798 +/- 0.032164 Energy evaluation 441 returned -0.976127 +/- 0.036049 Energy evaluation 442 returned -1.002969 +/- 0.029743 Energy evaluation 443 returned -1.006420 +/- 0.035515 Energy evaluation 444 returned -0.982368 +/- 0.029373 Energy evaluation 445 returned -0.964947 +/- 0.033148 Energy evaluation 446 returned -0.937968 +/- 0.034143 Energy evaluation 447 returned -1.006509 +/- 0.032840 Energy evaluation 448 returned -0.957410 +/- 0.032633 Energy evaluation 449 returned -1.014134 +/- 0.030123 Energy evaluation 450 returned -0.983561 +/- 0.033592 Energy evaluation 451 returned -0.980554 +/- 0.031279 Energy evaluation 452 returned -1.050600 +/- 0.033505 Energy evaluation 453 returned -0.993651 +/- 0.032879 Energy evaluation 454 returned -1.074560 +/- 0.032001 Energy evaluation 455 returned -1.029234 +/- 0.030294 Energy evaluation 456 returned -1.003847 +/- 0.034213 Energy evaluation 457 returned -0.950252 +/- 0.035070 Energy evaluation 458 returned -1.028179 +/- 0.030379 Energy evaluation 459 returned -0.987700 +/- 0.034023 Energy evaluation 460 returned -0.981527 +/- 0.031284 Energy evaluation 461 returned -0.989066 +/- 0.034299 Energy evaluation 462 returned -1.000623 +/- 0.031202 Energy evaluation 463 returned -0.977427 +/- 0.031713 Energy evaluation 464 returned -1.012188 +/- 0.032250 Energy evaluation 465 returned -0.967973 +/- 0.036625 Energy evaluation 466 returned -0.923976 +/- 0.030984 Energy evaluation 467 returned -1.029864 +/- 0.030466 Energy evaluation 468 returned -1.002377 +/- 0.034042 Energy evaluation 469 returned -0.878645 +/- 0.034058 Energy evaluation 470 returned -1.020950 +/- 0.032586 Energy evaluation 471 returned -0.974169 +/- 0.032483 Energy evaluation 472 returned -1.005770 +/- 0.033422 Energy evaluation 473 returned -0.976655 +/- 0.034523 Energy evaluation 474 returned -1.013175 +/- 0.031325 Energy evaluation 475 returned -0.928425 +/- 0.036282 Energy evaluation 476 returned -0.976816 +/- 0.030044 Energy evaluation 477 returned -0.987502 +/- 0.030663 Energy evaluation 478 returned -0.993940 +/- 0.033243 Energy evaluation 479 returned -1.040751 +/- 0.033380 Energy evaluation 480 returned -1.016890 +/- 0.030555 Energy evaluation 481 returned -0.997512 +/- 0.032322 Energy evaluation 482 returned -1.096973 +/- 0.030969 Energy evaluation 483 returned -1.014311 +/- 0.029794 Energy evaluation 484 returned -1.004891 +/- 0.034609 Energy evaluation 485 returned -1.048068 +/- 0.031611 Energy evaluation 486 returned -0.961648 +/- 0.032815 Energy evaluation 487 returned -1.025263 +/- 0.031735 Energy evaluation 488 returned -1.016035 +/- 0.032308 Energy evaluation 489 returned -1.071246 +/- 0.032941 Energy evaluation 490 returned -0.996000 +/- 0.030892 Energy evaluation 491 returned -1.057613 +/- 0.030503 Energy evaluation 492 returned -0.956940 +/- 0.034917 Energy evaluation 493 returned -1.059492 +/- 0.029583 Energy evaluation 494 returned -1.013948 +/- 0.033787 Energy evaluation 495 returned -0.994675 +/- 0.035504 Energy evaluation 496 returned -0.992800 +/- 0.029146 Energy evaluation 497 returned -1.022280 +/- 0.031587 Energy evaluation 498 returned -0.984216 +/- 0.032121 Energy evaluation 499 returned -0.965070 +/- 0.029694 Energy evaluation 500 returned -0.953302 +/- 0.035433 Energy evaluation 501 returned -1.035340 +/- 0.033660 Energy evaluation 502 returned -1.001688 +/- 0.029450 Energy evaluation 503 returned -0.959789 +/- 0.031297 Energy evaluation 504 returned -1.013799 +/- 0.032944 Energy evaluation 505 returned -0.995515 +/- 0.033172 Energy evaluation 506 returned -1.051521 +/- 0.030207 Energy evaluation 507 returned -0.972944 +/- 0.030614 Energy evaluation 508 returned -1.048456 +/- 0.032678 Energy evaluation 509 returned -1.006209 +/- 0.033392 Energy evaluation 510 returned -0.960848 +/- 0.030923 Energy evaluation 511 returned -0.969968 +/- 0.033746 Energy evaluation 512 returned -1.010864 +/- 0.031346 Energy evaluation 513 returned -0.957659 +/- 0.036303 Energy evaluation 514 returned -1.050995 +/- 0.028719 Energy evaluation 515 returned -0.951850 +/- 0.031649 Energy evaluation 516 returned -1.014952 +/- 0.031061 Energy evaluation 517 returned -0.939665 +/- 0.032013 Energy evaluation 518 returned -0.955058 +/- 0.032624 Energy evaluation 519 returned -1.067582 +/- 0.031208 Energy evaluation 520 returned -1.039710 +/- 0.031412 Energy evaluation 521 returned -0.993945 +/- 0.028773 Energy evaluation 522 returned -0.943741 +/- 0.035908 Energy evaluation 523 returned -1.045390 +/- 0.027814 Energy evaluation 524 returned -0.965730 +/- 0.034288 Energy evaluation 525 returned -1.003305 +/- 0.031317 Energy evaluation 526 returned -1.018857 +/- 0.030095 Energy evaluation 527 returned -1.010540 +/- 0.031156 Energy evaluation 528 returned -0.991946 +/- 0.030360 Energy evaluation 529 returned -0.979156 +/- 0.029014 Energy evaluation 530 returned -1.016292 +/- 0.030647 Energy evaluation 531 returned -1.022724 +/- 0.028941 Energy evaluation 532 returned -0.988778 +/- 0.032371 Energy evaluation 533 returned -1.011546 +/- 0.032738 Energy evaluation 534 returned -0.980756 +/- 0.029701 Energy evaluation 535 returned -0.952508 +/- 0.029945 Energy evaluation 536 returned -1.018182 +/- 0.031490 Energy evaluation 537 returned -0.999212 +/- 0.030024 Energy evaluation 538 returned -1.027207 +/- 0.031778 Energy evaluation 539 returned -1.025887 +/- 0.033347 Energy evaluation 540 returned -0.963410 +/- 0.029249 Energy evaluation 541 returned -1.001434 +/- 0.031549 Energy evaluation 542 returned -1.023199 +/- 0.030787 Energy evaluation 543 returned -1.028214 +/- 0.029520 Energy evaluation 544 returned -1.089364 +/- 0.032002 Energy evaluation 545 returned -0.963328 +/- 0.029420 Energy evaluation 546 returned -1.006060 +/- 0.034298 Energy evaluation 547 returned -1.004926 +/- 0.030784 Energy evaluation 548 returned -0.936162 +/- 0.034047 Energy evaluation 549 returned -0.987594 +/- 0.030723 Energy evaluation 550 returned -0.973283 +/- 0.033399 Energy evaluation 551 returned -1.023130 +/- 0.031903 Energy evaluation 552 returned -1.009196 +/- 0.031835 Energy evaluation 553 returned -1.027381 +/- 0.029082 Energy evaluation 554 returned -1.017901 +/- 0.034015 Energy evaluation 555 returned -1.039330 +/- 0.031891 Energy evaluation 556 returned -0.944196 +/- 0.031919 Energy evaluation 557 returned -0.979869 +/- 0.034114 Energy evaluation 558 returned -1.026812 +/- 0.030751 Energy evaluation 559 returned -0.995032 +/- 0.029004 Energy evaluation 560 returned -1.010751 +/- 0.034615 Energy evaluation 561 returned -1.034300 +/- 0.030509 Energy evaluation 562 returned -0.999724 +/- 0.032972 Energy evaluation 563 returned -1.030567 +/- 0.031390 Energy evaluation 564 returned -1.028057 +/- 0.031698 Energy evaluation 565 returned -0.983225 +/- 0.031516 Energy evaluation 566 returned -0.981437 +/- 0.032229 Energy evaluation 567 returned -0.991819 +/- 0.031917 Energy evaluation 568 returned -0.971221 +/- 0.032305 Energy evaluation 569 returned -0.987603 +/- 0.033334 Energy evaluation 570 returned -0.990186 +/- 0.030241 Energy evaluation 571 returned -0.929368 +/- 0.032397 Energy evaluation 572 returned -1.012252 +/- 0.031809 Energy evaluation 573 returned -1.036311 +/- 0.030772 Energy evaluation 574 returned -0.972394 +/- 0.032450 Energy evaluation 575 returned -1.076663 +/- 0.034213 Energy evaluation 576 returned -0.970258 +/- 0.029165 Energy evaluation 577 returned -1.046261 +/- 0.034306 Energy evaluation 578 returned -1.009718 +/- 0.032290 Energy evaluation 579 returned -0.972293 +/- 0.032586 Energy evaluation 580 returned -0.891893 +/- 0.034608 Energy evaluation 581 returned -0.996240 +/- 0.032876 Energy evaluation 582 returned -1.024206 +/- 0.031540 Energy evaluation 583 returned -0.929837 +/- 0.033739 Energy evaluation 584 returned -0.971852 +/- 0.032720 Energy evaluation 585 returned -0.972019 +/- 0.034334 Energy evaluation 586 returned -1.031714 +/- 0.030253 Energy evaluation 587 returned -1.000786 +/- 0.034823 Energy evaluation 588 returned -0.992489 +/- 0.030302 Energy evaluation 589 returned -1.049408 +/- 0.031914 Energy evaluation 590 returned -1.036746 +/- 0.031921 Energy evaluation 591 returned -1.009492 +/- 0.029426 Energy evaluation 592 returned -0.983450 +/- 0.034687 Energy evaluation 593 returned -0.986823 +/- 0.034395 Energy evaluation 594 returned -0.955310 +/- 0.031437 Energy evaluation 595 returned -0.969234 +/- 0.033622 Energy evaluation 596 returned -1.002952 +/- 0.030711 Energy evaluation 597 returned -0.995221 +/- 0.029093 Energy evaluation 598 returned -0.933211 +/- 0.035834 Energy evaluation 599 returned -0.936643 +/- 0.030695 Energy evaluation 600 returned -0.979818 +/- 0.034666 Energy evaluation 601 returned -0.984730 +/- 0.031350 Energy evaluation 602 returned -1.042079 +/- 0.032905 Energy evaluation 603 returned -1.027927 +/- 0.031557 Energy evaluation 604 returned -1.036683 +/- 0.032508 Energy evaluation 605 returned -1.074637 +/- 0.029606 Energy evaluation 606 returned -0.928519 +/- 0.035209 Energy evaluation 607 returned -1.039397 +/- 0.029376 Energy evaluation 608 returned -1.010675 +/- 0.032600 Energy evaluation 609 returned -0.974155 +/- 0.032483 Energy evaluation 610 returned -1.006290 +/- 0.032286 Energy evaluation 611 returned -0.956239 +/- 0.035438 Energy evaluation 612 returned -0.993433 +/- 0.028643 Energy evaluation 613 returned -0.965238 +/- 0.031499 Energy evaluation 614 returned -1.020369 +/- 0.031257 Energy evaluation 615 returned -0.969603 +/- 0.029712 Energy evaluation 616 returned -1.009274 +/- 0.034099 Energy evaluation 617 returned -1.005207 +/- 0.031170 Energy evaluation 618 returned -0.999903 +/- 0.031753 Energy evaluation 619 returned -1.054106 +/- 0.032258 Energy evaluation 620 returned -0.942992 +/- 0.031452 Energy evaluation 621 returned -0.943677 +/- 0.029239 Energy evaluation 622 returned -0.988561 +/- 0.033565 Energy evaluation 623 returned -1.001683 +/- 0.030746 Energy evaluation 624 returned -1.007030 +/- 0.033233 Energy evaluation 625 returned -0.976863 +/- 0.034788 Energy evaluation 626 returned -0.957005 +/- 0.030099 Energy evaluation 627 returned -0.918693 +/- 0.035358 Energy evaluation 628 returned -1.031175 +/- 0.030598 Energy evaluation 629 returned -0.989867 +/- 0.035789 Energy evaluation 630 returned -0.979748 +/- 0.029361 Energy evaluation 631 returned -0.975632 +/- 0.029311 Energy evaluation 632 returned -0.966509 +/- 0.034548 Energy evaluation 633 returned -0.984557 +/- 0.031173 Energy evaluation 634 returned -0.994839 +/- 0.033105 Energy evaluation 635 returned -0.949819 +/- 0.033577 Energy evaluation 636 returned -0.991537 +/- 0.030511 Energy evaluation 637 returned -0.931647 +/- 0.029839 Energy evaluation 638 returned -1.017722 +/- 0.034335 Energy evaluation 639 returned -1.029145 +/- 0.029456 Energy evaluation 640 returned -0.948801 +/- 0.036204 Energy evaluation 641 returned -0.959679 +/- 0.031221 Energy evaluation 642 returned -0.999159 +/- 0.032920 Energy evaluation 643 returned -0.918685 +/- 0.033690 Energy evaluation 644 returned -0.978681 +/- 0.031986 Energy evaluation 645 returned -0.962767 +/- 0.034981 Energy evaluation 646 returned -0.993459 +/- 0.029786 Energy evaluation 647 returned -0.972128 +/- 0.029595 Energy evaluation 648 returned -0.978744 +/- 0.034792 Energy evaluation 649 returned -0.977396 +/- 0.030370 Energy evaluation 650 returned -1.049111 +/- 0.033010 Energy evaluation 651 returned -0.978840 +/- 0.033113 Energy evaluation 652 returned -0.984712 +/- 0.031440 Energy evaluation 653 returned -1.036778 +/- 0.031908 Energy evaluation 654 returned -1.019459 +/- 0.031034 Energy evaluation 655 returned -1.058992 +/- 0.030549 Energy evaluation 656 returned -1.074926 +/- 0.031189 Energy evaluation 657 returned -0.952937 +/- 0.031955 Energy evaluation 658 returned -0.992718 +/- 0.033537 Energy evaluation 659 returned -0.973436 +/- 0.033886 Energy evaluation 660 returned -0.985200 +/- 0.031059 Energy evaluation 661 returned -1.049019 +/- 0.032863 Energy evaluation 662 returned -0.994951 +/- 0.030617 Energy evaluation 663 returned -0.921898 +/- 0.036989 Energy evaluation 664 returned -1.038529 +/- 0.028634 Energy evaluation 665 returned -0.993090 +/- 0.028645 Energy evaluation 666 returned -0.986769 +/- 0.035376 Energy evaluation 667 returned -1.007652 +/- 0.034412 Energy evaluation 668 returned -0.934283 +/- 0.030143 Energy evaluation 669 returned -0.987199 +/- 0.035112 Energy evaluation 670 returned -1.007441 +/- 0.029554 Energy evaluation 671 returned -0.999794 +/- 0.031547 Energy evaluation 672 returned -1.007346 +/- 0.031205 Energy evaluation 673 returned -1.032093 +/- 0.033564 Energy evaluation 674 returned -1.042363 +/- 0.029741 Energy evaluation 675 returned -1.001997 +/- 0.029051 Energy evaluation 676 returned -1.014303 +/- 0.034685 Energy evaluation 677 returned -0.972362 +/- 0.032336 Energy evaluation 678 returned -0.980537 +/- 0.032768 Energy evaluation 679 returned -0.953759 +/- 0.033697 Energy evaluation 680 returned -0.979535 +/- 0.030478 Energy evaluation 681 returned -0.973782 +/- 0.031959 Energy evaluation 682 returned -0.976236 +/- 0.032698 Energy evaluation 683 returned -0.980629 +/- 0.035398 Energy evaluation 684 returned -0.984031 +/- 0.028788 Energy evaluation 685 returned -0.980808 +/- 0.035333 Energy evaluation 686 returned -0.965896 +/- 0.030832 Energy evaluation 687 returned -1.042597 +/- 0.033426 Energy evaluation 688 returned -0.999065 +/- 0.030225 Energy evaluation 689 returned -0.969973 +/- 0.030716 Energy evaluation 690 returned -0.943360 +/- 0.034709 Energy evaluation 691 returned -0.959710 +/- 0.034933 Energy evaluation 692 returned -0.971909 +/- 0.029123 Energy evaluation 693 returned -1.024716 +/- 0.030861 Energy evaluation 694 returned -1.060949 +/- 0.032082 Energy evaluation 695 returned -1.007178 +/- 0.029946 Energy evaluation 696 returned -0.930918 +/- 0.035992 Energy evaluation 697 returned -1.011320 +/- 0.030011 Energy evaluation 698 returned -0.993373 +/- 0.032298 Energy evaluation 699 returned -0.996451 +/- 0.029783 Energy evaluation 700 returned -0.918388 +/- 0.033902 Energy evaluation 701 returned -1.019353 +/- 0.030803 Energy evaluation 702 returned -1.073879 +/- 0.029856 Energy evaluation 703 returned -0.972164 +/- 0.033206 Energy evaluation 704 returned -1.051799 +/- 0.028810 Energy evaluation 705 returned -0.999437 +/- 0.032129 Energy evaluation 706 returned -0.980088 +/- 0.029926 Energy evaluation 707 returned -0.966663 +/- 0.029118 Energy evaluation 708 returned -0.974849 +/- 0.033914 Energy evaluation 709 returned -0.993400 +/- 0.030968 Energy evaluation 710 returned -1.000463 +/- 0.031809 Energy evaluation 711 returned -0.975266 +/- 0.031663 Energy evaluation 712 returned -0.972005 +/- 0.031418 Energy evaluation 713 returned -0.963563 +/- 0.030811 Energy evaluation 714 returned -0.977604 +/- 0.032697 Energy evaluation 715 returned -0.982693 +/- 0.033093 Energy evaluation 716 returned -1.024791 +/- 0.028784 Energy evaluation 717 returned -0.987277 +/- 0.031107 Energy evaluation 718 returned -0.992344 +/- 0.030684 Energy evaluation 719 returned -0.989957 +/- 0.031046 Energy evaluation 720 returned -0.992341 +/- 0.030713 Energy evaluation 721 returned -1.000068 +/- 0.033326 Energy evaluation 722 returned -0.895167 +/- 0.030186 Energy evaluation 723 returned -1.002746 +/- 0.033865 Energy evaluation 724 returned -1.051960 +/- 0.030034 Energy evaluation 725 returned -1.016700 +/- 0.032136 Energy evaluation 726 returned -1.008865 +/- 0.031153 Energy evaluation 727 returned -0.951339 +/- 0.030567 Energy evaluation 728 returned -0.929524 +/- 0.034660 Energy evaluation 729 returned -0.985642 +/- 0.033689 Energy evaluation 730 returned -1.052020 +/- 0.028033 Energy evaluation 731 returned -0.971969 +/- 0.030807 Energy evaluation 732 returned -0.929532 +/- 0.031724 Energy evaluation 733 returned -0.988612 +/- 0.030512 Energy evaluation 734 returned -0.989589 +/- 0.032019 Energy evaluation 735 returned -1.004770 +/- 0.032072 Energy evaluation 736 returned -0.993128 +/- 0.029444 Energy evaluation 737 returned -0.990498 +/- 0.031154 Energy evaluation 738 returned -0.977570 +/- 0.031867 Energy evaluation 739 returned -0.990868 +/- 0.028780 Energy evaluation 740 returned -0.958024 +/- 0.035400 Energy evaluation 741 returned -0.970288 +/- 0.033572 Energy evaluation 742 returned -0.913655 +/- 0.029127 Energy evaluation 743 returned -1.026623 +/- 0.033780 Energy evaluation 744 returned -1.002492 +/- 0.028294 Energy evaluation 745 returned -0.996699 +/- 0.030633 Energy evaluation 746 returned -0.965894 +/- 0.033199 Energy evaluation 747 returned -0.997163 +/- 0.030490 Energy evaluation 748 returned -0.981813 +/- 0.032343 Energy evaluation 749 returned -1.041569 +/- 0.027856 Energy evaluation 750 returned -0.959162 +/- 0.034511 Energy evaluation 751 returned -0.994574 +/- 0.033209 Energy evaluation 752 returned -0.961525 +/- 0.029210 Energy evaluation 753 returned -1.026168 +/- 0.033079 Energy evaluation 754 returned -0.988586 +/- 0.028943 Energy evaluation 755 returned -0.975484 +/- 0.030840 Energy evaluation 756 returned -0.985998 +/- 0.032522 Energy evaluation 757 returned -1.032955 +/- 0.030877 Energy evaluation 758 returned -0.997871 +/- 0.031025 Energy evaluation 759 returned -1.047527 +/- 0.033414 Energy evaluation 760 returned -1.004757 +/- 0.028784 Energy evaluation 761 returned -0.982824 +/- 0.032117 Energy evaluation 762 returned -0.951649 +/- 0.032909 Energy evaluation 763 returned -1.003190 +/- 0.032192 Energy evaluation 764 returned -0.997364 +/- 0.031216 Energy evaluation 765 returned -1.023945 +/- 0.032904 Energy evaluation 766 returned -1.003769 +/- 0.029624 Energy evaluation 767 returned -1.013126 +/- 0.031193 Energy evaluation 768 returned -1.011417 +/- 0.031433 Energy evaluation 769 returned -1.016887 +/- 0.032008 Energy evaluation 770 returned -0.962909 +/- 0.031238 Energy evaluation 771 returned -1.059198 +/- 0.029801 Energy evaluation 772 returned -0.967365 +/- 0.033954 Energy evaluation 773 returned -1.042015 +/- 0.029561 Energy evaluation 774 returned -1.022986 +/- 0.032939 Energy evaluation 775 returned -1.033502 +/- 0.030646 Energy evaluation 776 returned -1.013076 +/- 0.031431 Energy evaluation 777 returned -0.971543 +/- 0.029432 Energy evaluation 778 returned -1.017103 +/- 0.034101 Energy evaluation 779 returned -0.979708 +/- 0.033835 Energy evaluation 780 returned -0.985553 +/- 0.030280 Energy evaluation 781 returned -0.947871 +/- 0.029605 Energy evaluation 782 returned -1.002736 +/- 0.034119 Energy evaluation 783 returned -0.965405 +/- 0.032359 Energy evaluation 784 returned -0.980855 +/- 0.031951 Energy evaluation 785 returned -0.981987 +/- 0.033888 Energy evaluation 786 returned -0.960744 +/- 0.032261 Energy evaluation 787 returned -0.984188 +/- 0.030049 Energy evaluation 788 returned -0.969833 +/- 0.034628 Energy evaluation 789 returned -1.010905 +/- 0.028469 Energy evaluation 790 returned -0.980266 +/- 0.034341 Energy evaluation 791 returned -1.110909 +/- 0.032043 Energy evaluation 792 returned -0.972959 +/- 0.030339 Energy evaluation 793 returned -0.965471 +/- 0.034154 Energy evaluation 794 returned -0.983553 +/- 0.031628 Energy evaluation 795 returned -0.958872 +/- 0.035482 Energy evaluation 796 returned -0.980918 +/- 0.029551 Energy evaluation 797 returned -0.971562 +/- 0.032417 Energy evaluation 798 returned -0.985414 +/- 0.031848 Energy evaluation 799 returned -0.993806 +/- 0.031453 Energy evaluation 800 returned -1.057047 +/- 0.031037 Energy evaluation 801 returned -0.999504 +/- 0.030802 Energy evaluation 802 returned -0.971602 +/- 0.034525 Energy evaluation 803 returned -0.939703 +/- 0.033025 Energy evaluation 804 returned -0.991937 +/- 0.031924 Energy evaluation 805 returned -0.937699 +/- 0.031469 Energy evaluation 806 returned -1.019361 +/- 0.032607 Energy evaluation 807 returned -0.962611 +/- 0.031821 Energy evaluation 808 returned -0.969412 +/- 0.034241 Energy evaluation 809 returned -1.029352 +/- 0.033220 Energy evaluation 810 returned -0.973684 +/- 0.030717 Energy evaluation 811 returned -0.989216 +/- 0.035250 Energy evaluation 812 returned -0.997807 +/- 0.029865 Energy evaluation 813 returned -0.963783 +/- 0.031100 Energy evaluation 814 returned -0.946039 +/- 0.035765 Energy evaluation 815 returned -0.973332 +/- 0.033811 Energy evaluation 816 returned -0.984619 +/- 0.031367 Energy evaluation 817 returned -1.019452 +/- 0.031707 Energy evaluation 818 returned -0.965002 +/- 0.032568 Energy evaluation 819 returned -1.020313 +/- 0.030407 Energy evaluation 820 returned -1.011095 +/- 0.033902 Energy evaluation 821 returned -0.998524 +/- 0.033924 Energy evaluation 822 returned -0.971269 +/- 0.032055 Energy evaluation 823 returned -0.999140 +/- 0.032204 Energy evaluation 824 returned -1.023219 +/- 0.032946 Energy evaluation 825 returned -1.034648 +/- 0.029358 Energy evaluation 826 returned -1.000369 +/- 0.035229 Energy evaluation 827 returned -0.988710 +/- 0.029695 Energy evaluation 828 returned -1.077652 +/- 0.032634 Energy evaluation 829 returned -1.032578 +/- 0.032284 Energy evaluation 830 returned -1.011198 +/- 0.031987 Energy evaluation 831 returned -0.960760 +/- 0.034280 Energy evaluation 832 returned -1.024146 +/- 0.030337 Energy evaluation 833 returned -1.032693 +/- 0.030582 Energy evaluation 834 returned -0.991135 +/- 0.034010 Energy evaluation 835 returned -0.943894 +/- 0.035838 Energy evaluation 836 returned -1.002710 +/- 0.030519 Energy evaluation 837 returned -1.052773 +/- 0.030112 Energy evaluation 838 returned -1.014261 +/- 0.032930 Energy evaluation 839 returned -1.035608 +/- 0.034239 Energy evaluation 840 returned -1.011169 +/- 0.028710 Energy evaluation 841 returned -1.041459 +/- 0.032657 Energy evaluation 842 returned -0.995856 +/- 0.031301 Energy evaluation 843 returned -1.008846 +/- 0.029670 Energy evaluation 844 returned -1.006045 +/- 0.033802 Energy evaluation 845 returned -0.918895 +/- 0.034622 Energy evaluation 846 returned -0.977759 +/- 0.029454 Energy evaluation 847 returned -0.969228 +/- 0.032622 Energy evaluation 848 returned -1.009704 +/- 0.031187 Energy evaluation 849 returned -0.984614 +/- 0.033686 Energy evaluation 850 returned -0.980893 +/- 0.029801 Energy evaluation 851 returned -1.043636 +/- 0.029642 Energy evaluation 852 returned -0.920283 +/- 0.033614 Energy evaluation 853 returned -1.028215 +/- 0.029932 Energy evaluation 854 returned -0.997361 +/- 0.032675 Energy evaluation 855 returned -1.066655 +/- 0.028259 Energy evaluation 856 returned -1.034839 +/- 0.031737 Energy evaluation 857 returned -1.045831 +/- 0.028364 Energy evaluation 858 returned -1.021447 +/- 0.032307 Energy evaluation 859 returned -0.971358 +/- 0.029860 Energy evaluation 860 returned -1.041095 +/- 0.030735 Energy evaluation 861 returned -0.981135 +/- 0.031038 Energy evaluation 862 returned -0.991986 +/- 0.031503 Energy evaluation 863 returned -0.994583 +/- 0.031722 Energy evaluation 864 returned -0.961378 +/- 0.031083 Energy evaluation 865 returned -1.021680 +/- 0.030781 Energy evaluation 866 returned -1.001550 +/- 0.031792 Energy evaluation 867 returned -1.082979 +/- 0.031255 Energy evaluation 868 returned -1.028607 +/- 0.029809 Energy evaluation 869 returned -0.950352 +/- 0.029112 Energy evaluation 870 returned -1.001934 +/- 0.033564 Energy evaluation 871 returned -0.998879 +/- 0.029733 Energy evaluation 872 returned -0.971831 +/- 0.033513 Energy evaluation 873 returned -0.982483 +/- 0.032137 Energy evaluation 874 returned -1.015443 +/- 0.030364 Energy evaluation 875 returned -0.998631 +/- 0.032045 Energy evaluation 876 returned -0.976688 +/- 0.032485 Energy evaluation 877 returned -1.064392 +/- 0.031338 Energy evaluation 878 returned -0.950804 +/- 0.030879 Energy evaluation 879 returned -1.054708 +/- 0.028824 Energy evaluation 880 returned -0.919401 +/- 0.035599 Energy evaluation 881 returned -0.938161 +/- 0.031746 Energy evaluation 882 returned -0.926528 +/- 0.031959 Energy evaluation 883 returned -0.983400 +/- 0.032860 Energy evaluation 884 returned -0.997837 +/- 0.029965 Energy evaluation 885 returned -0.980783 +/- 0.032968 Energy evaluation 886 returned -0.999638 +/- 0.030176 Energy evaluation 887 returned -0.977962 +/- 0.030498 Energy evaluation 888 returned -0.986658 +/- 0.030896 Energy evaluation 889 returned -0.989520 +/- 0.030864 Energy evaluation 890 returned -0.949058 +/- 0.032621 Energy evaluation 891 returned -0.964865 +/- 0.029875 Energy evaluation 892 returned -1.031578 +/- 0.031103 Energy evaluation 893 returned -1.000529 +/- 0.028826 Energy evaluation 894 returned -1.012788 +/- 0.031123 Energy evaluation 895 returned -1.034517 +/- 0.029283 Energy evaluation 896 returned -1.017239 +/- 0.031185 Energy evaluation 897 returned -0.999251 +/- 0.030423 Energy evaluation 898 returned -1.062275 +/- 0.031705 Energy evaluation 899 returned -0.974157 +/- 0.031552 Energy evaluation 900 returned -0.997518 +/- 0.030198 Energy evaluation 901 returned -0.975608 +/- 0.029869 Energy evaluation 902 returned -1.014098 +/- 0.031442 Energy evaluation 903 returned -0.986103 +/- 0.031682 Energy evaluation 904 returned -0.996213 +/- 0.030508 Energy evaluation 905 returned -1.016772 +/- 0.029295 Energy evaluation 906 returned -0.994155 +/- 0.033181 Energy evaluation 907 returned -1.022150 +/- 0.029334 Energy evaluation 908 returned -1.023815 +/- 0.032588 Energy evaluation 909 returned -1.002598 +/- 0.032531 Energy evaluation 910 returned -1.007208 +/- 0.029137 Energy evaluation 911 returned -0.972256 +/- 0.030676 Energy evaluation 912 returned -0.926175 +/- 0.032557 Energy evaluation 913 returned -0.997694 +/- 0.032784 Energy evaluation 914 returned -1.013493 +/- 0.028782 Energy evaluation 915 returned -0.976425 +/- 0.030376 Energy evaluation 916 returned -1.018574 +/- 0.031818 Energy evaluation 917 returned -1.026767 +/- 0.032126 Energy evaluation 918 returned -1.021173 +/- 0.029315 Energy evaluation 919 returned -1.067505 +/- 0.029937 Energy evaluation 920 returned -1.012345 +/- 0.031443 Energy evaluation 921 returned -0.977361 +/- 0.034089 Energy evaluation 922 returned -0.986489 +/- 0.029154 Energy evaluation 923 returned -1.020429 +/- 0.029857 Energy evaluation 924 returned -1.037755 +/- 0.029674 Energy evaluation 925 returned -0.969929 +/- 0.032822 Energy evaluation 926 returned -0.950369 +/- 0.030652 Energy evaluation 927 returned -1.077733 +/- 0.030715 Energy evaluation 928 returned -0.996456 +/- 0.030839 Energy evaluation 929 returned -0.987424 +/- 0.031532 Energy evaluation 930 returned -1.014396 +/- 0.031060 Energy evaluation 931 returned -1.029922 +/- 0.033124 Energy evaluation 932 returned -1.015794 +/- 0.028127 Energy evaluation 933 returned -1.005317 +/- 0.028318 Energy evaluation 934 returned -0.998756 +/- 0.033667 Energy evaluation 935 returned -0.999579 +/- 0.031165 Energy evaluation 936 returned -1.021820 +/- 0.029453 Energy evaluation 937 returned -1.019211 +/- 0.029909 Energy evaluation 938 returned -0.985463 +/- 0.032547 Energy evaluation 939 returned -0.997831 +/- 0.030804 Energy evaluation 940 returned -1.022745 +/- 0.030701 Energy evaluation 941 returned -1.004677 +/- 0.031083 Energy evaluation 942 returned -0.975577 +/- 0.031519 Energy evaluation 943 returned -1.016243 +/- 0.032682 Energy evaluation 944 returned -0.997222 +/- 0.028332 Energy evaluation 945 returned -0.975944 +/- 0.029629 Energy evaluation 946 returned -1.026117 +/- 0.031854 Energy evaluation 947 returned -0.982106 +/- 0.028470 Energy evaluation 948 returned -0.970373 +/- 0.034399 Energy evaluation 949 returned -1.030061 +/- 0.032243 Energy evaluation 950 returned -0.979772 +/- 0.029733 Energy evaluation 951 returned -1.007426 +/- 0.032182 Energy evaluation 952 returned -0.981690 +/- 0.030516 Energy evaluation 953 returned -1.048511 +/- 0.028117 Energy evaluation 954 returned -0.986743 +/- 0.032962 Energy evaluation 955 returned -0.945073 +/- 0.029383 Energy evaluation 956 returned -0.963330 +/- 0.031855 Energy evaluation 957 returned -0.972405 +/- 0.028709 Energy evaluation 958 returned -0.992808 +/- 0.034245 Energy evaluation 959 returned -0.961358 +/- 0.030839 Energy evaluation 960 returned -0.995489 +/- 0.032402 Energy evaluation 961 returned -0.996751 +/- 0.031584 Energy evaluation 962 returned -1.014605 +/- 0.030775 Energy evaluation 963 returned -1.021467 +/- 0.030147 Energy evaluation 964 returned -0.989439 +/- 0.032361 Energy evaluation 965 returned -1.051029 +/- 0.031157 Energy evaluation 966 returned -1.002468 +/- 0.031887 Energy evaluation 967 returned -0.982325 +/- 0.028898 Energy evaluation 968 returned -1.019646 +/- 0.033579 Energy evaluation 969 returned -1.021551 +/- 0.030269 Energy evaluation 970 returned -1.017417 +/- 0.031815 Energy evaluation 971 returned -1.037527 +/- 0.031218 Energy evaluation 972 returned -1.005724 +/- 0.031348 Energy evaluation 973 returned -1.007502 +/- 0.031525 Energy evaluation 974 returned -1.029416 +/- 0.030400 Energy evaluation 975 returned -1.004617 +/- 0.030743 Energy evaluation 976 returned -0.991374 +/- 0.032936 Energy evaluation 977 returned -1.015038 +/- 0.030327 Energy evaluation 978 returned -0.957069 +/- 0.032742 Energy evaluation 979 returned -1.008622 +/- 0.030322 Energy evaluation 980 returned -0.991707 +/- 0.032422 Energy evaluation 981 returned -0.977856 +/- 0.029463 Energy evaluation 982 returned -0.987152 +/- 0.033559 Energy evaluation 983 returned -0.934635 +/- 0.032375 Energy evaluation 984 returned -1.026034 +/- 0.029977 Energy evaluation 985 returned -0.959344 +/- 0.028684 Energy evaluation 986 returned -1.030021 +/- 0.033757 Energy evaluation 987 returned -0.980538 +/- 0.031838 Energy evaluation 988 returned -1.057853 +/- 0.031025 Energy evaluation 989 returned -0.948215 +/- 0.035459 Energy evaluation 990 returned -0.972401 +/- 0.029887 Energy evaluation 991 returned -1.033349 +/- 0.032353 Energy evaluation 992 returned -0.972230 +/- 0.030471 Energy evaluation 993 returned -1.004425 +/- 0.033173 Energy evaluation 994 returned -1.003661 +/- 0.030472 Energy evaluation 995 returned -0.972430 +/- 0.034363 Energy evaluation 996 returned -0.964977 +/- 0.029878 Energy evaluation 997 returned -0.979914 +/- 0.031422 Energy evaluation 998 returned -0.945564 +/- 0.034027 Energy evaluation 999 returned -1.055920 +/- 0.030135 Energy evaluation 1000 returned -1.064126 +/- 0.031370 Energy evaluation 1001 returned -0.961398 +/- 0.033662 Energy evaluation 1002 returned -1.038466 +/- 0.030300 Energy evaluation 1003 returned -1.037960 +/- 0.029957 Energy evaluation 1004 returned -1.022867 +/- 0.032898 Energy evaluation 1005 returned -0.979184 +/- 0.030808 Energy evaluation 1006 returned -0.989504 +/- 0.033410 Energy evaluation 1007 returned -0.995529 +/- 0.032002 Energy evaluation 1008 returned -1.000105 +/- 0.029643 Energy evaluation 1009 returned -1.029865 +/- 0.029766 Energy evaluation 1010 returned -1.016752 +/- 0.032832 Energy evaluation 1011 returned -0.983467 +/- 0.030661 Energy evaluation 1012 returned -0.994240 +/- 0.032735 Energy evaluation 1013 returned -1.014989 +/- 0.030127 Energy evaluation 1014 returned -0.983941 +/- 0.032412 Energy evaluation 1015 returned -1.041868 +/- 0.031115 Energy evaluation 1016 returned -1.017627 +/- 0.031439 Energy evaluation 1017 returned -1.006392 +/- 0.028511 Energy evaluation 1018 returned -0.946356 +/- 0.034198 Energy evaluation 1019 returned -1.034708 +/- 0.029980 Energy evaluation 1020 returned -1.039788 +/- 0.030809 Energy evaluation 1021 returned -1.020616 +/- 0.030983 Energy evaluation 1022 returned -0.973869 +/- 0.031002 Energy evaluation 1023 returned -1.020920 +/- 0.032453 Energy evaluation 1024 returned -0.994614 +/- 0.029941 Energy evaluation 1025 returned -0.977376 +/- 0.032127 Energy evaluation 1026 returned -0.978485 +/- 0.030124 Energy evaluation 1027 returned -0.978233 +/- 0.033071 Energy evaluation 1028 returned -0.929290 +/- 0.031602 Energy evaluation 1029 returned -1.035471 +/- 0.031174 Energy evaluation 1030 returned -0.987792 +/- 0.031540 Energy evaluation 1031 returned -1.029508 +/- 0.033234 Energy evaluation 1032 returned -0.963405 +/- 0.029284 Energy evaluation 1033 returned -0.988925 +/- 0.032675 Energy evaluation 1034 returned -1.001834 +/- 0.031181 Energy evaluation 1035 returned -1.005719 +/- 0.031815 Energy evaluation 1036 returned -0.970747 +/- 0.029856 Energy evaluation 1037 returned -1.016290 +/- 0.031457 Energy evaluation 1038 returned -1.055224 +/- 0.031060 Energy evaluation 1039 returned -1.037417 +/- 0.030456 Energy evaluation 1040 returned -0.989888 +/- 0.033688 Energy evaluation 1041 returned -0.991445 +/- 0.033937 Energy evaluation 1042 returned -1.031271 +/- 0.028795 Energy evaluation 1043 returned -0.977898 +/- 0.033402 Energy evaluation 1044 returned -1.005856 +/- 0.029799 Energy evaluation 1045 returned -1.079747 +/- 0.029947 Energy evaluation 1046 returned -1.004045 +/- 0.031639 Energy evaluation 1047 returned -1.036121 +/- 0.032812 Energy evaluation 1048 returned -1.027332 +/- 0.029499 Energy evaluation 1049 returned -0.991534 +/- 0.033142 Energy evaluation 1050 returned -1.034950 +/- 0.028632 Energy evaluation 1051 returned -1.009399 +/- 0.030947
https://github.com/avkhadiev/schwinger-vqe
avkhadiev
from qiskit import * import qiskit.tools.jupyter import numpy as np IBMQ.load_account() optimizer = qiskit.aqua.components.optimizers.SPSA() print(optimizer.setting)
https://github.com/avkhadiev/schwinger-vqe
avkhadiev
https://github.com/avkhadiev/schwinger-vqe
avkhadiev
from qiskit import * import qiskit.tools.jupyter import numpy as np IBMQ.load_account() # so far, this is an input from a Mathematica notebook โ€” decomposition of target Hamiltonian into pauli basis ops # diag = 9, 12, 15, 16 coeffs = np.array([ # smart sort # greedy sort 0.424179, #1 YY/XX -> YY/XX YY/XX -> YY/XX 0., #2 0., #3 0., #4 0.424179, #5 YY/XX -> YY/XX YY/XX -> YY/XX 0., #6 0.175701, #7 ZX -> ZX ZX -> ZX 0., #8 -0.10018, #9 ZZ -> ZZ ZZ -> ZZ 1.02406, #10 IX -> XX IX -> XX 0., #11 -0.5, #12 IZ -> ZZ IZ -> ZZ 0., #13 0., #14 -1.10018, #15 ZI -> ZZ ZI -> ZZ 1.5 #16 (trace) II -> YY II -> XX ]) # 0.25 * Tr[H * O] for some operators is 0 # find non-zero coefficients, excluding the traceless part; # make 1-indexed rather than 0-indexed nonzero_proj=np.nonzero(coeffs[:-1])[0]+1 diag = np.array([9, 12, 15]) nondiag = np.setdiff1d(nonzero_proj, diag) qubit_order = ['00', '10', '01', '11'] # try various orderings od = { # O(diagonal) # corresponds to outcomes given by qubit_order # TODO add other diagonal form for completeness 1: [1., -1., -1., 1.], # 3: None, # 4: None, 5: [1., -1., -1., 1.], # 6: None, 7: [1., -1., -1., 1.], # 8: None, 9: [1., -1., -1., 1.], 10: [1., -1., 1., -1.], # 11: None, 12: [1., -1., 1., -1.], # 13: None, # 14: None, 15: [1., 1., -1., -1.], } # because IBM ordering and textbook ordering of qubits differs, # associate each diagonal element with qubit ordering explicitly for index, diag_form in od.items(): od[index] = dict(zip(qubit_order, diag_form)) # group non-diagonal operators into groups that have the same circuit # TODO: how to do this automatically? nondiag_circ_groups = [[1,], [5,], [7, 10,]] # TODO circuit indices corresponding to operator indices # all necessary circuits are indexed (from 0); these indices are values of this dict, # keyed on all indices of those Pauli operators that have a non-zero contribution # to the traceless part of the Hamiltonian circ_idx = {} for diag_idx in diag: # assign circuit index 0 to operator indices for diagonal operator; circ_idx[diag_idx] = 0 # assign higher indices to all groups of non-diagonal operators, # where all operators in a group have the same circuit circ_index = 1 for circ_group in nondiag_circ_groups: for nondiag_idx in circ_group: circ_idx[nondiag_idx] = circ_index circ_index += 1 ncircuits = len(np.unique(list(circ_idx.values()))) print(f'There are {ncircuits:d} unique circuits') # stores indexes circuits circ = {} # define number of qubits and bits nqubits = 2 nclbits = 2 # create registers vqs_qreg = QuantumRegister(nqubits, name="q") vqs_creg = ClassicalRegister(nclbits, name="c") regs = [vqs_qreg, vqs_creg] # FIXME: some circuits are the same for different operators # => don't actually need separate measurements; # store operator indices grouped in arrays, # with the same circuit for each array. # Thus, all diagonal operators will have the same circuit, and # some non-diagonal operators will have the same circuit. # This circuit is the same for all diagonal operators for icirc in range(ncircuits): circ[icirc] = QuantumCircuit(*regs, name=str(icirc)) # measurement circuit meas = QuantumCircuit(*regs, name="meas") # .barrier prevents optimizations # from reordering gates across its source line meas.barrier(range(nqubits)) meas.measure(range(nqubits), range(nqubits)) # map qubits to clbits # constructs the non-diagonal circuits for operators 1, 5, and 7 and 10 # 1 circ[circ_idx[1]].h(0) circ[circ_idx[1]].iden(0) ## circ[circ_idx[1]].iden(1) circ[circ_idx[1]].h(1) # 5 ## circ[circ_idx[5]].h(0) circ[circ_idx[5]].iden(1) ## circ[circ_idx[5]].sdg(0) # conjugate of sqrt(Z) gate circ[circ_idx[5]].iden(1) ## circ[circ_idx[5]].iden(0) circ[circ_idx[5]].h(1) ## circ[circ_idx[5]].iden(0) circ[circ_idx[5]].sdg(1) # 7 and 10 circ[circ_idx[7]].iden(0) circ[circ_idx[7]].h(1) # add measurement to all operator circuits for icirc in range(ncircuits): # add measurement # can't see to modify value of this dict # by using an iterator over values: # probably, the QuantumCircuit object is # copied by value to the iterator in that case circ[icirc] = circ[icirc] + meas # can browse through various circuits associated to operators index = 9 print(f'Circuit for O{index:1d}') circ[circ_idx[index]].draw(output='latex', scale=0.5) backend_sim = Aer.get_backend('qasm_simulator') # execute the circuit on qasm_simulator backend; # set repeats (measurement shots) at 1024 (default) # memory = True: # per-shot measurement bitstrings are returned # as well (provided the backend supports it) nshots = 8*1021 # stores results indexed by operator job = {} res = {} for icirc in range(ncircuits): job[icirc] = execute(circ[icirc], backend_sim, shots=nshots, memory=True) res[icirc] = job[icirc].result() # takes in results from a single circuit # with memory=True, and estimates # the uncertanities on the probability of each outcome # (currently with bootstrap) # returns outcome:(pba, std) dictionary def compute_stats(results): # check that there is a single circuit in the results # (ambiguous otherwise) # TODO # pull number of qubits from results # generates all possible outcomes given \ # the number of qubits def _generate_bitstrings(nqubits=2): if (nqubits == 2): return ['00', '10', '01', '11'] else: print("I am hardcoded at the moment") raise # bootstrap specific? # given ensembles of outcomes and a particular outcome # calculates the statistics of that outcome: # returns outcome:(pba, std) estimates for the outcome def _calc_outcome_stats(ensembles, nshots, outcome): cts = np.count_nonzero(ensembles==outcome, axis=0) pba = np.mean(cts)/nshots std = np.std(cts/nshots, ddof = 1) # use unbiased estimator return (pba, std) outcomes = _generate_bitstrings() mem = res.get_memory() # stores pba[i][outcome] = [mean, std] pba[i] = {outcome:[0.,0.] for outcome in outcomes} # build ensembles # TODO retrieve nshots from results nshots = 1024 nens = nshots # choose number of ensemles = number of samples nsam = nshots ensembles = np.random.choice(mem[i], (nens, nsam)) stats = {map(lambda outcome: outcome:_calc_outcome_stats(ensembles, nshots, outcome), outcomes)} return stats import numpy as np # Function to generate all binary strings def _generate_bitstrings(nqubits, all_strings, a_string, irecur): if irecur == nqubits: all_strings.append(''.join([bit for bit in a_string])) return _generate_bitstrings(nqubits, all_strings, a_string + ['0'], irecur + 1) _generate_bitstrings(nqubits, all_strings, a_string + ['1'], irecur + 1) all_strings = [] _generate_bitstrings(2, all_strings, [], 0) print(all_strings) # computes probabilities and statistical uncertainties; # also saves raw counts to bootstrap on H directly mem = {} # stores all measurement results cts = {} # stores a total count of results pba = {} # stores final probabilities outcomes = ['00', '10', '01', '11'] # specific two 2-qubit register for i in range(ncircuits): cts[i] = res[i].get_counts(circ[i]) # this just sets the right shape for cts array mem[i] = res[i].get_memory(circ[i]) pba[i] = {outcome:[0.,0.] for outcome in outcomes} # stores pba[i][outcome] = [mean, std] nens = nshots nsam = nshots ensembles = np.random.choice(mem[i], (nens, nsam)) print(f'{i:d}') for outcome in outcomes: cts[i][outcome] = np.count_nonzero(ensembles==outcome, axis=0) pba[i][outcome][0] = (np.mean(cts[i][outcome])/nshots) pba[i][outcome][1] = (np.std(cts[i][outcome], ddof = 1)/nshots) print(f'{outcome}: {pba[i][outcome][0]:1.3g}, {pba[i][outcome][1]:1.1g}') # get array of operator indices corresponding to a circuit index op_idx = {} for op_index, circ_index in circ_idx.items(): op_idx[circ_index] = op_idx.setdefault(circ_index, []) op_idx[circ_index].append(op_index) # compute the value of identity measurement id_meas = [0.0, 0.0] # value, error # circuit index for diagonal operators is 0 id_mem = res[0].get_memory(circ[0]) # also compute measurement results to bootstrap on H directly id_cts = res[0].get_counts(circ[0]) # this just sets the right shape for cts array for outcome in outcomes: nens = len(id_mem) nsam = len(id_mem) ensembles = np.random.choice(id_mem, (nens, nsam)) id_cts[outcome] = np.count_nonzero(ensembles==outcome, axis=0) id_meas[0] += pba[0][outcome][0] id_meas[1] += pba[0][outcome][1]**2. id_meas[1] = np.sqrt(id_meas[1]) print(id_meas) # expect value = 1.0 from probability normalization # computing expectation values of operators, which have one set of indices # from measurement outcomes, which are indexed by circuits. Some operators correspond to the same circuit # circ_idx[operator_index] is a dictionary of circuit indices keyed on operator indices # also propagating raw measurement results to bootstrap on H directly od_meas = {index:[0.0, 0.0] for index in od.keys()} # store (measurement, uncert) for operators here #od_cts = {} for circ_index in range(ncircuits): # loop over various circuits print(f'circuit index {circ_index:d}') for outcome in outcomes: # probabilities of measurements are associated with circuits print(f'{outcome}: {pba[circ_index][outcome][0]:3.3f}, {pba[circ_index][outcome][1]:3.3f}') print(op_idx[circ_index]) for op_index in op_idx[circ_index]:# consider every operator corresponding to current circuit # copies counts from circuit measurements to corresponding operator #od_cts[op_index] = cts[circ_index][:] # does not modify the counts array #print(od_cts[op_index]) print(f'operator {op_index:d}') for outcome in outcomes: # loop over possible outcomes (measured qubit configurations) # eigenvalues multiplying the probabilities are associated with operators eigenval = od[op_index][outcome] print(f'{outcome}: {eigenval:1.1f}') # propagate counts, weighted by the eigenvalues #od_cts[op_index][outcome] = np.array(od_cts[op_index][outcome], dtype=np.float64) #print(od_cts[op_index][outcome]) #od_cts[op_index][outcome] *= eigenval #print(od_cts[op_index][outcome]) # multiply probabilities of outcomes by corresponding eigenvalue, sum over eigenvalues od_meas[op_index][0] += eigenval * pba[circ_index][outcome][0] # probability * eigenvalue od_meas[op_index][1] += abs(eigenval) * pba[circ_index][outcome][1] # propagated uncertainty ? FIXME # take squre root of sum of squares of uncertainties (assuming uncorrelated projected measurements) # od_meas[op_index][1] = np.sqrt(od_meas[op_index][1]) print(f'{od_meas[op_index][0]:4.4f}, {od_meas[op_index][1]:4.4f}') # combine probabilities and uncertainties to get the the expectation value of H in the fidicial state H_expect = [0.,0.] test = {outcome:0.0 for outcome in outcomes} # counts for i_nz_c in nonzero_proj: coeff = coeffs[i_nz_c-1] # shift back to 0-indexed value = od_meas[i_nz_c][0] error = od_meas[i_nz_c][1] H_expect[0] += coeff*value H_expect[1] += abs(coeff)*error for outcome in outcomes: eigenval = od[op_index][outcome] test[outcome] += (coeff * eigenval * cts[circ_idx[i_nz_c]][outcome] / nshots) test2=np.zeros(nsam) for outcome in outcomes: test2 += test[outcome] test2 += coeffs[15]*(id_cts[outcome]/nshots) # add the trace back mean2= np.mean(test2) std2 = np.std(test2) print((mean2, std2)) # add the trace back H_expect[0] += coeffs[15] * id_meas[0] H_expect[1] += abs(coeffs[15]) * id_meas[1] print(H_expect) mathematica_res = -0.20035992801439712 #print(H_expect) print((mean2, std2)) #print(H_expect[0]+H_expect[1], H_expect[0]-H_expect[1]) print((mean2+std2, mean2-std2)) print(mathematica_res) import matplotlib.pyplot as plt diag_bars = np.arange(len(diag)) avgs = [od_meas[diag_index][0] for diag_index in diag] stds = [od_meas[diag_index][1] for diag_index in diag] fig, ax = plt.subplots() ax.bar(diag_bars, avgs, yerr=stds, align='center', alpha=0.5, ecolor='black', edgecolor='k', error_kw=dict(lw=0.5, capsize=10, capthick=2.0), label='IBM sim') ax.set_ylabel(r'$\langle O \rangle_{\psi_{\mathrm{ini}}}$', fontsize=16) ax.set_xlabel('Diagonal Operators', fontsize=16) ax.set_xticks(diag_bars) ax.set_xticklabels(diag) ax.set_title(f'nshots={nshots:d}', fontsize=16) ax.axhline(y = 1.0, color='r', linewidth = 0.5, label='Mathematica') plt.ylim([0.99, 1.001]) plt.tight_layout() plt.legend(frameon=False, fontsize=16, bbox_to_anchor=(1.04,1), loc="upper left") plt.savefig("op_diag.png", dpi=300) nondiag_bars = np.arange(len(nondiag)) avgs = [od_meas[diag_index][0] for diag_index in nondiag] stds = [od_meas[diag_index][1] for diag_index in nondiag] fig, ax = plt.subplots() ax.bar(nondiag_bars, avgs, yerr=stds, align='center', alpha=0.5, ecolor='black', edgecolor='k', error_kw=dict(lw=0.5, capsize=10, capthick=2.0), label='IBM sim') ax.set_ylabel(r'$\langle O \rangle_{\psi_{\mathrm{ini}}}$', fontsize=16) ax.set_xlabel('Non-Diagonal Operators', fontsize=16) ax.set_xticks(nondiag_bars) ax.set_xticklabels(nondiag) ax.set_title(f'nshots={nshots:d}', fontsize=16) ax.axhline(y = 0.0, color='r', linewidth = 0.5, label='Mathematica') plt.tight_layout() plt.legend(frameon=False, fontsize=16, bbox_to_anchor=(1.04,1), loc="upper left") plt.savefig("op_nondiag.png", dpi=300)
https://github.com/avkhadiev/schwinger-vqe
avkhadiev
from qiskit import * import qiskit.tools.jupyter import numpy as np IBMQ.load_account() class SchwingerAnsatz(qiskit.aqua.components.variational_forms.VariationalForm): """ Variational Layer from Martin's Paper """ CONFIGURATION = { 'name': 'Schwinger Ansatz', 'description': 'Variational Form for Schwinger VQE', 'input_schema': { '$schema': 'http://json-schema.org/draft-07/schema#', 'id': 'schwinger_schema', 'type': 'object', 'properties': { 'depth': { 'type': 'integer', 'default': 3, 'minimum': 1 }, 'entangler_map': { 'type': ['array', 'null'], 'default': None }, 'entanglement_gate': { 'type': 'string', 'default': 'cx', 'enum': ['cx'] }, }, 'additionalProperties': False }, 'depends': [ { 'pluggable_type': 'initial_state', 'default': { 'name': 'ZERO', } }, ], } def __init__(self, depth=3, entangler_map=None, initial_state=None): """ Constructor. Args: depth (int) : number of rotation layers entangler_map (list[list]): describe the connectivity of qubits, each list describes [source, target], or None for full entanglement. Note that the order is the list is the order of applying the two-qubit gate. initial_state (InitialState): an initial state object """ self.validate(locals()) super().__init__() # hard-coded, first pass through FIXME num_qubits = 2 num_parameters = 3 entanglement='full' entanglement_gate='cx' skip_unentangled_qubits = False self._num_qubits = num_qubits self._depth = depth if entangler_map is None: self._entangler_map = qiskit.aqua.components.variational_forms.VariationalForm.get_entangler_map(entanglement, num_qubits) else: self._entangler_map = qiskit.aqua.components.variational_forms.VariationalForm.validate_entangler_map(entangler_map, num_qubits) # determine the entangled qubits all_qubits = [] for src, targ in self._entangler_map: all_qubits.extend([src, targ]) self._entangled_qubits = sorted(list(set(all_qubits))) self._initial_state = initial_state self._entanglement_gate = entanglement_gate self._skip_unentangled_qubits = skip_unentangled_qubits # for the first layer self._num_parameters = num_parameters # for repeated block self._num_parameters += num_parameters * (depth-1) self._bounds = [(-np.pi, np.pi)] * self._num_parameters def construct_circuit(self, parameters, q=None): """ Construct the variational form, given its parameters. Args: parameters (numpy.ndarray): circuit parameters q (QuantumRegister): Quantum Register for the circuit. Returns: QuantumCircuit: a quantum circuit with given `parameters` Raises: ValueError: the number of parameters is incorrect. """ if len(parameters) != self._num_parameters: raise ValueError('The number of parameters has to be {}'.format(self._num_parameters)) if q is None: q = QuantumRegister(self._num_qubits, name='q') if self._initial_state is not None: circuit = self._initial_state.construct_circuit('circuit', q) else: circuit = QuantumCircuit(q) # param_idx = 0 def angle(theta=0., phi=0., lam=0.): return [theta, phi, lam] for _ in range(self._depth): # get variational parameters for this layer t0 = parameters[param_idx] # theta-angle values t1 = parameters[param_idx+1] t2 = parameters[param_idx+2] t = [angle(t_i) for t_i in [t0, t1, t2]] # Construct circuit circuit.u3(*(t[1]), 0) # u3(*angles, q) circuit.u3(*(t[0]), 1) circuit.cx(0, 1) # entangling qubit cx(ctrl, tgt) circuit.u3(*(t[0]), 1) circuit.cx(0, 1) # entangling qubit cx(ctrl, tgt) circuit.u3(*(t[2]), 1) circuit.barrier(q) return circuit test = SchwingerAnsatz(1) vqs_circ = test.construct_circuit([-0.386244, 0.317799, -0.416888]) vqs_circ.draw(output='latex', scale=0.5)
https://github.com/avkhadiev/schwinger-vqe
avkhadiev
from qiskit import * import qiskit.tools.jupyter import numpy as np IBMQ.load_account() from qiskit.aqua.components.variational_forms import VariationalForm from qiskit.aqua.components.initial_states import Zero, VarFormBased from qiskit.aqua.operators import MatrixOperator, TPBGroupedWeightedPauliOperator from qiskit.aqua.operators.op_converter import to_tpb_grouped_weighted_pauli_operator from qiskit.aqua.components.optimizers import SPSA from qiskit.aqua.algorithms.adaptive import VQE from scipy.sparse import * from scipy import * num_qubits = 3 num_var_params = 6 var_form_depth = 1 initial_params = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] class ConcatenatedSchwingerAnsatz(VariationalForm): """ Variational Layer from Martin's Paper """ CONFIGURATION = { 'name': 'Schwinger Ansatz', 'description': 'Variational Form for Schwinger VQE', 'input_schema': { '$schema': 'http://json-schema.org/draft-07/schema#', 'id': 'schwinger_schema', 'type': 'object', 'properties': { 'depth': { 'type': 'integer', 'default': 3, 'minimum': 1 }, 'entangler_map': { 'type': ['array', 'null'], 'default': None }, 'entanglement_gate': { 'type': 'string', 'default': 'cx', 'enum': ['cx'] }, }, 'additionalProperties': False }, 'depends': [ { 'pluggable_type': 'initial_state', 'default': { 'name': 'ZERO', } }, ], } def __init__(self, depth=3, entangler_map=None, initial_state=None): """ Constructor. Args: depth (int) : number of rotation layers entangler_map (list[list]): describe the connectivity of qubits, each list describes [source, target], or None for full entanglement. Note that the order is the list is the order of applying the two-qubit gate. initial_state (InitialState): an initial state object """ self.validate(locals()) super().__init__() #_support_parameterized_circuit = True # hard-coded, first pass through FIXME num_qubits = 3 num_parameters = 6 entanglement='full' entanglement_gate='cx' skip_unentangled_qubits = False self._num_qubits = num_qubits self._depth = depth if entangler_map is None: self._entangler_map = VariationalForm.get_entangler_map(entanglement, num_qubits) else: self._entangler_map = VariationalForm.validate_entangler_map(entangler_map, num_qubits) # determine the entangled qubits all_qubits = [] for src, targ in self._entangler_map: all_qubits.extend([src, targ]) self._entangled_qubits = sorted(list(set(all_qubits))) self._initial_state = initial_state self._entanglement_gate = entanglement_gate self._skip_unentangled_qubits = skip_unentangled_qubits # for the first layer self._num_parameters = num_parameters # for repeated block self._num_parameters += num_parameters * (depth-1) self._bounds = [(-np.pi, np.pi)] * self._num_parameters def construct_circuit(self, parameters, q=None): """ Construct the variational form, given its parameters. Args: parameters (numpy.ndarray): circuit parameters q (QuantumRegister): Quantum Register for the circuit. Returns: QuantumCircuit: a quantum circuit with given `parameters` Raises: ValueError: the number of parameters is incorrect. """ if len(parameters) != self._num_parameters: raise ValueError('The number of parameters has to be {}'.format(self._num_parameters)) if q is None: q = QuantumRegister(self._num_qubits, name='q') if self._initial_state is not None: circuit = self._initial_state.construct_circuit('circuit', q) else: circuit = QuantumCircuit(q) # param_idx = 0 def angle(theta=0., phi=0., lam=0.): return [theta, phi, lam] for _ in range(self._depth): # get variational parameters for this layer t0_1 = parameters[param_idx] # theta-angle values t1_1 = parameters[param_idx+1] t2_1 = parameters[param_idx+2] t0_2 = parameters[param_idx] # theta-angle values t1_2 = parameters[param_idx+1] t2_3 = parameters[param_idx+2] t1 = [angle(t_i) for t_i in [t0_1, t1_1, t2_1]] t2 = [angle(t_i) for t_i in [t0_1, t1_1, t2_1]] # FIRST circuit.u3(*(t1[1]), 1) # u3(*angles, q) circuit.u3(*(t1[0]), 2) circuit.cx(1, 2) # entangling qubit cx(ctrl, tgt) circuit.u3(*(t1[0]), 1) circuit.cx(1, 2) # entangling qubit cx(ctrl, tgt) circuit.u3(*(t1[2]), 2) circuit.barrier(range(3)) # SECOND circuit.cx(0,2) # circuit.u3(*(t2[1]), 1) # u3(*angles, q) circuit.u3(*(t2[0]), 2) circuit.cx(1, 2) # entangling qubit cx(ctrl, tgt) circuit.u3(*(t2[0]), 1) circuit.cx(1, 2) # entangling qubit cx(ctrl, tgt) circuit.u3(*(t1[2]), 2) # circuit.cx(0,2) circuit.barrier(range(3)) return circuit schwinger_form = ConcatenatedSchwingerAnsatz(var_form_depth) vqs_circ = schwinger_form.construct_circuit(initial_params) vqs_circ.draw(output='latex', scale=0.5) #qiskit.compiler.transpile(qc, basis_gates=['u3', 'cx'], optimization_level=3).draw(output='latex') # even space # [0.13028114, -1.18048464, 0.17737505] # [ 0.12398951, -1.18068356, 0.15356187] t0_1 = 0.13028114 # theta-angle values t1_1 = -1.18048464 t2_1 = 0.17737505 # odd space # [-0.30306561, -1.02142291, 0.15013751 # [ 2.8238186 , -5.22031494, 0.16478762] t0_2 = 2.8238186 t1_2 = -5.22031494 t2_2 = 0.16478762 def angle(theta=0., phi=0., lam=0.): return [theta, phi, lam] t1 = [angle(t_i) for t_i in [t0_1, t1_1, t2_1]] t2 = [angle(t_i) for t_i in [t0_2, t1_2, t2_2]] # create registers q = QuantumRegister(3, name="q") c = ClassicalRegister(3, name="c") regs = [q, c] circ = QuantumCircuit(*regs, name="super+") # FIRST circ.u3(*(t1[1]), 1) # u3(*angles, q) circ.u3(*(t1[0]), 2) circ.cx(1, 2) # entangling qubit cx(ctrl, tgt) circ.u3(*(t1[0]), 1) circ.cx(1, 2) # entangling qubit cx(ctrl, tgt) circ.u3(*(t1[2]), 2) circ.barrier(range(3)) # SECOND circ.cx(0,2) # circ.u3(*(t2[1]), 1) # u3(*angles, q) circ.u3(*(t2[0]), 2) circ.cx(1, 2) # entangling qubit cx(ctrl, tgt) circ.u3(*(t2[0]), 1) circ.cx(1, 2) # entangling qubit cx(ctrl, tgt) circ.u3(*(t1[2]), 2) # circ.cx(0,2) circ.barrier(range(3)) # MEAS meas = QuantumCircuit(*regs, name="meas") meas.measure(q, c)# map qubits to clbits # Full circuit qc = circ + meas qc.draw(output='latex', scale=0.5, filename='my_circuit.png', plot_barriers=True, fold=40) fiducial_state = Zero(num_qubits) fid_circ = fiducial_state.construct_circuit() fid_circ.draw(output='latex', scale=0.5) var_form_wavefunction = VarFormBased(schwinger_form, initial_params) var_form_wavefunction.construct_circuit().draw(output='latex', scale=0.5) # these correspond to L=2 spatial sites. # They have slightly different truncations so that the dimensions of the matrices are the same. h = np.array([ [-0.20036, 1.19976, 0., 0., 0., 0., 0., 0.], #1 [1.19976, 1., 0.848358, 0., 0., 0., 0., 0.], #2 [0., 0.848358, 2.20036, 0.848358, 0., 0., 0., 0.], #3 [0., 0., 0.848358, 3., 0., 0., 0., 0.], #4 [0., 0., 0., 0., 1., 0.848358, 0., 0.], #5 [0., 0., 0., 0., 0.848358, 2.20036, -0.848358, 0.], #6 [0., 0., 0., 0., 0., -0.848358, 3., -0.848358], #7 [0., 0., 0., 0., 0., 0., -0.848358, 3.79964] #8 ]) # trying different ordering? h = np.array([ [-0.20036, 1.19976, 0., 0., 0., 0., 0., 0.], #1 [0., 0., 0., 0., 1., 0.848358, 0., 0.], #5 [0., 0.848358, 2.20036, 0.848358, 0., 0., 0., 0.], #3 [0., 0., 0., 0., 0., -0.848358, 3., -0.848358], #7 [1.19976, 1., 0.848358, 0., 0., 0., 0., 0.], #2 [0., 0., 0.848358, 3., 0., 0., 0., 0.], #4 [0., 0., 0., 0., 0.848358, 2.20036, -0.848358, 0.], #6 [0., 0., 0., 0., 0., 0., -0.848358, 3.79964] #8 ]) H_mat = csr_matrix(h) H_MatrixOperator = MatrixOperator(H_mat) H_Operator = to_tpb_grouped_weighted_pauli_operator(H_MatrixOperator, TPBGroupedWeightedPauliOperator.sorted_grouping) print(H_Operator.print_details()) operator_mode=None input_circuit=var_form_wavefunction.construct_circuit() backend=None qr=None cr=None use_simulator_operator_mode=False use_simulator_snapshot_mode=False wave_function=fid_circ statevector_mode=False input_circuit.draw(output='latex') H_circs = H_Operator.construct_evaluation_circuit(input_circuit, # wavefunction statevector_mode, qr, cr, use_simulator_snapshot_mode) H_circs[0].draw(output='latex', scale=0.5) max_trials = 500 optimizer = qiskit.aqua.components.optimizers.SPSA(max_trials) print(optimizer.setting) # a callback that can access the intermediate data # during the optimization. # Internally, four arguments are provided as follows # the index of evaluation, parameters of variational form, # evaluated mean, evaluated standard deviation. def simple_callback(eval_count, parameter_set, mean, std): if eval_count % 1 == 0: print('Energy evaluation %s returned %4f +/- %4f' % (eval_count, np.real(mean), np.real(std))) # classVQE(operator, var_form, optimizer, # operator_mode=None, initial_point=None, # max_evals_grouped=1, # aux_operators=None, callback=None, # auto_conversion=True) operator_mode = None initial_point = initial_params max_evals_grouped=1 # max number of evaluations performed simultaneously aux_operators = None auto_conversion=False sim = VQE(H_Operator, schwinger_form, optimizer, # operator_mode, not needed in the most recent version initial_point, max_evals_grouped, aux_operators, simple_callback, auto_conversion) backend = None use_simulator_operator_mode=False # is backend from AerProvider, # if True and mode is paulis, single circuit is generated. use_simulator_snapshot_mode=True statevector_mode=False sim_circs = sim.construct_circuit(initial_params, statevector_mode, use_simulator_snapshot_mode) backend_sim = Aer.get_backend('qasm_simulator') from qiskit.aqua import QuantumInstance nshots = 1024 my_quantum_instance = QuantumInstance(backend_sim, nshots) print(my_quantum_instance) print(sim.print_settings()) res = sim.run(my_quantum_instance) res sim.get_optimal_vector() sim.get_optimal_cost() energy_eval = sim.get_optimal_cost() energy_eval_err = 0.011 sim._ret['opt_params'] sim._energy_evaluation(sim._ret['opt_params']) sim._energy_evaluation(sim._ret['opt_params']) sim._energy_evaluation(sim._ret['opt_params']) sim._energy_evaluation(sim._ret['opt_params']) sim._energy_evaluation(sim._ret['opt_params']) sim.quantum_instance.backend sim.quantum_instance.run_config.shots sim.quantum_instance.set_config(shots=1024, memory=True) sim.quantum_instance.run_config from qiskit.aqua.utils.run_circuits import find_regs_by_name opt_circ = sim.get_optimal_circuit() c = ClassicalRegister(opt_circ.width(), name='c') q = find_regs_by_name(opt_circ, 'q') opt_circ.add_register(c) opt_circ.barrier(q) opt_circ.measure(q, c) opt_circ.draw(output='latex', filename='example_gate.png', scale=1.0) # takes in results from a single circuit # with memory=True, and estimates # the uncertanities on the probability of each outcome # (currently with bootstrap) # returns outcome:(pba, std) dictionary def compute_stats(res, invert_qubit_order = False): # check that there is a single circuit in the results # (ambiguous otherwise) assert(len(res.results)==1) # generates all possible outcomes given \ # the number of qubits def _generate_bitstrings(nqubits, invert_qubit_order): # (recursive, modifies all_strings in place) def _generate_bitstrings_rec(nqubits, all_strings, a_string, irecur): # base if irecur == nqubits: all_strings.append(''.join([bit for bit in a_string])) return # append 0 _generate_bitstrings_rec(nqubits, all_strings, a_string + ['0'], irecur + 1) # append 1 _generate_bitstrings_rec(nqubits, all_strings, a_string + ['1'], irecur + 1) all_strings = [] _generate_bitstrings_rec(nqubits, all_strings, [], 0) if (invert_qubit_order): # pesky Qiskit messes up qubit ordering... this may or may not be necessary to translate the results. all_strings = [''.join(reversed(bitstring)) for bitstring in all_strings] return all_strings # bootstrap specific? # given ensembles of outcomes and a particular outcome # calculates the statistics of that outcome: # returns outcome:(pba, std) estimates for the outcome def _calc_outcome_stats(ensembles, nshots, outcome): cts = np.count_nonzero(ensembles==outcome, axis=0) pba = np.mean(cts)/nshots std = np.std(cts/nshots, ddof = 1) # use unbiased estimator return (pba, std) nqubits = int(np.log2(len(res.get_counts(0)))) # pull number of qubits from results outcomes = _generate_bitstrings(nqubits, invert_qubit_order) mem = res.get_memory(0) nshots = sum(list(res.get_counts(0).values())) nens = nshots # choose number of ensemles = number of samples nsam = nshots ensembles = np.random.choice(mem, (nens, nsam)) stats = map(lambda outcome: (outcome, _calc_outcome_stats(ensembles, nshots, outcome)), outcomes) return dict(stats) sim.quantum_instance.set_config(shots=8*1024, memory=True) opt_res = sim.quantum_instance.execute(opt_circ) sim.quantum_instance.set_config(shots=8*1024, memory=False) # reset to no memory! saves resources? from qiskit.visualization import plot_histogram plot_histogram(opt_res.get_counts(opt_circ)) transp_circ = transpile(opt_circ, sim.quantum_instance.backend, optimization_level=3) transp_circ.draw(output='latex', scale=0.5) opt_circ.decompose().draw(output='latex', scale=0.5) measured_coeffs =compute_stats(opt_res, False) measured_coeffs # compare with Mathematica's expectations mathematica_res = -1.01162 # Even mathematica_res2 = 0.486204 # Odd # odd coefficients even_coeffs = [0.669069, 0.305919, 0.023941, 0.00107068] even_coeffs_at_theta = [0.664109, 0.309821, 0.0236388, 0.00243079] odd_coeffs = [0.7041621406145364, 0.2582831083289985, 0.03524433188695736, 0.002310419169507747] import matplotlib.pyplot as plt outcomes = list(measured_coeffs.keys()) outcomes_bars = np.arange(len(outcomes)) avgs = [measured_coeffs[outcome][0] for outcome in outcomes] stds = [measured_coeffs[outcome][1] for outcome in outcomes] fig, ax = plt.subplots() ax.bar(outcomes_bars, avgs, yerr=stds, align='center', alpha=0.5, ecolor='black', edgecolor='k', error_kw=dict(lw=0.5, capsize=10, capthick=2.0), label='IBM sim') ax.set_ylabel(r'$|c_i|^2$', fontsize=16) ax.set_xlabel(r'outcome', fontsize=16) ax.set_xticks(outcomes_bars) ax.set_xticklabels(outcomes) ax.set_title('ibmqx2: $E \\pm \\Delta E = %.3f \\pm %.3f$\n($E = %.3f$ exact),\n nshots=%d' % (energy_eval, energy_eval_err, mathematica_res, sim.quantum_instance.run_config.shots), fontsize=16) for icoeff in range(len(even_coeffs)): ax.axhline(y = even_coeffs[icoeff], color ='red', linewidth = 0.5, label=r'exact $|c_{%d}|^2 = %.3f$' % (icoeff+1, even_coeffs[icoeff])) ax.axhline(y = even_coeffs_at_theta[icoeff], color ='green', linewidth = 0.5, label=r'exact $|c(\theta)_{%d}|^2 = %.3f$''\n'r'vs measured $%.3f \pm %.3f$' % (icoeff+1, even_coeffs_at_theta[icoeff], *list(measured_coeffs.values())[icoeff])) ax.set_yscale('log') # plt.tight_layout() plt.legend(frameon=False, fontsize=16, bbox_to_anchor=(1.04,1), loc="upper left") plt.savefig("ibmqx2_log.png", dpi=300)
https://github.com/avkhadiev/schwinger-vqe
avkhadiev
#Assign these values as per your requirements. global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion min_qubits=4 max_qubits=15 #reference files are upto 12 Qubits only skip_qubits=2 max_circuits=3 num_shots=4092 gate_counts_plots = True Noise_Inclusion = False saveplots = False Memory_utilization_plot = True Type_of_Simulator = "built_in" #Inputs are "built_in" or "FAKE" or "FAKEV2" backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends #Change your Specification of Simulator in Declaring Backend Section #By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2() import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute from qiskit.opflow import PauliTrotterEvolution, Suzuki from qiskit.opflow.primitive_ops import PauliSumOp import time,os,json import matplotlib.pyplot as plt # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error) # Benchmark Name benchmark_name = "VQE Simulation" # Selection of basis gate set for transpilation # Note: selector 1 is a hardware agnostic gate set basis_selector = 1 basis_gates_array = [ [], ['rx', 'ry', 'rz', 'cx'], # a common basis set, default ['cx', 'rz', 'sx', 'x'], # IBM default basis set ['rx', 'ry', 'rxx'], # IonQ default basis set ['h', 'p', 'cx'], # another common basis set ['u', 'cx'] # general unitaries basis gates ] np.random.seed(0) def get_QV(backend): import json # Assuming backend.conf_filename is the filename and backend.dirname is the directory path conf_filename = backend.dirname + "/" + backend.conf_filename # Open the JSON file with open(conf_filename, 'r') as file: # Load the JSON data data = json.load(file) # Extract the quantum_volume parameter QV = data.get('quantum_volume', None) return QV def checkbackend(backend_name,Type_of_Simulator): if Type_of_Simulator == "built_in": available_backends = [] for i in Aer.backends(): available_backends.append(i.name) if backend_name in available_backends: platform = backend_name return platform else: print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!") print(f"available backends are : {available_backends}") platform = "qasm_simulator" return platform elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2": import qiskit.providers.fake_provider as fake_backends if hasattr(fake_backends,backend_name) is True: print(f"Backend {backend_name} is available for type {Type_of_Simulator}.") backend_class = getattr(fake_backends,backend_name) backend_instance = backend_class() return backend_instance else: print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!") if Type_of_Simulator == "FAKEV2": backend_class = getattr(fake_backends,"FakeSantiagoV2") else: backend_class = getattr(fake_backends,"FakeSantiago") backend_instance = backend_class() return backend_instance if Type_of_Simulator == "built_in": platform = checkbackend(backend_name,Type_of_Simulator) #By default using "Qasm Simulator" backend = Aer.get_backend(platform) QV_=None print(f"{platform} device is capable of running {backend.num_qubits}") print(f"backend version is {backend.backend_version}") elif Type_of_Simulator == "FAKE": basis_selector = 0 backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting. max_qubits=backend.configuration().n_qubits print(f"{platform} device is capable of running {backend.configuration().n_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") elif Type_of_Simulator == "FAKEV2": basis_selector = 0 if "V2" not in backend_name: backend_name = backend_name+"V2" backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.name +"-" +backend.backend_version max_qubits=backend.num_qubits print(f"{platform} device is capable of running {backend.num_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") else: print("Enter valid Simulator.....") # saved circuits for display QC_ = None Hf_ = None CO_ = None ################### Circuit Definition ####################################### # Construct a Qiskit circuit for VQE Energy evaluation with UCCSD ansatz # param: n_spin_orbs - The number of spin orbitals. # return: return a Qiskit circuit for this VQE ansatz def VQEEnergy(n_spin_orbs, na, nb, circuit_id=0, method=1): # number of alpha spin orbitals norb_a = int(n_spin_orbs / 2) # construct the Hamiltonian qubit_op = ReadHamiltonian(n_spin_orbs) # allocate qubits num_qubits = n_spin_orbs qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr, name=f"vqe-ansatz({method})-{num_qubits}-{circuit_id}") # initialize the HF state Hf = HartreeFock(num_qubits, na, nb) qc.append(Hf, qr) # form the list of single and double excitations excitationList = [] for occ_a in range(na): for vir_a in range(na, norb_a): excitationList.append((occ_a, vir_a)) for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): excitationList.append((occ_b, vir_b)) for occ_a in range(na): for vir_a in range(na, norb_a): for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): excitationList.append((occ_a, vir_a, occ_b, vir_b)) # get cluster operators in Paulis pauli_list = readPauliExcitation(n_spin_orbs, circuit_id) # loop over the Pauli operators for index, PauliOp in enumerate(pauli_list): # get circuit for exp(-iP) cluster_qc = ClusterOperatorCircuit(PauliOp, excitationList[index]) # add to ansatz qc.append(cluster_qc, [i for i in range(cluster_qc.num_qubits)]) # method 1, only compute the last term in the Hamiltonian if method == 1: # last term in Hamiltonian qc_with_mea, is_diag = ExpectationCircuit(qc, qubit_op[1], num_qubits) # return the circuit return qc_with_mea # now we need to add the measurement parts to the circuit # circuit list qc_list = [] diag = [] off_diag = [] global normalization normalization = 0.0 # add the first non-identity term identity_qc = qc.copy() identity_qc.measure_all() qc_list.append(identity_qc) # add to circuit list diag.append(qubit_op[1]) normalization += abs(qubit_op[1].coeffs[0]) # add to normalization factor diag_coeff = abs(qubit_op[1].coeffs[0]) # add to coefficients of diagonal terms # loop over rest of terms for index, p in enumerate(qubit_op[2:]): # get the circuit with expectation measurements qc_with_mea, is_diag = ExpectationCircuit(qc, p, num_qubits) # accumulate normalization normalization += abs(p.coeffs[0]) # add to circuit list if non-diagonal if not is_diag: qc_list.append(qc_with_mea) else: diag_coeff += abs(p.coeffs[0]) # diagonal term if is_diag: diag.append(p) # off-diagonal term else: off_diag.append(p) # modify the name of diagonal circuit qc_list[0].name = qubit_op[1].primitive.to_list()[0][0] + " " + str(np.real(diag_coeff)) normalization /= len(qc_list) return qc_list # Function that constructs the circuit for a given cluster operator def ClusterOperatorCircuit(pauli_op, excitationIndex): # compute exp(-iP) exp_ip = pauli_op.exp_i() # Trotter approximation qc_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=1, reps=1)).convert(exp_ip) # convert to circuit qc = qc_op.to_circuit(); qc.name = f'Cluster Op {excitationIndex}' global CO_ if CO_ == None or qc.num_qubits <= 4: if qc.num_qubits < 7: CO_ = qc # return this circuit return qc # Function that adds expectation measurements to the raw circuits def ExpectationCircuit(qc, pauli, nqubit, method=2): # copy the unrotated circuit raw_qc = qc.copy() # whether this term is diagonal is_diag = True # primitive Pauli string PauliString = pauli.primitive.to_list()[0][0] # coefficient coeff = pauli.coeffs[0] # basis rotation for i, p in enumerate(PauliString): target_qubit = nqubit - i - 1 if (p == "X"): is_diag = False raw_qc.h(target_qubit) elif (p == "Y"): raw_qc.sdg(target_qubit) raw_qc.h(target_qubit) is_diag = False # perform measurements raw_qc.measure_all() # name of this circuit raw_qc.name = PauliString + " " + str(np.real(coeff)) # save circuit global QC_ if QC_ == None or nqubit <= 4: if nqubit < 7: QC_ = raw_qc return raw_qc, is_diag # Function that implements the Hartree-Fock state def HartreeFock(norb, na, nb): # initialize the quantum circuit qc = QuantumCircuit(norb, name="Hf") # alpha electrons for ia in range(na): qc.x(ia) # beta electrons for ib in range(nb): qc.x(ib+int(norb/2)) # Save smaller circuit global Hf_ if Hf_ == None or norb <= 4: if norb < 7: Hf_ = qc # return the circuit return qc ################ Helper Functions # Function that converts a list of single and double excitation operators to Pauli operators def readPauliExcitation(norb, circuit_id=0): # load pre-computed data filename = os.path.join(f'ansatzes/{norb}_qubit_{circuit_id}.txt') with open(filename) as f: data = f.read() ansatz_dict = json.loads(data) # initialize Pauli list pauli_list = [] # current coefficients cur_coeff = 1e5 # current Pauli list cur_list = [] # loop over excitations for ext in ansatz_dict: if cur_coeff > 1e4: cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] elif abs(abs(ansatz_dict[ext]) - abs(cur_coeff)) > 1e-4: pauli_list.append(PauliSumOp.from_list(cur_list)) cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] else: cur_list.append((ext, ansatz_dict[ext])) # add the last term pauli_list.append(PauliSumOp.from_list(cur_list)) # return Pauli list return pauli_list # Get the Hamiltonian by reading in pre-computed file def ReadHamiltonian(nqubit): # load pre-computed data filename = os.path.join(f'Hamiltonians/{nqubit}_qubit.txt') with open(filename) as f: data = f.read() ham_dict = json.loads(data) # pauli list pauli_list = [] for p in ham_dict: pauli_list.append( (p, ham_dict[p]) ) # build Hamiltonian ham = PauliSumOp.from_list(pauli_list) # return Hamiltonian return ham # Create an empty noise model noise_parameters = NoiseModel() if Type_of_Simulator == "built_in": # Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5% depol_one_qb_error = 0.05 depol_two_qb_error = 0.005 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx']) # Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0% amp_damp_one_qb_error = 0.0 amp_damp_two_qb_error = 0.0 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx']) # Add reset noise to all single qubit resets reset_to_zero_error = 0.005 reset_to_one_error = 0.005 noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"]) # Add readout error p0given1_error = 0.000 p1given0_error = 0.000 error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]]) noise_parameters.add_all_qubit_readout_error(error_meas) #print(noise_parameters) elif Type_of_Simulator == "FAKE"or"FAKEV2": noise_parameters = NoiseModel.from_backend(backend) #print(noise_parameters) ### Analysis methods to be expanded and eventually compiled into a separate analysis.py file import math, functools def hellinger_fidelity_with_expected(p, q): """ p: result distribution, may be passed as a counts distribution q: the expected distribution to be compared against References: `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ Qiskit Hellinger Fidelity Function """ p_sum = sum(p.values()) q_sum = sum(q.values()) if q_sum == 0: print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0") return 0 p_normed = {} for key, val in p.items(): p_normed[key] = val/p_sum # if p_sum != 0: # p_normed[key] = val/p_sum # else: # p_normed[key] = 0 q_normed = {} for key, val in q.items(): q_normed[key] = val/q_sum total = 0 for key, val in p_normed.items(): if key in q_normed.keys(): total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2 del q_normed[key] else: total += val total += sum(q_normed.values()) # in some situations (error mitigation) this can go negative, use abs value if total < 0: print(f"WARNING: using absolute value in fidelity calculation") total = abs(total) dist = np.sqrt(total)/np.sqrt(2) fidelity = (1-dist**2)**2 return fidelity def polarization_fidelity(counts, correct_dist, thermal_dist=None): """ Combines Hellinger fidelity and polarization rescaling into fidelity calculation used in every benchmark counts: the measurement outcomes after `num_shots` algorithm runs correct_dist: the distribution we expect to get for the algorithm running perfectly thermal_dist: optional distribution to pass in distribution from a uniform superposition over all states. If `None`: generated as `uniform_dist` with the same qubits as in `counts` returns both polarization fidelity and the hellinger fidelity Polarization from: `https://arxiv.org/abs/2008.11294v1` """ num_measured_qubits = len(list(correct_dist.keys())[0]) #print(num_measured_qubits) counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()} # calculate hellinger fidelity between measured expectation values and correct distribution hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist) # to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits if num_measured_qubits > 16: return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity } # if not provided, generate thermal dist based on number of qubits if thermal_dist == None: thermal_dist = uniform_dist(num_measured_qubits) # set our fidelity rescaling value as the hellinger fidelity for a depolarized state floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist) # rescale fidelity result so uniform superposition (random guessing) returns fidelity # rescaled to 0 to provide a better measure of success of the algorithm (polarization) new_floor_fidelity = 0 fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity) return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity } ## Uniform distribution function commonly used def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity): """ Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks fidelity: raw fidelity to rescale floor_fidelity: threshold fidelity which is equivalent to random guessing new_floor_fidelity: what we rescale the floor_fidelity to Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0: 1 -> 1; 0.25 -> 0; 0.5 -> 0.3333; """ rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1 # ensure fidelity is within bounds (0, 1) if rescaled_fidelity < 0: rescaled_fidelity = 0.0 if rescaled_fidelity > 1: rescaled_fidelity = 1.0 return rescaled_fidelity def uniform_dist(num_state_qubits): dist = {} for i in range(2**num_state_qubits): key = bin(i)[2:].zfill(num_state_qubits) dist[key] = 1/(2**num_state_qubits) return dist from matplotlib.patches import Rectangle import matplotlib.cm as cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize from matplotlib.patches import Circle ############### Color Map functions # Create a selection of colormaps from which to choose; default to custom_spectral cmap_spectral = plt.get_cmap('Spectral') cmap_greys = plt.get_cmap('Greys') cmap_blues = plt.get_cmap('Blues') cmap_custom_spectral = None # the default colormap is the spectral map cmap = cmap_spectral cmap_orig = cmap_spectral # current cmap normalization function (default None) cmap_norm = None default_fade_low_fidelity_level = 0.16 default_fade_rate = 0.7 # Specify a normalization function here (default None) def set_custom_cmap_norm(vmin, vmax): global cmap_norm if vmin == vmax or (vmin == 0.0 and vmax == 1.0): print("... setting cmap norm to None") cmap_norm = None else: print(f"... setting cmap norm to [{vmin}, {vmax}]") cmap_norm = Normalize(vmin=vmin, vmax=vmax) # Remake the custom spectral colormap with user settings def set_custom_cmap_style( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): #print("... set custom map style") global cmap, cmap_custom_spectral, cmap_orig cmap_custom_spectral = create_custom_spectral_cmap( fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate) cmap = cmap_custom_spectral cmap_orig = cmap_custom_spectral # Create the custom spectral colormap from the base spectral def create_custom_spectral_cmap( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): # determine the breakpoint from the fade level num_colors = 100 breakpoint = round(fade_low_fidelity_level * num_colors) # get color list for spectral map spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)] #print(fade_rate) # create a list of colors to replace those below the breakpoint # and fill with "faded" color entries (in reverse) low_colors = [0] * breakpoint #for i in reversed(range(breakpoint)): for i in range(breakpoint): # x is index of low colors, normalized 0 -> 1 x = i / breakpoint # get color at this index bc = spectral_colors[i] r0 = bc[0] g0 = bc[1] b0 = bc[2] z0 = bc[3] r_delta = 0.92 - r0 #print(f"{x} {bc} {r_delta}") # compute saturation and greyness ratio sat_ratio = 1 - x #grey_ratio = 1 - x ''' attempt at a reflective gradient if i >= breakpoint/2: xf = 2*(x - 0.5) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (yf + 0.5) else: xf = 2*(0.5 - x) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (0.5 - yf) ''' grey_ratio = 1 - math.pow(x, 1/fade_rate) #print(f" {xf} {yf} ") #print(f" {sat_ratio} {grey_ratio}") r = r0 + r_delta * sat_ratio g_delta = r - g0 b_delta = r - b0 g = g0 + g_delta * grey_ratio b = b0 + b_delta * grey_ratio #print(f"{r} {g} {b}\n") low_colors[i] = (r,g,b,z0) #print(low_colors) # combine the faded low colors with the regular spectral cmap to make a custom version cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:]) #spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)] #for i in range(10): print(spectral_colors[i]) #print("") return cmap_custom_spectral # Make the custom spectral color map the default on module init set_custom_cmap_style() # Arrange the stored annotations optimally and add to plot def anno_volumetric_data(ax, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True): # sort all arrays by the x point of the text (anno_offs) global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos)) x_anno_offs = [a for a,b,c,d,e in all_annos] y_anno_offs = [b for a,b,c,d,e in all_annos] anno_labels = [c for a,b,c,d,e in all_annos] x_annos = [d for a,b,c,d,e in all_annos] y_annos = [e for a,b,c,d,e in all_annos] #print(f"{x_anno_offs}") #print(f"{y_anno_offs}") #print(f"{anno_labels}") for i in range(len(anno_labels)): x_anno = x_annos[i] y_anno = y_annos[i] x_anno_off = x_anno_offs[i] y_anno_off = y_anno_offs[i] label = anno_labels[i] if i > 0: x_delta = abs(x_anno_off - x_anno_offs[i - 1]) y_delta = abs(y_anno_off - y_anno_offs[i - 1]) if y_delta < 0.7 and x_delta < 2: y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6 #x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1 ax.annotate(label, xy=(x_anno+0.0, y_anno+0.1), arrowprops=dict(facecolor='black', shrink=0.0, width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)), xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='baseline', color=(0.2,0.2,0.2), clip_on=True) if saveplots == True: plt.savefig("VolumetricPlotSample.jpg") # Plot one group of data for volumetric presentation def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True, x_size=1.0, y_size=1.0, zorder=1, offset_flag=False, max_depth=0, suppress_low_fidelity=False): # since data may come back out of order, save point at max y for annotation i_anno = 0 x_anno = 0 y_anno = 0 # plot data rectangles low_fidelity_count = True last_y = -1 k = 0 # determine y-axis dimension for one pixel to use for offset of bars that start at 0 (_, dy) = get_pixel_dims(ax) # do this loop in reverse to handle the case where earlier cells are overlapped by later cells for i in reversed(range(len(d_data))): x = depth_index(d_data[i], depth_base) y = float(w_data[i]) f = f_data[i] # each time we star a new row, reset the offset counter # DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars # that represent time starting from 0 secs. We offset by one pixel each and center the group if y != last_y: last_y = y; k = 3 # hardcoded for 8 cells, offset by 3 #print(f"{i = } {x = } {y = }") if max_depth > 0 and d_data[i] > max_depth: #print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}") break; # reject cells with low fidelity if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True # the only time this is False is when doing merged gradation plots if do_border == True: # this case is for an array of x_sizes, i.e. each box has different width if isinstance(x_size, list): # draw each of the cells, with no offset if not offset_flag: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder)) # use an offset for y value, AND account for x and width to draw starting at 0 else: ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder)) # this case is for only a single cell else: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size)) # save the annotation point with the largest y value if y >= y_anno: x_anno = x y_anno = y i_anno = i # move the next bar down (if using offset) k -= 1 # if no data rectangles plotted, no need for a label if x_anno == 0 or y_anno == 0: return x_annos.append(x_anno) y_annos.append(y_anno) anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 ) # adjust radius of annotation circle based on maximum width of apps anno_max = 10 if w_max > 10: anno_max = 14 if w_max > 14: anno_max = 18 scale = anno_max / anno_dist # offset of text from end of arrow if scale > 1: x_anno_off = scale * x_anno - x_anno - 0.5 y_anno_off = scale * y_anno - y_anno else: x_anno_off = 0.7 y_anno_off = 0.5 x_anno_off += x_anno y_anno_off += y_anno # print(f"... {xx} {yy} {anno_dist}") x_anno_offs.append(x_anno_off) y_anno_offs.append(y_anno_off) anno_labels.append(label) if do_label: ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2)) x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # init arrays to hold annotation points for label spreading def vplot_anno_init (): global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # Number of ticks on volumetric depth axis max_depth_log = 22 # average transpile factor between base QV depth and our depth based on results from QV notebook QV_transpile_factor = 12.7 # format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1 # (sign handling may be incorrect) def format_number(num, digits=0): if isinstance(num, str): num = float(num) num = float('{:.3g}'.format(abs(num))) sign = '' metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1} for index in metric: num_check = num / metric[index] if num_check >= 1: num = round(num_check, digits) sign = index break numstr = f"{str(num)}" if '.' in numstr: numstr = numstr.rstrip('0').rstrip('.') return f"{numstr}{sign}" # Return the color associated with the spcific value, using color map norm def get_color(value): # if there is a normalize function installed, scale the data if cmap_norm: value = float(cmap_norm(value)) if cmap == cmap_spectral: value = 0.05 + value*0.9 elif cmap == cmap_blues: value = 0.00 + value*1.0 else: value = 0.0 + value*0.95 return cmap(value) # Return the x and y equivalent to a single pixel for the given plot axis def get_pixel_dims(ax): # transform 0 -> 1 to pixel dimensions pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0)) xpix = pixdims[1][0] ypix = pixdims[0][1] #determine x- and y-axis dimension for one pixel dx = (1 / xpix) dy = (1 / ypix) return (dx, dy) ############### Helper functions # return the base index for a circuit depth value # take the log in the depth base, and add 1 def depth_index(d, depth_base): if depth_base <= 1: return d if d == 0: return 0 return math.log(d, depth_base) + 1 # draw a box at x,y with various attributes def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1): value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.5*y_size, zorder=zorder) # draw a circle at x,y with various attributes def circle_at(x, y, value, type=1, fill=True): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Circle((x, y), size/2, alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell edgecolor = ec, facecolor = fc, fill=fill, lw=0.5) def box4_at(x, y, value, type=1, fill=True, alpha=1.0): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.3,0.3,0.3) ec = fc return Rectangle((x - size/8, y - size/2), size/4, size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.1) # Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value def qv_box_at(x, y, qv_width, qv_depth, value, depth_base): #print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}") return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width, edgecolor = (value,value,value), facecolor = (value,value,value), fill=True, lw=1) def bkg_box_at(x, y, value=0.9): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (value,value,value), fill=True, lw=0.5) def bkg_empty_box_at(x, y): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (1.0,1.0,1.0), fill=True, lw=0.5) # Plot the background for the volumetric analysis def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"): if suptitle == None: suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}" QV0 = QV qv_estimate = False est_str = "" if QV == 0: # QV = 0 indicates "do not draw QV background or label" QV = 2048 elif QV < 0: # QV < 0 indicates "add est. to label" QV = -QV qv_estimate = True est_str = " (est.)" if avail_qubits > 0 and max_qubits > avail_qubits: max_qubits = avail_qubits max_width = 13 if max_qubits > 11: max_width = 18 if max_qubits > 14: max_width = 20 if max_qubits > 16: max_width = 24 if max_qubits > 24: max_width = 33 #print(f"... {avail_qubits} {max_qubits} {max_width}") plot_width = 6.8 plot_height = 0.5 + plot_width * (max_width / max_depth_log) #print(f"... {plot_width} {plot_height}") # define matplotlib figure and axis; use constrained layout to fit colorbar to right fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True) plt.suptitle(suptitle) plt.xlim(0, max_depth_log) plt.ylim(0, max_width) # circuit depth axis (x axis) xbasis = [x for x in range(1,max_depth_log)] xround = [depth_base**(x-1) for x in xbasis] xlabels = [format_number(x) for x in xround] ax.set_xlabel('Circuit Depth') ax.set_xticks(xbasis) plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor") # other label options #plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left') #plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor") # circuit width axis (y axis) ybasis = [y for y in range(1,max_width)] yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now ylabels = [str(y) for y in yround] # not used now #ax.set_ylabel('Circuit Width (Number of Qubits)') ax.set_ylabel('Circuit Width') ax.set_yticks(ybasis) #create simple line plot (not used right now) #ax.plot([0, 10],[0, 10]) log2QV = math.log2(QV) QV_width = log2QV QV_depth = log2QV * QV_transpile_factor # show a quantum volume rectangle of QV = 64 e.g. (6 x 6) if QV0 != 0: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base)) else: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base)) # the untranspiled version is commented out - we do not show this by default # also show a quantum volume rectangle un-transpiled # ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base)) # show 2D array of volumetric cells based on this QV_transpiled # DEVNOTE: we use +1 only to make the visuals work; s/b without # Also, the second arg of the min( below seems incorrect, needs correction maxprod = (QV_width + 1) * (QV_depth + 1) for w in range(1, min(max_width, round(QV) + 1)): # don't show VB squares if width greater than known available qubits if avail_qubits != 0 and w > avail_qubits: continue i_success = 0 for d in xround: # polarization factor for low circuit widths maxtest = maxprod / ( 1 - 1 / (2**w) ) # if circuit would fail here, don't draw box if d > maxtest: continue if w * d > maxtest: continue # guess for how to capture how hardware decays with width, not entirely correct # # reduce maxtext by a factor of number of qubits > QV_width # # just an approximation to account for qubit distances # if w > QV_width: # over = w - QV_width # maxtest = maxtest / (1 + (over/QV_width)) # draw a box at this width and depth id = depth_index(d, depth_base) # show vb rectangles; if not showing QV, make all hollow (or less dark) if QV0 == 0: #ax.add_patch(bkg_empty_box_at(id, w)) ax.add_patch(bkg_box_at(id, w, 0.95)) else: ax.add_patch(bkg_box_at(id, w, 0.9)) # save index of last successful depth i_success += 1 # plot empty rectangle after others d = xround[i_success] id = depth_index(d, depth_base) ax.add_patch(bkg_empty_box_at(id, w)) # Add annotation showing quantum volume if QV0 != 0: t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12, horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2), bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1)) # add colorbar to right of plot plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax, shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7)) return ax # Function to calculate circuit depth def calculate_circuit_depth(qc): # Calculate the depth of the circuit depth = qc.depth() return depth def calculate_transpiled_depth(qc,basis_selector): # use either the backend or one of the basis gate sets if basis_selector == 0: qc = transpile(qc, backend) else: basis_gates = basis_gates_array[basis_selector] qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0) transpiled_depth = qc.depth() return transpiled_depth,qc def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title): avg_fidelity_means = [] avg_Hf_fidelity_means = [] avg_num_qubits_values = list(fidelity_data.keys()) # Calculate the average fidelity and Hamming fidelity for each unique number of qubits for num_qubits in avg_num_qubits_values: avg_fidelity = np.average(fidelity_data[num_qubits]) avg_fidelity_means.append(avg_fidelity) avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits]) avg_Hf_fidelity_means.append(avg_Hf_fidelity) return avg_fidelity_means,avg_Hf_fidelity_means list_of_gates = [] def list_of_standardgates(): import qiskit.circuit.library as lib from qiskit.circuit import Gate import inspect # List all the attributes of the library module gate_list = dir(lib) # Filter out non-gate classes (like functions, variables, etc.) gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)] # Get method names from QuantumCircuit circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction) method_names = [name for name, _ in circuit_methods] # Map gate class names to method names gate_to_method = {} for gate in gates: gate_class = getattr(lib, gate) class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name for method in method_names: if method == class_name or method == class_name.replace('cr', 'c-r'): gate_to_method[gate] = method break # Add common operations that are not strictly gates additional_operations = { 'Measure': 'measure', 'Barrier': 'barrier', } gate_to_method.update(additional_operations) for k,v in gate_to_method.items(): list_of_gates.append(v) def update_counts(gates,custom_gates): operations = {} for key, value in gates.items(): operations[key] = value for key, value in custom_gates.items(): if key in operations: operations[key] += value else: operations[key] = value return operations def get_gate_counts(gates,custom_gate_defs): result = gates.copy() # Iterate over the gate counts in the quantum circuit for gate, count in gates.items(): if gate in custom_gate_defs: custom_gate_ops = custom_gate_defs[gate] # Multiply custom gate operations by the count of the custom gate in the circuit for _ in range(count): result = update_counts(result, custom_gate_ops) # Remove the custom gate entry as we have expanded it del result[gate] return result dict_of_qc = dict() custom_gates_defs = dict() # Function to count operations recursively def count_operations(qc): dict_of_qc.clear() circuit_traverser(qc) operations = dict() operations = dict_of_qc[qc.name] del dict_of_qc[qc.name] # print("operations :",operations) # print("dict_of_qc :",dict_of_qc) for keys in operations.keys(): if keys not in list_of_gates: for k,v in dict_of_qc.items(): if k in operations.keys(): custom_gates_defs[k] = v operations=get_gate_counts(operations,custom_gates_defs) custom_gates_defs.clear() return operations def circuit_traverser(qc): dict_of_qc[qc.name]=dict(qc.count_ops()) for i in qc.data: if str(i.operation.name) not in list_of_gates: qc_1 = i.operation.definition circuit_traverser(qc_1) def get_memory(): import resource usage = resource.getrusage(resource.RUSAGE_SELF) max_mem = usage.ru_maxrss/1024 #in MB return max_mem def analyzer(qc,references,num_qubits): # total circuit name (pauli string + coefficient) total_name = qc.name # pauli string pauli_string = total_name.split()[0] # get the correct measurement if (len(total_name.split()) == 2): correct_dist = references[pauli_string] else: circuit_id = int(total_name.split()[2]) correct_dist = references[f"Qubits - {num_qubits} - {circuit_id}"] return correct_dist,total_name # Max qubits must be 12 since the referenced files only go to 12 qubits MAX_QUBITS = 12 method = 1 def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=2, max_circuits=max_circuits, num_shots=num_shots): creation_times = [] elapsed_times = [] quantum_times = [] circuit_depths = [] transpiled_depths = [] fidelity_data = {} Hf_fidelity_data = {} numckts = [] mem_usage = [] algorithmic_1Q_gate_counts = [] algorithmic_2Q_gate_counts = [] transpiled_1Q_gate_counts = [] transpiled_2Q_gate_counts = [] print(f"{benchmark_name} Benchmark Program - {platform}") #defining all the standard gates supported by qiskit in a list if gate_counts_plots == True: list_of_standardgates() max_qubits = max(max_qubits, min_qubits) # max must be >= min # validate parameters (smallest circuit is 4 qubits and largest is 10 qubits) max_qubits = min(max_qubits, MAX_QUBITS) min_qubits = min(max(4, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even skip_qubits = max(1, skip_qubits) if method == 2: max_circuits = 1 if max_qubits < 4: print(f"Max number of qubits {max_qubits} is too low to run method {method} of VQE algorithm") return global max_ckts max_ckts = max_circuits global min_qbits,max_qbits,skp_qubits min_qbits = min_qubits max_qbits = max_qubits skp_qubits = skip_qubits print(f"min, max qubits = {min_qubits} {max_qubits}") # Execute Benchmark Program N times for multiple circuit sizes for input_size in range(min_qubits, max_qubits + 1, skip_qubits): # reset random seed np.random.seed(0) # determine the number of circuits to execute for this group num_circuits = min(3, max_circuits) num_qubits = input_size fidelity_data[num_qubits] = [] Hf_fidelity_data[num_qubits] = [] # decides number of electrons na = int(num_qubits/4) nb = int(num_qubits/4) # random seed np.random.seed(0) numckts.append(num_circuits) # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() # circuit list qc_list = [] # Method 1 (default) if method == 1: # loop over circuits for circuit_id in range(num_circuits): # construct circuit qc_single = VQEEnergy(num_qubits, na, nb, circuit_id, method) qc_single.name = qc_single.name + " " + str(circuit_id) # add to list qc_list.append(qc_single) # method 2 elif method == 2: # construct all circuits qc_list = VQEEnergy(num_qubits, na, nb, 0, method) print(qc_list) print(f"************\nExecuting [{len(qc_list)}] circuits with num_qubits = {num_qubits}") for qc in qc_list: print("*********************************************") #print(f"qc of {qc} qubits for qc_list value: {qc_list}") # get circuit id if method == 1: circuit_id = qc.name.split()[2] else: circuit_id = qc.name.split()[0] #creation time creation_time = time.time() - ts creation_times.append(creation_time) #print(qc) print(f"creation time = {creation_time*1000} ms") # Calculate gate count for the algorithmic circuit (excluding barriers and measurements) if gate_counts_plots == True: operations = count_operations(qc) n1q = 0; n2q = 0 if operations != None: for key, value in operations.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c") or key.startswith("mc"): n2q += value else: n1q += value print("operations: ",operations) algorithmic_1Q_gate_counts.append(n1q) algorithmic_2Q_gate_counts.append(n2q) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc=qc.decompose() #print(qc) # Calculate circuit depth depth = calculate_circuit_depth(qc) circuit_depths.append(depth) # Calculate transpiled circuit depth transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector) transpiled_depths.append(transpiled_depth) #print(qc) print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}") if gate_counts_plots == True: # Calculate gate count for the transpiled circuit (excluding barriers and measurements) tr_ops = qc.count_ops() #print("tr_ops = ",tr_ops) tr_n1q = 0; tr_n2q = 0 if tr_ops != None: for key, value in tr_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c"): tr_n2q += value else: tr_n1q += value transpiled_1Q_gate_counts.append(tr_n1q) transpiled_2Q_gate_counts.append(tr_n2q) print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}") print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}") #execution if Type_of_Simulator == "built_in": #To check if Noise is required if Noise_Inclusion == True: noise_model = noise_parameters else: noise_model = None ts = time.time() job = execute(qc, backend, shots=num_shots, noise_model=noise_model) elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" : ts = time.time() job = backend.run(qc,shots=num_shots, noise_model=noise_parameters) #retrieving the result result = job.result() #print(result) #calculating elapsed time elapsed_time = time.time() - ts elapsed_times.append(elapsed_time) # Calculate quantum processing time quantum_time = result.time_taken quantum_times.append(quantum_time) print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms") #counts in result object counts = result.get_counts() # load pre-computed data if len(qc.name.split()) == 2: filename = os.path.join(f'_common/precalculated_data_{num_qubits}_qubit.json') with open(filename) as f: references = json.load(f) else: filename = os.path.join(f'_common/precalculated_data_{num_qubits}_qubit_method2.json') with open(filename) as f: references = json.load(f) #Correct distribution to compare with counts correct_dist,total_name = analyzer(qc,references,num_qubits) #fidelity calculation comparision of counts and correct_dist fidelity_dict = polarization_fidelity(counts, correct_dist) print(fidelity_dict) # modify fidelity based on the coefficient if (len(total_name.split()) == 2): fidelity_dict *= ( abs(float(total_name.split()[1])) / normalization ) fidelity_data[num_qubits].append(fidelity_dict['fidelity']) Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity']) #maximum memory utilization (if required) if Memory_utilization_plot == True: max_mem = get_memory() print(f"Maximum Memory Utilized: {max_mem} MB") mem_usage.append(max_mem) print("*********************************************") ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nHartree Fock Generator 'Hf' ="); print(Hf_ if Hf_ != None else " ... too large!") print("\nCluster Operator Example 'Cluster Op' ="); print(CO_ if CO_ != None else " ... too large!") return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths, fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) # Execute the benchmark program, accumulate metrics, and calculate circuit depths (creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts, algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run() # Define the range of qubits for the x-axis num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits) print("num_qubits_range =",num_qubits_range) # Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits avg_creation_times = [] avg_elapsed_times = [] avg_quantum_times = [] avg_circuit_depths = [] avg_transpiled_depths = [] avg_1Q_algorithmic_gate_counts = [] avg_2Q_algorithmic_gate_counts = [] avg_1Q_Transpiled_gate_counts = [] avg_2Q_Transpiled_gate_counts = [] max_memory = [] start = 0 for num in numckts: avg_creation_times.append(np.mean(creation_times[start:start+num])) avg_elapsed_times.append(np.mean(elapsed_times[start:start+num])) avg_quantum_times.append(np.mean(quantum_times[start:start+num])) avg_circuit_depths.append(np.mean(circuit_depths[start:start+num])) avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num])) if gate_counts_plots == True: avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num]))) avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num]))) avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num]))) avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num]))) if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num])) start += num # Calculate the fidelity data avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison") # Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits # Add labels to the bars def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"): for rect in rects: height = rect.get_height() ax.annotate(str.format(height), # Formatting to two decimal places xy=(rect.get_x() + rect.get_width() / 2, height / 2), xytext=(0, 0), textcoords="offset points", ha='center', va=va,color=text_color,rotation=90) bar_width = 0.3 # Determine the number of subplots and their arrangement if Memory_utilization_plot and gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30)) # Plotting for both memory utilization and gate counts # ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available elif Memory_utilization_plot: fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30)) # Plotting for memory utilization only # ax1, ax2, ax3, ax6, ax7 are available elif gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30)) # Plotting for gate counts only # ax1, ax2, ax3, ax4, ax5, ax6 are available else: fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30)) # Default plotting # ax1, ax2, ax3, ax6 are available fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16) for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000 avg_creation_times[i] *= 1000 ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue') autolabel(ax1.patches, ax1) ax1.set_xlabel('Number of Qubits') ax1.set_ylabel('Average Creation Time (ms)') ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14) ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000 avg_elapsed_times[i] *= 1000 for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000 avg_quantum_times[i] *= 1000 Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time') Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time') autolabel(Elapsed,ax2,str='{:.1f}') autolabel(Quantum,ax2,str='{:.1f}') ax2.set_xlabel('Number of Qubits') ax2.set_ylabel('Average Time (ms)') ax2.set_title('Average Time vs Number of Qubits') ax2.legend() ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here autolabel(Normalized,ax3,str='{:.2f}') autolabel(Algorithmic,ax3,str='{:.2f}') ax3.set_xlabel('Number of Qubits') ax3.set_ylabel('Average Circuit Depth') ax3.set_title('Average Circuit Depth vs Number of Qubits') ax3.legend() if gate_counts_plots == True: ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_1Q_counts,ax4,str='{}') autolabel(Algorithmic_1Q_counts,ax4,str='{}') ax4.set_xlabel('Number of Qubits') ax4.set_ylabel('Average 1-Qubit Gate Counts') ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits') ax4.legend() ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_2Q_counts,ax5,str='{}') autolabel(Algorithmic_2Q_counts,ax5,str='{}') ax5.set_xlabel('Number of Qubits') ax5.set_ylabel('Average 2-Qubit Gate Counts') ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits') ax5.legend() ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here autolabel(Hellinger,ax6,str='{:.2f}') autolabel(Normalized,ax6,str='{:.2f}') ax6.set_xlabel('Number of Qubits') ax6.set_ylabel('Average Value') ax6.set_title("Fidelity Comparison") ax6.legend() if Memory_utilization_plot == True: ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations") autolabel(ax7.patches, ax7) ax7.set_xlabel('Number of Qubits') ax7.set_ylabel('Maximum Memory Utilized (MB)') ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14) plt.tight_layout(rect=[0, 0, 1, 0.96]) if saveplots == True: plt.savefig("ParameterPlotsSample.jpg") plt.show() # Quantum Volume Plot Suptitle = f"Volumetric Positioning - {platform}" appname=benchmark_name if QV_ == None: QV=2048 else: QV=QV_ depth_base =2 ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity") w_data = num_qubits_range # determine width for circuit w_max = 0 for i in range(len(w_data)): y = float(w_data[i]) w_max = max(w_max, y) d_tr_data = avg_transpiled_depths f_data = avg_f plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
https://github.com/avkhadiev/schwinger-vqe
avkhadiev
https://github.com/snow0369/qiskit_tutorial_2021_summerschool
snow0369
!pip install -r requirements.txt
https://github.com/snow0369/qiskit_tutorial_2021_summerschool
snow0369
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.providers.aer import AerProvider from qiskit import execute qr = QuantumRegister(2) # 2 qubits cr = ClassicalRegister(2) # 2 classical bits qc = QuantumCircuit(qr, cr) # a quantum circuit with 2 qubits and 2 bits qc.draw() qc.h(qr[0]) # 0๋ฒˆ์งธ qubit์— hadamard ์—ฐ์‚ฐ์„ ์ทจํ•ฉ๋‹ˆ๋‹ค. qc.cx(qr[0], qr[1]) # 0๋ฒˆ์งธ qubit์„ control, 1๋ฒˆ์งธ qubit๋ฅผ target์œผ๋กœ ํ•˜๋Š” CNOT ์—ฐ์‚ฐ์„ ์ทจํ•ฉ๋‹ˆ๋‹ค. qc.measure(qr, cr) # qr์„ ์ธก์ •ํ•˜์—ฌ cr์— ์ €์žฅํ•˜๋Š” ์ธก์ • ์—ฐ์‚ฐ์„ ์ทจํ•ฉ๋‹ˆ๋‹ค. qc.draw('mpl') # ์™„์„ฑ๋œ ํšŒ๋กœ๋ฅผ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค. qasm_simulator = AerProvider().get_backend('qasm_simulator') job_qasm = execute(qc, backend=qasm_simulator, shots=2048) # ๋‹ค๋ฅธ ๋ฐฉ๋ฒ• # job_qasm = qasm_simulator.run(qc, shots=2048) # # ๋˜๋Š” # # from qiskit.utils import QuantumInstance # qi = QuantumInstance(qasm_simulator, shots=2048) # result = qi.execute(qc) # counts = result.get_counts() counts = job_qasm.result().get_counts() print("Bell measurement result") for k, v in counts.items(): print(k, v) from qiskit.visualization import plot_histogram plot_histogram(counts)
https://github.com/snow0369/qiskit_tutorial_2021_summerschool
snow0369
import numpy as np from qiskit.providers.aer import AerProvider from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Parameter from qiskit.tools.visualization import plot_histogram import qiskit.providers.aer.noise as noise from qiskit.quantum_info import hellinger_fidelity qr = QuantumRegister(3) cr = ClassicalRegister(3) qc = QuantumCircuit(qr, cr) tau = Parameter('ฯ„') qc.h(qr) qc.cx(qr[0], qr[1]) qc.cx(qr[1], qr[2]) qc.rz(-2 * tau, qr[2]) qc.cx(qr[1], qr[2]) qc.cx(qr[0], qr[1]) qc.h(qr) qc.draw('mpl') meas = QuantumCircuit(qr, cr) meas.measure(qr, cr) meas.draw('mpl') qasm_qc = qc.compose(meas) qasm_qc.draw('mpl') bind_qasm_qc = qasm_qc.bind_parameters({tau: np.pi/4}) qasm_backend = AerProvider().get_backend('qasm_simulator') job_qasm = qasm_backend.run(bind_qasm_qc, shots=4096) counts_qasm = job_qasm.result().get_counts() print(counts_qasm) plot_histogram(counts_qasm) # Error probabilities prob_1 = 0.001 # 1-qubit gate prob_2 = 0.01 # 2-qubit gate # Depolarizing quantum errors error_1 = noise.depolarizing_error(prob_1, num_qubits=1) error_2 = noise.depolarizing_error(prob_2, num_qubits=2) # Add errors to noise model noise_model = noise.NoiseModel() noise_model.add_all_qubit_quantum_error(error_1, ['h', 'rz']) noise_model.add_all_qubit_quantum_error(error_2, ['cx']) job_qasm_noisy = qasm_backend.run(bind_qasm_qc, shots=4096, noise_model=noise_model) counts_qasm_noisy = job_qasm_noisy.result().get_counts() print(counts_qasm_noisy) plot_histogram(counts_qasm_noisy) print(hellinger_fidelity(counts_qasm, counts_qasm_noisy)) qc.draw('mpl') bind_qc = qc.bind_parameters({tau: np.pi/4}) sv_backend = AerProvider().get_backend('statevector_simulator') job_sv = sv_backend.run(bind_qc) final_sv = job_sv.result().get_statevector() np.set_printoptions(suppress=True) print(final_sv) unitary_backend = AerProvider().get_backend('unitary_simulator') job_unitary = unitary_backend.run(bind_qc) unitary = job_unitary.result().get_unitary() print(unitary) for idx, x in np.ndenumerate(unitary): if abs(x) > 1e-7: print(f"{idx}, {x.real if abs(x.real) > 1e-7 else 0.0} {' + j'+ str(x.imag) if abs(x.imag) > 1e-7 else 0.0}")
https://github.com/snow0369/qiskit_tutorial_2021_summerschool
snow0369
from qiskit import IBMQ, QuantumRegister, QuantumCircuit, ClassicalRegister, transpile from qiskit.tools import backend_overview, backend_monitor from qiskit.providers.ibmq.job import job_monitor from qiskit.quantum_info import hellinger_fidelity from qiskit.providers.ibmq import IBMQAccountCredentialsNotFound from qiskit.providers.aer import AerProvider from qiskit.tools.visualization import plot_gate_map, plot_histogram token = 'f5876d2c6ea00ce4cefe8fcf6324956e042cd2a7cd57f6efc1e7ba38727964f10cef560830337f64c1de3743c420c1b23ded52bc01b197c6d8ce96394f13f1e0'# Input token here try: IBMQ.disable_account() except IBMQAccountCredentialsNotFound: pass IBMQ.enable_account(token) backend_overview() IBMQ_provider = IBMQ.get_provider() ibmq_manila_backend = IBMQ_provider.get_backend('ibmq_manila') backend_monitor(ibmq_manila_backend) plot_gate_map(ibmq_manila_backend, plot_directed=True) qr = QuantumRegister(3) cr = ClassicalRegister(3) ghz3 = QuantumCircuit(qr, cr) ghz3.h(qr[0]) ghz3.cx(qr[0], qr[1]) ghz3.cx(qr[0], qr[2]) ghz3.barrier() ghz3.measure(qr, cr) ghz3.draw('mpl') job_exp = ibmq_manila_backend.run(ghz3, shots=2048) job_monitor(job_exp) # An error must be raised here. print(ibmq_manila_backend.configuration().basis_gates) transpiled_circuit = transpile(ghz3, backend=ibmq_manila_backend) transpiled_circuit.draw('mpl') transpiled_circuit_opt = transpile(ghz3, backend=ibmq_manila_backend, optimization_level=3) transpiled_circuit_opt.draw('mpl') job_exp = ibmq_manila_backend.run(transpiled_circuit_opt, shots=2048) job_monitor(job_exp) noisy_counts = job_exp.result().get_counts() plot_histogram(noisy_counts) qasm_backend = AerProvider().get_backend('qasm_simulator') job_ideal = qasm_backend.run(ghz3, shots=2048) ideal_counts = job_ideal.result().get_counts() print(hellinger_fidelity(noisy_counts, ideal_counts)) from qiskit.test.mock import FakeRome fake_rome = FakeRome() rome_transpiled = transpile(ghz3, backend=fake_rome, optimization_level=3) job_fake_rome = fake_rome.run(rome_transpiled, shots=2048) counts_fake_rome = job_fake_rome.result().get_counts() plot_histogram(counts_fake_rome)
https://github.com/snow0369/qiskit_tutorial_2021_summerschool
snow0369
import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.test.mock import FakeRome from qiskit.providers.aer import AerProvider from qiskit.quantum_info import hellinger_fidelity qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0,1) qc.barrier() qc.measure(qr, cr) qc.draw('mpl') num_shots = 4096 fake_rome = FakeRome() job_fake_rome = fake_rome.run(qc, shots=4096) result_fake_rome = job_fake_rome.result() counts_fake_rome = result_fake_rome.get_counts() print(counts_fake_rome) pr_m = np.zeros(4, dtype=float) for b, v in counts_fake_rome.items(): pr_m[int(b, base=2)] = v/num_shots print(pr_m) pr_m_p = np.zeros((4,4), dtype=float) qr_mit = QuantumRegister(2) cr_mit = ClassicalRegister(2) # state prep = 00 qc_00 = QuantumCircuit(qr_mit, cr_mit) qc_00.barrier() qc_00.measure(qr_mit, cr_mit) counts_00 = fake_rome.run(qc_00, shots=num_shots)\ .result().get_counts() pr_m_p[0][0] = counts_00['00']/num_shots if '00' in counts_00 else 0.0 pr_m_p[1][0] = counts_00['01']/num_shots if '01' in counts_00 else 0.0 pr_m_p[2][0] = counts_00['10']/num_shots if '10' in counts_00 else 0.0 pr_m_p[3][0] = counts_00['11']/num_shots if '11' in counts_00 else 0.0 # state prep = 01 qc_01 = QuantumCircuit(qr_mit, cr_mit) qc_01.x(0) qc_01.barrier() qc_01.measure(qr_mit, cr_mit) counts_01 = fake_rome.run(qc_01, shots=num_shots)\ .result().get_counts() pr_m_p[0][1] = counts_01['00']/num_shots if '00' in counts_01 else 0.0 pr_m_p[1][1] = counts_01['01']/num_shots if '01' in counts_01 else 0.0 pr_m_p[2][1] = counts_01['10']/num_shots if '10' in counts_01 else 0.0 pr_m_p[3][1] = counts_01['11']/num_shots if '11' in counts_01 else 0.0 # state prep = 10 qc_10 = QuantumCircuit(qr_mit, cr_mit) qc_10.x(1) qc_10.barrier() qc_10.measure(qr_mit, cr_mit) counts_10 = fake_rome.run(qc_10, shots=num_shots)\ .result().get_counts() pr_m_p[0][2] = counts_10['00']/num_shots if '00' in counts_10 else 0.0 pr_m_p[1][2] = counts_10['01']/num_shots if '01' in counts_10 else 0.0 pr_m_p[2][2] = counts_10['10']/num_shots if '10' in counts_10 else 0.0 pr_m_p[3][2] = counts_10['11']/num_shots if '11' in counts_10 else 0.0 # state prep = 11 qc_11 = QuantumCircuit(qr_mit, cr_mit) qc_11.x(0) qc_11.x(1) qc_11.barrier() qc_11.measure(qr_mit, cr_mit) counts_11 = fake_rome.run(qc_11, shots=num_shots)\ .result().get_counts() pr_m_p[0][3] = counts_11['00']/num_shots if '00' in counts_11 else 0.0 pr_m_p[1][3] = counts_11['01']/num_shots if '01' in counts_11 else 0.0 pr_m_p[2][3] = counts_11['10']/num_shots if '10' in counts_11 else 0.0 pr_m_p[3][3] = counts_11['11']/num_shots if '11' in counts_11 else 0.0 np.set_printoptions(suppress=True) print(pr_m_p) pr_p = np.matmul(np.linalg.inv(pr_m_p), pr_m) print("Before mitigation: ", pr_m) print("After mitigation: ", pr_p) qasm_backend = AerProvider().get_backend("qasm_simulator") counts_qasm = qasm_backend.run(qc, shots=num_shots).result().get_counts() pr_ideal = np.zeros(4, dtype=float) for b, v in counts_qasm.items(): pr_ideal[int(b, base=2)] = v/num_shots print("Ideal probs: ", pr_ideal) # convert pr_p to dict form counts_mit = dict() for i, v in enumerate(pr_p): counts_mit[bin(i)[2:].rjust(2, '0')] = v * num_shots print("Fidelity without mitigation: ", hellinger_fidelity(counts_fake_rome, counts_qasm)) print("Fidelity with mitigation: ", hellinger_fidelity(counts_mit, counts_qasm)) from qiskit.visualization import plot_histogram plot_histogram([counts_fake_rome, counts_mit, counts_qasm], legend=['no mit', 'mitigated', 'ideal']) from qiskit.ignis.mitigation import CompleteMeasFitter, complete_meas_cal meas_calibs, state_labels = complete_meas_cal(qr=qr_mit, circlabel='mcal') for ckt in meas_calibs: print(ckt) job_calibs = fake_rome.run(meas_calibs, shots=num_shots) meas_fitter = CompleteMeasFitter(job_calibs.result(), state_labels, circlabel='mcal') print(meas_fitter.cal_matrix) meas_fitter.plot_calibration() # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(result_fake_rome) mitigated_counts = mitigated_results.get_counts(0) print("Fidelity with mitigation: ", hellinger_fidelity(mitigated_counts, counts_qasm))
https://github.com/snow0369/qiskit_tutorial_2021_summerschool
snow0369
import numpy as np from qiskit import transpile, QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.algorithms.phase_estimators import PhaseEstimation from qiskit.providers.aer import AerProvider from qiskit.tools.visualization import plot_histogram from qiskit.utils import QuantumInstance num_unitary_qubits = 2 unitary_qubit = QuantumRegister(num_unitary_qubits) unitary_circuit = QuantumCircuit(unitary_qubit) for i in range(num_unitary_qubits): unitary_circuit.rx(0.5*np.pi, i) for i in range(num_unitary_qubits - 1): unitary_circuit.cx(i, i+1) for i in range(num_unitary_qubits): unitary_circuit.rz(0.5*np.pi, i) print("depth = ", unitary_circuit.depth()) unitary_circuit.draw('mpl') state_prep = QuantumCircuit(unitary_qubit) state_prep.h(unitary_qubit) state_prep.draw('mpl') num_evaluation_qubits = 3 qasm_backend = AerProvider().get_backend("qasm_simulator") qpe = PhaseEstimation(num_evaluation_qubits=num_evaluation_qubits, quantum_instance=QuantumInstance(backend=qasm_backend, shots=4096, optimization_level=3)) ckt = qpe.construct_circuit(unitary_circuit, state_preparation=state_prep) ckt = transpile(ckt, backend=qasm_backend) print(f"depth = {ckt.depth()}") ckt.draw('mpl') res = qpe.estimate(unitary_circuit, state_prep) plot_histogram(res.phases) phase_list = sorted(res.phases.keys(), key=lambda x: res.phases[x], reverse=True) for p in sorted(phase_list): bin_p = int(p, 2) / 2**num_evaluation_qubits print(f"phase[rad] : {2*bin_p*np.pi}, occurence : {res.phases[p]}") unitary_simulator = AerProvider().get_backend('unitary_simulator') job_unitary = unitary_simulator.run(unitary_circuit) mat = job_unitary.result().get_unitary() print(mat) eigval, eigvec = np.linalg.eig(mat) assert all(np.isclose(np.abs(eigval), 1.0)) eigph = np.angle(eigval) for i, p in enumerate(eigph): if p < 0: eigph[i] = 2*np.pi + p print("eig phase = ", sorted(eigph)) for i, v in enumerate(eigvec): print(f"eigvec {i} = {v/np.linalg.norm(v, ord=2)}") from qiskit.test.mock import FakeRome fake_rome = FakeRome() # ์ธก์ •๊ฒŒ์ดํŠธ ์ถ”๊ฐ€ eval_qubits = ckt.qregs[0] creg = ClassicalRegister(len(eval_qubits)) ckt.add_register(creg) ckt.measure(eval_qubits, creg) ckt_lv0 = transpile(ckt, backend=fake_rome, optimization_level=0) ckt_lv1 = transpile(ckt, backend=fake_rome, optimization_level=1) ckt_lv2 = transpile(ckt, backend=fake_rome, optimization_level=2) ckt_lv3 = transpile(ckt, backend=fake_rome, optimization_level=3) for i, ckt_opt in enumerate([ckt_lv0, ckt_lv1, ckt_lv2, ckt_lv3]): cnot_count = ckt_opt.count_ops()['cx'] if 'cx' in ckt_opt.count_ops() else 0 print(f"opt_level={i}, depth={ckt_opt.depth()}, cnot_count={cnot_count}")
https://github.com/snow0369/qiskit_tutorial_2021_summerschool
snow0369
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, transpile from qiskit.providers.aer import AerProvider from qiskit.tools.visualization import plot_histogram import random import numpy as np def ghz(n): # ๊ฐ์ฒด์˜ ์„ ์–ธ # ํšŒ๋กœ ๊ตฌ์„ฑ return qc_ghz # 5-ghz ํšŒ๋กœ ์ถœ๋ ฅ qc = ghz(5) qc.draw('mpl') # qasm ์‹œ๋ฎฌ๋ ˆ์ด์…˜ # ์‹œ๊ฐํ™” bell_qr = QuantumRegister(2, 'bell') message_qr = QuantumRegister(1, 'message') cr1 = ClassicalRegister(1) cr2 = ClassicalRegister(1) qtel_qc = QuantumCircuit(message_qr, bell_qr, cr1, cr2) a1, a2, a3 = ( random.random() * np.pi for _ in range(3) ) # complete the circuit # qtel_qc.x(bell_qr[1]).c_if(cr2, 1) # qtel_qc.z(bell_qr[1]).c_if(cr1, 1) qtel_qc.draw('mpl'); sv_simulator = AerProvider().get_backend('statevector_simulator') job_sv = sv_simulator.run(qtel_qc) sv = job_sv.result().get_statevector() print(sv) print([sum(sv[:4]), sum(sv[4:])]) verif_ckt = QuantumCircuit(1) verif_ckt.u3(a1, a2, a3, 0) sv_verif = sv_simulator.run(verif_ckt).result().get_statevector() print(sv_verif) from qiskit.circuit.library.basis_change.qft import QFT qft_ckt = QFT(5) qft_ckt.draw("mpl") qft_ckt_tr = qft_ckt_tr.draw('mpl'); coupling_map = list() for i in range(5 - 1): coupling_map.append([i, i+1]) coupling_map.append([i+1, i]) qft_ckt_tr_lin = transpile(qft_ckt, basis_gates=['u1', 'u2', 'cx'], coupling_map=coupling_map) print(coupling_map) qft_ckt_tr_lin.draw('mpl');
https://github.com/snow0369/qiskit_tutorial_2021_summerschool
snow0369
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, transpile from qiskit.providers.aer import AerProvider from qiskit.tools.visualization import plot_histogram import random import numpy as np def ghz(n): # ๊ฐ์ฒด์˜ ์„ ์–ธ qr_ghz = QuantumRegister(n) cr_ghz = ClassicalRegister(n) qc_ghz = QuantumCircuit(qr_ghz, cr_ghz) # ํšŒ๋กœ ๊ตฌ์„ฑ qc_ghz.h(qr_ghz[0]) for i in range(1, n): qc_ghz.cx(0, i) qc_ghz.barrier() qc_ghz.measure(qr_ghz, cr_ghz) return qc_ghz # 5-ghz ํšŒ๋กœ ์ถœ๋ ฅ qc = ghz(5) qc.draw('mpl'); # qasm ์‹œ๋ฎฌ๋ ˆ์ด์…˜ qasm_simulator = AerProvider().get_backend("qasm_simulator") job_qasm = execute(qc, backend=qasm_simulator, shots=1024) counts = job_qasm.result().get_counts() # ์‹œ๊ฐํ™” plot_histogram(counts); bell_qr = QuantumRegister(2, 'bell') message_qr = QuantumRegister(1, 'message') cr1 = ClassicalRegister(1) cr2 = ClassicalRegister(1) qtel_qc = QuantumCircuit(message_qr, bell_qr, cr1, cr2) a1, a2, a3 = ( random.random() * np.pi for _ in range(3) ) # complete the circuit qtel_qc.h(bell_qr[0]) qtel_qc.cx(bell_qr[0], bell_qr[1]) qtel_qc.barrier() qtel_qc.u3(a1, a2, a3, message_qr) qtel_qc.cx(message_qr, bell_qr[0]) qtel_qc.h(message_qr) qtel_qc.barrier() qtel_qc.measure(message_qr, cr1) qtel_qc.measure(bell_qr[0], cr2) qtel_qc.barrier() qtel_qc.x(bell_qr[1]).c_if(cr2, 1) qtel_qc.z(bell_qr[1]).c_if(cr1, 1) qtel_qc.draw('mpl'); sv_simulator = AerProvider().get_backend('statevector_simulator') job_sv = sv_simulator.run(qtel_qc) sv = job_sv.result().get_statevector() print(sv) print([sum(sv[:4]), sum(sv[4:])]) verif_ckt = QuantumCircuit(1) verif_ckt.u3(a1, a2, a3, 0) sv_verif = sv_simulator.run(verif_ckt).result().get_statevector() print(sv_verif) from qiskit.circuit.library.basis_change.qft import QFT qft_ckt = QFT(5) qft_ckt.draw("mpl"); qft_ckt_tr = transpile(qft_ckt, basis_gates=['u1', 'u2', 'cx']) qft_ckt_tr.draw('mpl'); coupling_map = list() for i in range(5 - 1): coupling_map.append([i, i+1]) coupling_map.append([i+1, i]) qft_ckt_tr_lin = transpile(qft_ckt, basis_gates=['u1', 'u2', 'cx'], coupling_map=coupling_map) print(coupling_map) qft_ckt_tr_lin.draw('mpl');
https://github.com/qiskit-community/qiskit-device-benchmarking
qiskit-community
import numpy as np import rustworkx as rx import matplotlib.pyplot as plt from qiskit_ibm_runtime import QiskitRuntimeService from qiskit import QuantumCircuit from qiskit_experiments.framework import ParallelExperiment, BatchExperiment from qiskit_experiments.library import (StateTomography, MitigatedStateTomography) from qiskit_device_benchmarking.utilities import graph_utils as gu #enter your device hub/group/project here #and device hgp = 'ibm-q/open/main' service = QiskitRuntimeService() backend_real=service.backend('ibm_kyiv',instance=hgp) nq = backend_real.configuration().n_qubits coupling_map = backend_real.configuration().coupling_map #build a set of gates G = gu.build_sys_graph(nq, coupling_map) #get all length 2 paths in the device paths = rx.all_pairs_all_simple_paths(G,2,2) #flatten those paths into a list from the rustwork x iterator paths = gu.paths_flatten(paths) #remove permutations paths = gu.remove_permutations(paths) #convert to the coupling map of the device paths = gu.path_to_edges(paths,coupling_map) #make into separate sets sep_sets = gu.get_separated_sets(G, paths, min_sep=2) #state tomography of all the two qubit edgges in parallel tomo_batch_list = [] #got through for each of the edge sets for ii in range(len(sep_sets)): tomo_exp_list = [] tomo_exp_list_b = [] twoq_circ_b = QuantumCircuit(2) twoq_circ = QuantumCircuit(2) if (1): twoq_circ.h(0) twoq_circ.cx(0,1) if 'ecr' in backend_real.configuration().basis_gates: twoq_gate='ecr' elif 'cz' in backend_real.configuration().basis_gates: twoq_gate='cz' for two_i, two_set in enumerate(sep_sets[ii]): tomo_exp = MitigatedStateTomography(circuit=twoq_circ, physical_qubits=two_set[0:2], backend = backend_real) tomo_exp_list.append(tomo_exp) tomo_exp = MitigatedStateTomography(circuit=twoq_circ_b, physical_qubits=two_set[0:2], backend = backend_real) tomo_exp_list_b.append(tomo_exp) tomo_exp_p = ParallelExperiment(tomo_exp_list, backend = backend_real) tomo_exp_pb = ParallelExperiment(tomo_exp_list_b, backend = backend_real) tomo_batch_list.append(tomo_exp_p) tomo_batch_list.append(tomo_exp_pb) #back all of them together full_tomo_exp = BatchExperiment(tomo_batch_list, backend = backend_real) full_tomo_exp.set_run_options(shots=1000) #run tomo_data = full_tomo_exp.run() set_list = [] bell_err = [] id_err = [] gate_err = [] read_err = [] back_prop = backend_real.properties() for i in range(len(sep_sets)): for j in range(len(sep_sets[i])): set_list.append(sep_sets[i][j]) bell_err.append(1-tomo_data.child_data()[2*i].child_data()[j].analysis_results()[1].value) id_err.append(1-tomo_data.child_data()[2*i+1].child_data()[j].analysis_results()[1].value) gate_err.append(back_prop.gate_error(twoq_gate,set_list[-1])) read_err.append(1-(1-back_prop.readout_error(set_list[-1][0]))**0.5*(1-back_prop.readout_error(set_list[-1][1]))**0.5) print('Q%s, bell error (purity) %.2e (%.2e)/ id error (purity) %.2e (%.2e)'%(sep_sets[i][j], 1-tomo_data.child_data()[2*i].child_data()[j].analysis_results()[1].value, 1-np.abs(tomo_data.child_data()[2*i].child_data()[j].analysis_results()[0].value.purity())**0.5, 1-tomo_data.child_data()[2*i+1].child_data()[j].analysis_results()[1].value, 1-np.abs(tomo_data.child_data()[2*i+1].child_data()[j].analysis_results()[0].value.purity())**0.5)) #print(backend_real.properties().gate_error(twoq_gate,sep_sets[0][i])) #plot the data ordered by Bell state fidelity (need to run the cell above first) plt.figure(dpi=150,figsize=[15,5]) argind = np.argsort(bell_err) plt.semilogy(range(len(set_list)),np.array(bell_err)[argind],label='Bell', marker='.') plt.semilogy(range(len(set_list)),np.array(id_err)[argind], label='Identity', marker='.') plt.xticks(range(len(set_list)),np.array(set_list)[argind],rotation=90,fontsize=5); plt.grid(True) plt.legend() plt.title('Bell and |0> State Tomography for %s'%backend_real.name) import datetime from IPython.display import HTML, display def qiskit_copyright(line="", cell=None): """IBM copyright""" now = datetime.datetime.now() html = "<div style='width: 100%; background-color:#d5d9e0;" html += "padding-left: 10px; padding-bottom: 10px; padding-right: 10px; padding-top: 5px'>" html += "<p>&copy; Copyright IBM 2017, %s.</p>" % now.year html += "<p>This code is licensed under the Apache License, Version 2.0. You may<br>" html += "obtain a copy of this license in the LICENSE.txt file in the root directory<br> " html += "of this source tree or at http://www.apache.org/licenses/LICENSE-2.0." html += "<p>Any modifications or derivative works of this code must retain this<br>" html += "copyright notice, and modified files need to carry a notice indicating<br>" html += "that they have been altered from the originals.</p>" html += "</div>" return display(HTML(html)) qiskit_copyright()
https://github.com/qiskit-community/qiskit-device-benchmarking
qiskit-community
import pandas as pd import numpy as np import scipy.stats as stats import matplotlib.pyplot as plt import rustworkx as rx from qiskit_ibm_runtime import QiskitRuntimeService import qiskit_device_benchmarking #preferred that the qiskit_device_benchmark package is installed as 'pip install .' but if not #uncomment the following #import sys #sys.path.append('../') #import paths_flatten,remove_permutations,path_to_edges,build_sys_graph,get_separated_sets import qiskit_device_benchmarking.utilities.graph_utils as gu #for testing from qiskit_aer import AerSimulator #import the qiskit experiment modules #uses Tphi experiment from qiskit_experiments.library import Tphi from qiskit_experiments.framework import ParallelExperiment, BatchExperiment #import the custom bell experiment from qiskit_device_benchmarking.bench_code.bell.bell_experiment import BellExperiment #enter your device hub/group/project here #and device hgp = 'ibm-q/open/main' service = QiskitRuntimeService() backend_real=service.backend('ibm_kyiv',instance=hgp) nq = backend_real.configuration().n_qubits coupling_map = backend_real.configuration().coupling_map #if you want to use the simulator #uncomment if (0): backend_sim = AerSimulator.from_backend(backend) backend = backend_sim else: backend = backend_real #build a set of gates G = gu.build_sys_graph(nq, coupling_map) #get all length 2 paths in the device paths = rx.all_pairs_all_simple_paths(G,2,2) #flatten those paths into a list from the rustwork x iterator paths = gu.paths_flatten(paths) #remove permutations paths = gu.remove_permutations(paths) #convert to the coupling map of the device paths = gu.path_to_edges(paths,coupling_map) #make into separate sets sep_sets = gu.get_separated_sets(G, paths, min_sep=2) qubits_nns = gu.get_iso_qubit_list(G) # Time intervals to wait before measurement for t1 and t2 delays_t1 = [0] + np.arange(1e-6, 100e-6, 10e-6).tolist() + np.arange(130e-6, 300e-6, 40e-6).tolist() delays_t2 = [0] + np.arange(1e-6, 100e-6, 10e-6).tolist() + np.arange(130e-6, 300e-6, 40e-6).tolist() num_periods = 5 max_T = delays_t2[-1] osc_freq = num_periods/(max_T) #Construct the experiments #First the Tphi exp_batches = [] for qubits in qubits_nns: coh_exps = ParallelExperiment([ Tphi((int(qubit),), delays_t1=delays_t1,delays_t2=delays_t2,t2type='hahn',osc_freq=osc_freq,backend=backend) for qubit in np.array(qubits).flatten()], flatten_results=False) exp_batches.append(coh_exps) #Bell bell_exp = BellExperiment(sep_sets,backend=backend) exp_batches.append(bell_exp) #Batch all together batch_exp = BatchExperiment(exp_batches,backend=backend,flatten_results=False) %%time #Run batch_exp.set_run_options(shots=300) batch_exp_data = batch_exp.run() batch_exp_data.status() plot_q = 0 #0 for the T1, 1 for the T2 plot_type = 0 plot_ind = [] for i in range(len(qubits_nns)): for j in range(len(qubits_nns[i])): if plot_q==qubits_nns[i][j]: plot_ind = [i,j] break print('Plotting Q%d'%plot_q) batch_exp_data.child_data()[i].child_data()[j].figure(plot_type) #generate a T1/T2 list q_list = [] t1_list = [] t2_list = [] for i in range(len(qubits_nns)): data1 = batch_exp_data.child_data()[i] for j in range(len(qubits_nns[i])): q_list.append(qubits_nns[i][j]) t1_list.append(data1.child_data()[j].analysis_results()[2].value.nominal_value) t2_list.append(data1.child_data()[j].analysis_results()[4].value.nominal_value) #plot the data ordered by Bell state fidelity (need to run the cell above first) plt.figure(dpi=150,figsize=[15,5]) argind = np.argsort(t1_list) plt.semilogy(range(len(q_list)),np.array(t1_list)[argind]/1e-6,label='T1', marker='.',color='blue') plt.semilogy(range(len(q_list)),np.array(t2_list)[argind]/1e-6,label='T2', marker='x',color='lightskyblue') plt.xticks(range(len(q_list)),np.array(q_list)[argind],rotation=90,fontsize=6); plt.ylabel('Time (us)') plt.ylim([10,1000]) plt.grid(True) plt.legend() plt.title('Device Coherence for %s, job %s'%(backend_real.name, batch_exp_data.job_ids[0])) #Quantile plot plt.figure(dpi=100) x1 = stats.probplot(t1_list) x2 = stats.probplot(t2_list) plt.semilogy(x1[0][0],x1[0][1]/1e-6,linestyle='None',marker='.',markersize=10,label='T1',color='blue') plt.semilogy(x2[0][0],x2[0][1]/1e-6,linestyle='None',marker='.',markersize=10,label='T2',color='lightskyblue') plt.grid(True,which='both') plt.legend(fontsize=16) plt.xlabel('Normal Quantile',fontsize=16) plt.ylabel('Coherence (us)',fontsize=16) plt.ylim([10,700]) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.title('Device Coherence for %s, job %s'%(backend_real.name, batch_exp_data.job_ids[0])) #Pull the data from the dataframe df = batch_exp_data.child_data()[2].analysis_results()[0].value bell_edge_list = [] bell_fid_list = [] for i in df.iterrows(): bell_edge_list.append(i[1]['connection']) bell_fid_list.append(i[1]['fidelity']) #plot the data ordered by Bell state fidelity (need to run the cell above first) plt.figure(dpi=150,figsize=[15,5]) argind = np.argsort(1-np.array(bell_fid_list)) plt.semilogy(range(len(bell_edge_list)),1-np.array(bell_fid_list)[argind],label='T1', color='blue', marker='.') plt.xticks(range(len(bell_edge_list)),np.array(bell_edge_list)[argind],rotation=90,fontsize=6); plt.ylabel('Bell Hellinger Error (1-Fid.)') plt.ylim([1e-3,1]) plt.grid(True) plt.legend() plt.title('Bell Edges for %s, job %s'%(backend_real.name, batch_exp_data.job_ids[0])) from IPython.display import HTML, display import datetime def qiskit_copyright(line="", cell=None): """IBM copyright""" now = datetime.datetime.now() html = "<div style='width: 100%; background-color:#d5d9e0;" html += "padding-left: 10px; padding-bottom: 10px; padding-right: 10px; padding-top: 5px'>" html += "<p>&copy; Copyright IBM 2017, %s.</p>" % now.year html += "<p>This code is licensed under the Apache License, Version 2.0. You may<br>" html += "obtain a copy of this license in the LICENSE.txt file in the root directory<br> " html += "of this source tree or at http://www.apache.org/licenses/LICENSE-2.0." html += "<p>Any modifications or derivative works of this code must retain this<br>" html += "copyright notice, and modified files need to carry a notice indicating<br>" html += "that they have been altered from the originals.</p>" html += "</div>" return display(HTML(html)) qiskit_copyright()