repo
stringclasses 900
values | file
stringclasses 754
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
from crypto.six_state.participant import Participant
from qiskit import QuantumCircuit
from numpy.random import rand
from qiskit import transpile
## The Receiver entity in the Six-State implementation
## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html
class Receiver(Participant):
## Constructor
def __init__(self, name='', original_bits_size=0):
super().__init__(name, original_bits_size)
## Decode the message measuring the circuit (density-dependent)
def decode_quantum_message(self, message, density, backend):
## The values of the participant
self.values = []
for i, qc in enumerate(message):
qc.barrier()
if rand() < density:
if self.axes[i] == 1:
qc.h(0)
elif self.axes[i] == 2:
qc.append(self.hy, [0])
qc.measure(0, 0)
transpiled_qc = transpile(qc, backend=backend)
result = backend.run(transpiled_qc, shots=1, memory=True).result()
measured_bit = int(result.get_memory()[0])
self.values.append(measured_bit)
else:
self.values.append(-1)
return message
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
from crypto.six_state.participant import Participant
from qiskit import QuantumCircuit
## The Sender entity in the Six-State implementation
## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html
class Sender(Participant):
## Constructor
def __init__(self, name='', original_bits_size=0):
super().__init__(name, original_bits_size)
## Encode the message (values) using a quantum circuit
def encode_quantum_message(self):
encoded_message = []
for i in range(len(self.axes)):
qc = QuantumCircuit(1, 1)
if self.values[i] == 1:
qc.x(0)
if self.axes[i] == 1:
qc.h(0)
elif self.axes[i] == 2:
qc.append(self.hy, [0])
encoded_message.append(qc)
return encoded_message
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
from qiskit import QuantumCircuit
from random import vonmisesvariate as random_angle
from qiskit.circuit.library import UGate
from crypto.elgamal.sender import Sender
from crypto.elgamal.receiver import Receiver
from qiskit.quantum_info import Statevector
import qiskit.quantum_info as qi
import numpy as np
ELGAMAL_SIMULATOR = 'ElGamal SIMULATOR'
## An implementation of the ElGamal protocol
## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html
class ElGamalAlgorithm:
## Run the implementation of ElGamal protocol
def run(self, message):
msg_qc = QuantumCircuit(1, name='message')
msg_sv = Statevector([complex(x) for x in message.split(',')])
msg_qc.initialize(msg_sv)
u1, u2 = self.public_keys_generation()
# Receiver Bob
bob = Receiver('Bob', u1, u2)
bob.generate_keys()
# Sender Alice
alice = Sender('Alice', u1, u2)
alice.set_message(msg_qc)
alice.generate_keys()
alice.compute_shared_secret(bob.public_key)
# Encryption
c1 = alice.public_key
c2 = alice.get_encripted_message()
# Decryption
bob.compute_shared_secret(c1)
decrypted_message = bob.decrypt_message(c2)
encrypted_message = c2
shared_secret = alice.shared_secret
decrypted_message_sv = qi.Statevector.from_instruction(decrypted_message)
encrypted_message_sv = qi.Statevector.from_instruction(encrypted_message)
return msg_sv, encrypted_message, decrypted_message, encrypted_message_sv, decrypted_message_sv, alice, bob
## Gets random public matrices
def public_keys_generation(self):
u1 = QuantumCircuit(1, name='U1')
u1.append(UGate(random_angle(0, 0), random_angle(0, 0), random_angle(0, 0)), [0])
u2 = QuantumCircuit(1, name='U2')
u2.append(UGate(random_angle(0, 0), random_angle(0, 0), random_angle(0, 0)), [0])
return (u1, u2)
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
from abc import ABC, abstractmethod
from qiskit import QuantumCircuit
from qiskit.circuit.library import YGate, ZGate
from qiskit.circuit.gate import Gate
import qiskit.quantum_info as qi
from numpy.random import randint
import numpy as np
from math import ceil
## An abstract class of a participant entity in the Six-State implementation
## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html
class Participant(ABC):
## Constructor
@abstractmethod
def __init__(self, name='', original_bits_size=0):
## The name of the participant
self.name = name
## The original size of the message
self.original_bits_size = original_bits_size
## The values of the participant
self.values = None
## The axes of the participant
self.axes = None
## The key of the participant
self.key = None
## If the key is determined safe
self.is_safe_key = False
## The otp of the participant
self.otp = None
## The gate measuring z and y axes
self.set_hy()
## Values setter
def set_values(self, values=None):
if values == None:
self.values = list(randint(2, size=self.original_bits_size))
else:
self.values = values
## Axes setter
def set_axes(self, axes=None):
if axes == None:
self.axes = list(randint(3, size=self.original_bits_size))
else:
self.axes = axes
## Print values
def show_values(self):
print('\n' + self.name, 'Values:')
print(self.values)
## Print axes
def show_axes(self):
print('\n' + self.name, 'Axes:')
print(self.axes)
## Print key
def show_key(self):
print('\n' + self.name, 'Key:')
print(self.key)
## Print otp
def show_otp(self):
print('\n' + self.name, 'OTP:')
print(self.otp)
## Remove the values of the qubits that were measured on the wrong axis
def remove_garbage(self, another_axes):
self.key = []
for i in range(self.original_bits_size):
if self.axes[i] == another_axes[i]:
self.key.append(self.values[i])
## Check if the shared key is equal to the current key
def check_key(self, shared_key):
return shared_key == self.key[:len(shared_key)]
## Use the rest of the key and validate it
def confirm_key(self, shared_size):
self.key = self.key[shared_size:]
self.is_safe_key = True
## Generate an One-Time Pad
def generate_otp(self, n_bits):
self.otp = []
for i in range(ceil(len(self.key) / n_bits)):
bits_string = ''.join(map(str, self.key[i * n_bits: (i + 1) * n_bits]))
self.otp.append(int(bits_string, 2))
## Performs an XOR operation between the message and the One-Time Pad
def xor_otp_message(self, message):
final_message = ''
CHR_LIMIT = 1114112
if len(self.otp) > 0:
for i, char in enumerate(message):
final_message += chr((ord(char) ^ self.otp[i % len(self.otp)]) % CHR_LIMIT)
return final_message
## New gate setter
def set_hy(self):
hy_op = qi.Operator(1/np.sqrt(2)*(YGate().to_matrix() + ZGate().to_matrix()))
hy_gate = QuantumCircuit(1)
hy_gate.unitary(hy_op, [0], label='h_y')
self.hy = hy_gate.to_gate()
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
from crypto.six_state.participant import Participant
from qiskit import QuantumCircuit
from numpy.random import rand
from qiskit import transpile
## The Receiver entity in the Six-State implementation
## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html
class Receiver(Participant):
## Constructor
def __init__(self, name='', original_bits_size=0):
super().__init__(name, original_bits_size)
## Decode the message measuring the circuit (density-dependent)
def decode_quantum_message(self, message, density, backend):
## The values of the participant
self.values = []
for i, qc in enumerate(message):
qc.barrier()
if rand() < density:
if self.axes[i] == 1:
qc.h(0)
elif self.axes[i] == 2:
qc.append(self.hy, [0])
qc.measure(0, 0)
transpiled_qc = transpile(qc, backend=backend)
result = backend.run(transpiled_qc, shots=1, memory=True).result()
measured_bit = int(result.get_memory()[0])
self.values.append(measured_bit)
else:
self.values.append(-1)
return message
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
from crypto.six_state.participant import Participant
from qiskit import QuantumCircuit
## The Sender entity in the Six-State implementation
## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html
class Sender(Participant):
## Constructor
def __init__(self, name='', original_bits_size=0):
super().__init__(name, original_bits_size)
## Encode the message (values) using a quantum circuit
def encode_quantum_message(self):
encoded_message = []
for i in range(len(self.axes)):
qc = QuantumCircuit(1, 1)
if self.values[i] == 1:
qc.x(0)
if self.axes[i] == 1:
qc.h(0)
elif self.axes[i] == 2:
qc.append(self.hy, [0])
encoded_message.append(qc)
return encoded_message
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
from crypto.six_state.participant import Participant
from qiskit import QuantumCircuit
from numpy.random import rand
from qiskit import transpile
## The Receiver entity in the Six-State implementation
## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html
class Receiver(Participant):
## Constructor
def __init__(self, name='', original_bits_size=0):
super().__init__(name, original_bits_size)
## Decode the message measuring the circuit (density-dependent)
def decode_quantum_message(self, message, density, backend):
## The values of the participant
self.values = []
for i, qc in enumerate(message):
qc.barrier()
if rand() < density:
if self.axes[i] == 1:
qc.h(0)
elif self.axes[i] == 2:
qc.append(self.hy, [0])
qc.measure(0, 0)
transpiled_qc = transpile(qc, backend=backend)
result = backend.run(transpiled_qc, shots=1, memory=True).result()
measured_bit = int(result.get_memory()[0])
self.values.append(measured_bit)
else:
self.values.append(-1)
return message
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
import binascii
from math import sqrt
from qiskit import execute, QuantumCircuit, transpile, assemble
from qiskit.quantum_info import Statevector
from qiskit.extensions import Initialize
from crypto.rsa_substitute.sender import Sender
from crypto.rsa_substitute.receiver import Receiver
RSA_SUBSTITUTE_SIMULATOR = 'RSA SUBSTITUTE SIMULATOR'
## An implementation of the RSA substitute protocol
## @see https://journals.aijr.org/index.php/ajgr/article/view/699/168
class RsaSubstituteAlgorithm:
## Run the implementation of RSA substitute protocol
def run(self, measure_zero_prob, n_shots, backend, verbose):
bob = Receiver('Bob', 6, 5)
alice = Sender('Alice', 4, bob.p)
message = self.generate_message(measure_zero_prob)
alice_encoded_message = alice.encode(message)
alice_bob_encoded_message = bob.encode(alice_encoded_message)
bob_encoded_message = alice.decode(alice_bob_encoded_message)
decoded_message = bob.decode(bob_encoded_message)
decoded_message.measure(0, 0)
test = transpile(decoded_message, backend)
qobj = assemble(test)
counts = backend.run(qobj, shots=n_shots).result().get_counts()
if not '0' in counts.keys():
counts['0'] = 0
obtained_prob = counts['0'] / n_shots
EPSILON = 5
relative_error = abs(measure_zero_prob - obtained_prob)
check_probability = relative_error <= 0.01 * EPSILON
if verbose:
print('\nOutput: ' + str(counts))
print('\nInitial Message:')
print(message)
print('\nAlice-Encoded Message:')
print(alice_encoded_message)
print('\nAlice-and-Bob-Encoded Message:')
print(alice_bob_encoded_message)
print('\nBob-Encoded Message:')
print(bob_encoded_message)
print('\n💡 Decoded Message:')
print(decoded_message)
print('\nInput Probability:')
print(measure_zero_prob)
print('\nObtained Probability:')
print(obtained_prob)
print('\nRelative Error: ' + str(relative_error) + ' %')
if check_probability:
print('\n✅ The expected probability is obtained within an error range of ±' + str(EPSILON) + '%')
else:
print('\n❌ The expected probability is obtained with an error greater than ±' + str(EPSILON) + '%')
return check_probability, relative_error
def generate_message(self, measure_zero_prob):
a1 = sqrt(measure_zero_prob)
a2 = sqrt(1 - measure_zero_prob)
psi = Statevector([complex(a1, 0), complex(a2, 0)])
init_gate = Initialize(psi)
init_gate.label = 'Init'
qc = QuantumCircuit(1, 1)
qc.append(init_gate, [0])
qc.barrier()
return qc
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
from crypto.six_state.participant import Participant
from qiskit import QuantumCircuit
## The Sender entity in the Six-State implementation
## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html
class Sender(Participant):
## Constructor
def __init__(self, name='', original_bits_size=0):
super().__init__(name, original_bits_size)
## Encode the message (values) using a quantum circuit
def encode_quantum_message(self):
encoded_message = []
for i in range(len(self.axes)):
qc = QuantumCircuit(1, 1)
if self.values[i] == 1:
qc.x(0)
if self.axes[i] == 1:
qc.h(0)
elif self.axes[i] == 2:
qc.append(self.hy, [0])
encoded_message.append(qc)
return encoded_message
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
from abc import ABC, abstractmethod
from qiskit import QuantumCircuit
from qiskit.circuit.library import YGate, ZGate
from qiskit.circuit.gate import Gate
import qiskit.quantum_info as qi
from numpy.random import randint
import numpy as np
from math import ceil
## An abstract class of a participant entity in the Six-State implementation
## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html
class Participant(ABC):
## Constructor
@abstractmethod
def __init__(self, name='', original_bits_size=0):
## The name of the participant
self.name = name
## The original size of the message
self.original_bits_size = original_bits_size
## The values of the participant
self.values = None
## The axes of the participant
self.axes = None
## The key of the participant
self.key = None
## If the key is determined safe
self.is_safe_key = False
## The otp of the participant
self.otp = None
## The gate measuring z and y axes
self.set_hy()
## Values setter
def set_values(self, values=None):
if values == None:
self.values = list(randint(2, size=self.original_bits_size))
else:
self.values = values
## Axes setter
def set_axes(self, axes=None):
if axes == None:
self.axes = list(randint(3, size=self.original_bits_size))
else:
self.axes = axes
## Print values
def show_values(self):
print('\n' + self.name, 'Values:')
print(self.values)
## Print axes
def show_axes(self):
print('\n' + self.name, 'Axes:')
print(self.axes)
## Print key
def show_key(self):
print('\n' + self.name, 'Key:')
print(self.key)
## Print otp
def show_otp(self):
print('\n' + self.name, 'OTP:')
print(self.otp)
## Remove the values of the qubits that were measured on the wrong axis
def remove_garbage(self, another_axes):
self.key = []
for i in range(self.original_bits_size):
if self.axes[i] == another_axes[i]:
self.key.append(self.values[i])
## Check if the shared key is equal to the current key
def check_key(self, shared_key):
return shared_key == self.key[:len(shared_key)]
## Use the rest of the key and validate it
def confirm_key(self, shared_size):
self.key = self.key[shared_size:]
self.is_safe_key = True
## Generate an One-Time Pad
def generate_otp(self, n_bits):
self.otp = []
for i in range(ceil(len(self.key) / n_bits)):
bits_string = ''.join(map(str, self.key[i * n_bits: (i + 1) * n_bits]))
self.otp.append(int(bits_string, 2))
## Performs an XOR operation between the message and the One-Time Pad
def xor_otp_message(self, message):
final_message = ''
CHR_LIMIT = 1114112
if len(self.otp) > 0:
for i, char in enumerate(message):
final_message += chr((ord(char) ^ self.otp[i % len(self.otp)]) % CHR_LIMIT)
return final_message
## New gate setter
def set_hy(self):
hy_op = qi.Operator(1/np.sqrt(2)*(YGate().to_matrix() + ZGate().to_matrix()))
hy_gate = QuantumCircuit(1)
hy_gate.unitary(hy_op, [0], label='h_y')
self.hy = hy_gate.to_gate()
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
from crypto.six_state.participant import Participant
from qiskit import QuantumCircuit
from numpy.random import rand
from qiskit import transpile
## The Receiver entity in the Six-State implementation
## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html
class Receiver(Participant):
## Constructor
def __init__(self, name='', original_bits_size=0):
super().__init__(name, original_bits_size)
## Decode the message measuring the circuit (density-dependent)
def decode_quantum_message(self, message, density, backend):
## The values of the participant
self.values = []
for i, qc in enumerate(message):
qc.barrier()
if rand() < density:
if self.axes[i] == 1:
qc.h(0)
elif self.axes[i] == 2:
qc.append(self.hy, [0])
qc.measure(0, 0)
transpiled_qc = transpile(qc, backend=backend)
result = backend.run(transpiled_qc, shots=1, memory=True).result()
measured_bit = int(result.get_memory()[0])
self.values.append(measured_bit)
else:
self.values.append(-1)
return message
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
from crypto.six_state.participant import Participant
from qiskit import QuantumCircuit
## The Sender entity in the Six-State implementation
## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html
class Sender(Participant):
## Constructor
def __init__(self, name='', original_bits_size=0):
super().__init__(name, original_bits_size)
## Encode the message (values) using a quantum circuit
def encode_quantum_message(self):
encoded_message = []
for i in range(len(self.axes)):
qc = QuantumCircuit(1, 1)
if self.values[i] == 1:
qc.x(0)
if self.axes[i] == 1:
qc.h(0)
elif self.axes[i] == 2:
qc.append(self.hy, [0])
encoded_message.append(qc)
return encoded_message
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito, Andrea Hernández Martín
from qiskit import QuantumCircuit
from crypto.six_state.sender import Sender
from crypto.six_state.receiver import Receiver
import binascii
SIX_STATE_SIMULATOR = 'SIX-STATE SIMULATOR'
## An implementation of the Six-State protocol
## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html
class SixStateAlgorithm:
## Generate a key for Alice and Bob
def __generate_key(self, backend, original_bits_size, verbose):
# Encoder Alice
alice = Sender('Alice', original_bits_size)
alice.set_values()
alice.set_axes()
message = alice.encode_quantum_message()
# Interceptor Eve
eve = Receiver('Eve', original_bits_size)
eve.set_axes()
message = eve.decode_quantum_message(message, self.measure_density, backend)
# Decoder Bob
bob = Receiver('Bob', original_bits_size)
bob.set_axes()
message = bob.decode_quantum_message(message, 1, backend)
# Alice - Bob Remove Garbage
alice_axes = alice.axes # Alice share her axes
bob_axes = bob.axes # Bob share his axes
# Delete the difference
alice.remove_garbage(bob_axes)
bob.remove_garbage(alice_axes)
# Bob share some values of the key to check
SHARED_SIZE = round(0.5 * len(bob.key))
shared_key = bob.key[:SHARED_SIZE]
if verbose:
alice.show_values()
alice.show_axes()
eve.show_values()
eve.show_axes()
bob.show_values()
bob.show_axes()
alice.show_key()
bob.show_key()
print('\nShared Bob Key:')
print(shared_key)
# Alice check the shared key
if alice.check_key(shared_key):
shared_size = len(shared_key)
alice.confirm_key(shared_size)
bob.confirm_key(shared_size)
if verbose:
print('\nFinal Keys')
alice.show_key()
bob.show_key()
print('\nSecure Communication!')
elif verbose:
print('\nUnsecure Communication! Eve has been detected intercepting messages\n')
return alice, bob
## Run the implementation of Six-State protocol
def run(self, message, backend, original_bits_size, measure_density, n_bits, verbose):
## The original size of the message
self.original_bits_size = original_bits_size
## The probability of an interception occurring
self.measure_density = measure_density
alice, bob = self.__generate_key(backend, original_bits_size, verbose)
if not (alice.is_safe_key and bob.is_safe_key):
if verbose:
print('❌ Message not send')
return False
alice.generate_otp(n_bits)
bob.generate_otp(n_bits)
encoded_message = alice.xor_otp_message(message)
decoded_message = bob.xor_otp_message(encoded_message)
if verbose:
alice.show_otp()
bob.show_otp()
print('\nInitial Message:')
print(message)
print('Encoded Message:')
print(encoded_message)
print('💡 Decoded Message:')
print(decoded_message)
if message == decoded_message:
print('\n✅ The initial message and the decoded message are identical')
else:
print('\n❌ The initial message and the decoded message are different')
return True
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
from qiskit import transpile, Aer
from qiskit.providers.ibmq import IBMQFactory
from qiskit.utils import QuantumInstance
from qiskit.test.mock import FakeProvider
## The component that manages the execution of quantum algorithms for QuantumSolver
class QExecute:
## Constructor
def __init__(self, token: str = ''):
## The IBMQ Experience token
self.token = token
## The fake backends provider
self.provider_fake = FakeProvider()
## The available backends
self.backends = [
Aer.get_backend('aer_simulator')
]
fake_backends = [
'fake_armonk',
'fake_tenerife',
'fake_casablanca',
'fake_melbourne',
'fake_guadalupe',
'fake_tokyo',
'fake_paris',
'fake_cambridge',
'fake_rochester',
'fake_brooklyn'
]
for fake_backend in fake_backends:
self.backends.append(self.provider_fake.get_backend(fake_backend))
if self.token:
## The IBMQ provider
self.provider = IBMQFactory().enable_account(self.token)
self.backends += self.provider.backends()
## The current backend
self.current_backend = None
## Current backend setter
def set_current_backend(self, backend_name: str):
if backend_name == 'aer_simulator':
self.current_backend = self.backends[0]
elif backend_name[0:5] == 'fake_':
self.current_backend = self.provider_fake.get_backend(backend_name)
elif self.provider:
self.current_backend = self.provider.get_backend(backend_name)
## Check if the guest mode is activated
def is_guest_mode(self):
return self.token == ''
## Print the available backends
def print_avaiable_backends(self):
print('\nAvaliable backends:')
for i in range(len(self.backends)):
backend = self.backends[i]
status = backend.status()
config = backend.configuration()
jobs_in_queue = status.pending_jobs
q_instance = QuantumInstance(backend)
is_simulator = q_instance.is_simulator or str(backend)[0:5] == 'fake_'
is_operational = status.operational
print('[' + str(i + 1) + ']\tName:', str(backend), \
'\n\tNumber of qubits:', str(config.n_qubits) + \
'\n\tMaximum shots:', str(config.max_shots) + \
'\n\tJobs in queue:', str(jobs_in_queue))
print('\tIs ' + ('' if is_simulator else 'NOT ') + 'a simulator')
if is_operational:
print('\t✅ Is operational')
else:
print('\t❌ Is NOT operational')
print()
## Backend selection menu
def select_backend(self):
range_backends = '[1 - ' + str(len(self.backends)) + ']'
index = -2
while index < 0 or index >= len(self.backends):
msg = '[&] Select a backend of the list ' + str(range_backends) + ': '
index = int(input(msg)) - 1
if index == -1:
self.current_backend = None
print('[$] Backend not selected')
return
if index < 0 or index >= len(self.backends) or \
not self.backends[index].status().operational:
index = -1
print('[!] The backend must be one of the list', range_backends, \
'and must be operational')
else:
self.current_backend = self.backends[index]
print('[$]', str(self.current_backend), 'selected')
## Run the circuit using the current backend
def run(self, circuit: 'QuantumCircuit', n_shots: int):
# Compile the circuit down to low-level QASM instructions
# supported by the backend
compiled_circuit = transpile(circuit, self.current_backend)
# Execute the circuit on the current backend
job = self.current_backend.run(compiled_circuit, shots=n_shots)
# Return the counts from the job results
return job.result().get_counts(compiled_circuit)
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
'''
Quantum Phase Estimation
By Abdulah Amer
T gate leaves |0> state alone and adds a phase of e^pi/4 to
|1> state. Quantum Phase Estimation measures theta where
T|1> = e^2ipitheta|1>
First n-1 qubits are used for the protocol and get measured
the nth qubit is put into the eigenstate of the operator whose phase
we are measuring this is important
'''
from qiskit import *
import numpy as np
from math import *
from qiskit.visualization import plot_histogram
import matplotlib.pyplot as plt
from fractions import Fraction
S_simulator=Aer.backends(name='statevector_simulator')[0]
M_simulator=Aer.backends(name='qasm_simulator')[0]
# # a circuit with 4 qubits and 3 classical bits
#
# n=4 #number of qubits
# m=3 #number of classical bits
#
# # a circuit with n qubits and m classical
# qc=QuantumCircuit(n,m)
#
# qc.x(3)
#
# for qubit in range(3):
# qc.h(qubit)
#
# #Now estimate phase for T gate with phase of pi/4
# # apply the T gate a bunch of times
#
# reps=1
# for counting_qubit in range(3):
# for i in range(reps):
# #applies T gate using the counting qubits as control
# #qubits and the last qubit as the target qubit.
# #
# qc.cu1(pi/4, counting_qubit, 3)
#
# reps *=2 #doubles the number of T gates to each adjacent qubit
#
#
# qc.draw(output='mpl')
#
#
# #Do the inverse qft to find the state
#
def qft_inverse(qc,n):
for qubit in range(n//2): #floor division for odd number of qubits
qc.swap(qubit, n-qubit-1)
#swaps the current qubit with n-qubit-1
for j in range(n):
for m in range(j):
qc.cu1(-pi/float(2**(j-m)),m,j)
qc.h(j)
#
#
# qc.barrier()
#
# qft_inverse(qc,3)
#
# qc.barrier()
#
# for n in range(3):
# qc.measure(n,n)
#
#
# #qc.draw(output='mpl')
#
#lol
#
#
# results=execute(qc,backend=M_simulator, shots=4096).result()
# histogram=results.get_counts()
#
# plot_histogram(histogram)
# After measurement we divide the decimal equivalent by 2^n
# 1/2^3 =1/8 , theta =1/8, therefore e^2ipitheta = e^ipi/4
#Which is the phase added by the T gate.
#This was a pretty trivial result since we perfectly get
#one highest probability
#make functions to generalize even better
# def prepQPE(qc, n,m): #prepares the circuit
# for qubit in range(m):
# qc.h(qubit)
#
# qc.x(m)
#
#
# def CU(theta, qc, n,m): #performs controlled unitary operations
#
# prepQPE(qc,n,m)
#
# angle=theta
# reps=1
# for counting_qubit in range(m):
# for i in range(reps):
# qc.cu1(angle, counting_qubit,5)
# reps*=2
#
#Let us also Automate more of the process so we can scale these things
#To learn even more from them
'''
Note we are making circuits to measure known thetas
But we will try to build up to design a circuit to do
Arbitrary Phase Estimation
'''
#Makes an isntance of a quantum circuit that runs the QPE protocol
def makeQPE(theta, n): #m=n-1
m=n-1
qc=QuantumCircuit(n,m)
#Prep
for qubit in range(m):
qc.h(qubit)
qc.x(m)
#CU1 gates
reps=1
for counting_qubit in range(m):
for i in range(reps):
qc.cu1(theta, counting_qubit, m)
reps*=2
qc.barrier()
qft_inverse(qc,m)
qc.barrier()
for n in range(m):
qc.measure(n,n)
return qc
#gets out results and aquires the one with the most hits
def get_results(q,n):
m=n-1
results=execute(q, backend=M_simulator).result()
histo=results.get_counts()
higher=0
hits=histo.values()
for i in hits:
if i>higher:
higher=i
newhisto=dict([(value,key) for key, value in histo.items()])
answer=int(newhisto[higher],2)
check=(answer/(2**m))
return check
#simple finding error function
def error(expected, actual):
expected_minus_actual=abs(expected-actual)
percent_error=expected_minus_actual/100
return percent_error
#tie it all together
def graph_qubits_error(piece_of_pi, qubits):
#set up
angle=pi*piece_of_pi
expected=(piece_of_pi/2)
qubits=[]
results=[]
errors=[]
n=2
while n<=qubits:
#make circuit and measure
q=makeQPE(angle,n)
actual=get_results(q,n)
#our error
err=error(expected, actual)
#Dont forget how to graph
qubits.append(n)
results.append(actual)
errors.append(err)
n+=1
#Plotting##########
# plt.figure(1)
# plt.title('Value vs qubits used')
# plt.plot(qubits,results, color='green', label='Experimental Result')
# plt.hlines(expected,2,16, color='blue', linestyles='dashed', label=' Expected Value')
# plt.xlabel('Number of Qubits')
# plt.ylabel('Result of Measurement')
#
#
# plt.figure(2)
# plt.title('Error vs qubits used')
# plt.plot(qubits, errors)
# plt.xlabel('Number of Qubits')
# plt.ylabel('Percent Error')
# plt.show()
piece_of_pi=1/2
qubits=8
#graph_qubits_error(piece_of_pi,qubits)
def error_per_slice(piece_of_pi, qubits):
angle=pi*piece_of_pi
expected=(piece_of_pi/2)
q=makeQPE(angle,qubits)
actual=get_results(q,qubits)
err=error(expected, actual)
return err
def yeet():
slices=[]
list_of_errors=[]
qubits=5
i=1
while i<=16:
piece_of_pi=1/i
slices.append(piece_of_pi)
list_of_errors.append(error_per_slice(piece_of_pi, qubits))
i+=1
title= ('Error for different slices of pi using '+ str(qubits)+ ' qubits')
plt.title(title)
plt.plot(slices,list_of_errors, color='green')
#plt.hlines(expected,2,16, color='blue', linestyles='dashed', label=' Expected Value')
plt.xlabel('Slices')
plt.ylabel('Error in measurement')
#plt.show()
return list_of_errors
def get_slices():
slices=[]
i=1
while i<=16:
piece_of_pi=1/i
slices.append(piece_of_pi)
i+=1
return slices
'''
some stuff to look at the fractions
'''
def frac_stuff(slices):
integers=[]
for i in range(len(slices)):
two_to_the_n=2**(qubits-1)
it_theta=slices[i]
integers.append(two_to_the_n*it_theta)
fracslices=[]
for i in range(len(slices)+1):
piece='1/' + str(i)
fracslices.append(piece)
#gets rid of the 1/0 at the front of the list
fracslices.pop(0)
#inserts a 1 instead of 1/1 in our list
fracslices.insert(0,1)
#gets ride of 1/1
fracslices.pop(1)
'''
Make a Table!
'''
Dabois=yeet()
header=['2^n*', 'Slice']
head1='2^n*'+ 'Theta'
head2='Slice'
head3='Error amounts'
col1=integers
col2=fracslices
col3=Dabois
from tabulate import tabulate
table=tabulate({head2: col2, head1: col1, head3:col3}, headers='keys', tablefmt='github')
for i in range(len(col1)):
print(col2[i], '&' , round(col1[i],5), '&', round(col3[i],5))
return table
#print(table)
from qiskit.visualization import plot_bloch_vector
'''
The following code is execute in Jupyter notebooks file called QPE final
It gives us images Rx and Ry respectively
#Rx
q=QuantumRegister(1, 'l')
blocher=QuantumCircuit(q)
blocher.ry(pi/2,0)
bloch_job=execute(blocher, S_simulator).result()
plot_bloch_multivector(bloch_job.get_statevector(blocher), title='initial')
#Ry
blocher=QuantumCircuit(q)
blocher.ry(pi/2,0)
blocher.u1(pi/2,0)
bloch_job=execute(blocher, S_simulator).result()
plot_bloch_multivector(bloch_job.get_statevector(blocher), title='final')
'''
piece_of_pi=1/4
qubits=3
q=makeQPE(piece_of_pi,qubits)
#q.draw(output='mpl').savefig('The Circuit is Here.png')
print(frac_stuff(get_slices()))
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
"""The following is python code utilizing the qiskit library that can be run on extant quantum
hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding,
for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find
r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1,
results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>).
To find the factor, use the equivalence a^r mod 15. From this:
(a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r
values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15
Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients,
gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15,
so the result of running shors algorithm to find the prime factors of an integer using quantum
hardware are demonstrated. Note, this is not the same as the technical implementation of shor's
algorithm described in this section for breaking the discrete log hardness assumption,
though the proof of concept remains."""
# Import libraries
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from numpy import pi
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.visualization import plot_histogram
# Initialize qubit registers
qreg_q = QuantumRegister(5, 'q')
creg_c = ClassicalRegister(5, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
circuit.reset(qreg_q[0])
circuit.reset(qreg_q[1])
circuit.reset(qreg_q[2])
circuit.reset(qreg_q[3])
circuit.reset(qreg_q[4])
# Apply Hadamard transformations to qubit registers
circuit.h(qreg_q[0])
circuit.h(qreg_q[1])
circuit.h(qreg_q[2])
# Apply first QFT, modular exponentiation, and another QFT
circuit.h(qreg_q[1])
circuit.cx(qreg_q[2], qreg_q[3])
circuit.crx(pi/2, qreg_q[0], qreg_q[1])
circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4])
circuit.h(qreg_q[0])
circuit.rx(pi/2, qreg_q[2])
circuit.crx(pi/2, qreg_q[1], qreg_q[2])
circuit.crx(pi/2, qreg_q[1], qreg_q[2])
circuit.cx(qreg_q[0], qreg_q[1])
# Measure the qubit registers 0-2
circuit.measure(qreg_q[2], creg_c[2])
circuit.measure(qreg_q[1], creg_c[1])
circuit.measure(qreg_q[0], creg_c[0])
# Get least busy quantum hardware backend to run on
provider = IBMQ.load_account()
device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and
not x.configuration().simulator and x.status().operational==True))
print("Running on current least busy device: ", device)
# Run the circuit on available quantum hardware and plot histogram
from qiskit.tools.monitor import job_monitor
job = execute(circuit, backend=device, shots=1024, optimization_level=3)
job_monitor(job, interval = 2)
results = job.result()
answer = results.get_counts(circuit)
plot_histogram(answer)
#largest amplitude results correspond with r values used to find the prime factor of N.
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
"""Qiskit code for running Simon's algorithm on quantum hardware for 2 qubits and b = '11' """
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, execute
# import basic plot tools
from qiskit.visualization import plot_histogram
from qiskit_textbook.tools import simon_oracle
#set b equal to '11'
b = '11'
#1) initialize qubits
n = 2
simon_circuit_2 = QuantumCircuit(n*2, n)
#2) Apply Hadamard gates before querying the oracle
simon_circuit_2.h(range(n))
#3) Query oracle
simon_circuit_2 += simon_oracle(b)
#5) Apply Hadamard gates to the input register
simon_circuit_2.h(range(n))
#3) and 6) Measure qubits
simon_circuit_2.measure(range(n), range(n))
# Load saved IBMQ accounts and get the least busy backend device
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= n and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Execute and monitor the job
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(simon_circuit_2, backend=backend, shots=shots, optimization_level=3)
job_monitor(job, interval = 2)
# Get results and plot counts
device_counts = job.result().get_counts()
plot_histogram(device_counts)
#additionally, function for calculating dot product of results
def bdotz(b, z):
accum = 0
for i in range(len(b)):
accum += int(b[i]) * int(z[i])
return (accum % 2)
print('b = ' + b)
for z in device_counts:
print( '{}.{} = {} (mod 2) ({:.1f}%)'.format(b, z, bdotz(b,z), device_counts[z]*100/shots))
#the most significant results are those for which b dot z=0(mod 2).
'''b = 11
11.00 = 0 (mod 2) (45.0%)
11.01 = 1 (mod 2) (6.2%)
11.10 = 1 (mod 2) (6.4%)
11.11 = 0 (mod 2) (42.4%)'''
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
import unittest
import sys
import os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/../src')
from bb84.participant import Participant
from bb84.sender import Sender
from bb84.receiver import Receiver
from qiskit import Aer
ALICE = 'Alice'
BOB = 'Bob'
EXAMPLE_LIST_1 = [1, 0, 0, 1, 0, 1, 1]
EXAMPLE_LIST_2 = [1, 1, 0, 0, 0, 1, 0]
ORIGINAL_BITS_SIZE = len(EXAMPLE_LIST_1)
INDEX_SHARED_KEY = 2
def is_lambda(x):
return callable(x) and x.__name__ == '<lambda>'
class BB84EntitiesTests(unittest.TestCase):
def setUp(self):
self.sender = Sender(ALICE, ORIGINAL_BITS_SIZE)
self.receiver = Receiver(BOB, ORIGINAL_BITS_SIZE)
@unittest.expectedFailure
def test_participant(self):
_ = Participant('Participant', ORIGINAL_BITS_SIZE)
def test_name(self):
self.assertEqual(self.sender.name, ALICE)
self.assertEqual(self.receiver.name, BOB)
def test_original_bits_size(self):
self.assertEqual(self.sender.original_bits_size, ORIGINAL_BITS_SIZE)
self.assertEqual(self.receiver.original_bits_size, ORIGINAL_BITS_SIZE)
def test_setter_values(self):
self.sender.set_values(EXAMPLE_LIST_1)
self.receiver.set_values(EXAMPLE_LIST_1)
self.assertEqual(self.sender.values, EXAMPLE_LIST_1)
self.assertEqual(self.receiver.values, EXAMPLE_LIST_1)
def test_set_random_values(self):
self.sender.set_values()
self.receiver.set_values()
self.assertTrue(isinstance(self.sender.values, list) and \
len(self.sender.values) == ORIGINAL_BITS_SIZE)
self.assertTrue(isinstance(self.receiver.values, list) and \
len(self.receiver.values) == ORIGINAL_BITS_SIZE)
def test_show_values(self):
self.assertTrue(self.sender.show_values is not None)
self.assertTrue(self.receiver.show_values is not None)
def test_setter_axes(self):
self.sender.set_axes(EXAMPLE_LIST_1)
self.receiver.set_axes(EXAMPLE_LIST_1)
self.assertEqual(self.sender.axes, EXAMPLE_LIST_1)
self.assertEqual(self.receiver.axes, EXAMPLE_LIST_1)
def test_set_random_axes(self):
self.sender.set_axes()
self.receiver.set_axes()
self.assertTrue(isinstance(self.sender.axes, list) and \
len(self.sender.axes) == ORIGINAL_BITS_SIZE)
self.assertTrue(isinstance(self.receiver.axes, list) and \
len(self.receiver.axes) == ORIGINAL_BITS_SIZE)
def test_show_axes(self):
self.assertTrue(self.sender.show_axes is not None)
self.assertTrue(self.receiver.show_axes is not None)
def test_remove_garbage(self):
self.sender.set_values(EXAMPLE_LIST_1)
self.receiver.set_values(EXAMPLE_LIST_2)
self.sender.set_axes(EXAMPLE_LIST_1)
self.receiver.set_axes(EXAMPLE_LIST_2)
self.sender.remove_garbage(EXAMPLE_LIST_2)
self.receiver.remove_garbage(EXAMPLE_LIST_1)
def test_check_key(self):
self.test_remove_garbage()
shared_key = self.receiver.key[:INDEX_SHARED_KEY]
self.assertTrue(self.sender.check_key(shared_key))
def test_confirm_key(self):
self.test_check_key()
shared_key = self.receiver.key[:INDEX_SHARED_KEY]
self.sender.confirm_key(len(shared_key))
def test_is_safe_key(self):
self.test_confirm_key()
self.assertTrue(self.sender.is_safe_key)
def test_show_key(self):
self.test_is_safe_key()
self.assertTrue(self.sender.show_key is not None)
def test_generate_otp(self):
self.test_is_safe_key()
self.sender.generate_otp(ORIGINAL_BITS_SIZE)
self.assertTrue(isinstance(self.sender.otp, list))
def test_show_otp(self):
self.test_generate_otp()
self.assertTrue(self.sender.show_otp is not None)
def test_xor_otp_message(self):
self.test_generate_otp()
msg = 'qwertyuiopasdfghjklñzxcvbnm012345789QWERTYUIOPASDFGHJKLÑZXCVBNM,._-'
encoded_msg = self.sender.xor_otp_message(msg)
decoded_msg = self.sender.xor_otp_message(encoded_msg)
self.assertEqual(decoded_msg, msg)
def test_encode_quantum_message(self):
self.test_set_random_axes()
self.test_set_random_values()
self.msg = self.sender.encode_quantum_message()
for i, qc in enumerate(self.msg):
for gate in qc.data:
if gate[0].name == 'x':
self.assertTrue(self.sender.values[i] == 1)
if gate[0].name == 'h':
self.assertTrue(self.sender.axes[i] == 1)
def test_decode_quantum_message(self):
self.test_encode_quantum_message()
backend = Aer.get_backend('aer_simulator')
self.msg = self.receiver.decode_quantum_message(self.msg, 1, backend)
for i in self.receiver.axes:
if self.receiver.axes[i] == self.sender.axes[i]:
self.assertEqual(self.receiver.values[i], self.sender.values[i])
if __name__ == '__main__':
unittest.main()
|
https://github.com/stefan-woerner/qiskit_optimization_circuits
|
stefan-woerner
|
# useful additional packages
import matplotlib.pyplot as plt
import matplotlib.axes as axes
import numpy as np
import networkx as nx
from qiskit import Aer, execute, QuantumCircuit
from qiskit.quantum_info import Statevector
# auxilliary function to plot graphs
def plot_result(G, x):
colors = ['r' if x[i] == 0 else 'b' for i in range(n)]
pos, default_axes = nx.spring_layout(G), plt.axes(frameon=True)
nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, pos=pos)
# create graph
G = nx.Graph()
# add nodes
n = 5
G.add_nodes_from(range(n))
# add edges: tuple is (i,j,weight) where (i,j) is the edge
edges = [(0, 1, 1.0), (0, 2, 1.0), (0, 3, 1.0), (1, 2, 1.0), (2, 3, 1.0), (2, 4, 1.0), (3, 4, 1.0)]
G.add_weighted_edges_from(edges)
# plot graph
plot_result(G, [0]*n)
from docplex.mp.model import Model
mdl = Model('MaxCut')
x = mdl.binary_var_list('x{}'.format(i) for i in range(n))
objective = mdl.sum([ w * (x[i] + x[j] - 2*x[i]*x[j]) for (i, j, w) in edges])
mdl.maximize(objective)
mdl.prettyprint()
b = 2
mdl.add_constraint(mdl.sum(x) == b)
mdl.prettyprint()
from qiskit.optimization import QuadraticProgram
from qiskit.optimization.algorithms import CplexOptimizer
# convert from DOcplex model to Qiskit Quadratic Program
qp = QuadraticProgram()
qp.from_docplex(mdl)
# Solve Quadratic Program using CPLEX
cplex = CplexOptimizer()
result = cplex.solve(qp)
print(result)
plot_result(G, result.x)
from qiskit.optimization.converters import (
InequalityToEquality, # converts inequality constraints to equality constraints by adding slack variables
LinearEqualityToPenalty, # converts linear equality constraints to quadratic penalty terms
IntegerToBinary, # converts integer variables to binary variables
QuadraticProgramToQubo # combines the previous three converters
)
lineq2penalty = LinearEqualityToPenalty(penalty=1)
qp_wo_constr = lineq2penalty.convert(qp)
qp_wo_constr
# Solve converted Quadratic Program using CPLEX
result = cplex.solve(qp_wo_constr)
print(result)
plot_result(G, result.x)
H, offset = qp_wo_constr.to_ising()
print('offset =', offset)
print()
print('H =', H)
# print Ising Hamiltonian as matrix
H_matrix = np.real(H.to_matrix())
print('dim(H):', H_matrix.shape)
print(H_matrix)
# plot diagonal of matrix
opt_indices = list(np.where(H_matrix.diagonal() == min(H_matrix.diagonal())))[0]
plt.figure(figsize=(12, 5))
plt.bar(range(2**n), H_matrix.diagonal())
plt.bar(opt_indices, H_matrix.diagonal()[opt_indices], color='g')
plt.xticks(range(2**n), ['('+str(i)+') {0:05b}'.format(i) for i in range(2**n)], rotation=90, fontsize=14)
plt.yticks(fontsize=14)
plt.show()
from qiskit.circuit.library import RealAmplitudes
qc = RealAmplitudes(5, reps=1)
qc.draw(fold=120)
# run VQE
from qiskit.aqua.algorithms import VQE
vqe = VQE(H, qc, quantum_instance=Aer.get_backend('statevector_simulator'))
result = vqe.run()
print('optimal value:', np.round(result.eigenvalue, decimals=4))
# plot probabilities
probabilities = np.abs(result.eigenstate)**2
plt.figure(figsize=(12, 5))
plt.bar(range(2**n), probabilities)
plt.bar(opt_indices, probabilities[opt_indices], color='g')
plt.xticks(range(2**n), ['('+str(i)+') {0:05b}'.format(i) for i in range(2**n)], rotation=90, fontsize=14)
plt.yticks(fontsize=14)
plt.show()
from qiskit.circuit import Parameter
gamma, beta = Parameter('gamma'), Parameter('beta')
qc = QuantumCircuit(1)
qc.h(0)
qc.barrier()
qc.rz(gamma, 0)
qc.rx(beta, 0)
qc.barrier()
qc.draw()
def construct_schedule(T, N):
delta_t = T/N
gammas, betas = [], [] # H_C, H_X parameters
for i in range(N+1):
t = i * delta_t
gammas += [ 2 * delta_t * t/T ] # H_C
betas += [ -2 * delta_t * (1 - t/T) ] # H_X
return gammas, betas
T = 5
N = 10
gammas, betas = construct_schedule(T, N)
plt.figure(figsize=(10, 4))
plt.plot(np.linspace(0, T, N+1), gammas, label='gammas')
plt.plot(np.linspace(0, T, N+1), betas, label='betas')
plt.legend(fontsize=14)
plt.xticks(fontsize=14)
plt.xlabel('time', fontsize=14)
plt.yticks(fontsize=14)
plt.ylabel('parameters', fontsize=14);
# track probabilities during trotterized annealing
probabilities = np.zeros((2, N+1))
# construct circuit
qc = QuantumCircuit(1)
qc.h(0)
qc.barrier()
for i, (gamma, beta) in enumerate(zip(gammas, betas)):
qc.rz(gamma, 0)
qc.rx(beta, 0)
qc.barrier()
probabilities[:, i] = Statevector.from_instruction(qc).probabilities()
qc.draw()
plt.figure(figsize=(12, 7))
plt.plot(np.linspace(0, T, N+1), probabilities[1, :], 'gd-', label=r'$|1\rangle$')
plt.plot(np.linspace(0, T, N+1), probabilities[0, :], 'bo-', label=r'$|0\rangle$')
plt.legend(fontsize=14)
plt.xticks(fontsize=14)
plt.xlabel('time $t$', fontsize=14)
plt.yticks(fontsize=14)
plt.ylabel('probabilities', fontsize=14);
plt.figure(figsize=(12, 7))
plt.plot(np.linspace(0, T, N+1), probabilities[0, :] - probabilities[1, :], 'gd-')
plt.xticks(fontsize=14)
plt.xlabel('time $t$', fontsize=14)
plt.yticks(fontsize=14)
plt.ylabel('objective value', fontsize=14);
gamma = Parameter('gamma')
qc1 = QuantumCircuit(2)
qc1.cx(0, 1)
qc1.rz(gamma, 1)
qc1.cx(0, 1)
qc1.draw()
qc2 = QuantumCircuit(2)
qc2.rzz(gamma, 0, 1)
qc2.draw()
from qiskit.aqua.components.optimizers import COBYLA
# QAOA circuit for p = 1
gamma, beta = Parameter('gamma'), Parameter('beta')
qc = QuantumCircuit(1)
qc.h(0)
qc.rz(gamma, 0)
qc.rx(beta, 0)
def objective(params):
qc_ = qc.bind_parameters({gamma: params[0], beta: params[1]})
probs = Statevector.from_instruction(qc_).probabilities()
return probs @ [1, -1]
optimizer = COBYLA()
result = optimizer.optimize(num_vars=2, objective_function=objective, initial_point=[0.5, 0.5])
print('optimal params:', np.round(result[0], decimals=4))
print('optimal value: ', np.round(result[1], decimals=4))
print('optimal state: ', np.round(Statevector.from_instruction(qc.bind_parameters(
{gamma: result[0][0], beta: result[0][1]})).data, decimals=4))
from qiskit.aqua.algorithms.minimum_eigen_solvers.qaoa.var_form import QAOAVarForm
# construct parameters from annealing schedule
T = 10
N = 20
gammas, betas = construct_schedule(T, N)
# construct variational form
var_form = QAOAVarForm(H, N+1)
# evaluate circuit
qc = var_form.construct_circuit(gammas + betas)
sv = Statevector.from_instruction(qc)
# plot probabilities
probabilities = sv.probabilities()
plt.figure(figsize=(12, 5))
plt.bar(range(2**n), probabilities)
plt.bar(opt_indices, probabilities[opt_indices], color='g')
plt.xticks(range(2**n), ['('+str(i)+') {0:05b}'.format(i) for i in range(2**n)], rotation=90, fontsize=14)
plt.yticks(fontsize=14);
# illustrating the QAOA var form
p = 1
var_form = QAOAVarForm(H, p)
var_form.construct_circuit([gamma, beta]).draw()
from qiskit.aqua.algorithms import QAOA
qaoa_mes = QAOA(H, p=1, optimizer=optimizer, quantum_instance=Aer.get_backend('statevector_simulator'))
result = qaoa_mes.run()
print('optimal params: ', result.optimal_parameters)
print('optimal value: ', result.optimal_value)
print('optimal probability: ', sum(np.abs(result.eigenstate[opt_indices])**2))
# plot probabilities
probabilities = np.abs(result['eigenstate'])**2
plt.figure(figsize=(12, 5))
plt.bar(range(2**n), probabilities)
plt.bar(opt_indices, probabilities[opt_indices], color='g')
plt.xticks(range(2**n), ['('+str(i)+') {0:05b}'.format(i) for i in range(2**n)], rotation=90, fontsize=14)
plt.yticks(fontsize=14)
plt.show()
from qiskit.optimization.algorithms import MinimumEigenOptimizer
# construct QAOA as Minimum Eigensolver
qaoa_mes = QAOA(p=1, optimizer=optimizer, quantum_instance=Aer.get_backend('statevector_simulator'))
# construct Minimum Eigen Optimizer based on QAOA
qaoa = MinimumEigenOptimizer(qaoa_mes)
# solve Quadratic Program
result = qaoa.solve(qp)
print(result)
plot_result(G, result.x)
# converts two's complement bit string to corresponding integer
def twos_complement(val, num_bits):
val = int(val, 2)
if (val & (1 << (num_bits - 1))) != 0:
val = val - (1 << num_bits)
return val
print(twos_complement('0011', 4))
print(twos_complement('1011', 4))
from qiskit.circuit.library import QFT
def encode(num_qubits, k):
qc = QuantumCircuit(num_qubits, name='enc({})'.format(k))
for i in range(num_qubits):
theta = 2*np.pi * 2**i / 2**num_qubits * k
qc.rz(theta, i)
return qc
num_value_qubits = 4
qc = QuantumCircuit(num_value_qubits, num_value_qubits)
qc.h(range(num_value_qubits))
qc.barrier()
qc.extend(encode(num_value_qubits, 2))
qc.barrier()
qc.append(QFT(num_value_qubits, do_swaps=False).inverse(), qc.qubits)
qc.measure(qc.qregs[0], qc.cregs[0][::-1])
qc.draw(fold=120)
num_value_qubits = 4
qc = QuantumCircuit(num_value_qubits, num_value_qubits)
qc.h(range(num_value_qubits))
qc.barrier()
qc.extend(encode(num_value_qubits, 2))
# qc.extend(encode(num_value_qubits, -3))
# qc.extend(encode(num_value_qubits, 4))
qc.barrier()
qc.append(QFT(num_value_qubits, do_swaps=False, inverse=True), qc.qubits)
qc.measure(qc.qregs[0], qc.cregs[0][::-1])
qc.draw(fold=120)
counts = execute(qc, Aer.get_backend('qasm_simulator')).result().get_counts()
for key in counts:
print(key, ' -->', twos_complement(key, num_value_qubits))
num_input_qubits = 3
num_total_qubits = num_input_qubits + num_value_qubits
qc = QuantumCircuit(num_total_qubits)
qc.h([0, 1, 2])
qc.barrier()
qc.h(range(num_input_qubits, num_total_qubits))
qc.append(encode(num_value_qubits, 2).control(2), [0, 2] + list(range(num_input_qubits, num_total_qubits)))
qc.append(encode(num_value_qubits, -3).control(), [1] + list(range(num_input_qubits, num_total_qubits)))
qc.append(encode(num_value_qubits, 4).control(), [2] + list(range(num_input_qubits, num_total_qubits)))
qc.append(QFT(num_value_qubits, do_swaps=False).inverse(), range(num_input_qubits, num_total_qubits))
qc.measure_all()
qc.draw(fold=120)
counts = execute(qc, Aer.get_backend('qasm_simulator')).result().get_counts()
for key, value in counts.items():
x = key[num_value_qubits:]
y_bin = key[:num_value_qubits][::-1]
y_int = twos_complement(y_bin, num_value_qubits)
print(x, '-->', y_bin, '-->', y_int, '\t(counts: {})'.format(value))
from qiskit.circuit.library import QuadraticForm
# get quadratic / linear / constant part of quadratic program
A = qp_wo_constr.objective.quadratic.to_array()
b = qp_wo_constr.objective.linear.to_array()
c = qp_wo_constr.objective.constant
# set number of results qubits
num_value_qubits = 5
# construct circuit to evaluate quadratic form
qf = QuadraticForm(num_value_qubits, A, b, c)
qf.draw(fold=115)
qc = QuantumCircuit(n + num_value_qubits)
qc.h(range(n))
qc.append(qf, range(n + num_value_qubits))
qc.measure_all()
qc.draw()
counts = execute(qc, backend=Aer.get_backend('qasm_simulator')).result().get_counts()
for key, value in counts.items():
x_ = key[num_value_qubits:]
x = [0 if x__ == '0' else 1 for x__ in x_][::-1]
y_bin = key[:num_value_qubits]
y_int = twos_complement(y_bin, num_value_qubits)
qx = qp_wo_constr.objective.evaluate(x)
print('x =', x_, '\ty_bin =', y_bin, '\ty_int =', y_int, '\tQ(x) =', qx, '\t(counts: {})'.format(value))
qc = QuantumCircuit(n + num_value_qubits)
qc.append(qf, range(n + num_value_qubits)) # 1. compute Q(x)
qc.z(qc.qubits[-1]) # 2. multiply all |x>|Q(x)> by -1 where Q(x) < 0.
qc.append(qf.inverse(), range(n + num_value_qubits)) # 3. uncompute Q(x).
qc.draw(output='text', vertical_compression="high")
from qiskit.optimization.algorithms import GroverOptimizer
# set up Grover Optimizer
grover = GroverOptimizer(num_value_qubits=5, quantum_instance=Aer.get_backend('statevector_simulator'))
grover._qubo_converter.penalty = 1 # set to small value to reduce required number of value qubits
# solver problem
result = grover.solve(qp)
print(result)
plot_result(G, result.x)
|
https://github.com/Dirac231/BCHamming
|
Dirac231
|
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
def num_to_binary(n, N):
"""Returns the binary representation of n
Args:
n (int): The number to be represented in binary
N (int): The number of digits of the rapresentation
Returns:
bool: The binary representation of n
es: num_to_binary(5,4) = 0101
"""
Nbits=2**N
if n>=Nbits: return 0
return bin(n+2*Nbits)[4:]
def is_power_2(n):
"""Returns True if the number is a power of two"""
return n & (n-1) == 0
def HammingCircuit(N, classical_registers=False, name=None, ancillas=None):
"""It gives you a circuit with 2^N qbits of (message + redundancy)
Args:
N (int): Order of the Hamming cirucit
classical_registers (Bool, int): If True if gives an amount of classical registers equal to the number of qbits, if you want a specific number of classical registers just write the number you want. Defaults to False.
name (str): Name of the circuit. Defaults to None.
ancillas (int): Is the number of ancillas of the circuit. Defaults to zero.
Returns:
circuit: Returns a circuit with just the qbits labeled as the parity and signal
"""
if ancillas is None: ancillas = 2*N-1
registers=[]
for i in range(2**N):
prefix='s' #s stands for signal
if is_power_2(i): prefix='p' #c stands for parity
registers.append(QuantumRegister(1,prefix+num_to_binary(i, N)))
if classical_registers!=False:
if classical_registers==True: registers.append(ClassicalRegister(2**N + ancillas))
else: registers.append(ClassicalRegister(classical_registers))
if ancillas > 0: registers.append(QuantumRegister(ancillas))
circuit=QuantumCircuit(*registers) #circuit already with ancillas
circuit.N=N
if name is not None: circuit.name = name
return circuit
def Swapper(N):
"""Circuit that shifts the every qubit right by the number of
power-of-two qubits before it
Args:
N (int): Order of Hamming code
Returns:
gate: swapper
"""
qc = HammingCircuit(N, name="Swapper", ancillas=0)
source = 2**N - N - 2
target = 2**N - 1
while source >= 0:
if is_power_2(target):
target -= 1
qc.swap(source, target)
source -= 1
target -= 1
return qc.to_gate(label="Swapper")
def ReverseSwapper(N):
"""
Circuit that shifts the every qubit left by the number of
power-of-two qubits before it
"""
qc = HammingCircuit(N, ancillas=0)
source = 0
target = 0
while target < 2**N:
if is_power_2(target):
target += 1
continue
qc.swap(source, target)
source += 1
target += 1
return qc.to_gate(label="Reverse Swapper")
def Encoder(N):
"""Encoder for the quantum hamming code"""
qc = HammingCircuit(N, name="Encoder", ancillas=0)
for p in range(N):
p = 2**p
[qc.cx(i, p) for i in range(2**N) if (i & p) == p and i != p]
return qc.to_gate(label="Encoder")
def Hamming_bit_encoder(N, kind="bit", name="bit encoder"):
"""Creates quantum Hamming bit encoder circuit of order N
Args:
N (int): Order of the circuit
name (str, optional): Name of the circuit. Defaults to "bit encoder".
kind (str, optional): Set to "bit" for correcting bit flip errors,
"phase" for correcting phase flip errors.
Returns:
Gates: Quantum Hamming bit encoder circuit of order N
"""
qc = HammingCircuit(N, ancillas=0)
qc.append(Swapper(N), [*range(2**N)])
qc.append(Encoder(N), [*range(2**N)])
if kind=="phase":
qc.h([*range(2**N)])
return qc.to_gate(label=name)
def is_valid_input(kind):
"""Helper function that checks if kind="bit", "phase" or "both" and raises
an exeption if it isn't
"""
if kind not in ["bit", "phase", "both"]:
message = f"The kind argument must be one of bit, phase or both, received {kind} instead"
raise Exception(message)
return True
def HammingOrder(n):
"""Gives you the order of the Hamming gate as a function of n
Args:
n (int): lenght of the input message
Returns:
N (int): order of the Hamming gate
"""
for i in range(0,15):
N=2**i
if N-i-1>=n: return i
def syndrome(N):
"""This gate calculates the syndrome, this gives the position of the faulty qbit"""
circ=HammingCircuit(N, ancillas=N)
nqubits=2**N
for i in range(1,nqubits):
for j in range(0,N):
if i & 2**j == 2**j: circ.cx(i,nqubits+j)
return circ.to_gate(label='syndrome')
def apply_syndrome(N):
"""This gate that corrects the faulty qbit identified in the syndrome"""
circ=HammingCircuit(N, ancillas=N)
nqubits=2**N
count=np.zeros(N)
for i in range(1,nqubits):
count=count+1
for j in range(N):
count[j]=count[j]%(2**j)
if count[j]==0 and i!=1: circ.x(nqubits+j)
if i==1 and j!=0: circ.x(nqubits+j)
circ.mct([*range(nqubits,nqubits+N)],i)
return circ.to_gate(label='Correction')
def Hamming_bit_decoder(N,kind='bit',read=True,name='decoder'):
"""Hamming Gate resistant to bit-fips"""
circ=HammingCircuit(N, ancillas=N)
if kind=='phase':
circ.h([*range(2**N)])
circ.append(syndrome(N),[*range(2**N+N)])
circ.append(apply_syndrome(N),[*range(2**N+N)])
if read==True: circ.append(ReverseSwapper(N), [*range(2**N)])
return circ.to_gate(label=name)
def HammingSize(n, gate='decoder', kind='both'):
"""Gives you the number of qubits that must be present in the circuit
Args:
n (int): lenght of the input message
gate (str): It's either 'encoder' or 'decoder'
kind (str): The kind argument must be one of bit, phase or both
Returns:
n (int): Number of qubits required for the circuit
"""
is_valid_input(kind)
N=HammingOrder(n)
if gate=='encoder':
if kind=='both': return 2**(N+1)
return 2**N
if gate=='decoder':
if kind=='both': return 2**(N+1) + 2*N + 1
return 2**N + N
raise Exception('Gate not valid, the input must be either \'encoder\' or \'decoder\'')
# I don't know if these functions are still useful
def HammingRedundant(n):
"""Takes a integer "n" and makes the binary representation of that integer hamming redundant"""
bits=int(np.log2(n))+1
parity=int(np.log2(bits))+2
total=2**(parity-1)
N,j=0,0
#shift the digits in the correct positions for the hamming code
for i in range(total):
if i!=0 and int(np.log2(i))!=np.log2(i):
N=N+(n&(2**j)==2**j)*(2**i)
j=j+1
#puts the parity bit in place except for the global parity bit
for i in range(parity):
i=2**i
for j in range(i,total):
N=N^((2**i)*((j&i==i)&((N&2**j)!=0)))
#Global parity bit (yet to be tested)
#for i in range(1,total):N=N^((N&2**i)==1)
return N
def classic_input(n,N=None):
#n is the number in integer format, N is the size of the gate
#doesn't work and i
if N==None: N=int(np.log2(n))+1
if (n>=2**N): raise 'ma sei trimò'
registers=QuantumRegister(N)
circuit=QuantumCircuit(registers)
for i in range(N):
j=2**i
if (n&j)==j: circuit.x(i)
return circuit.to_gate(num_to_binary(n,N))
|
https://github.com/Dirac231/BCHamming
|
Dirac231
|
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister,QuantumCircuit, transpile, Aer
from qiskit import IBMQ, Aer
from qiskit.providers.aer import QasmSimulator
from qiskit.providers.aer.noise import NoiseModel
from Hamming import *
import qiskit
%matplotlib inline
from random import randint
# Create a hamming circuit
N = 3
enc=HammingEncode(N)
dec=HammingDecode(N,read=True)
circuit = QuantumCircuit(dec.size,dec.size)
# Create a input
circuit.h(0)
circuit.cx(0,1)
circuit.x(1)
circuit.cx(0,2)
# Add the encoder to the circuit
circuit.append(enc, range(enc.size))
# Add errors
circuit.y(4)
# Add the decoder to the circuit
circuit.append(dec,range(dec.size))
# Measure the qubits
circuit.measure(list(range(N)),list(range(N)))
circuit.draw(output='mpl')
# Simulate the circuit
simulator = Aer.get_backend("qasm_simulator")
result = qiskit.execute(circuit, backend = simulator, shots=1000).result()
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
|
https://github.com/Dirac231/BCHamming
|
Dirac231
|
from qiskit import *
from unireedsolomon import *
from matplotlib import *
from math import *
from collections import defaultdict
import numpy as np
from numpy.polynomial import Polynomial
from qiskit.providers.aer import AerSimulator
from qiskit.circuit.library import QFT
from qiskit.visualization import plot_histogram
from qiskit.providers.aer.noise import NoiseModel
#NOISE MODULE
#Needed in order to load the ibm-mps simulator for an optimal simulation
provider = IBMQ.load_account()
##the following adds the noise model that is based on ibmq_vigo
backend = provider.get_backend('ibmq_16_melbourne')
noise_model = NoiseModel.from_backend(backend) #noise model from real machines
##The following adds custom noise model to the circuit
# Error probabilities
#prob_1 = 0.001 # x error
#prob_2 = 0.01 # depolarizing error
# Depolarizing quantum errors
#error_1 = noise.depolarizing_error(prob_1, 1)
#error_2 = noise.depolarizing_error(prob_2, 2)
#error_1 = NoiseModel.depolarizing_error(prob_1, 1)
#error_2 = NoiseModel.depolarizing_error(prob_2, 2)
# Get basis gates from noise model
basis_gates = noise_model.basis_gates
basis_gates = ['cx', 'id', 'u1', 'sx', 'x']
#--------------------------------------------------------------------------------------
#PARAMETERS SETUP
#Parameters of the classical code used to generate the optimal quantum code.
#The code is built so that everything is a function of k_cl, the order of the finite field.
#The initial state is read from the file states.txt
def init_decoder():
global initial_state, k_cl, delta, K, ENC, encode_reg, ecc, shots, fourier, inv_fourier,provider
provider = IBMQ.load_account()
initial_state = np.loadtxt('states.txt')
k_cl = len(initial_state) #Order of the finite field in terms of powers of 2, corresponds to the amount of qbits sent
delta = floor((2**k_cl-1)/2+2) #Classical optimal minimum distance of the code
K = (2**k_cl) - delta #Number of classical bits sent, directly related to the error-correcting capability of the code ecc = floor((K+1)/2)
ENC = k_cl*(2**k_cl - 1) #Total encoding Qbits needed
encode_reg = QuantumRegister(ENC+2*k_cl*K) #Quantum Register used to construct the full circuit
ecc = floor((K+1)/2) #Maximum error correction capability per symbol
shots = 100
#Initialization of the parameters is completed
print("")
print("Reading from file: found ",k_cl," Qbits: \n")
print("Parameters of the code: ")
print("-------------------------------------------")
print("Encoding Qbits: ", ENC)
print("Sent Qbits: ", k_cl*(2**k_cl-1-2*K))
print("Maximum error-correcting: ", ecc, "/Symbol = ", ecc*k_cl, "/Encoded Qbit")
print("-------------------------------------------")
#--------------------------------------------------------------------------------------
#QTF IMPLEMENTATION
#A quantum fourier transform is used both for encoding and decoding purposes
fourier = QFT(num_qubits=ENC, approximation_degree=0, do_swaps=True, inverse=False, insert_barriers=False, name='qft')
inv_fourier = QFT(num_qubits=ENC, approximation_degree=0, do_swaps=True, inverse=True, insert_barriers=False, name='qft-inverse')
#-----------------------------------------------------------------------------------
#SIMULATES THE CIRCUIT
def simulate(qc):
"""Simulates the circuit using the cloud-computing services of IBMq, this is always the recommended choice to run simulations"""
provider = IBMQ.get_provider(hub='ibm-q')
backend=provider.get_backend('simulator_mps')
result = execute(circ, backend,shots=shots,
basis_gates=basis_gates,
noise_model=noise_model).result() #add noise module
print('Simulation Success: {}'.format(result.success))
print("Time taken: {} sec".format(result.time_taken))
counts = result.get_counts(0)
return counts
#------------------------------------------------------------------------------------
#MEASURE FUNCTIONS
def measure_encoding(qc):
"""Measure the Qbits used in the encoding, i.e. if the lenght is 3, the first 21 Qbits"""
cr = ClassicalRegister(ENC, 'encoded')
qc.add_register(cr)
for i in range(0, ENC):
qc.measure(i,cr[i])
results = simulate(qc)
encoded = max(results, key=results.get)
return encoded
def get_qbits(qc):
"""Measure the Qbits with the message, i.e. if the lenght is 3, the first 3 Qbits"""
cr = ClassicalRegister(k_cl*(2**k_cl-1-2*K), 'out')
qc.add_register(cr)
for i in range(0,k_cl):
qc.measure(i, cr[i])
for i in range(k_cl*(K + 1), ENC-k_cl*K):
qc.measure(i, cr[i])
results = simulate(qc)
qbits = max(results, key=results.get)
return qbits,results
def get_syndrome(qc):
"""Measure the Qbits with the syndrome, i.e. if the lenght is 3, the last 18 Qbits"""
cr = ClassicalRegister(2*k_cl*K)
qc.add_register(cr)
for i in range(0, 2*k_cl*K):
qc.measure(ENC+i,cr[i])
#orders the syndromes in descending order in term of the occurrences
ordered_res = {k: v for k, v in sorted(simulate(qc).items(), key=lambda item: item[1])}
syndromes = list(ordered_res)[::-1]
return syndromes
#------------------------------------------------------------------------------------
#GIVEN THE CLASSICAL SYNDROME, RETURNS THE POSITIONS OF THE ERRORS USING CLASSICAL BERLEKAMP-MASSEY
#Performs a Berlekamp-Massey algorithm in order to find the error locator polynomial relative to the syndrome#
def error_string(classical_syn):
k1 = int(ENC/k_cl)
k2 = int(((ENC-K*k_cl)/k_cl))
prime = int(hex(find_prime_polynomials(c_exp=k_cl,single=True)),16)
coder = rs.RSCoder(k1, k2, prim=prime,c_exp=k_cl)
error_bf, sigma_bf = coder._berlekamp_massey_fast(coder._list2gfpoly(str(classical_syn)))
eval_tmp_bf, bf = coder._chien_search_faster(error_bf)
Y = coder._forney(sigma_bf, eval_tmp_bf)
Elist = []
if(classical_syn != "0"*k_cl):
if len(Y) >= len(bf):
for i in range(coder.gf2_charac):
if i in bf:
Elist.append(Y[bf.index(i)])
E = Polynomial( Elist[::-1])
error_bits = [bin(int(i))[2:] for i in Elist]
s = ""
for i in range(len(error_bits)):
s += error_bits[i]
s = s[::-1]
return s
else:
return ""
def error_locator(syn):
"""take the syndrome computed by the quantum circuit and apply error_string"""
for x in syn:
BFsyndrome = oct(int((x[::-1])[:k_cl*K],2))[2:] #bit flip syndrome string
PFsyndrome = oct(int((x[::-1])[k_cl*K:],2))[2:] #phase flip syndrome string
#Performs the error locator finding for each measured syndrome, if a error occurs, it computes the errors associated with the next most probable syndrome
try: #uses functions in the unireedsolomon library to compute the error locations bf, pf
bf = error_string(BFsyndrome)
pf = error_string(PFsyndrome)
return bf,pf,x
except (RSCodecError,ValueError):
continue
print("No valid syndrome was found, too many errors try increasing the number of shots.")
exit()
#------------------------------------------------------------------------------------
"""ENCODING: takes a message and return the circuit that encodes it"""
def encoder(initial_state):
"""Takes a message and return the circuit that encodes it"""
qc = QuantumCircuit(encode_reg)
for i in range(0,k_cl):
qc.initialize(initial_state[i], i)
for i in range(k_cl*(K + 1), ENC-k_cl*K):
qc.initialize(initial_state[i], i)
for i in range(ENC - k_cl*K,ENC):
qc.h(i)
qc.append(inv_fourier, encode_reg[:ENC])
return qc
#CIRCUIT TO COMPUTE THE SYNDROME
def decoder(qc):
"""Takes the ecoding circuit, computes the syndrome and corrects the message"""
qc.append(fourier, encode_reg[:ENC])
for i in range(k_cl+1,k_cl*(K+1)+1):
qc.cx(i-1, i+ENC-k_cl-1)
for i in range(ENC -k_cl*K, ENC):
qc.h(i)
for i in range(ENC-k_cl*K-1,ENC-1):
qc.cx(i+1, i+ENC-k_cl+1)
for i in range(ENC -k_cl*K-1, ENC-1):
qc.h(i+1)
qc.append(inv_fourier, encode_reg[:ENC])
syn = get_syndrome(qc)
bf,pf,x = error_locator(syn)
if(bf != "1" or x[:k_cl*K] != "0"*k_cl*K):
for i in range(len(bf)):
if (bf[i] == "1"):
qc.x(i)
if (pf != "1" or x[k_cl*K:] != "0"*k_cl*K):
for i in range(ENC):
qc.h(i)
for i in range(len(pf)):
if (pf[i] == "1"):
qc.z(i)
for i in range(ENC):
qc.h(i)
qc.append(fourier, encode_reg[:ENC])
message,occurrences = get_qbits(qc)
occurrences = zip([x[:3][::-1] for x in occurrences.keys()] , list(occurrences.values()))
D = defaultdict(int)
for k,v in occurrences:
D[k]+= int(v)
occurrences = dict(D)
return qc,message,x,occurrences
#------------------------------------------------------------------------------------
def send_message(initial_state):
"""Auxiliary testing function, sends the message contained in the file states.txt and returns the simulation circuit."""
qc = encoder(initial_state) #Classical optimal minimum distance of the code
#INSERT ERRORS HERE: (such as qc.x(4) or z-errors)
qc,retrieved,syn,occurrences = decoder(qc)
plot_histogram(occurrences, color='midnightblue', title="Message occurrences").savefig("histogram.png")
print("Most probable message: ", retrieved[:3][::-1])
print("Occurrences: ", occurrences)
print("Compared with: ")
for i in initial_state:
print(i,"\n")
print("Syndrome was: ", syn[::-1])
qc.draw(output='mpl', filename='prova.png')
return qc
#------------------------------------------------------------------------------------
qc = send_message(initial_state)
|
https://github.com/Dirac231/BCHamming
|
Dirac231
|
from qiskit import *
from unireedsolomon import *
from matplotlib import *
from math import *
from collections import defaultdict
import numpy as np
from numpy.polynomial import Polynomial
from qiskit.providers.aer import AerSimulator
from qiskit.circuit.library import QFT
from qiskit.visualization import plot_histogram
#PARAMETERS SETUP
#Parameters of the classical code used to generate the optimal quantum code.
#The code is built so that everything is a function of k_cl, the order of the finite field.
#The initial state is read from the file states.txt
def init_decoder():
global initial_state, k_cl, delta, K, ENC, encode_reg, ecc, shots, fourier, inv_fourier,provider
provider = IBMQ.load_account()
initial_state = np.loadtxt('states.txt')
k_cl = len(initial_state) #Order of the finite field in terms of powers of 2, corresponds to the amount of qbits sent
delta = floor((2**k_cl-1)/2+2) #Classical optimal minimum distance of the code
K = (2**k_cl) - delta #Number of classical bits sent, directly related to the error-correcting capability of the code ecc = floor((K+1)/2)
ENC = k_cl*(2**k_cl - 1) #Total encoding Qbits needed
encode_reg = QuantumRegister(ENC+2*k_cl*K) #Quantum Register used to construct the full circuit
ecc = floor((K+1)/2) #Maximum error correction capability per symbol
shots = 128
#Initialization of the parameters is completed
print("")
print("Reading from file: found ",k_cl," Qbits: \n")
print("Parameters of the code: ")
print("-------------------------------------------")
print("Encoding Qbits: ", ENC)
print("Sent Qbits: ", k_cl*(2**k_cl-1-2*K))
print("Maximum error-correcting: ", ecc, "/Symbol = ", ecc*k_cl, "/Encoded Qbit")
print("-------------------------------------------")
#--------------------------------------------------------------------------------------
#QTF IMPLEMENTATION
#A quantum fourier transform is used both for encoding and decoding purposes
fourier = QFT(num_qubits=ENC, approximation_degree=0, do_swaps=True, inverse=False, insert_barriers=False, name='qft')
inv_fourier = QFT(num_qubits=ENC, approximation_degree=0, do_swaps=True, inverse=True, insert_barriers=False, name='qft-inverse')
#-----------------------------------------------------------------------------------
#SIMULATES THE CIRCUIT
def simulate(qc):
"""Simulates the circuit using the cloud-computing services of IBMq, this is always the recommended choice to run simulations"""
provider = IBMQ.get_provider(hub='ibm-q')
backend=provider.get_backend('simulator_mps')
result = execute(qc, backend,shots=shots).result()
print('Simulation Success: {}'.format(result.success))
print("Time taken: {} sec".format(result.time_taken))
counts = result.get_counts(0)
return counts
#------------------------------------------------------------------------------------
#MEASURE FUNCTIONS
def measure_encoding(qc):
"""Measure the Qbits used in the encoding, i.e. if the lenght is 3, the first 21 Qbits"""
cr = ClassicalRegister(ENC, 'encoded')
qc.add_register(cr)
for i in range(0, ENC):
qc.measure(i,cr[i])
results = simulate(qc)
encoded = max(results, key=results.get)
return encoded
def get_qbits(qc):
"""Measure the Qbits with the message, i.e. if the lenght is 3, the first 3 Qbits"""
cr = ClassicalRegister(k_cl*(2**k_cl-1-2*K), 'out')
qc.add_register(cr)
for i in range(0,k_cl):
qc.measure(i, cr[i])
for i in range(k_cl*(K + 1), ENC-k_cl*K):
qc.measure(i, cr[i])
results = simulate(qc)
qbits = max(results, key=results.get)
return qbits,results
def get_syndrome(qc):
"""Measure the Qbits with the syndrome, i.e. if the lenght is 3, the last 18 Qbits"""
cr = ClassicalRegister(2*k_cl*K)
qc.add_register(cr)
for i in range(0, 2*k_cl*K):
qc.measure(ENC+i,cr[i])
#orders the syndromes in descending order in term of the occurrences
ordered_res = {k: v for k, v in sorted(simulate(qc).items(), key=lambda item: item[1])}
syndromes = list(ordered_res)[::-1]
return syndromes
#------------------------------------------------------------------------------------
#GIVEN THE CLASSICAL SYNDROME, RETURNS THE POSITIONS OF THE ERRORS USING CLASSICAL BERLEKAMP-MASSEY
#Performs a Berlekamp-Massey algorithm in order to find the error locator polynomial relative to the syndrome#
def error_string(classical_syn):
k1 = int(ENC/k_cl)
k2 = int(((ENC-K*k_cl)/k_cl))
prime = int(hex(find_prime_polynomials(c_exp=k_cl,single=True)),16)
coder = rs.RSCoder(k1, k2, prim=prime,c_exp=k_cl)
error_bf, sigma_bf = coder._berlekamp_massey_fast(coder._list2gfpoly(str(classical_syn)))
eval_tmp_bf, bf = coder._chien_search_faster(error_bf)
Y = coder._forney(sigma_bf, eval_tmp_bf)
Elist = []
if(classical_syn != "0"*k_cl):
if len(Y) >= len(bf):
for i in range(coder.gf2_charac):
if i in bf:
Elist.append(Y[bf.index(i)])
E = Polynomial( Elist[::-1])
error_bits = [bin(int(i))[2:] for i in Elist]
s = ""
for i in range(len(error_bits)):
s += error_bits[i]
s = s[::-1]
return s
else:
return ""
def error_locator(syn):
"""take the syndrome computed by the quantum circuit and apply error_string"""
for x in syn:
BFsyndrome = oct(int((x[::-1])[:k_cl*K],2))[2:] #bit flip syndrome string
PFsyndrome = oct(int((x[::-1])[k_cl*K:],2))[2:] #phase flip syndrome string
#Performs the error locator finding for each measured syndrome, if a error occurs, it computes the errors associated with the next most probable syndrome
try: #uses functions in the unireedsolomon library to compute the error locations bf, pf
bf = error_string(BFsyndrome)
pf = error_string(PFsyndrome)
return bf,pf,x
except (RSCodecError,ValueError):
continue
print("No valid syndrome was found, too many errors try increasing the number of shots.")
exit()
#------------------------------------------------------------------------------------
"""ENCODING: takes a message and return the circuit that encodes it"""
def encoder(initial_state):
"""Takes a message and return the circuit that encodes it"""
qc = QuantumCircuit(encode_reg)
for i in range(0,k_cl):
qc.initialize(initial_state[i], i)
for i in range(k_cl*(K + 1), ENC-k_cl*K):
qc.initialize(initial_state[i], i)
for i in range(ENC - k_cl*K,ENC):
qc.h(i)
qc.append(inv_fourier, encode_reg[:ENC])
return qc
#CIRCUIT TO COMPUTE THE SYNDROME
def decoder(qc):
"""Takes the ecoding circuit, computes the syndrome and corrects the message"""
qc.append(fourier, encode_reg[:ENC])
for i in range(k_cl+1,k_cl*(K+1)+1):
qc.cx(i-1, i+ENC-k_cl-1)
for i in range(ENC -k_cl*K, ENC):
qc.h(i)
for i in range(ENC-k_cl*K-1,ENC-1):
qc.cx(i+1, i+ENC-k_cl+1)
for i in range(ENC -k_cl*K-1, ENC-1):
qc.h(i+1)
qc.append(inv_fourier, encode_reg[:ENC])
syn = get_syndrome(qc)
bf,pf,x = error_locator(syn)
if(bf != "1" or x[:k_cl*K] != "0"*k_cl*K):
for i in range(len(bf)):
if (bf[i] == "1"):
qc.x(i)
if (pf != "1" or x[k_cl*K:] != "0"*k_cl*K):
for i in range(ENC):
qc.h(i)
for i in range(len(pf)):
if (pf[i] == "1"):
qc.z(i)
for i in range(ENC):
qc.h(i)
qc.append(fourier, encode_reg[:ENC])
message,occurrences = get_qbits(qc)
occurrences = zip([x[:3][::-1] for x in occurrences.keys()] , list(occurrences.values()))
D = defaultdict(int)
for k,v in occurrences:
D[k]+= int(v)
occurrences = dict(D)
return qc,message,x,occurrences
#------------------------------------------------------------------------------------
def send_message(initial_state):
"""Auxiliary testing function, sends the message contained in the file states.txt and returns the simulation circuit."""
qc = encoder(initial_state) #Classical optimal minimum distance of the code
#INSERT ERRORS HERE: (such as qc.x(4) or z-errors)
qc,retrieved,syn,occurrences = decoder(qc)
plot_histogram(occurrences, color='midnightblue', title="Message occurrences").savefig("histogram.png")
print("Most probable message: ", retrieved[:3][::-1])
print("Occurrences: ", occurrences)
print("Compared with: ")
for i in initial_state:
print(i,"\n")
print("Syndrome was: ", syn[::-1])
qc.draw(output='mpl', filename='prova.png')
return qc
#------------------------------------------------------------------------------------
|
https://github.com/rubenandrebarreiro/ibm-qiskit-quantum-explorers-2023-2024
|
rubenandrebarreiro
|
# build your code here
answer1 = [3]
# run this cell to submit your answer
# import the grader for the exercise 1 of the lab/badge 1
from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex1
# expected result type: List
grade_badge1_ex1(answer1)
# build your code here
answer2 = [1]
# eun this cell to submit your answer
# import the grader for the exercise 2 of the lab/badge 1
from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex2
# expected result type: List
grade_badge1_ex2(answer2)
# build your code here
answer3 = [4]
# run this cell to submit your answer
# import the grader for the exercise 3 of the lab/badge 1
from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex3
# expected result type: List
grade_badge1_ex3(answer3)
# build your code here
answer4 = [2]
# run this cell to submit your answer
# import the grader for the exercise 4 of the lab/badge 1
from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex4
# expected result type: List
grade_badge1_ex4(answer4)
# build your code here
answer5 = [2]
# run this cell to submit your answer
# import the grader for the exercise 5 of the lab/badge 1
from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex5
# expected result type: List
grade_badge1_ex5(answer5)
# build your code here
answer6 = [4]
# run this cell to submit your answer
# import the grader for the exercise 6 of the lab/badge 1
from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex6
# expected result type: List
grade_badge1_ex6(answer6)
# build your code here
answer7 = [2]
# run this cell to submit your answer
# import the grader for the exercise 7 of the lab/badge 1
from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex7
# expected result type: List
grade_badge1_ex7(answer7)
# build your code here
answer8 = [4]
# run this cell to submit your answer
# import the grader for the exercise 8 of the lab/badge 1
from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex8
# expected result type: List
grade_badge1_ex8(answer8)
# build your code here
answer9 = [1]
# run this cell to submit your answer
# import the grader for the exercise 9 of the lab/badge 1
from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex9
# expected result type: List
grade_badge1_ex9(answer9)
# build your code here
answer10 = [2]
# run this cell to submit your answer
# import the grader for the exercise 10 of the lab/badge 1
from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex10
# expected result type: List
grade_badge1_ex10(answer10)
# build your code here
answer11 = [1]
# run this cell to submit your answer
# import the grader for the exercise 11 of the lab/badge 1
from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex11
# expected result type: List
grade_badge1_ex11(answer11)
# build your code here
answer12 = [2]
# run this cell to submit your answer
# import the grader for the exercise 12 of the lab/badge 1
from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex12
# expected result type: List
grade_badge1_ex12(answer12)
# import the quantum circuit
# from the IBM's Qiskit library
from qiskit import QuantumCircuit
# import the plotting state of qsphere function
# from the IBM's Qiskit Visualization module
from qiskit.visualization import plot_state_qsphere
####### build your code below #########
# create a quantum circuit with
# a quantum register with 4 qubits
circuit = QuantumCircuit(4)
# apply the Hadamard gate to all the 4 qubits
# to see all the possible combinations of quantum states
# note: uncomment to see all the possible
# combinations of quantum states
# circuit.h( [0, 1, 2, 3] )
# the (entangled) quantum state we need is
# |psi> = 1/sqrt(2) * ( |0010> + |1101> )
# apply the Hadamard gate to the 2nd qubit on
# the quantum register of the quantum circuit
circuit.h(1)
# apply the CX/CNOT gate on the 2nd qubit
# as control and on the 1st qubit as target,
# both on the quantum register of the quantum circuit
circuit.cx(1, 0)
# apply the CX/CNOT gate on the 2nd qubit
# as control and on the 3rd qubit as target,
# both on the quantum register of the quantum circuit
circuit.cx(1, 2)
# apply the CX/CNOT gate on the 2nd qubit
# as control and on the 4th qubit as target,
# both on the quantum register of the quantum circuit
circuit.cx(1, 3)
# apply the Pauli-X gate to the 2nd qubit on
# the quantum register of the quantum circuit
circuit.x(1)
####### build your code above #########
# display the plot of the quantum state from the QSphere
# applied to the quantum circuit defined before
display( plot_state_qsphere( circuit ) )
# draw the quantum circuit defined before
display( circuit.draw("mpl") )
# run this cell to submit your answer
# import the grader for the coding exercise of the lab/badge 1
from qc_grader.challenges.quantum_explorers23 import grade_badge1_code
# expected result type: QuantumCircuit
answer_code = grade_badge1_code(circuit)
#### get statevector from a quantum circuit ####
# import the statevector from the IBM's Qiskit
# Quantum Information module
from qiskit.quantum_info import Statevector
# retrieve the statevector from the instructions of
# the quantum circuit defined before
statevector = Statevector.from_instruction( circuit )
#### run this cell to view the output of ####
#### your quantum circuit as a histogram ####
# import the Sampler from the IBM's Qiskit Aer Primitives module,
# with the 'AerSampler' alias being defined
from qiskit_aer.primitives import Sampler as AerSampler
# import the plot distribution function
# from the IBM's Qiskit Tools for Visualization module
from qiskit.tools.visualization import plot_distribution
#### run the circuit on the simulator ####
#### and get probability distribution ####
# create an Aer Sampler object
sampler = AerSampler()
# measure all the qubits from
# the quantum circuit defined before
circuit.measure_all()
# execute the quantum circuit defined before,
# on the Aer Sampler, retrieving the respective job
job = sampler.run(circuit)
# retrieve the probability distribution
# from the quasi-distribution of
# the results obtained from the execution of
# the quantum circuit created before
prob_distribution = job.result().quasi_dists[0].binary_probabilities()
# print the statevector from the instructions of
# the quantum circuit defined before
print( statevector )
# print the probability distribution
# from the quasi-distribution of
# the results obtained from the execution of
# the quantum circuit created before
print( "Simulator Probability Distribution:", prob_distribution )
# plot the probability distribution
# from the quasi-distribution of
# the results obtained from the execution of
# the quantum circuit created before
plot_distribution( prob_distribution, color=[ "lightblue" ] )
# import the Qiskit's Runtime Service, Session, and Sampler
# from the Qiskit's IBM Runtime module
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler
# create a Qiskit's Runtime Service object,
# using the IBM Quantum channel
service = QiskitRuntimeService( channel="ibm_quantum" )
# retrieve the least busy backend
# (this step may take a while)
real_backend = service.least_busy( min_num_qubits=4, simulator=False )
# within the context of a session
with Session( service, backend=real_backend ) as session:
# create the Sampler object for the Session defined before
sampler = Sampler( session=session )
# execute the quantum simulation of
# the quantum circuit created before,
# using the Sampler, and retrieving
# the respective job on
# a real quantum device
job_real = sampler.run( circuit )
# retrieve and show the status of
# the job created for the execution of
# the quantum circuit defined before,
# on the Aer Sampler, using
# a real quantum device
job_real.status()
# retrieve the probability distribution
# from the quasi-distribution of
# the results obtained from the execution of
# the quantum circuit created before,
# using a real quantum device
prob_distribution_real = job_real.result().quasi_dists[0].binary_probabilities()
# fix the probability distributions
# from the quasi-distributions of
# the results obtained from the execution of
# the quantum circuit created before,
# using the simulator, for values
# lower or equal to 0 (zero)
prob_distribution = { binary_string : prob if prob > 0 else 1e-8
for binary_string, prob in prob_distribution.items() }
# create a list with all the possible binary strings
# with 4 bits (i.e., a total of 16 possible different values)
binary_strings_4_bits = [ bin( num )[2:].zfill(4) for num in range( 2**4 ) ]
# for each possible binary string with 4 bits
for binary_string_4_bits in binary_strings_4_bits:
# if the current binary string with 4 bits is
# not in the diectionary of the probability
# distributions from the quasi-distributions of
# the results obtained from the execution of
# the quantum circuit created before,
# using the simulator
if binary_string_4_bits not in prob_distribution:
# add the missing binary string with 4 bits to
# the diectionary of the probability
# distributions from the quasi-distributions of
# the results obtained from the execution of
# the quantum circuit created before,
# using the simulator, with a negligible value
prob_distribution[ binary_string_4_bits ] = 1e-8
# fix the probability distributions
# from the quasi-distributions of
# the results obtained from the execution of
# the quantum circuit created before,
# using a real quantum device,
# for values lower or equal to 0 (zero)
prob_distribution_real = { binary_string : prob if prob > 0 else 1e-8
for binary_string, prob in prob_distribution_real.items() }
# plot the probability distributions
# from the quasi-distributions of
# the results obtained from the execution of
# the quantum circuit created before,
# using the simulator and a real quantum device
plot_distribution(
data=[ prob_distribution, prob_distribution_real ],
legend=[ "Simulator", "Quantum Real Device" ],
color=[ "lightblue", "black" ],
bar_labels = False
)
# import the Quantum Circuit and the execute
# instruction from the IBM's Qiskit library
from qiskit import QuantumCircuit, execute
# import the Qiskit's Aer object
# from the IBM's Qiskit library
from qiskit import Aer
# retrieve the Unitary Simulator object
backend = Aer.get_backend( "unitary_simulator" )
######################################
#### for the 1st quantum circuit ####
# create the 1st quantum circuit,
# with a quantum register of 2 qubits
qc_1 = QuantumCircuit(2)
# apply the inverse of S gate on
# the 2nd qubit on the quantum register of
# the 1st quantum circuit created before
qc_1.sdg(1)
# apply the CX/CNOT gate on the 1st qubit
# as control and on the 2nd qubit as target,
# both on the quantum register of
# the 1st quantum circuit created before
qc_1.cx( 0, 1 )
# apply the S gate on the 2nd
# qubit on the quantum register of
# the 1st quantum circuit created before
qc_1.s(1)
# execute the quantum simulation of
# the 1st quantum circuit created before,
# and retrieve the respective job
job = execute( qc_1, backend, shots=10000 )
# retrieve the result obtained
# from the quantum simulation of
# the 1st quantum circuit created before
result = job.result()
# retrieve the unitary operator from the results
# obtained from the quantum simulation of
# the 1st quantum circuit created before
qc_1_unitary = result.get_unitary( qc_1, decimals = 3 )
######################################
#### for the 2nd quantum circuit ####
# create the 2nd quantum circuit,
# with a quantum register of 2 qubits
qc_2 = QuantumCircuit(2)
# apply the CY gate on the 1st qubit
# as control and on the 2nd qubit as target,
# both on the quantum register of
# the 2nd quantum circuit created before
qc_2.cy( 0, 1)
# execute the quantum simulation of
# the 2nd quantum circuit created before,
# and retrieve the respective job
job = execute( qc_2, backend, shots=10000 )
# retrieve the result obtained
# from the quantum simulation of
# the 2nd quantum circuit created before
result = job.result()
# retrieve the unitary operator from the results
# obtained from the quantum simulation of
# the 2nd quantum circuit created before
qc_2_unitary = result.get_unitary( qc_2, decimals = 3 )
# if the two quantum circuits are
# represented by the same unitary operator
if( qc_1_unitary == qc_2_unitary ):
# print an informative success message,
# in the case that the two quantum circuits
# are represented by the same unitary operator
print( "The two quantum circuits are represented by "
"the same unitary operator!" )
# build your code here
answer13 = [3]
# run this cell to submit your answer
# import the grader for the exercise 13 of the lab/badge 1
from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex13
# expected result type: List
grade_badge1_ex13(answer13)
# build your code here
answer14 = [3]
# run this cell to submit your answer
# import the grader for the exercise 14 of the lab/badge 1
from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex14
# expected result type: List
grade_badge1_ex14(answer14)
# build your code here
answer15 = [4]
# run this cell to submit your answer
# import the grader for the exercise 15 of the lab/badge 1
from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex15
# expected result type: List
grade_badge1_ex15(answer15)
# run this cell to check whether you have passed
# import the grader for the badge 1 of
# the IBM Qiskit's Quantum Explorers 2023-2024
from qc_grader.challenges.quantum_explorers23 import grade_badge1_score
# grade the score of the quiz of the lab for the badge 1
grade_badge1_score("en")
|
https://github.com/rubenandrebarreiro/ibm-qiskit-quantum-explorers-2023-2024
|
rubenandrebarreiro
|
# build your code here
password = "Experiment%"
# submit your answer using following code
# import the grader for the badge 3 of
# the IBM Qiskit's Quantum Explorers 2023-2024
from qc_grader.challenges.quantum_explorers23 import grade_badge3_ex1
# expected result type: string
grade_badge3_ex1(password)
|
https://github.com/rubenandrebarreiro/ibm-qiskit-quantum-explorers-2023-2024
|
rubenandrebarreiro
|
# build your code here
answer1 = [3]
# run this cell to submit your answer
# import the grader for the exercise 1 of the lab/badge 4
from qc_grader.challenges.quantum_explorers23 import grade_badge4_ex1
# expected result type: List
grade_badge4_ex1(answer1)
# build your code here
answer2 = [3]
# run this cell to submit your answer
# import the grader for the exercise 2 of the lab/badge 4
from qc_grader.challenges.quantum_explorers23 import grade_badge4_ex2
# expected result type: List
grade_badge4_ex2(answer2)
# build your code here
answer3 = [1]
# run this cell to submit your answer
# import the grader for the exercise 3 of the lab/badge 4
from qc_grader.challenges.quantum_explorers23 import grade_badge4_ex3
# expected result type: List
grade_badge4_ex3(answer3)
# build your code here
answer4 = [4]
# run this cell to submit your answer
# import the grader for the exercise 4 of the lab/badge 4
from qc_grader.challenges.quantum_explorers23 import grade_badge4_ex4
# expected result type: List
grade_badge4_ex4(answer4)
# build your code here
answer5 = [2]
# run this cell to submit your answer
# import the grader for the exercise 5 of the lab/badge 4
from qc_grader.challenges.quantum_explorers23 import grade_badge4_ex5
# expected result type: List
grade_badge4_ex5(answer5)
# build your code here
answer6 = [2]
# run this cell to submit your answer
# import the grader for the exercise 6 of the lab/badge 4
from qc_grader.challenges.quantum_explorers23 import grade_badge4_ex6
# expected result type: List
grade_badge4_ex6(answer6)
# build your code here
answer7 = [4]
# run this cell to submit your answer
# import the grader for the exercise 7 of the lab/badge 4
from qc_grader.challenges.quantum_explorers23 import grade_badge4_ex7
# expected result type: List
grade_badge4_ex7(answer7)
# build your code here
answer8 = [2]
# run this cell to submit your answer
# import the grader for the exercise 8 of the lab/badge 4
from qc_grader.challenges.quantum_explorers23 import grade_badge4_ex8
# expected result type: List
grade_badge4_ex8(answer8)
# build your code here
answer9 = [3]
# run this cell to submit your answer
# import the grader for the exercise 9 of the lab/badge 4
from qc_grader.challenges.quantum_explorers23 import grade_badge4_ex9
# expected result type: List
grade_badge4_ex9(answer9)
# build your code here
answer10 = [1]
# run this cell to submit your answer
# import the grader for the exercise 10 of the lab/badge 4
from qc_grader.challenges.quantum_explorers23 import grade_badge4_ex10
# expected result type: List
grade_badge4_ex10(answer10)
# build your code here
answer11 = [1]
# run this cell to submit your answer
# import the grader for the exercise 11 of the lab/badge 4
from qc_grader.challenges.quantum_explorers23 import grade_badge4_ex11
# expected result type: List
grade_badge4_ex11(answer11)
# build your code here
answer12 = [2]
# run this cell to submit your answer
# import the grader for the exercise 12 of the lab/badge 4
from qc_grader.challenges.quantum_explorers23 import grade_badge4_ex12
# expected result type: List
grade_badge4_ex12(answer12)
#### do not edit this code ####
#### you will use this circuit ####
#### for your code question ####
# import the quantum circuit
# from the IBM's Qiskit libtrary
from qiskit import QuantumCircuit
# create a quantum circuit with
# a quantum register of two qubits
qc = QuantumCircuit(2)
# apply a Hadamard gate to the 1st
# qubit on the quantum register of
# the quantum circuit before
qc.h(0)
# apply a Pauli-X gate to the 2nd
# qubit on the quantum register of
# the quantum circuit before
qc.x(1)
# apply the CX/CNOT gate on the 1st qubit
# as control and on the 2nd qubit as target,
# both on the quantum register of the quantum circuit
qc.cx(0, 1)
# perform a meausrement of all
# the qubits on the quantum register of
# the Quantum Circuit created before
qc.measure_all()
# draw the Quantum Circuit created before
qc.draw()
# import the Qiskit Runtime Service, Session, Options,
# and Sampler from the Qiksit's IBM Runtime module
from qiskit_ibm_runtime import QiskitRuntimeService,\
Session, Options, Sampler
# import the Fake Manila provider from
# the Qiskit's Provider - Fake Provider module
from qiskit.providers.fake_provider import FakeManila
# import the Noise Model from
# the Qiskit's Aer Noise module
from qiskit_aer.noise import NoiseModel
#### save the Qiskit Runtime account ####
#### credentials if you have not done so already ####
#### if you need to overwrite the account info, ####
#### please add the `overwrite=True` option ####
# perform the instruction call to save
# the Qiskit Runtime account credentials
#QiskitRuntimeService.save_account( channel="ibm_quantum",
# token="my_token", overwrite=True)
# create a Qiskit's Runtime Service object,
# using the IBM Quantum channel
service = QiskitRuntimeService( channel="ibm_quantum" )
# retrieve the IBM's QASM Simulator as the backend service
# note: we will be using the QASM Simulator
backend = service.get_backend( "ibmq_qasm_simulator" )
# print the existing information about
# the IBM's QASM Simulator backend service
print( backend )
# create a Fake Manila backend object
# note: here, from a fake noisy backend,
# we obtain the noise model, which we will apply to
# the selected simulator backend from above
fake_backend = FakeManila()
# retrieve the noise model from
# the noisy Fake Manila backend object
noise_model = NoiseModel.from_backend( fake_backend )
# create the quantum simulation object
# note: use this when defining the quantum simulator
# in your options instances
sim = {
# define the noise model to use
# in the quantum simulation
"noise_model": noise_model,
# define the seed to use
# in the quantum simulation
# note: do not change this value
# doing so may result in
# your answer being marked
# as an incorrect one
"seed_simulator": 42
}
###########################################################
####### build your code below #########
# create the options for the quantum simulation
# configured with no error mitigation
options = Options(
simulator=sim,
resilience_level=0,
)
# create the options for the quantum simulation
# configured with the M3 error mitigation
options_with_m3 = Options(
simulator=sim,
resilience_level=1,
)
# within the context of a Session configured
# with the Qiskit's Runtime Service object,
# created before, using the IBM Quantum channel,
# and also using the backend defined before
with Session( service=service, backend=backend ):
# first, we will run the quntum simulation
# configured with no error mitigation
# create the Sampler object with
# the Session context defined
# and the relevant options
sampler = Sampler( options=options )
# run the Sampler object with
# a number of shots equal to 4000,
# retrieving the resulting submitted
# job for the quantum simulation
job = sampler.run( qc, shots=4000 )
# retrieve the count results
# from the submitted job of
# the quantum simulation configured
# with no error mitigation
results_no_em = job.result()
# retrieve a dictionary (not a list) of
# the quasi-distribution probabilities
# from the count results obtained for
# the quantum simulation configured
# with no error mitigation
quasi_dist_no_em = results_no_em.quasi_dists[0]
########################################
# second, we will run the quantum simulation
# configured with the M3 error mitigation
# create the Sampler object with
# the Session context defined
# and the relevant options
sampler = Sampler( options=options_with_m3 )
# run the Sampler object with
# a number of shots equal to 4000,
# retrieving the resulting submitted
# job for the quantum simulation
job = sampler.run( qc, shots=4000 )
# retrieve the count results
# from the submitted job of
# the quantum simulation configured
# with the T-REX error mitigation,
# as well as with the M3 Sampler
results_with_m3 = job.result()
# retrieve a dictionary (not a list) of
# the quasi-distribution probabilities
# from the count results obtained for
# the quantum simulation configured
# with the T-REX error mitigation,
# as well as with the M3 Sampler
quasi_dist_with_m3 = results_with_m3.quasi_dists[0]
####### build your code above #########
###########################################################
# print the quasi-distribution probabilities
# from the count results obtained for
# the quantum simulation configured
# with no error mitigation
print( "Quasi-distribution with No Error Mitigation: ", quasi_dist_no_em )
# print the quasi-distribution probabilities
# from the count results obtained for
# the quantum simulation configured
# with the T-REX error mitigation,
# as well as with the M3 Sampler
print( "Quasi-distribution with Error Mitigation (M3): ", quasi_dist_with_m3 )
########### cell to visualise your results ###########
# import the statevector object from
# the IBM's Qiskit Quantum Information module
from qiskit.quantum_info import Statevector
# import the plotting histogram function from
# the IBM's Qiskit Visualization module
from qiskit.visualization import plot_histogram
######################################################
#### get the probability distribution results ####
# retrieve the probability distribution
# from the quasi-distribution of
# the results obtained from the execution of
# the quantum circuit created before,
# with no error mitigation applied
binary_prob_dist_no_em = quasi_dist_no_em.binary_probabilities()
# retrieve the probability distribution
# from the quasi-distribution of
# the results obtained from the execution of
# the quantum circuit created before,
# with T-REX error mitigation and M3 sampler applied
binary_prob_dist_with_m3 = quasi_dist_with_m3.binary_probabilities()
######################################################
#### compute the theoretical results ####
# remove all the final measurements on
# all the quantum registers of the quantum circuit
# created before for the quantum simulation
qc.remove_final_measurements()
# retrieve the theoretical measurement probabilities
# from the statevector representing the quantum circuit
# created before, without the measurements applied
theory_probabilities = Statevector(qc).probabilities_dict()
# create a copy of the theoretical measurement probabilities
# from the statevector representing the quantum circuit
# created before, without the measurements applied
theory_probabilities_plot = theory_probabilities.copy()
# create a list with all the possible binary strings
# with 2 bits (i.e., a total of 4 possible different values)
binary_strings_2_bits = [ bin( num )[2:].zfill(2) for num in range( 2**2 ) ]
# for each possible binary string with 2 bits
for binary_string_2_bits in binary_strings_2_bits:
# if the current binary string with 2 bits is
# not in the dictionary of the probability
# distributions from the quasi-distributions of
# the results obtained from the execution of
# the quantum circuit created before,
# using the simulator
if binary_string_2_bits not in theory_probabilities_plot:
# add the missing binary string with 2 bits to
# the dictionary of the probability
# distributions from the quasi-distributions of
# the results obtained from the execution of
# the quantum circuit created before,
# using the simulator, with a negligible value
theory_probabilities_plot[ binary_string_2_bits ] = 1e-8
# perform (again) all the final measurements on
# all the quantum registers of the quantum circuit
# created before for the quantum simulation
qc.measure_all()
######################################################
#### plot all the probability distribution results ####
# create the list of the captions for the legend of
# the histogram for the probability distributions
# from the quasi-distributions of the results obtained
# from the execution of the quantum circuit created before,
# without and with error mitigation, as well as
# the theoretically expected results
legends = [ "No Error Mitigation",
"Error Mitigation Applied", "Theory" ]
# plot the histogram for the probability distributions
# from the quasi-distributions of the results obtained
# from the execution of the quantum circuit created before,
# without and with error mitigation, as well as
# the theoretically expected results
plot_histogram( [ binary_prob_dist_no_em,
binary_prob_dist_with_m3,
theory_probabilities_plot ], legend=legends )
# run this cell to submit your answer
# import the grader for the coding exercise of the lab/badge 4
from qc_grader.challenges.quantum_explorers23 import grade_badge4_code
# expected result type: List
answer_code = grade_badge4_code( [ results_no_em, results_with_m3 ],
[ quasi_dist_no_em, quasi_dist_with_m3 ] )
#### run this cell to run your quantum circuit ####
#### on a real quantum device ####
# retrieve the least-busy backend
# with a minimum number of two qubits
# (this step can take a while)
real_backend = service.least_busy( min_num_qubits=2, simulator=False )
# print the information about the best (i.e., the least-busy)
# backend with a minimum number of two qubits, and an informative
# message about the job submission on this backend
print( "The best backend is " + real_backend.name )
print( "Submitting your job..." )
###########################################################
####### add your answers from above #########
####### before running the cell #########
# define the options for the quantum simulation
# configured with no error mitigation
options = Options(
simulator=sim,
resilience_level=0,
)
# define the options for the quantum simulation
# configured with the M3 error mitigation
options_with_m3 = Options(
simulator=sim,
resilience_level=1,
)
# within the context of a Session configured
# with the Qiskit's Runtime Service object,
# created before, using the IBM Quantum channel,
# and also using the backend defined before
with Session( service=service, backend=real_backend ):
# first, we will run the quantum simulation
# configured with no error mitigation
# create the Sampler object with
# the Session context defined
# and the relevant options
sampler = Sampler( options=options )
# run the Sampler object with
# a number of shots equal to 4000,
# retrieving the resulting submitted
# job for the quantum simulation
job = sampler.run( qc, shots=4000 )
# print the ID of the job submitted
# for the quantum simulation configured
# with no error mitigation
# note: do not change this code
print( f"Job ID: { job.job_id() }" )
# retrieve the count results
# from the submitted job of
# the quantum simulation configured
# with no error mitigation
results_no_em = job.result()
# retrieve a dictionary (not a list) of
# the quasi-distribution probabilities
# from the count results obtained for
# the quantum simulation configured
# with no error mitigation
quasi_dist_no_em = results_no_em.quasi_dists[0]
###########################################
# second, we will run the quantum simulation
# configured with the M3 error mitigation
# create the Sampler object with
# the Session context defined
# and the relevant options
sampler = Sampler( options=options_with_m3 )
# run the Sampler object with
# a number of shots equal to 4000,
# retrieving the resulting submitted
# job for the quantum simulation
job = sampler.run( qc, shots=4000 )
# print the ID of the job submitted
# for the quantum simulation configured
# with the T-REX error mitigation,
# as well as with the M3 Sampler
# note: do not change this code
print( f"Job ID: { job.job_id() }" )
# retrieve the count results
# from the submitted job of
# the quantum simulation configured
# with the T-REX error mitigation,
# as well as with the M3 Sampler
results_with_m3 = job.result()
# retrieve a dictionary (not a list) of
# the quasi-distribution probabilities
# from the count results obtained for
# the quantum simulation configured
# with the T-REX error mitigation,
# as well as with the M3 Sampler
quasi_dist_with_m3 = results_with_m3.quasi_dists[0]
####### add your answers from above #########
####### before running the cell #########
###########################################################
# run this cell to view the output histogram and
# compare the two probability distributions obtained
# retrieve the probability distribution
# from the quasi-distribution of
# the results obtained from the execution of
# the quantum circuit created before,
# with no error mitigation applied,
# but now executed on a real quantum device
binary_prob_dist_no_em = quasi_dist_no_em.binary_probabilities()
# retrieve the probability distribution
# from the quasi-distribution of
# the results obtained from the execution of
# the quantum circuit created before,
# with T-REX error mitigation and M3 sampler applied,
# but now executed on a real quantum device
binary_prob_dist_with_m3 = quasi_dist_with_m3.binary_probabilities()
# create a copy of the probability distribution
# from the quasi-distribution of
# the results obtained from the execution of
# the quantum circuit created before,
# with no error mitigation applied,
# but now executed on a real quantum device
binary_prob_dist_no_em_plot = binary_prob_dist_no_em.copy()
# create a copy of the probability distribution
# from the quasi-distribution of
# the results obtained from the execution of
# the quantum circuit created before,
# with T-REX error mitigation and M3 sampler applied,
# but now executed on a real quantum device
binary_prob_dist_with_m3_plot = binary_prob_dist_with_m3.copy()
# create a list with all the possible binary strings
# with 2 bits (i.e., a total of 4 possible different values)
binary_strings_2_bits = [ bin( num )[2:].zfill(2) for num in range( 2**2 ) ]
# for each possible binary string with 2 bits
for binary_string_2_bits in binary_strings_2_bits:
# if the current binary string with 2 bits is
# not in the dictionary of the probability
# distributions from the quasi-distribution of
# the results obtained from the execution of
# the quantum circuit created before,
# with no error mitigation applied,
# but now executed on a real quantum device
if binary_string_2_bits not in binary_prob_dist_no_em_plot:
# add the missing binary string with 2 bits to
# the dictionary of the probability
# distributions from the quasi-distributions of
# the results obtained from the execution of
# the quantum circuit created before,
# using the simulator, with a negligible value
binary_prob_dist_no_em_plot[ binary_string_2_bits ] = 1e-8
# if the probability distribution
# from the quasi-distribution of
# the results obtained from the execution of
# the quantum circuit created before,
# with no error mitigation applied,
# but now executed on a real quantum device,
# is lower or equal to 0 (zero)
elif binary_prob_dist_no_em_plot[ binary_string_2_bits ] <= 0:
# flip the signal of the probability
# distribution from the quasi-distributions of
# the results obtained from the execution of
# the quantum circuit created before,
# using the simulator, for a positive value
binary_prob_dist_no_em_plot[ binary_string_2_bits ] *= -1
# for each possible binary string with 2 bits
for binary_string_2_bits in binary_strings_2_bits:
# if the current binary string with 2 bits is
# not in the dictionary of the probability
# distributions from the quasi-distribution of
# the results obtained from the execution of
# the quantum circuit created before,
# with T-REX error mitigation and M3 sampler applied,
# but now executed on a real quantum device
if binary_string_2_bits not in binary_prob_dist_with_m3_plot:
# add the missing binary string with 2 bits to
# the dictionary of the probability
# distributions from the quasi-distributions of
# the results obtained from the execution of
# the quantum circuit created before,
# using the simulator, with a negligible value
binary_prob_dist_with_m3_plot[ binary_string_2_bits ] = 1e-8
# if the probability distribution
# from the quasi-distribution of
# the results obtained from the execution of
# the quantum circuit created before,
# with T-REX error mitigation and M3 sampler applied,
# but now executed on a real quantum device,
# is lower or equal to 0 (zero)
elif binary_prob_dist_with_m3_plot[ binary_string_2_bits ] <= 0:
# flip the signal of the probability
# distribution from the quasi-distributions of
# the results obtained from the execution of
# the quantum circuit created before,
# using the simulator, for a positive value
binary_prob_dist_with_m3_plot[ binary_string_2_bits ] *= -1
# create the list of the captions for the legend of
# the histogram for the probability distributions
# from the quasi-distributions of the results obtained
# from the execution of the quantum circuit created before,
# without and with error mitigation, as well as
# the theoretically expected results,
# but now executed on a real quantum device
legend = [ "No Error Mitigation",
"Error Mitigation Applied", "Theory" ]
# plot the histogram for the probability distributions
# from the quasi-distributions of the results obtained
# from the execution of the quantum circuit created before,
# without and with error mitigation, as well as
# the theoretically expected results,
# but now executed on a real quantum device
plot_histogram( [ binary_prob_dist_no_em_plot,
binary_prob_dist_with_m3_plot,
theory_probabilities_plot ],
legend=legend )
# build your code here
answer13 = [3]
# run this cell to submit your answer
# import the grader for the exercise 13 of the lab/badge 4
from qc_grader.challenges.quantum_explorers23 import grade_badge4_ex13
# expected result type: List
grade_badge4_ex13(answer13)
# build your code here
answer14 = [4]
# run this cell to submit your answer
# import the grader for the exercise 14 of the lab/badge 4
from qc_grader.challenges.quantum_explorers23 import grade_badge4_ex14
# expected result type: List
grade_badge4_ex14(answer14)
# build your code here
answer15 = [2]
# run this cell to submit your answer
# import the grader for the exercise 15 of the lab/badge 4
from qc_grader.challenges.quantum_explorers23 import grade_badge4_ex15
# expected result type: List
grade_badge4_ex15(answer15)
# run this cell to check whether you have passed
# import the grader for the badge 4 of
# the IBM Qiskit's Quantum Explorers 2023-2024
from qc_grader.challenges.quantum_explorers23 import grade_badge4_score
# grade the score of the quiz of the lab for the badge 4
grade_badge4_score("en")
|
https://github.com/rubenandrebarreiro/ibm-qiskit-quantum-explorers-2023-2024
|
rubenandrebarreiro
|
# build your code here
answer1 = [1]
# run this cell to submit your answer
# import the grader for the exercise 1 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex1
# expected result type: List
grade_badge5_ex1(answer1)
# build your code here
answer2 = [2]
# run this cell to submit your answer
# import the grader for the exercise 2 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex2
# expected result type: List
grade_badge5_ex2(answer2)
# build your code here
answer3 = [4]
# run this cell to submit your answer
# import the grader for the exercise 3 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex3
# expected result type: List
grade_badge5_ex3(answer3)
# build your code here
answer4 = [4]
# run this cell to submit your answer
# import the grader for the exercise 4 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex4
# expected result type: List
grade_badge5_ex4(answer4)
# build your code here
answer5 = [3]
# run this cell to submit your answer
# import the grader for the exercise 5 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex5
# expected result type: List
grade_badge5_ex5(answer5)
# build your code here
answer6 = [1]
# run this cell to submit your answer
# import the grader for the exercise 6 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex6
# expected result type: List
grade_badge5_ex6(answer6)
# build your code here
answer7 = [1]
# run this cell to submit your answer
# import the grader for the exercise 7 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex7
# expected result type: List
grade_badge5_ex7(answer7)
# build your code here
answer8 = [2]
# run this cell to submit your answer
# import the grader for the exercise 8 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex8
# expected result type: List
grade_badge5_ex8(answer8)
# build your code here
answer9 = [1]
# run this cell to submit your answer
# import the grader for the exercise 9 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex9
# expected result type: List
grade_badge5_ex9(answer9)
# build your code here
answer10 = [3]
# run this cell to submit your answer
# import the grader for the exercise 10 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex10
# expected result type: List
grade_badge5_ex10(answer10)
# build your code here
answer11 = [1]
# run this cell to submit your answer
# import the grader for the exercise 11 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex11
# expected result type: List
grade_badge5_ex11(answer11)
# build your code here
answer12 = [4]
# run this cell to submit your answer
# import the grader for the exercise 12 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex12
# expected result type: List
grade_badge5_ex12(answer12)
# import the NumPy library with 'np' alias
import numpy as np
# import the Quantum Support Vector Classifier (QSVC) from
# the Qiskit's Machine Learning - Algorithms module
from qiskit_machine_learning.algorithms import QSVC
# define the features X of the initial training dataset
x_train = np.array([
[1.25663706, 5.02654825, 3.76991118],
[3.76991118, 0. , 0.62831853],
[4.08407045, 3.76991118, 1.88495559],
[0.62831853, 2.82743339, 2.51327412],
[0.9424778 , 5.96902604, 5.02654825],
[5.02654825, 2.51327412, 0.31415927],
[5.34070751, 0.62831853, 3.45575192],
[0.31415927, 3.45575192, 3.76991118],
[1.25663706, 4.39822972, 5.96902604],
[3.76991118, 1.25663706, 2.82743339],
[3.14159265, 5.34070751, 1.88495559],
[3.45575192, 0.31415927, 1.57079633],
[1.57079633, 0. , 5.96902604],
[4.08407045, 3.14159265, 0. ],
[1.57079633, 4.39822972, 0.9424778 ],
[0. , 1.57079633, 0.31415927],
[5.02654825, 2.82743339, 4.71238898],
[2.51327412, 0.62831853, 0.62831853],
[3.14159265, 5.34070751, 1.88495559],
[5.65486678, 4.71238898, 4.08407045],
[0. , 2.19911486, 3.45575192],
[0.62831853, 0.31415927, 3.45575192],
[5.65486678, 2.51327412, 5.65486678],
[2.19911486, 0.62831853, 5.02654825],
[5.34070751, 3.45575192, 4.39822972],
[4.08407045, 2.51327412, 4.08407045],
[0.62831853, 5.65486678, 4.08407045],
[5.96902604, 4.39822972, 0.62831853],
[5.96902604, 4.39822972, 5.96902604],
[0. , 5.96902604, 4.08407045]
])
# define the labels Y of the initial training dataset
y_train = np.array([ 0, 0, 1, 1, 1, 1, 1, 0, 0, 0,
0, 0, 1, 0, 1, 1, 1, 1, 0, 0,
1, 1, 1, 0, 0, 0, 0, 1, 1, 0 ])
# compute the size of metric to
# split the initial training dataset into
# a final training set and a final test set,
# where 80% of the data will be used for training,
# and 20% of the data will be used for testing
train_size = int( 0.8 * len(x_train) )
# split the initial training dataset
# into a final training set,
# for the data features X
x_train_split = x_train[:train_size]
# split the initial training dataset
# into a final training set,
# for the data labels Y
y_train_split = y_train[:train_size]
# split the initial training dataset
# into a final testing set,
# for the data features X
x_test = x_train[train_size:]
# split the initial training dataset
# into a final testing set,
# for the data labels Y
y_test = y_train[train_size:]
####### build your code below #########
# import the Z Feature Map from
# the Qiskit's Circuit Library module
from qiskit.circuit.library import ZFeatureMap
# import the Sampler from
# the Qiskit's Primitives module
from qiskit.primitives import Sampler
# import the Compute-Uncompute method from
# the Qiskit's Algorithms - State Fidelities module
from qiskit.algorithms.state_fidelities import ComputeUncompute
# import the Fidelity Quantum Kernel from
# the Qiskit's Machine Learning - Kernels module
from qiskit_machine_learning.kernels import FidelityQuantumKernel
# compute the number of features X of
# the samples present in the final training set
num_features = x_train_split.shape[1]
# define the number of repetitions of
# the quantum circuits for the Z Feature Map
num_repetitions = 1
# create a Z Feature Map for the number of
# features X and number of repetitions defined before,
# to be used for the creation of the Quantum Kernel
feature_map = ZFeatureMap( feature_dimension=num_features, reps=num_repetitions )
# create the Sampler object
# for the Compute-Uncompute method
sampler = Sampler()
# create the Fidelity object object
# with the Sampler object defined before
fidelity = ComputeUncompute( sampler=sampler )
# create the Fidelity Quantum Kernel object
# with the Fidelity and the Z Feature Map defined before
quantum_kernel = FidelityQuantumKernel( fidelity=fidelity, feature_map=feature_map )
# create the Quantum Support Vector Classifier (QSVC)
# with the Fidelity Quantum Kernel defined before
qsvc = QSVC( quantum_kernel=quantum_kernel )
# fit the data features X and data labels Y of
# the final training dataset into the previously
# created Quantum Support Vector Classifier (QSVC)
qsvc.fit( x_train_split, y_train_split )
####### build your code above #########
# evaluate the performance score of
# the quantum learning model of
# the Quantum Support Vector Classifier (QSVC)
# note: you need achieve a score higher
# than 0.8 to pass the code question
qsvc_score = qsvc.score(x_test, y_test)
# print the performance score of
# the quantum learning model of
# the Quantum Support Vector Classifier (QSVC)
print(f"QSVC classification test score: {qsvc_score} ( { ( round( qsvc_score * 100 , 2 ) ) }% )")
# run this cell to submit your answer
# import the grader for the coding exercise of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_code
# expected result type: QSVC
answer_code = grade_badge5_code(qsvc)
# import the Qiskit Runtime Service
# from the Qiksit's IBM Runtime module
from qiskit_ibm_runtime import QiskitRuntimeService
# create a Qiskit's Runtime Service object,
# using the IBM Quantum channel
service = QiskitRuntimeService( channel="ibm_quantum" )
# compute the number of features X of
# the samples present in the final training set
num_features = x_train_split.shape[1]
# retrieve the least-busy backend
# with a minimum number of two qubits
# (this step can take a while)
real_backend = service.least_busy( min_num_qubits=num_features, simulator=False )
# print the information about the best (i.e., the least-busy)
# backend with a minimum number of two qubits, and an informative
# message about the job submission on this backend
print( "The best backend is " + real_backend.name + "!" )
# import the ZZ Feature Map from
# the Qiskit's Circuit Library module
from qiskit.circuit.library import ZZFeatureMap
# import the Quantum Support Vector Classifier (QSVC) from
# the Qiskit's Machine Learning - Algorithms module
from qiskit_machine_learning.algorithms import QSVC
# import the Session from
# the Qiksit's IBM Runtime module
from qiskit_ibm_runtime import Session
# import the Sampler from
# the Qiskit's Primitives module
from qiskit.primitives import Sampler
# import the Compute-Uncompute method from
# the Qiskit's Algorithms - State Fidelities module
from qiskit.algorithms.state_fidelities import ComputeUncompute
# import the Fidelity Quantum Kernel from
# the Qiskit's Machine Learning - Kernels module
from qiskit_machine_learning.kernels import FidelityQuantumKernel
# compute the number of features X of
# the samples present in the final training set
num_features = x_train_split.shape[1]
# create a ZZ Feature Map for
# the number of features X defined before,
# to be used for the creation of the Quantum Kernel
fm = feature_map = ZZFeatureMap( num_features )
# within the context of a Session configured
# with the Qiskit's Runtime Service object,
# created before, using the IBM Quantum channel,
# and also using the backend defined before
with Session( service=service, backend=real_backend ) as session:
# create the Sampler object
# for the Compute-Uncompute method
sampler = Sampler()
# create the Fidelity object,
# using the Compute-Uncompute method
# applied on the Sampler object defined before
fidelity = ComputeUncompute( sampler )
# create the Fidelity Quantum Kernel object
# with the Fidelity and the ZZ Feature Map defined before
quantum_kernel = FidelityQuantumKernel( feature_map=fm, fidelity=fidelity )
# create the Quantum Support Vector Classifier (QSVC)
# with the Fidelity Quantum Kernel defined before
qsvc = QSVC( quantum_kernel=quantum_kernel )
###### add your answers from above before running the cell #######
# fit the data features X and data labels Y of
# the final training dataset into the previously
# created Quantum Support Vector Classifier (QSVC)
qsvc.fit( x_train_split, y_train_split )
# evaluate the performance score of
# the quantum learning model of
# the Quantum Support Vector Classifier (QSVC)
qsvc_score = qsvc.score(x_test, y_test)
# print the performance score of
# the quantum learning model of
# the Quantum Support Vector Classifier (QSVC)
print(f"QSVC classification test score: {qsvc_score} ( { ( round( qsvc_score * 100 , 2 ) ) }% )")
# build your code here
answer13 = [4]
# run this cell to submit your answer
# import the grader for the exercise 13 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex13
# expected result type: List
grade_badge5_ex13(answer13)
# build your code here
answer14 = [3]
# run this cell to submit your answer
# import the grader for the exercise 14 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex14
# expected result type: List
grade_badge5_ex14(answer14)
# build your code here
answer15 = [2]
# run this cell to submit your answer
# import the grader for the exercise 15 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex15
# expected result type: List
grade_badge5_ex15(answer15)
# run this cell to check whether you have passed
# import the grader for the badge 5 of
# the IBM Qiskit's Quantum Explorers 2023-2024
from qc_grader.challenges.quantum_explorers23 import grade_badge5_score
# grade the score of the quiz of the lab for the badge 5
grade_badge5_score("en")
|
https://github.com/rubenandrebarreiro/ibm-qiskit-quantum-explorers-2023-2024
|
rubenandrebarreiro
|
# update/upgrade Python's pip module
!pip install --upgrade pip -q
# install the IBM Qiskit's Machine Learning and Optimization modules
!pip install qiskit_machine_learning qiskit_optimization -q
# build your code here
answer1 = [2]
# run this cell to submit your answer
# import the grader for the exercise 1 of the lab/badge 6
from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex1
# expected result type: List
grade_badge6_ex1(answer1)
# build your code here
answer2 = [4]
# run this cell to submit your answer
# import the grader for the exercise 2 of the lab/badge 6
from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex2
# expected result type: List
grade_badge6_ex2(answer2)
# build your code here
answer3 = [3]
# run this cell to submit your answer
# import the grader for the exercise 3 of the lab/badge 6
from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex3
# expected result type: List
grade_badge6_ex3(answer3)
# build your code here
answer4 = [2]
# run this cell to submit your answer
# import the grader for the exercise 4 of the lab/badge 6
from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex4
# expected result type: List
grade_badge6_ex4(answer4)
# build your code here
answer5 = [3]
# run this cell to submit your answer
# import the grader for the exercise 5 of the lab/badge 6
from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex5
# expected result type: List
grade_badge6_ex5(answer5)
# build your code here
answer6 = [1]
# run this cell to submit your answer
# import the grader for the exercise 6 of the lab/badge 6
from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex6
# expected result type: List
grade_badge6_ex6(answer6)
# build your code here
answer7 = [2]
# run this cell to submit your answer
# import the grader for the exercise 7 of the lab/badge 6
from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex7
# expected result type: list
grade_badge6_ex7(answer7)
# build your code here
answer8 = [1]
# run this cell to submit your answer
# import the grader for the exercise 8 of the lab/badge 6
from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex8
# expected result type: List
grade_badge6_ex8(answer8)
# build your code here
answer9 = [3]
# run this cell to submit your answer
# import the grader for the exercise 9 of the lab/badge 6
from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex9
# expected result type: List
grade_badge6_ex9(answer9)
# build your code here
answer10 = [2]
# run this cell to submit your answer
# import the grader for the exercise 10 of the lab/badge 6
from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex10
# expected result type: List
grade_badge6_ex10(answer10)
# build your code here
answer11 = [3]
# run this cell to submit your answer
# import the grader for the exercise 11 of the lab/badge 6
from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex11
# expected result type: List
grade_badge6_ex11(answer11)
# build your code here
answer12 = [4]
# run this cell to submit your answer
# import the grader for the exercise 12 of the lab/badge 6
from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex12
# expected result type: List
grade_badge6_ex12(answer12)
# cod block for the definition of helper functions
# to draw and visualize graph solution
# import the PyPlot module from the Matplot Library
import matplotlib.pyplot as plt
# import the NetworkX Library
import networkx as nx
# definition of a helper function to draw the graph,
# using the NetworkX library's functionalities
def draw_graph(G, colors, pos):
# retrieve the default axes of the plotting object with a frame-on
default_axes = plt.axes(frameon = True)
# draw a network representing the graph, with the respective nodes and edges
nx.draw_networkx(G, node_color = colors, node_size = 600, alpha = 0.8,
ax = default_axes, pos = pos, node_shape = "o")
# retrieve the weight labels of the edges of the graph
edge_labels = nx.get_edge_attributes(G, "weight")
# draw the weight labels of the edges to the resulting graph network
nx.draw_networkx_edge_labels(G, pos = pos, edge_labels = edge_labels)
# definition of a helper function to draw the solution of
# the Traveling Salesman Problem (TSP), in the respective graph representation
def draw_tsp_solution(G, order, colors, pos):
# convert the structure of the initial given
# undirected graph to a directed graph
G2 = nx.DiGraph()
# add the nodes from the initial given
# undirected graph to the created directed graph
G2.add_nodes_from(G)
# retrieves the number of edges of the directed graph representation
n = len(order)
# for any edge for the directed graph representing the solution
# for the given Traveling Salesman Problem (TSP)
for i in range(n):
# retrieve the destination node for the current directed edge
j = (i + 1) % n
# add the current directed edge to
# the directed graph representing the solution
# for the given Traveling Salesman Problem (TSP)
G2.add_edge(order[i], order[j], weight = G[order[i]][order[j]]["weight"])
# retrieve the default axes of the plotting object with a frame-on
default_axes = plt.axes(frameon = True)
# draw a network representing the new directed graph,
# with the respective nodes and edges, representing
# the solution for the given Traveling Salesman Problem (TSP)
nx.draw_networkx(G2, node_color = colors, edge_color = "b",
node_size = 600, alpha = 0.8,
ax = default_axes, pos = pos)
# retrieve the weight labels of the edges of the new directed graph,
# representing the solution for the given Traveling Salesman Problem (TSP)
edge_labels = nx.get_edge_attributes(G2, "weight")
# draw the weight labels of the edges to the resulting new directed graph network,
# representing the solution for the given Traveling Salesman Problem (TSP)
nx.draw_networkx_edge_labels(G2, pos, font_color = "b", edge_labels = edge_labels)
# import the Traveling Salesman Problem (TSP) from
# the IBM Qiskit's Optimization Application module
from qiskit_optimization.applications import Tsp
# create a random instance of the Traveling Salesman Problem (TSP),
# with 4 nodes and a fixed pseudo-random seed
tsp = Tsp.create_random_instance(4, seed=43)
# retrieve the adjoint matrix for the graph representation of
# the instance of the Traveling Salesman Problem (TSP) previously created
adj_matrix = nx.to_numpy_array(tsp.graph)
# print the adjoint matrix for the graph representation of
# the instance of the Traveling Salesman Problem (TSP) previously created,
# as the distances (edges' weigths) between the respective nodes
print("Distances:\n", adj_matrix)
# set the color of the nodes of
# the instance of the Traveling Salesman Problem (TSP)
# previously created, with the red color
colors = ["r"] * len(tsp.graph.nodes)
# retrieve the positions of the nodes of
# the instance of the Traveling Salesman Problem (TSP)
pos = [tsp.graph.nodes[node]["pos"] for node in tsp.graph.nodes]
# draw the graph representation of
# the instance of the Traveling Salesman Problem (TSP),
# using the NetworkX library's functionalities
draw_graph(tsp.graph, colors, pos)
# import the Quandratic Program to
# Quadratic Unconstrained Binary Optimization (QUBO) converter,
# from the IBM Qiskit's Optimization Convertes module
from qiskit_optimization.converters import QuadraticProgramToQubo
# convert the original optimization formulation of
# the Traveling Salesman Problem (TSP) created before,
# to a Quadratic Program, to solve it using a quantum computer
qp = tsp.to_quadratic_program()
# initialize the Quandratic Program to
# Quadratic Unconstrained Binary Optimization (QUBO) converter
qp2qubo = QuadraticProgramToQubo()
# convert the Quadratic Program formulation of
# the Traveling Salesman Problem (TSP) created before,
# to a Quadratic Unconstrained Binary Optimization (QUBO) Program,
# to solve it using a quantum computer
qubo = qp2qubo.convert(qp)
# convert the Quadratic Unconstrained Binary Optimization (QUBO)
# formulation of the Traveling Salesman Problem (TSP) created before,
# to an Ising Hamiltonian, to solve it using a quantum computer,
# retrieving the respective qubit operations
qubitOp, offset = qubo.to_ising()
# import the Sampling Variational Quantum Eigensolver (VQE) algorithm
# from the IBM Qiskit's Minimum Eigesolvers Algorithms module
from qiskit.algorithms.minimum_eigensolvers import SamplingVQE
# import the Nakanishi-Fujii-Todo (NFT) Optimizer
# from the IBM Qiskit's Optimizers Algorithms module
from qiskit.algorithms.optimizers import NFT
# import the parametrized two-local quantum circuits
# from the IBM Qiskit's Circuit Library module
from qiskit.circuit.library import TwoLocal
# import the Aer Sample from
# the IBM Qiskit's Aer Primitives module
from qiskit_aer.primitives import Sampler as AerSampler
# import the Algorithm's Global Parameters from
# the IBM Qiskit's Utilities module
from qiskit.utils import algorithm_globals
# set a fixed pseudo-random seed
# as an Algorithm's Global Parameter
algorithm_globals.random_seed = 123
# create a Nakanishi-Fujii-Todo (NFT) Optimizer instance,
# with a maximum number of 100 iterations
optimizer = NFT(maxiter=100)
# create a Parametrized Two-Local Ansatz Quantum Circuit,
# for the parametrized y-axis rotations for the qubits,
# aiming a linear quantum entanglement
ry = TwoLocal(qubitOp.num_qubits, "ry", "cz",
reps = 2, entanglement = "linear")
####### build your code below #########
# build a Variational Quantum Eigensolver (VQE) algorithm instance,
# with the respective Aer Sample, Parametrized Two-Local Ansatz
# Quantum Circuit, and Nakanishi-Fujii-Todo (NFT) Optimizer,
# to solve the Traveling Salesman Problem (TSP) created before
vqe = SamplingVQE(sampler=AerSampler(), ansatz=ry, optimizer=optimizer)
####### build your code above #########
# compute the minimum eigenvalue for
# the Variational Quantum Eigensolver (VQE) algorithm instance
# created before to solve the Traveling Salesman Problem (TSP)
# created before, using the Qubit Operations retrieved before
result = vqe.compute_minimum_eigenvalue(qubitOp)
# print the energy values from minimum eigenvalue computed before
# from Variational Quantum Eigensolver (VQE) algorithm instance
# that solved the Traveling Salesman Problem (TSP)
print("Energy:", result.eigenvalue.real)
# print the elepsed time to compute minimum eigenvalue
# from Variational Quantum Eigensolver (VQE) algorithm instance
# that solved the Traveling Salesman Problem (TSP)
print("Elapsed Time (secs):", result.optimizer_time)
# retrieve the most likely saple from the eigenstate
# from the minimum eigenvalue computed before
# from Variational Quantum Eigensolver (VQE) algorithm instance
# that solved the Traveling Salesman Problem (TSP),
# as one the possible solutions for it
x = tsp.sample_most_likely(result.eigenstate)
# retrieve the boolean flag with respect to
# the fact that the solution achieved is feasible
# for the Quadratic Unconstrained Binary Optimization (QUBO) Program
# formulating the pretended Traveling Salesman Problem (TSP)
print("Feasible:", qubo.is_feasible(x))
# retrieves (and interprets) the solution result as a list of
# nodes' indices corresponding to the real solution
# for the pretended Traveling Salesman Problem (TSP)
z = tsp.interpret(x)
# print the list of nodes' indices
# corresponding to the real solution (nodes' sequence)
# for the pretended Traveling Salesman Problem (TSP)
print("Solution:", z)
# print solution to the objective function
# corresponding to the real solution (nodes' sequence)
# for the pretended Traveling Salesman Problem (TSP)
print("Solution Objective:", tsp.tsp_value(z, adj_matrix))
# draw the solution of the pretended Traveling Salesman Problem (TSP)
# solution, in the respective graph representation
draw_tsp_solution(tsp.graph, z, colors, pos)
# run this cell to submit your answer
# import the grader for the coding exercise of the lab/badge 6
from qc_grader.challenges.quantum_explorers23 import grade_badge6_code
# expected result type: ( tsp: Tsp, qubo: QuadraticProgram,
# result: SamplingVQEResult )
grade_badge6_code(tsp, qubo, result)
# import the Qiskit Runtime Service, Session, and Sampler,
# from the Qiksit's IBM Runtime module
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler
# create a Qiskit's Runtime Service object,
# using the IBM Quantum channel
service = QiskitRuntimeService( channel="ibm_quantum" )
# retrieve the least-busy backend
# with a minimum number of qubits
# corresponding to the number of qubits
# required for the retrieved Qubit Operations
# (this step can take a while)
real_backend = service.least_busy( min_num_qubits=qubitOp.num_qubits,
simulator=False )
# print the information about the best (i.e., the least-busy)
# backend with a minimum number of two qubits, and an informative
# message about the job submission on this backend
print(f"The least busy backend is {real_backend.name}!")
# within the context of a Session configured
# with the Qiskit's Runtime Service object,
# created before, using the IBM Quantum channel,
# and also using the backend defined before
# with Session( service=service, backend=real_backend ) as session:
###### add your answers from the above code cell here #######
###### before running this code cell itself #######
# build a Variational Quantum Eigensolver (VQE) algorithm instance,
# with the respective Aer Sample, Parametrized Two-Local Ansatz
# Quantum Circuit, and Nakanishi-Fujii-Todo (NFT) Optimizer,
# to solve the Traveling Salesman Problem (TSP) created before
#vqe = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=optimizer)
# compute the minimum eigenvalue for
# the Variational Quantum Eigensolver (VQE) algorithm instance
# created before to solve the Traveling Salesman Problem (TSP)
# created before, using the Qubit Operations retrieved before
#result = vqe.compute_minimum_eigenvalue(qubitOp)
# compute the minimum eigenvalue for
# the Variational Quantum Eigensolver (VQE) algorithm instance
# created before to solve the Traveling Salesman Problem (TSP)
# created before, using the Qubit Operations retrieved before
#result = vqe.compute_minimum_eigenvalue(qubitOp)
# print the energy values from minimum eigenvalue computed before
# from Variational Quantum Eigensolver (VQE) algorithm instance
# that solved the Traveling Salesman Problem (TSP)
#print("Energy:", result.eigenvalue.real)
# print the elepsed time to compute minimum eigenvalue
# from Variational Quantum Eigensolver (VQE) algorithm instance
# that solved the Traveling Salesman Problem (TSP)
#print("Elapsed Time (secs):", result.optimizer_time)
# retrieve the most likely saple from the eigenstate
# from the minimum eigenvalue computed before
# from Variational Quantum Eigensolver (VQE) algorithm instance
# that solved the Traveling Salesman Problem (TSP),
# as one the possible solutions for it
#x = tsp.sample_most_likely(result.eigenstate)
# retrieve the boolean flag with respect to
# the fact that the solution achieved is feasible
# for the Quadratic Unconstrained Binary Optimization (QUBO) Program
# formulating the pretended Traveling Salesman Problem (TSP)
#print("Feasible:", qubo.is_feasible(x))
# retrieves (and interprets) the solution result as a list of
# nodes' indices corresponding to the real solution
# for the pretended Traveling Salesman Problem (TSP)
#z = tsp.interpret(x)
# print the list of nodes' indices
# corresponding to the real solution (nodes' sequence)
# for the pretended Traveling Salesman Problem (TSP)
#print("Solution:", z)
# print solution to the objective function
# corresponding to the real solution (nodes' sequence)
# for the pretended Traveling Salesman Problem (TSP)
#print("Solution Objective:", tsp.tsp_value(z, adj_matrix))
# draw the solution of the pretended Traveling Salesman Problem (TSP)
# solution, in the respective graph representation
#draw_tsp_solution(tsp.graph, z, colors, pos)
# build your code here
answer13 = [1]
# run this cell to submit your answer
# import the grader for the exercise 13 of the lab/badge 6
from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex13
# expected result type: List
grade_badge6_ex13(answer13)
# build your code here
answer14 = [1]
# run this cell to submit your answer
# import the grader for the exercise 14 of the lab/badge 6
from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex14
# expected result type: List
grade_badge6_ex14(answer14)
# build your code here
answer15 = [4]
# run this cell to submit your answer
# import the grader for the exercise 15 of the lab/badge 6
from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex15
# expected result type: List
grade_badge6_ex15(answer15)
# run this cell to check whether you have passed
# import the grader for the badge 6 of
# the IBM Qiskit's Quantum Explorers 2023-2024
from qc_grader.challenges.quantum_explorers23 import grade_badge6_score
# grade the score of the quiz of the lab for the badge 6
grade_badge6_score("en")
|
https://github.com/derivation/quantum_image_edge_detection
|
derivation
|
import numpy as np
from numpy import pi
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
filename = './schrodin_yang.png'
im = mpimg.imread(filename)
fig, ax = plt.subplots()
ax.imshow(im)
from skimage.transform import resize
n_pixels = 2**5
im = resize(im, (n_pixels, n_pixels))
fig, ax = plt.subplots()
ax.imshow(im)
data = im[:,:,0].ravel()
from qiskit_aqua.components.initial_states import Custom
n_qubits = np.int_(np.log2(len(data)))
init_state = Custom(n_qubits, state_vector=data)
circ = init_state.construct_circuit('circuit')
qr = circ.qregs
from copy import deepcopy
circ_init = deepcopy(circ)
circ.h(qr[0][0])
from qiskit import BasicAer, execute
simulator = BasicAer.get_backend('statevector_simulator')
result = execute(circ, simulator).result()
final_state_vector = result.get_statevector(circ)
edge_even = np.real(final_state_vector)
n_rows = int(np.sqrt(len(edge_even)))
edge_even = edge_even.reshape(n_rows, -1)
edge_even[:,::2] = 0
fig, ax = plt.subplots(1,2)
ax[0].imshow(edge_even)
ax[1].imshow(im)
def qft(c, q, n):
"""n-qubit QFT on q in c."""
for j in range(n):
for k in range(j):
c.cu1(pi/float(2**(j-k)), q[j], q[k])
c.h(q[j])
def iqft(c, q, n):
"""n-qubit IQFT on q in c."""
for j in range(n):
for k in range(j):
c.cu1(-pi/float(2**(j-k)), q[int(n-j-1)], q[int(n-k-1)])
c.h(q[int(n-j-1)])
def shiftBases(c, q, n, p):
"""Shift the register q by p positions"""
iqft(c,q,n)
for k in range(n):
c.u1(-p*2*pi/float(2**(n-k)), q[int(n-k-1)])
qft(c,q,n)
from qiskit import QuantumRegister, QuantumCircuit
n = 2
q = QuantumRegister(n,'q')
c = QuantumCircuit(q)
iqft(c,q,n)
shiftBases(c,q,n,1)
qft(c,q,n)
c.draw(output='mpl')
circ = deepcopy(circ_init)
qr = circ.qregs
shiftBases(circ,qr[0],n_qubits,1)
circ.h(qr[0][0])
shiftBases(circ,qr[0],n_qubits,-1)
simulator = BasicAer.get_backend('statevector_simulator')
result = execute(circ, simulator).result()
final_state_vector = result.get_statevector(circ)
edge_odd = np.real(final_state_vector)
n_rows = np.int_(np.sqrt(len(edge_odd)))
edge_odd = edge_odd.reshape(n_rows, -1)
edge_odd[:,1::2] = 0
fig, ax = plt.subplots(1,2)
ax[0].imshow(edge_odd)
ax[1].imshow(im)
edge = edge_even + edge_odd
fig, ax = plt.subplots(1,2)
ax[0].imshow(edge)
ax[1].imshow(im)
|
https://github.com/derivation/quantum_image_edge_detection
|
derivation
|
import numpy as np
from numpy import pi
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from skimage.transform import resize
filename = './schrodin_yang.png'
im = mpimg.imread(filename)
n_pixels = 2**5
im = resize(im, (n_pixels, n_pixels))
data = im[:,:,0].ravel()
fig, ax = plt.subplots()
ax.imshow(im)
n_qubits = int(np.log2(len(data)))
from qiskit_aqua.components.initial_states import Custom
init_state = Custom(n_qubits, state_vector=data)
circ = init_state.construct_circuit('circuit')
qr = circ.qregs
# circ.draw()
circ.h(qr[0][0])
from qiskit import BasicAer, execute
simulator = BasicAer.get_backend('statevector_simulator')
sim_result = execute(circ, simulator).result()
final_state = sim_result.get_statevector(circ)
edge = np.real(final_state)
n_rows = int(np.sqrt(len(edge)))
n_cols = n_rows
edge = edge.reshape(n_rows, n_cols)
edge[:,::2] = 0
fig, ax = plt.subplots(1,2)
ax[0].imshow(edge)
ax[1].imshow(im)
|
https://github.com/derivation/quantum_image_edge_detection
|
derivation
|
# import_demo_tools.py
import numpy as np
from numpy import pi
import matplotlib.pyplot as plt
from qiskit_aqua.components.initial_states import Custom
from qiskit import BasicAer, execute
|
https://github.com/derivation/quantum_image_edge_detection
|
derivation
|
import numpy as np
from numpy import pi
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from skimage.transform import resize
filename = './schrodin_yang.png'
im = mpimg.imread(filename)
n_pixels = 2**5
im = resize(im, (n_pixels, n_pixels))
data = im[:,:,0].ravel()
fig, ax = plt.subplots()
ax.imshow(im)
n_qubits = int(np.log2(len(data)))
from qiskit_aqua.components.initial_states import Custom
init_state = Custom(n_qubits, state_vector=data)
circ = init_state.construct_circuit('circuit')
qr = circ.qregs
# circ.draw()
circ.h(qr[0][0])
from qiskit import BasicAer, execute
simulator = BasicAer.get_backend('statevector_simulator')
sim_result = execute(circ, simulator).result()
final_state = sim_result.get_statevector(circ)
edge = np.real(final_state)
n_rows = int(np.sqrt(len(edge)))
n_cols = n_rows
edge = edge.reshape(n_rows, n_cols)
edge[:,::2] = 0
fig, ax = plt.subplots(1,2)
ax[0].imshow(edge)
ax[1].imshow(im)
|
https://github.com/qiskit-fall-fest-hackathon-france/qiskit-fall-fest-hackathon-france
|
qiskit-fall-fest-hackathon-france
|
import qiskit
qiskit.__qiskit_version__
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr,cr)
qc.draw()
qc.h(qr[0])
qc.draw()
qc = QuantumCircuit(qr,cr)
qc.h(qr[0])
qc.cx(qr[0],qr[1])
qc.measure(qr,cr)
qc.draw()
from qiskit import execute
from qiskit import Aer
print(Aer.backends()) #, nicer printout below:
backend_list = Aer.backends()
for be in backend_list:
print(be)
backend = Aer.get_backend('qasm_simulator')
job = execute(qc,backend,shots=100000)
print(job)
my_results = job.result()
print(my_results)
print(my_results.get_counts())
# with shots=1, you will get a count of 1 either on 00 or on 11
job = execute(qc,backend, shots=111)
my_results = job.result()
print(my_results.get_counts(qc))
from qiskit.tools.visualization import plot_histogram
plot_histogram(my_results.get_counts(qc))
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr,cr)
qc.x(qr[0])
qc.id(qr[1])
qc.measure(qr,cr)
qc.draw()
# with shots=1, you will get a count of 1 either on 00 or on 11
job = execute(qc,backend, shots=1024)
my_results = job.result()
print(my_results.get_counts(qc))
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr,cr)
qc.h(qr[0])
qc.cx(qr[0],qr[1])
qc.measure(qr,cr)
qc.draw(output='latex')
# how to use the machines and simulator in the cloud
from qiskit import IBMQ
MY_API_TOKEN= 'e5f5ed26c560465a044adb6bbbad67743cd41365ff700fe7ab7104ef83518ccff6b28b4b52ecd827de2df397aba6a6e8eb88cc154842ab203f1aadfbdff3f024'
IBMQ.save_account(MY_API_TOKEN, overwrite=True)
IBMQ.load_account()
sp = IBMQ.get_provider(hub='ibm-q')
# list backends available for this provider
print(sp.backends())
sp = IBMQ.get_provider(hub='ibm-q') # selected provider
backends_set = set()
for b in selected_provider.backends():
backends_set.add(str(b))
print("backend name queue qubits operational status message")
print("------------------------------- ----- ------ ----------- --------------")
for b in backends_set:
be = sp.get_backend(b)
pj = be.status().pending_jobs
qb = be.configuration().n_qubits
op = be.status().operational
sm = be.status().status_msg
print(f"{b:32} {pj:4} {qb:6}{op:12} {sm:6}")
print("------------------------------ ----- ------ ----------- --------------")
backend = selected_provider.get_backend('simulator_statevector')
# IBMQ for access to online devices and helps manage your IBM Q account data from your workstation.
from qiskit import IBMQ
MY_API_TOKEN= 'e5f5ed26c560465a044adb6bbbad67743cd41365ff700fe7ab7104ef83518ccff6b28b4b52ecd827de2df397aba6a6e8eb88cc154842ab203f1aadfbdff3f024'
IBMQ.save_account(MY_API_TOKEN, overwrite=True)
IBMQ.load_account()
# choose one available provider
selected_provider = IBMQ.get_provider(hub='ibm-q')
# list backends available for this provider
selected_provider.backends()
# small program to get backends configs and status
# using least_busy() is more straightforward, this is to show
# how we get info from the provider's backends
sp = IBMQ.get_provider(hub='ibm-q') # selected provider
backends_set = set()
for b in selected_provider.backends():
backends_set.add(str(b))
print("backend name queue qubits operational status message")
print("------------------------------- ----- ------ ----------- --------------")
for b in backends_set:
be = sp.get_backend(b)
pj = be.status().pending_jobs
qb = be.configuration().n_qubits
op = be.status().operational
sm = be.status().status_msg
print(f"{b:32} {pj:4} {qb:6}{op:12} {sm:6}")
print("------------------------------ ----- ------ ----------- --------------")
backend = sp.get_backend('ibmq_belem')
backend.name()
# we want more than 1 qubit (we need 2), on an operationnal backend which is not a simulator
from qiskit.providers.ibmq import least_busy
backend = least_busy(sp.backends(filters = lambda x: x.configuration().n_qubits >= 2 and
not x.configuration().simulator and x.status().operational == True))
print("least busy backend: ", backend)
# execution
from qiskit.tools.monitor import job_monitor
job = execute(qc,backend)
print(job.job_id())
job_monitor(job)
res = job.result()
from qiskit.tools.visualization import plot_histogram
d = (res.get_counts(qc))
d
plot_histogram(d)
import numpy as np
from qiskit import Aer, QuantumCircuit, execute
from qiskit.visualization import plot_histogram, plot_state_qsphere
from qiskit.quantum_info import Statevector
from IPython.display import display, Math, Latex
# 1
def create_circuit():
qc = QuantumCircuit(1)
#
# FILL YOUR CODE IN HERE
#
#
return qc
# check solution
qc = create_circuit()
sv = Statevector.from_label('0')
sv = sv.evolve(qc)
plot_state_qsphere(sv.data, show_state_labels=True, show_state_phases=True)
# 2
def create_circuit():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
return qc
qc = create_circuit()
sv = Statevector.from_label('0')
sv = sv.evolve(qc)
plot_state_qsphere(sv.data, show_state_labels=True, show_state_phases=True)
# 3
def create_circuit():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
return qc
qc = create_circuit()
sv = Statevector.from_label('0')
sv = sv.evolve(qc)
plot_state_qsphere(sv.data, show_state_labels=True, show_state_phases=True)
# 4
def create_circuit():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
#
return qc
qc = create_circuit()
sv = Statevector.from_label('0')
sv = sv.evolve(qc)
plot_state_qsphere(sv.data, show_state_labels=True, show_state_phases=True)
# 5
def create_circuit():
qc = QuantumCircuit(2)
#
#
# FILL YOUR CODE IN HERE
qc.h(0)
qc.cx(0,1)
#
return qc
qc = create_circuit()
sv = Statevector.from_label('00')
sv = sv.evolve(qc)
plot_state_qsphere(sv.data, show_state_labels=True, show_state_phases=True)
# 6
def create_circuit():
qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also
# two classical bits for the measurement later
#
#
# FILL YOUR CODE IN HERE
#
return qc
qc = create_circuit()
sv = Statevector.from_label('00')
sv = sv.evolve(qc)
print(sv)
plot_state_qsphere(sv.data, show_state_labels=True, show_state_phases=True)
# 7
qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0
qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1
qc.draw(output='mpl') # we draw the circuit
# 8
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc, backend, shots = 1000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc)
print(counts)
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
# 9
def create_circuit():
qc = QuantumCircuit(2)
## initializing part
qc.rx(np.pi/3,0)
qc.x(1)
## end of initializing
#
#
# FILL YOUR CODE IN HERE
#
#
return qc
qc = create_circuit()
sv = Statevector.from_label('00')
sv = sv.evolve(qc)
print(sv)
plot_state_qsphere(sv.data, show_state_labels=True, show_state_phases=True)
# 10
#
#
# FILL YOUR CODE IN HERE
#
#
#
#
# FILL YOUR CODE IN HERE
#
#
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
from qiskit.tools.visualization import plot_histogram
from qiskit import IBMQ, BasicAer
from qiskit.tools.jupyter import *
import matplotlib.pyplot as plt
%matplotlib inline
####
backend = BasicAer.get_backend('qasm_simulator')
shots_sim = 10
job_sim = execute(qc, backend, shots=shots_sim)
stats_sim = job_sim.result().get_counts()
def plot_letter (stats, shots):
### code from the qiskit.org smiley demo
for bitString in stats:
char = chr(int( bitString[0:7] ,2)) # get string of the leftmost 7 bits and convert to an ASCII character
prob = stats[bitString] / shots # fraction of shots for which this result occurred
# create plot with all characters on top of each other with alpha given by how often it turned up in the output
plt.annotate( char, (0.5,0.5), va="center", ha="center", color = (0,0,0, prob ), size = 300)
if (prob>0.05): # list prob and char for the dominant results (occurred for more than 5% of shots)
print(str(prob)+"\t"+char)
plt.axis('off')
plt.show()
print(shots_sim)
print(stats_sim)
plot_letter(stats_sim, shots_sim)
|
https://github.com/pbark/qiskit_tutorials
|
pbark
|
print("Hello! I'm a code cell")
print('Set up started...')
%matplotlib notebook
import sys
sys.path.append('game_engines')
import hello_quantum
print('Set up complete!')
initialize = []
success_condition = {}
allowed_gates = {'0': {'NOT': 3}, '1': {}, 'both': {}}
vi = [[1], False, False]
qubit_names = {'0':'the only bit', '1':None}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = []
success_condition = {}
allowed_gates = {'0': {}, '1': {'NOT': 0}, 'both': {}}
vi = [[], False, False]
qubit_names = {'0':'the bit on the left', '1':'the bit on the right'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '0']]
success_condition = {'IZ': -1.0}
allowed_gates = {'0': {'CNOT': 0}, '1': {'CNOT': 0}, 'both': {}}
vi = [[], False, False]
qubit_names = {'0':'the bit on the left', '1':'the bit on the right'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '0']]
success_condition = {'ZI': 1.0, 'IZ': -1.0}
allowed_gates = {'0': {'CNOT': 0}, '1': {'CNOT': 0}, 'both': {}}
vi = [[], False, False]
qubit_names = {'0':'the bit on the left', '1':'the bit on the right'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '0']]
success_condition = {'IZ': 0.0}
allowed_gates = {'0': {'CNOT': 0}, '1': {'CNOT': 0}, 'both': {}}
vi = [[], False, False]
qubit_names = {'0':'the bit on the left', '1':'the bit on the right'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '0']]
success_condition = {'ZZ': -1.0}
allowed_gates = {'0': {'NOT': 0, 'CNOT': 0}, '1': {'NOT': 0, 'CNOT': 0}, 'both': {}}
vi = [[], False, True]
qubit_names = {'0':'the bit on the left', '1':'the bit on the right'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '1']]
success_condition = {'IZ': -1.0}
allowed_gates = {'0': {'NOT': 0, 'CNOT': 0}, '1': {'NOT': 0, 'CNOT': 0}, 'both': {}}
vi = [[], False, True]
qubit_names = {'0':'the bit on the left', '1':'the bit on the right'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [ ["x","0"] ]
success_condition = {"ZI":1.0}
allowed_gates = { "0":{"x":3}, "1":{}, "both":{} }
vi = [[1],True,True]
qubit_names = {'0':'the only qubit', '1':None}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '0']]
success_condition = {'ZI': 1.0}
allowed_gates = {'0': {'x': 0}, '1': {}, 'both': {}}
vi = [[1], True, True]
qubit_names = {'0':'the only qubit', '1':None}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '1']]
success_condition = {'IZ': 1.0}
allowed_gates = {'0': {}, '1': {'x': 0}, 'both': {}}
vi = [[0], True, True]
qubit_names = {'0':None, '1':'the other qubit'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = []
success_condition = {'ZI': 0.0}
allowed_gates = {'0': {'h': 3}, '1': {}, 'both': {}}
vi = [[1], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '1']]
success_condition = {'IZ': 1.0}
allowed_gates = {'0': {}, '1': {'x': 3, 'h': 0}, 'both': {}}
vi = [[0], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '0'], ['z', '0']]
success_condition = {'XI': 1.0}
allowed_gates = {'0': {'z': 0, 'h': 0}, '1': {}, 'both': {}}
vi = [[1], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = []
success_condition = {'ZI': -1.0}
allowed_gates = {'0': {'z': 0, 'h': 0}, '1': {}, 'both': {}}
vi = [[1], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '0']]
success_condition = {'IX': 1.0}
allowed_gates = {'0': {}, '1': {'z': 0, 'h': 0}, 'both': {}}
vi = [[0], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['ry(pi/4)', '1']]
success_condition = {'IZ': -0.7071, 'IX': -0.7071}
allowed_gates = {'0': {}, '1': {'z': 0, 'h': 0}, 'both': {}}
vi = [[0], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '1']]
success_condition = {'ZI': 0.0, 'IZ': 0.0}
allowed_gates = {'0': {'x': 0, 'z': 0, 'h': 0}, '1': {'x': 0, 'z': 0, 'h': 0}, 'both': {}}
vi = [[], True, False]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h','0'],['h','1']]
success_condition = {'ZZ': -1.0}
allowed_gates = {'0': {'x': 0, 'z': 0, 'h': 0}, '1': {'x': 0, 'z': 0, 'h': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x','0']]
success_condition = {'XX': 1.0}
allowed_gates = {'0': {'x': 0, 'z': 0, 'h': 0}, '1': {'x': 0, 'z': 0, 'h': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = []
success_condition = {'XZ': -1.0}
allowed_gates = {'0': {'x': 0, 'z': 0, 'h': 0}, '1': {'x': 0, 'z': 0, 'h': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['ry(-pi/4)', '1'], ['ry(-pi/4)','0']]
success_condition = {'ZI': -0.7071, 'IZ': -0.7071}
allowed_gates = {'0': {'x': 0}, '1': {'x': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '1'], ['x','0']]
success_condition = {'XI':1, 'IX':1}
allowed_gates = {'0': {'z': 0, 'h': 0}, '1': {'z': 0, 'h': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '0']]
success_condition = {'ZI': 1.0, 'IZ': -1.0}
allowed_gates = {'0': {'cx': 0}, '1': {'cx': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '0'],['x', '1']]
success_condition = {'XI': -1.0, 'IZ': 1.0}
allowed_gates = {'0': {'h': 0, 'cz': 0}, '1': {'cx': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '0'],['x', '1'],['h', '1']]
success_condition = { }
allowed_gates = {'0':{'cz': 2}, '1':{'cz': 2}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '0']]
success_condition = {'IZ': -1.0}
allowed_gates = {'0': {'h':0}, '1': {'h':0}, 'both': {'cz': 0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '0'],['h', '1']]
success_condition = {'XI': -1.0, 'IX': -1.0}
allowed_gates = {'0': {}, '1': {'z':0,'cx': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = []
success_condition = {'IZ': -1.0}
allowed_gates = {'0': {'x':0,'h':0,'cx':0}, '1': {'h':0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['ry(-pi/4)','0'],['ry(-pi/4)','0'],['ry(-pi/4)','0'],['x','0'],['x','1']]
success_condition = {'ZI': -1.0,'XI':0,'IZ':0.7071,'IX':-0.7071}
allowed_gates = {'0': {'h':0}, '1': {'h':0}, 'both': {'cz': 0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x','0'],['h','1']]
success_condition = {'IX':1,'ZI':-1}
allowed_gates = {'0': {'h':0}, '1': {'h':0}, 'both': {'cz':3}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names,shots=2000)
initialize = [['x','1']]
success_condition = {'IZ':1.0,'ZI':-1.0}
allowed_gates = {'0': {'h':0}, '1': {'h':0}, 'both': {'cz':0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names,shots=2000)
initialize = []
success_condition = {}
allowed_gates = {'0': {'ry(pi/4)': 4}, '1': {}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x','0']]
success_condition = {'XX': 1.0}
allowed_gates = {'0': {'x': 0, 'z': 0, 'h': 0}, '1': {'x': 0, 'z': 0, 'h': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
initialize = []
success_condition = {'ZI': -1.0}
allowed_gates = {'0': {'bloch':1, 'ry(pi/4)': 0}, '1':{}, 'both': {'unbloch':0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
initialize = [['h','0'],['h','1']]
success_condition = {'ZI': -1.0,'IZ': -1.0}
allowed_gates = {'0': {'bloch':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, '1': {'bloch':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, 'both': {'unbloch':0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
initialize = [['h','0']]
success_condition = {'ZZ': 1.0}
allowed_gates = {'0': {}, '1': {'bloch':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, 'both': {'unbloch':0,'cz':0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
initialize = [['ry(pi/4)','0'],['ry(pi/4)','1']]
success_condition = {'ZI': 1.0,'IZ': 1.0}
allowed_gates = {'0': {'bloch':0, 'z':0, 'ry(pi/4)': 1}, '1': {'bloch':0, 'x':0, 'ry(pi/4)': 1}, 'both': {'unbloch':0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
initialize = [['x','0'],['h','1']]
success_condition = {'IZ': 1.0}
allowed_gates = {'0': {}, '1': {'bloch':0, 'cx':0, 'ry(pi/4)': 1, 'ry(-pi/4)': 1}, 'both': {'unbloch':0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
initialize = []
success_condition = {'IZ': 1.0,'IX': 1.0}
allowed_gates = {'0': {'bloch':0, 'x':0, 'z':0, 'h':0, 'cx':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, '1': {'bloch':0, 'x':0, 'z':0, 'h':0, 'cx':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, 'both': {'cz':0, 'unbloch':0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
import random
def setup_variables ():
### Replace this section with anything you want ###
r = random.random()
A = r*(2/3)
B = r*(1/3)
### End of section ###
return A, B
def hash2bit ( variable, hash ):
### Replace this section with anything you want ###
if hash=='V':
bit = (variable<0.5)
elif hash=='H':
bit = (variable<0.25)
bit = str(int(bit))
### End of section ###
return bit
shots = 8192
def calculate_P ( ):
P = {}
for hashes in ['VV','VH','HV','HH']:
# calculate each P[hashes] by sampling over `shots` samples
P[hashes] = 0
for shot in range(shots):
A, B = setup_variables()
a = hash2bit ( A, hashes[0] ) # hash type for variable `A` is the first character of `hashes`
b = hash2bit ( B, hashes[1] ) # hash type for variable `B` is the second character of `hashes`
P[hashes] += (a!=b) / shots
return P
P = calculate_P()
print(P)
def bell_test (P):
sum_P = sum(P.values())
for hashes in P:
bound = sum_P - P[hashes]
print("The upper bound for P['"+hashes+"'] is "+str(bound))
print("The value of P['"+hashes+"'] is "+str(P[hashes]))
if P[hashes]<=bound:
print("The upper bound is obeyed :)\n")
else:
if P[hashes]-bound < 0.1:
print("This seems to have gone over the upper bound, but only by a little bit :S\nProbably just rounding errors or statistical noise.\n")
else:
print("!!!!! This has gone well over the upper bound :O !!!!!\n")
bell_test(P)
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
def initialize_program ():
qubit = QuantumRegister(2)
A = qubit[0]
B = qubit[1]
bit = ClassicalRegister(2)
a = bit[0]
b = bit[1]
qc = QuantumCircuit(qubit, bit)
return A, B, a, b, qc
def hash2bit ( variable, hash, bit, qc ):
if hash=='H':
qc.h( variable )
qc.measure( variable, bit )
initialize = []
success_condition = {'ZZ':-0.7071,'ZX':-0.7071,'XZ':-0.7071,'XX':-0.7071}
allowed_gates = {'0': {'bloch':0, 'x':0, 'z':0, 'h':0, 'cx':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, '1': {'bloch':0, 'x':0, 'z':0, 'h':0, 'cx':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, 'both': {'cz':0, 'unbloch':0}}
vi = [[], True, True]
qubit_names = {'0':'A', '1':'B'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
import numpy as np
def setup_variables ( A, B, qc ):
for line in puzzle.program:
eval(line)
shots = 8192
from qiskit import execute
def calculate_P ( backend ):
P = {}
program = {}
for hashes in ['VV','VH','HV','HH']:
A, B, a, b, program[hashes] = initialize_program ()
setup_variables( A, B, program[hashes] )
hash2bit ( A, hashes[0], a, program[hashes])
hash2bit ( B, hashes[1], b, program[hashes])
# submit jobs
job = execute( list(program.values()), backend, shots=shots )
# get the results
for hashes in ['VV','VH','HV','HH']:
stats = job.result().get_counts(program[hashes])
P[hashes] = 0
for string in stats.keys():
a = string[-1]
b = string[-2]
if a!=b:
P[hashes] += stats[string] / shots
return P
device = 'qasm_simulator'
from qiskit import Aer, IBMQ
try:
IBMQ.load_accounts()
except:
pass
try:
backend = Aer.get_backend(device)
except:
backend = IBMQ.get_backend(device)
print(backend.status())
P = calculate_P( backend )
print(P)
bell_test( P )
|
https://github.com/pbark/qiskit_tutorials
|
pbark
|
# import common packages
import numpy as np
import matplotlib.pyplot as plt
from qiskit import Aer, IBMQ, QuantumRegister
from qiskit.providers.ibmq import least_busy
from qiskit.providers.aer import noise
# lib from Qiskit Aqua
from qiskit.aqua import Operator, QuantumInstance
from qiskit.aqua.algorithms import VQE, ExactEigensolver
from qiskit.aqua.components.optimizers import COBYLA, SPSA, L_BFGS_B
from qiskit.aqua.components.variational_forms import RY, RYRZ, SwapRZ
# lib from Qiskit Aqua Chemistry
from qiskit.chemistry import QiskitChemistry
from qiskit.chemistry import FermionicOperator
from qiskit.chemistry.drivers import PySCFDriver, UnitsType
from qiskit.chemistry.aqua_extensions.components.variational_forms import UCCSD
from qiskit.chemistry.aqua_extensions.components.initial_states import HartreeFock
# setup qiskit.chemistry logging
import logging
from qiskit.chemistry import set_qiskit_chemistry_logging
# function that allows us to create multiple figures in single notebook cell
def show_figure(fig):
dummy_fig = plt.figure()
new_dummy_fig_manager = dummy_fig.canvas.manager
new_dummy_fig_manager.canvas.figure = fig
fig.set_canvas(new_dummy_fig_manager.canvas)
set_qiskit_chemistry_logging(logging.INFO) # choose among DEBUG, INFO, WARNING, ERROR, CRITICAL and NOTSET
driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 1.6', unit=UnitsType.ANGSTROM,
charge=0, spin=0, basis='sto3g')
molecule = driver.run()
nuclear_repulsion_energy = molecule.nuclear_repulsion_energy
num_particles = molecule.num_alpha + molecule.num_beta
num_spin_orbitals = molecule.num_orbitals * 2
print("HF energy: {}".format(molecule.hf_energy - molecule.nuclear_repulsion_energy))
print("# of electrons: {}".format(num_particles))
print("# of spin orbitals: {}".format(num_spin_orbitals))
print("Contents of molecule object: \n{}".format(sorted(molecule.__dir__())))
# get the integrals from molecule object
h1 = molecule.one_body_integrals
h2 = molecule.two_body_integrals
# create a fermionic operator
ferOp = FermionicOperator(h1=h1, h2=h2)
map_type = 'parity' # 'jordan_wigner', 'parity', 'bravyi_kitaev', 'bksf'
# if 'parity' mapping is selected, reduce the number of qubits (-2 qubits)
qubit_reduction = True if map_type == 'parity' else False
qubitOp = ferOp.mapping(map_type=map_type, threshold=10**-10) # paulis with coefs below threshold are not considered
qubitOp = qubitOp.two_qubit_reduced_operator(num_particles) if qubit_reduction else qubitOp
qubitOp.chop(10**-10) # cut out the pauli strings with prefacator smaller then
print(qubitOp)
qubitOp.paulis
# to see all the contents of given class
# qubitOp.__dir__()
# one can group the Paulis
# qubitOp.to_grouped_paulis()
# qubitOp.paulis
for pauli in qubitOp.paulis:
print(pauli[0],str(pauli[1]))
max_iter = 200 # maximum number of iterations
# optimizer = COBYLA(maxiter=max_iter)
# optimizer = SPSA(maxiter=max_iter)
optimizer = L_BFGS_B(maxiter=max_iter)
HF_state = HartreeFock(qubitOp.num_qubits, num_spin_orbitals, num_particles, map_type,
qubit_reduction)
HF_state_vec = HF_state.construct_circuit(mode='vector')
# we can use qiskit's vizualisation module to plot the state
from qiskit.visualization import plot_state_city
plot_state_city(HF_state_vec)
# you might want to visualise on the Bloch sphere for a non-superposition state
from qiskit.visualization import plot_state_city, plot_bloch_multivector
plot_bloch_multivector(HF_state_vec)
var_form_uccsd = UCCSD(qubitOp.num_qubits, depth=1,
num_orbitals=num_spin_orbitals, num_particles=num_particles,
active_occupied=None, active_unoccupied=None, # you could modify the active space here
initial_state=HF_state, qubit_mapping=map_type,
two_qubit_reduction=qubit_reduction, num_time_slices=1)
var_form_swaprz = SwapRZ(qubitOp.num_qubits, depth=1,
initial_state=HF_state)
var_form_ryrz = RYRZ(qubitOp.num_qubits, depth=1,
initial_state=HF_state)
# var_form_ry = RY(qubitOp.num_qubits, depth=1,
# initial_state=HF_state)
simultation_type = 'state_vector'# qasm, qasm_cloud, real_device, state_vector
if simultation_type == 'qasm':
sv_mode = False
qasm_simulator = Aer.get_backend('qasm_simulator') # qasm_simulator, ibmq_qasm_simulator
# uncomment this and put your token from the IBMQ website.
#IBMQ.save_account('Your IBMQ API-token', overwrite=True)
IBMQ.load_accounts() # connect with your token to IBMQ
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
print(provider.backends()) # lists available backends
# set the noise model
device = provider.get_backend('ibmq_16_melbourne') # ibmq_16_melbourne
properties = device.properties()
coupling_map = device.configuration().coupling_map
noise_model = noise.device.basic_device_noise_model(properties)
basis_gates = noise_model.basis_gates
shots = 8192 # choose the maximal number of shots (8192 is max on the ibmq_qasm_simulator)
num_qubits = qubitOp.num_qubits
# run on qasm_simulator
quantum_instance = QuantumInstance(qasm_simulator, shots=shots, basis_gates=basis_gates, coupling_map=coupling_map, noise_model=noise_model)
# all the details of noise model
print(noise_model.to_dict())
elif simultation_type == 'qasm_cloud':
sv_mode = False
# uncomment this and put your token from the IBMQ website.
#IBMQ.save_account('Your IBMQ API-token', overwrite=True)
IBMQ.load_accounts() # connect with your token to IBMQ
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
print(provider.backends()) # lists available backends
qasm_simulator_cloud = provider.get_backend('ibmq_qasm_simulator') # ibmq_16_melbourne , ibmq_qasm_simulator
# set the qasm cloud simulator
shots = 8192
quantum_instance = QuantumInstance(qasm_simulator_cloud, shots=shots)
elif simultation_type == 'real_device':
sv_mode = False
# uncomment this and put your token from the IBMQ website.
#IBMQ.save_account('Your IBMQ API-token', overwrite=True)
IBMQ.load_accounts() # connect with your token to IBMQ
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
print(provider.backends()) # lists available backends
# set the noise model
device = provider.get_backend('ibmq_16_melbourne') # ibmq_16_melbourne
# run on qasm_simulator
shots = 8192
quantum_instance = QuantumInstance(device, shots=shots)
elif simultation_type == 'state_vector':
sv_mode = True
num_qubits = qubitOp.num_qubits
sv_simulator = Aer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(sv_simulator)
else:
raise Exception('Please select for simultation_type == qasm, qasm_cloud, real_device, state_vector')
vqe_uccsd = VQE(qubitOp, var_form_uccsd, optimizer)
vqe_ryrz = VQE(qubitOp, var_form_ryrz, optimizer)
vqe_swaprz = VQE(qubitOp, var_form_swaprz, optimizer)
for pauli in qubitOp.paulis:
print('Circuit for:', pauli[1])
circuit_uccsd = vqe_uccsd.construct_circuit(statevector_mode=sv_mode, parameter=np.ones(var_form_uccsd._num_parameters))
for i in range(len(circuit_uccsd)):
fig = circuit_uccsd[i].draw(output='mpl')
show_figure(fig)
fig.show()
circuit_swaprz = vqe_swaprz.construct_circuit(statevector_mode=sv_mode, parameter=np.ones(var_form_swaprz._num_parameters))
circuit_swaprz[1].draw(output='mpl')
circuit_ryrz = vqe_ryrz.construct_circuit(statevector_mode=sv_mode, parameter=np.ones(var_form_ryrz._num_parameters))
circuit_ryrz[1].draw(output='mpl')
results = vqe_uccsd.run(quantum_instance)
print('The computed ground state energy is: {:.12f}'.format(results['eigvals'][0]))
print('The total ground state energy is: {:.12f}'.format(results['eigvals'][0] + nuclear_repulsion_energy))
print("Parameters: {}".format(results['opt_params']))
evolution_time = 100 # how many time steps
num_time_slices = 4 # number of Trotter steps
qr = QuantumRegister(num_qubits,'q')
initial_circuit = HF_state.construct_circuit(mode='circuit')
evolution_circuit = qubitOp.evolve(state_in=initial_circuit, evo_time=evolution_time, evo_mode='circuit',num_time_slices=num_time_slices, expansion_mode='trotter')
evolution_circuit.draw(output='mpl')
max_time=evolution_time
statevector_of_t = np.zeros([max_time,2*num_qubits])
for evo_t in range(max_time):
evolution_circuit = qubitOp.evolve(state_in=initial_circuit, evo_time=evo_t, evo_mode='circuit',num_time_slices=num_time_slices, expansion_mode='trotter')
result = quantum_instance.execute(evolution_circuit)
statevector_of_t[evo_t,:] = np.asarray(result.get_statevector(evolution_circuit))
time_min = 0
time_max = 4
for i in range(time_min, time_max):
fig = plot_state_city(statevector_of_t[i,:])
show_figure(fig)
fig.show()
# First, we use classical eigendecomposition to get ground state energy (including nuclear repulsion energy) as reference.
qiskit_chemistry_dict = {
'driver': {'name': 'HDF5'},
'HDF5': {'hdf5_input': 'H2/H2_equilibrium_0.735_sto-3g.hdf5'},
'operator': {'name':'hamiltonian',
'qubit_mapping': 'parity',
'two_qubit_reduction': True},
'algorithm': {'name': 'ExactEigensolver'}
}
solver = QiskitChemistry()
result_classical = solver.run(qiskit_chemistry_dict)
# Second, we use variational quantum eigensolver (VQE)
qiskit_chemistry_dict['algorithm']['name'] = 'VQE'
qiskit_chemistry_dict['optimizer'] = {'name': 'SPSA', 'max_trials': 350}
qiskit_chemistry_dict['variational_form'] = {'name': 'RYRZ', 'depth': 3, 'entanglement':'full'}
backend = Aer.get_backend('statevector_simulator')
solver = QiskitChemistry()
result = solver.run(qiskit_chemistry_dict, backend=backend)
# We print out the results
print('Ground state energy (classical): {:.12f}'.format(result_classical['energy']))
print('Ground state energy (quantum) : {:.12f}'.format(result['energy']))
print("====================================================")
# You can also print out other info in the field 'printable'
for line in result['printable']:
print(line)
molecule='H2'
maxiter = 10 # increase to allow optimizer to converge, set low to test
mol_distances = np.arange(0.2, 3.1, 0.2)
mol_distances_vqe = np.arange(0.2, 3.1,1)
# Exact eigensolver
qiskit_chemistry_dict_ee = {
'driver': {'name': 'HDF5'},
'HDF5': {'hdf5_input': ''},
'operator': {'name':'hamiltonian',
'qubit_mapping': 'parity',
'two_qubit_reduction': True},
'algorithm': {'name': 'ExactEigensolver'}
}
# choose which backend want to use
# backend = Aer.get_backend('qasm_simulator')
backend = Aer.get_backend('statevector_simulator')
# VQE
qiskit_chemistry_dict_vqe = {
'driver': {'name': 'HDF5'},
'HDF5': {'hdf5_input': ''},
'operator': {'name':'hamiltonian',
'qubit_mapping': 'parity',
'two_qubit_reduction': True},
'algorithm': {'name': 'VQE'},
'optimizer': {'name': 'L_BFGS_B', 'maxiter': maxiter}, # or SPSA, max_trials=200
'variational_form': {'name': 'RY', 'depth': 1, 'entanglement':'full'}, # RYRZ, UCCSD (delete entanglement field)
'backend': {'shots': 1024}
}
algos = ['ExactEigensolver', 'VQE']
energy = np.zeros((len(algos), len(mol_distances)))
energy_vqe = np.zeros((len(algos), len(mol_distances_vqe)))
# Run the algos
for j, algo in enumerate([qiskit_chemistry_dict_ee, qiskit_chemistry_dict_vqe]):
algo_name = algo['algorithm']['name']
print("Using {}".format(algo_name))
if algo_name == 'VQE':
for i, dis in enumerate(mol_distances_vqe):
print("Processing atomic distance: {:1.1f} Angstrom".format(dis), end='\r')
algo['HDF5']['hdf5_input'] = "{}/{:1.1f}_sto-3g.hdf5".format(molecule, dis)
result = solver.run(algo, backend=backend if algo_name == 'VQE' else None)
energy_vqe[j][i] = result['energy']
else:
for i, dis in enumerate(mol_distances):
print("Processing atomic distance: {:1.1f} Angstrom".format(dis), end='\r')
algo['HDF5']['hdf5_input'] = "{}/{:1.1f}_sto-3g.hdf5".format(molecule, dis)
result = solver.run(algo, backend=backend if algo_name == 'VQE' else None)
energy[j][i] = result['energy']
for i, algo in enumerate(algos):
if algo == 'VQE':
plt.plot(mol_distances_vqe, energy_vqe[i], label=algo, linestyle='', marker='x')
else:
plt.plot(mol_distances, energy[i], label=algo)
plt.xlabel('Atomic distance (Angstrom)')
plt.ylabel('Energy [Ha]')
plt.legend()
plt.show()
mol_distances_errors = []
energy_errors = []
for i, pts_vqe in enumerate(mol_distances_vqe):
for j, pts in enumerate(mol_distances):
# find the entries with same bond distances
if pts_vqe == pts:
mol_distances_errors.append(pts)
energy_errors.append(abs(energy[0][j]-energy_vqe[1][i]))
# plot the errors
print('Errors |Exact - VQE|:\n',energy_errors)
plt.plot(mol_distances_errors, energy_errors, label='Errors(Exact-VQE)', linestyle='', marker='x')
# chemical accuracy of 1 mHa
plt.hlines(0.001, 0, 3, colors='k', label='Chemical Accuracy')
plt.legend()
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/anirban-m/qiskit-superstaq
|
anirban-m
|
import qiskit
import qiskit_superstaq
provider = qiskit_superstaq.superstaq_provider.SuperstaQProvider("YOUR API KEY")
circuit1 = qiskit.QuantumCircuit(8)
for i in range(4, 8):
circuit1.h(i)
circuit1.draw(fold=-1)
compiler_output = provider.aqt_compile(circuit1)
print(compiler_output.circuit)
compiler_output.seq.plot(element=0)
circuit2 = qiskit.QuantumCircuit(8)
circuit2.swap(4, 5)
circuit2.h(6)
circuit2.draw(fold=-1)
compiler_output = provider.aqt_compile([circuit1, circuit2])
print(compiler_output.circuits[0])
print()
print(compiler_output.circuits[1])
compiler_output.seq.plot(element=0)
compiler_output.seq.plot(element=1)
|
https://github.com/anirban-m/qiskit-superstaq
|
anirban-m
|
"""
Creates and simulates a bell circuit.
Example Output:
job has successfully run
{'00': 52, '11': 48}
"""
import qiskit
import qiskit_superstaq as qss
# SuperstaQ token retrieved through API
token = "insert api token"
# Create provider using authorization token
superstaq = qss.superstaq_provider.SuperstaQProvider(token)
# Retrieve backend from superstaq provider
backend = superstaq.get_backend("ibmq_qasm_simulator")
# Standard bell circuit
qc = qiskit.QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
# Submit job to backend
job = backend.run(qc, shots=100)
# Get job status
print(job.status().value)
# Get result of job
result = job.result()
# Print job counts
print(result.get_counts())
|
https://github.com/anirban-m/qiskit-superstaq
|
anirban-m
|
"""
Creates and simulates multiple circuits with batch submission.
Example Output:
job has successfully run
[{'00': 44, '11': 56}, {'000': 57, '111': 43}]
{'000': 57, '111': 43}
"""
import qiskit
import qiskit_superstaq as qss
# SuperstaQ token retrieved through API
token = "insert api token"
# Create provider using authorization token
superstaq = qss.superstaq_provider.SuperstaQProvider(token)
# Retrieve backend from superstaq provider
backend = superstaq.get_backend("ibmq_qasm_simulator")
# Standard bell circuit
qc1 = qiskit.QuantumCircuit(2, 2)
qc1.h(0)
qc1.cx(0, 1)
qc1.measure([0, 1], [0, 1])
# 3-qubit GHZ state
qc2 = qiskit.QuantumCircuit(3, 3)
qc2.h(0)
qc2.cx(0, 1)
qc2.cx(0, 2)
qc2.measure([0, 1, 2], [0, 1, 2])
# Submit list of jobs to backend. Circuits submitted simultaneously
# will run with the same backend and the same number of shots.
job = backend.run([qc1, qc2], shots=100)
# The status of the circuit furthest behind in the queue.
print(job.status().value)
# List of result counts
print(job.result().get_counts())
# ith result counts (0-indexed)
print(job.result().get_counts(1))
|
https://github.com/anirban-m/qiskit-superstaq
|
anirban-m
|
import importlib
from typing import List, Optional, Union
import applications_superstaq
import qiskit
try:
import qtrl.sequencer
except ModuleNotFoundError:
pass
class AQTCompilerOutput:
def __init__(
self,
circuits: Union[qiskit.QuantumCircuit, List[qiskit.QuantumCircuit]],
seq: Optional["qtrl.sequencer.Sequence"] = None,
pulse_lists: Optional[Union[List[List], List[List[List]]]] = None,
) -> None:
if isinstance(circuits, qiskit.QuantumCircuit):
self.circuit = circuits
self.pulse_list = pulse_lists
else:
self.circuits = circuits
self.pulse_lists = pulse_lists
self.seq = seq
def has_multiple_circuits(self) -> bool:
"""Returns True if this object represents multiple circuits.
If so, this object has .circuits and .pulse_lists attributes. Otherwise, this object
represents a single circuit, and has .circuit and .pulse_list attributes.
"""
return hasattr(self, "circuits")
def __repr__(self) -> str:
if not self.has_multiple_circuits():
return f"AQTCompilerOutput({self.circuit!r}, {self.seq!r}, {self.pulse_list!r})"
return f"AQTCompilerOutput({self.circuits!r}, {self.seq!r}, {self.pulse_lists!r})"
def read_json(json_dict: dict, circuits_list: bool) -> AQTCompilerOutput:
"""Reads out returned JSON from SuperstaQ API's AQT compilation endpoint.
Args:
json_dict: a JSON dictionary matching the format returned by /aqt_compile endpoint
circuits_list: bool flag that controls whether the returned object has a .circuits
attribute (if True) or a .circuit attribute (False)
Returns:
a AQTCompilerOutput object with the compiled circuit(s). If qtrl is available locally,
the returned object also stores the pulse sequence in the .seq attribute and the
list(s) of cycles in the .pulse_list(s) attribute.
"""
seq = None
pulse_lists = None
if importlib.util.find_spec(
"qtrl"
): # pragma: no cover, b/c qtrl is not open source so it is not in qiskit-superstaq reqs
state_str = json_dict["state_jp"]
state = applications_superstaq.converters.deserialize(state_str)
seq = qtrl.sequencer.Sequence(n_elements=1)
seq.__setstate__(state)
seq.compile()
pulse_lists_str = json_dict["pulse_lists_jp"]
pulse_lists = applications_superstaq.converters.deserialize(pulse_lists_str)
compiled_circuits = [qiskit.QuantumCircuit.from_qasm_str(q) for q in json_dict["qasm_strs"]]
if circuits_list:
return AQTCompilerOutput(compiled_circuits, seq, pulse_lists)
pulse_list = pulse_lists[0] if pulse_lists is not None else None
return AQTCompilerOutput(compiled_circuits[0], seq, pulse_list)
|
https://github.com/anirban-m/qiskit-superstaq
|
anirban-m
|
import importlib
import pickle
from unittest import mock
import applications_superstaq
import pytest
import qiskit
from qiskit_superstaq import aqt
def test_aqt_compiler_output_repr() -> None:
circuit = qiskit.QuantumCircuit(4)
assert repr(aqt.AQTCompilerOutput(circuit)) == f"AQTCompilerOutput({circuit!r}, None, None)"
circuits = [circuit, circuit]
assert repr(aqt.AQTCompilerOutput(circuits)) == f"AQTCompilerOutput({circuits!r}, None, None)"
@mock.patch.dict("sys.modules", {"qtrl": None})
def test_read_json() -> None:
importlib.reload(aqt)
circuit = qiskit.QuantumCircuit(4)
for i in range(4):
circuit.h(i)
state_str = applications_superstaq.converters.serialize({})
pulse_lists_str = applications_superstaq.converters.serialize([[[]]])
json_dict = {
"qasm_strs": [circuit.qasm()],
"state_jp": state_str,
"pulse_lists_jp": pulse_lists_str,
}
out = aqt.read_json(json_dict, circuits_list=False)
assert out.circuit == circuit
assert not hasattr(out, "circuits")
out = aqt.read_json(json_dict, circuits_list=True)
assert out.circuits == [circuit]
assert not hasattr(out, "circuit")
pulse_lists_str = applications_superstaq.converters.serialize([[[]], [[]]])
json_dict = {
"qasm_strs": [circuit.qasm(), circuit.qasm()],
"state_jp": state_str,
"pulse_lists_jp": pulse_lists_str,
}
out = aqt.read_json(json_dict, circuits_list=True)
assert out.circuits == [circuit, circuit]
assert not hasattr(out, "circuit")
def test_read_json_with_qtrl() -> None: # pragma: no cover, b/c test requires qtrl installation
qtrl = pytest.importorskip("qtrl", reason="qtrl not installed")
seq = qtrl.sequencer.Sequence(n_elements=1)
circuit = qiskit.QuantumCircuit(4)
for i in range(4):
circuit.h(i)
state_str = applications_superstaq.converters.serialize(seq.__getstate__())
pulse_lists_str = applications_superstaq.converters.serialize([[[]]])
json_dict = {
"qasm_strs": [circuit.qasm()],
"state_jp": state_str,
"pulse_lists_jp": pulse_lists_str,
}
out = aqt.read_json(json_dict, circuits_list=False)
assert out.circuit == circuit
assert pickle.dumps(out.seq) == pickle.dumps(seq)
assert out.pulse_list == [[]]
assert not hasattr(out, "circuits") and not hasattr(out, "pulse_lists")
out = aqt.read_json(json_dict, circuits_list=True)
assert out.circuits == [circuit]
assert pickle.dumps(out.seq) == pickle.dumps(seq)
assert out.pulse_lists == [[[]]]
assert not hasattr(out, "circuit") and not hasattr(out, "pulse_list")
pulse_lists_str = applications_superstaq.converters.serialize([[[]], [[]]])
json_dict = {
"qasm_strs": [circuit.qasm(), circuit.qasm()],
"state_jp": state_str,
"pulse_lists_jp": pulse_lists_str,
}
out = aqt.read_json(json_dict, circuits_list=True)
assert out.circuits == [circuit, circuit]
assert pickle.dumps(out.seq) == pickle.dumps(seq)
assert out.pulse_lists == [[[]], [[]]]
assert not hasattr(out, "circuit") and not hasattr(out, "pulse_list")
|
https://github.com/anirban-m/qiskit-superstaq
|
anirban-m
|
"""Integration checks that run daily (via Github action) between client and prod server."""
import os
import pytest
import qiskit
import qiskit_superstaq
@pytest.fixture
def provider() -> qiskit_superstaq.superstaq_provider.SuperstaQProvider:
token = os.environ["TEST_USER_TOKEN"]
provider = qiskit_superstaq.superstaq_provider.SuperstaQProvider(token)
return provider
def test_aqt_compile(provider: qiskit_superstaq.superstaq_provider.SuperstaQProvider) -> None:
circuit = qiskit.QuantumCircuit(8)
circuit.h(4)
expected = qiskit.QuantumCircuit(1)
expected.s(0)
expected.sx(0)
expected.s(0)
assert provider.aqt_compile(circuit).circuit == expected
assert provider.aqt_compile([circuit]).circuits == [expected]
assert provider.aqt_compile([circuit, circuit]).circuits == [expected, expected]
|
https://github.com/anirban-m/qiskit-superstaq
|
anirban-m
|
import io
from typing import List, Union
import applications_superstaq
import qiskit
import qiskit.circuit.qpy_serialization
def serialize_circuits(circuits: Union[qiskit.QuantumCircuit, List[qiskit.QuantumCircuit]]) -> str:
"""Serialize QuantumCircuit(s) into a single string
Args:
circuits: a QuantumCircuit or list of QuantumCircuits to be serialized
Returns:
str representing the serialized circuit(s)
"""
buf = io.BytesIO()
qiskit.circuit.qpy_serialization.dump(circuits, buf)
return applications_superstaq.converters._bytes_to_str(buf.getvalue())
def deserialize_circuits(serialized_circuits: str) -> List[qiskit.QuantumCircuit]:
"""Deserialize serialized QuantumCircuit(s)
Args:
serialized_circuits: str generated via qiskit_superstaq.serialization.serialize_circuit()
Returns:
a list of QuantumCircuits
"""
buf = io.BytesIO(applications_superstaq.converters._str_to_bytes(serialized_circuits))
return qiskit.circuit.qpy_serialization.load(buf)
|
https://github.com/anirban-m/qiskit-superstaq
|
anirban-m
|
import qiskit
import qiskit_superstaq
def test_circuit_serialization() -> None:
circuits = [qiskit.QuantumCircuit(3), qiskit.QuantumCircuit(2)]
circuits[0].cx(2, 1)
circuits[0].cz(0, 1)
circuits[1].swap(0, 1)
serialized_circuits = qiskit_superstaq.serialization.serialize_circuits(circuits)
assert isinstance(serialized_circuits, str)
assert qiskit_superstaq.serialization.deserialize_circuits(serialized_circuits) == circuits
|
https://github.com/anirban-m/qiskit-superstaq
|
anirban-m
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
from typing import Any, List, Union
import qiskit
import requests
import qiskit_superstaq as qss
class SuperstaQBackend(qiskit.providers.BackendV1):
def __init__(
self, provider: "qss.superstaq_provider.SuperstaQProvider", url: str, backend: str
) -> None:
self.url = url
self._provider = provider
self.configuration_dict = {
"backend_name": backend,
"backend_version": "n/a",
"n_qubits": -1,
"basis_gates": None,
"gates": [],
"local": False,
"simulator": False,
"conditional": False,
"open_pulse": False,
"memory": False,
"max_shots": -1,
"coupling_map": None,
}
super().__init__(
configuration=qiskit.providers.models.BackendConfiguration.from_dict(
self.configuration_dict
),
provider=provider,
)
@classmethod
def _default_options(cls) -> qiskit.providers.Options:
return qiskit.providers.Options(shots=1000)
def __eq__(self, other: Any) -> bool:
if not isinstance(other, qss.superstaq_backend.SuperstaQBackend):
return False
return (
self._provider == other._provider
and self.configuration_dict == other.configuration_dict
)
def run(
self, circuits: Union[qiskit.QuantumCircuit, List[qiskit.QuantumCircuit]], **kwargs: int
) -> "qss.superstaq_job.SuperstaQJob":
if isinstance(circuits, qiskit.QuantumCircuit):
circuits = [circuits]
superstaq_json = {
"qasm_strings": [circuit.qasm() for circuit in circuits],
"backend": self.name(),
"shots": kwargs.get("shots"),
"ibmq_token": kwargs.get("ibmq_token"),
"ibmq_hub": kwargs.get("ibmq_hub"),
"ibmq_group": kwargs.get("ibmq_group"),
"ibmq_project": kwargs.get("ibmq_project"),
"ibmq_pulse": kwargs.get("ibmq_pulse"),
}
headers = {
"Authorization": self._provider.get_access_token(),
"Content-Type": "application/json",
}
res = requests.post(
self.url + "/" + qss.API_VERSION + "/qasm_strings_multi_job",
json=superstaq_json,
headers=headers,
verify=(self.url == qss.API_URL),
)
res.raise_for_status()
response = res.json()
if "job_ids" not in response:
raise Exception
# we make a virtual job_id that aggregates all of the individual jobs
# into a single one, that comma-separates the individual jobs:
job_id = ",".join(response["job_ids"])
job = qss.superstaq_job.SuperstaQJob(self, job_id)
return job
|
https://github.com/anirban-m/qiskit-superstaq
|
anirban-m
|
import json
from typing import Any, Dict, List
import pytest
import qiskit
import requests
import qiskit_superstaq as qss
def test_default_options() -> None:
ss_provider = qss.superstaq_provider.SuperstaQProvider("MY_TOKEN")
device = qss.superstaq_backend.SuperstaQBackend(
provider=ss_provider,
url=qss.API_URL,
backend="ibmq_qasm_simulator",
)
assert qiskit.providers.Options(shots=1000) == device._default_options()
class MockResponse:
def __init__(self, job_ids: List[str]) -> None:
self.content = json.dumps({"job_ids": job_ids})
def json(self) -> Dict:
return json.loads(self.content)
def raise_for_status(self) -> None:
pass
class MockBadResponse:
def __init__(self) -> None:
self.content = json.dumps({})
def json(self) -> Dict:
return {}
def raise_for_status(self) -> None:
pass
class MockProvider(qss.superstaq_provider.SuperstaQProvider):
def __init__(self) -> None:
self.access_token = "super.tech"
class MockDevice(qss.superstaq_backend.SuperstaQBackend):
def __init__(self) -> None:
super().__init__(MockProvider(), "super.tech", "mock_backend")
self._provider = MockProvider()
def test_run(monkeypatch: Any) -> None:
qc = qiskit.QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 0], [1, 1])
device = MockDevice()
monkeypatch.setattr(requests, "post", lambda *_, **__: MockResponse(["123abc"]))
answer = device.run(circuits=qc)
expected = qss.superstaq_job.SuperstaQJob(device, "123abc")
assert answer == expected
monkeypatch.setattr(requests, "post", lambda *_, **__: MockBadResponse())
with pytest.raises(Exception):
device.run(circuits=qc)
def test_multi_circuit_run(monkeypatch: Any) -> None:
device = MockDevice()
qc1 = qiskit.QuantumCircuit(1, 1)
qc1.h(0)
qc1.measure(0, 0)
qc2 = qiskit.QuantumCircuit(2, 2)
qc2.h(0)
qc2.cx(0, 1)
qc2.measure([0, 1], [0, 1])
monkeypatch.setattr(requests, "post", lambda *_, **__: MockResponse(["123abc", "456efg"]))
answer = device.run(circuits=[qc1, qc2])
expected = qss.superstaq_job.SuperstaQJob(device, "123abc,456efg")
assert answer == expected
def test_eq() -> None:
assert MockDevice() != 3
provider = qss.superstaq_provider.SuperstaQProvider(access_token="123")
backend1 = qss.superstaq_backend.SuperstaQBackend(
provider=provider, backend="ibmq_qasm_simulator", url=qss.API_URL
)
backend2 = qss.superstaq_backend.SuperstaQBackend(
provider=provider, backend="ibmq_athens", url=qss.API_URL
)
assert backend1 != backend2
backend3 = qss.superstaq_backend.SuperstaQBackend(
provider=provider, backend="ibmq_qasm_simulator", url=qss.API_URL
)
assert backend1 == backend3
|
https://github.com/anirban-m/qiskit-superstaq
|
anirban-m
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import time
from typing import Any, Dict, List
import qiskit
import requests
import qiskit_superstaq as qss
class SuperstaQJob(qiskit.providers.JobV1):
def __init__(
self,
backend: qss.superstaq_backend.SuperstaQBackend,
job_id: str,
) -> None:
# Can we stop setting qobj and access_token to None
"""Initialize a job instance.
Parameters:
backend (BaseBackend): Backend that job was executed on.
job_id (str): The unique job ID from SuperstaQ.
access_token (str): The access token.
"""
super().__init__(backend, job_id)
def __eq__(self, other: Any) -> bool:
if not (isinstance(other, SuperstaQJob)):
return False
return self._job_id == other._job_id
def _wait_for_results(self, timeout: float = None, wait: float = 5) -> List[Dict]:
result_list: List[Dict] = []
job_ids = self._job_id.split(",") # separate aggregated job_ids
header = {
"Authorization": self._backend._provider.access_token,
"SDK": "qiskit",
}
for jid in job_ids:
start_time = time.time()
result = None
while True:
elapsed = time.time() - start_time
if timeout and elapsed >= timeout:
raise qiskit.providers.JobTimeoutError(
"Timed out waiting for result"
) # pragma: no cover b/c don't want slow test or mocking time
getstr = f"{self._backend.url}/" + qss.API_VERSION + f"/job/{jid}"
result = requests.get(
getstr, headers=header, verify=(self._backend.url == qss.API_URL)
).json()
if result["status"] == "Done":
break
if result["status"] == "Error":
raise qiskit.providers.JobError("API returned error:\n" + str(result))
time.sleep(wait) # pragma: no cover b/c don't want slow test or mocking time
result_list.append(result)
return result_list
def result(self, timeout: float = None, wait: float = 5) -> qiskit.result.Result:
# Get the result data of a circuit.
results = self._wait_for_results(timeout, wait)
# create list of result dictionaries
results_list = []
for result in results:
results_list.append(
{"success": True, "shots": result["shots"], "data": {"counts": result["samples"]}}
)
return qiskit.result.Result.from_dict(
{
"results": results_list,
"qobj_id": -1,
"backend_name": self._backend._configuration.backend_name,
"backend_version": self._backend._configuration.backend_version,
"success": True,
"job_id": self._job_id,
}
)
def status(self) -> str:
"""Query for the job status."""
header = {
"Authorization": self._backend._provider.access_token,
"SDK": "qiskit",
}
job_id_list = self._job_id.split(",") # separate aggregated job ids
status = "Done"
# when we have multiple jobs, we will take the "worst status" among the jobs
# For example, if any of the jobs are still queued, we report Queued as the status
# for the entire batch.
for job_id in job_id_list:
get_url = self._backend.url + "/" + qss.API_VERSION + f"/job/{job_id}"
result = requests.get(
get_url, headers=header, verify=(self._backend.url == qss.API_URL)
)
temp_status = result.json()["status"]
if temp_status == "Queued":
status = "Queued"
break
elif temp_status == "Running":
status = "Running"
assert status in ["Queued", "Running", "Done"]
if status == "Queued":
status = qiskit.providers.jobstatus.JobStatus.QUEUED
elif status == "Running":
status = qiskit.providers.jobstatus.JobStatus.RUNNING
else:
status = qiskit.providers.jobstatus.JobStatus.DONE
return status
def submit(self) -> None:
raise NotImplementedError("Submit through SuperstaQBackend, not through SuperstaqJob")
|
https://github.com/anirban-m/qiskit-superstaq
|
anirban-m
|
import json
from typing import Any, Dict
import pytest
import qiskit
import requests
import qiskit_superstaq as qss
class MockConfiguration:
backend_name = "superstaq_backend"
backend_version = qss.API_VERSION
class MockProvider(qss.superstaq_provider.SuperstaQProvider):
def __init__(self) -> None:
self.access_token = "very.tech"
class MockDevice(qss.superstaq_backend.SuperstaQBackend):
def __init__(self) -> None:
self._provider = MockProvider()
self.diff = ""
_configuration = MockConfiguration()
url = "super.tech"
class MockJob(qss.superstaq_job.SuperstaQJob):
def __init__(self) -> None:
self._backend = MockDevice()
self._job_id = "123abc"
self.qobj = None
class MockJobs(qss.superstaq_job.SuperstaQJob):
def __init__(self) -> None:
self._backend = MockDevice()
self._job_id = "123abc,456def"
self.qobj = None
class MockResponse:
def __init__(self, status_str: str) -> None:
self.content = json.dumps({"status": status_str, "samples": None, "shots": 100})
def json(self) -> Dict:
return json.loads(self.content)
def test_wait_for_results(monkeypatch: Any) -> None:
job = MockJob()
monkeypatch.setattr(requests, "get", lambda *_, **__: MockResponse("Done"))
assert job._wait_for_results() == [{"status": "Done", "samples": None, "shots": 100}]
monkeypatch.setattr(requests, "get", lambda *_, **__: MockResponse("Error"))
with pytest.raises(qiskit.providers.JobError, match="API returned error"):
job._wait_for_results()
jobs = MockJobs()
monkeypatch.setattr(requests, "get", lambda *_, **__: MockResponse("Done"))
assert jobs._wait_for_results() == [
{"status": "Done", "samples": None, "shots": 100},
{"status": "Done", "samples": None, "shots": 100},
]
def test_result(monkeypatch: Any) -> None:
job = MockJob()
monkeypatch.setattr(requests, "get", lambda *_, **__: MockResponse("Done"))
expected_results = [{"success": True, "shots": 100, "data": {"counts": None}}]
expected = qiskit.result.Result.from_dict(
{
"results": expected_results,
"qobj_id": -1,
"backend_name": "superstaq_backend",
"backend_version": qss.API_VERSION,
"success": True,
"job_id": "123abc",
}
)
ans = job.result()
assert ans.backend_name == expected.backend_name
assert ans.job_id == expected.job_id
def test_status(monkeypatch: Any) -> None:
job = MockJob()
monkeypatch.setattr(requests, "get", lambda *_, **__: MockResponse("Queued"))
assert job.status() == qiskit.providers.JobStatus.QUEUED
monkeypatch.setattr(requests, "get", lambda *_, **__: MockResponse("Running"))
assert job.status() == qiskit.providers.JobStatus.RUNNING
monkeypatch.setattr(requests, "get", lambda *_, **__: MockResponse("Done"))
assert job.status() == qiskit.providers.JobStatus.DONE
def test_submit() -> None:
job = qss.superstaq_job.SuperstaQJob(backend=MockDevice(), job_id="12345")
with pytest.raises(NotImplementedError, match="Submit through SuperstaQBackend"):
job.submit()
def test_eq() -> None:
job = qss.superstaq_job.SuperstaQJob(backend=MockDevice(), job_id="12345")
assert job != "super.tech"
job2 = qss.superstaq_job.SuperstaQJob(backend=MockDevice(), job_id="123456")
assert job != job2
job3 = qss.superstaq_job.SuperstaQJob(backend=MockDevice(), job_id="12345")
assert job == job3
|
https://github.com/anirban-m/qiskit-superstaq
|
anirban-m
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import os
from typing import List, Union
import qiskit
import requests
import qiskit_superstaq as qss
class SuperstaQProvider(qiskit.providers.ProviderV1):
"""Provider for SuperstaQ backend.
Typical usage is:
.. code-block:: python
import qiskit_superstaq as qss
ss_provider = qss.superstaq_provider.SuperstaQProvider('MY_TOKEN')
backend = ss_provider.get_backend('my_backend')
where `'MY_TOKEN'` is the access token provided by SuperstaQ,
and 'my_backend' is the name of the desired backend.
Attributes:
access_token (str): The access token.
name (str): Name of the provider instance.
url (str): The url that the API is hosted on.
"""
def __init__(
self,
access_token: str,
url: str = os.getenv("SUPERSTAQ_REMOTE_HOST") or qss.API_URL,
) -> None:
self.access_token = access_token
self._name = "superstaq_provider"
self.url = url
def __str__(self) -> str:
return f"<SuperstaQProvider(name={self._name})>"
def __repr__(self) -> str:
repr1 = f"<SuperstaQProvider(name={self._name}, "
return repr1 + f"access_token={self.access_token})>"
def get_backend(self, backend: str) -> "qss.superstaq_backend.SuperstaQBackend":
return qss.superstaq_backend.SuperstaQBackend(provider=self, url=self.url, backend=backend)
def get_access_token(self) -> str:
return self.access_token
def backends(self) -> List[qss.superstaq_backend.SuperstaQBackend]:
# needs to be fixed (#469)
backend_names = [
"aqt_device",
"ionq_device",
"rigetti_device",
"ibmq_botoga",
"ibmq_casablanca",
"ibmq_jakarta",
"ibmq_qasm_simulator",
]
backends = []
for name in backend_names:
backends.append(
qss.superstaq_backend.SuperstaQBackend(provider=self, url=self.url, backend=name)
)
return backends
def aqt_compile(
self, circuits: Union[qiskit.QuantumCircuit, List[qiskit.QuantumCircuit]]
) -> "qss.aqt.AQTCompilerOutput":
"""Compiles the given circuit(s) to AQT device, optimized to its native gate set.
Args:
circuits: qiskit QuantumCircuit(s)
Returns:
object whose .circuit(s) attribute is an optimized qiskit QuantumCircuit(s)
If qtrl is installed, the object's .seq attribute is a qtrl Sequence object of the
pulse sequence corresponding to the optimized qiskit.QuantumCircuit(s) and the
.pulse_list(s) attribute is the list(s) of cycles.
"""
if isinstance(circuits, qiskit.QuantumCircuit):
json_dict = {"qasm_strs": [circuits.qasm()]}
circuits_list = False
else:
json_dict = {"qasm_strs": [c.qasm() for c in circuits]}
circuits_list = True
headers = {
"Authorization": self.get_access_token(),
"Content-Type": "application/json",
}
res = requests.post(
self.url + "/" + qss.API_VERSION + "/aqt_compile",
json=json_dict,
headers=headers,
verify=(self.url == qss.API_URL),
)
res.raise_for_status()
json_dict = res.json()
from qiskit_superstaq import aqt
return aqt.read_json(json_dict, circuits_list)
|
https://github.com/anirban-m/qiskit-superstaq
|
anirban-m
|
from unittest.mock import MagicMock, patch
import applications_superstaq
import qiskit
import qiskit_superstaq as qss
def test_provider() -> None:
ss_provider = qss.superstaq_provider.SuperstaQProvider(access_token="MY_TOKEN")
assert str(ss_provider.get_backend("ibmq_qasm_simulator")) == str(
qss.superstaq_backend.SuperstaQBackend(
provider=ss_provider,
url=qss.API_URL,
backend="ibmq_qasm_simulator",
)
)
assert str(ss_provider) == "<SuperstaQProvider(name=superstaq_provider)>"
assert (
repr(ss_provider) == "<SuperstaQProvider(name=superstaq_provider, access_token=MY_TOKEN)>"
)
backend_names = [
"aqt_device",
"ionq_device",
"rigetti_device",
"ibmq_botoga",
"ibmq_casablanca",
"ibmq_jakarta",
"ibmq_qasm_simulator",
]
backends = []
for name in backend_names:
backends.append(
qss.superstaq_backend.SuperstaQBackend(
provider=ss_provider, url=qss.API_URL, backend=name
)
)
assert ss_provider.backends() == backends
@patch("requests.post")
def test_aqt_compile(mock_post: MagicMock) -> None:
provider = qss.superstaq_provider.SuperstaQProvider(access_token="MY_TOKEN")
qc = qiskit.QuantumCircuit(8)
qc.cz(4, 5)
out_qasm_str = """OPENQASM 2.0;
include "qelib1.inc";
//Qubits: [4, 5]
qreg q[2];
cz q[0],q[1];
"""
expected_qc = qiskit.QuantumCircuit(2)
expected_qc.cz(0, 1)
mock_post.return_value.json = lambda: {
"qasm_strs": [out_qasm_str],
"state_jp": applications_superstaq.converters.serialize({}),
"pulse_lists_jp": applications_superstaq.converters.serialize([[[]]]),
}
out = provider.aqt_compile(qc)
assert out.circuit == expected_qc
assert not hasattr(out, "circuits") and not hasattr(out, "pulse_lists")
out = provider.aqt_compile([qc])
assert out.circuits == [expected_qc]
assert not hasattr(out, "circuit") and not hasattr(out, "pulse_list")
mock_post.return_value.json = lambda: {
"qasm_strs": [out_qasm_str, out_qasm_str],
"state_jp": applications_superstaq.converters.serialize({}),
"pulse_lists_jp": applications_superstaq.converters.serialize([[[]], [[]]]),
}
out = provider.aqt_compile([qc, qc])
assert out.circuits == [expected_qc, expected_qc]
assert not hasattr(out, "circuit") and not hasattr(out, "pulse_list")
|
https://github.com/mareksubocz/QRBM-qiskit
|
mareksubocz
|
from qiskit import IBMQ
# IBMQ.save_account(MY_API_TOKEN)
import qiskit
qiskit.__version__
import scipy
import numpy as np
import random
from sklearn import preprocessing
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.quantum_info.operators import Operator
from qiskit import(QuantumCircuit, execute, Aer)
from qiskit.visualization import plot_histogram
from qiskit.extensions import Initialize # Import the Inititialize function
from qiskit.aqua.circuits.gates import multi_control_toffoli_gate
from qiskit.aqua.circuits.gates import multi_control_multi_target_gate
# JUŻ NIEPOTRZEBNE - TUTAJ BYŁY HIPERPARAMETRY OBWODU TESOWEGO
# #definicja rozmiaru sieci
# visible = 1
# hidden = 1
# ancilla = visible-1
# #definicja wejścia (x) oraz inicjalizacja macierzy wag
# x = np.array([random.uniform(0, 1) for n in range(visible)])
# weight_matrix = np.random.rand(visible, hidden) * np.pi
# JUŻ NIEPOTRZEBNE - TUTAJ BYŁ BUDOWANY OBWÓD TESTOWY
# # definicja obwodu (linii qubitów)
# # qc = QuantumCircuit(visible + hidden, visible)
# qr = QuantumRegister(visible + hidden + ancilla, 'q')
# cr = ClassicalRegister(visible + hidden, 'c')
# qc = QuantumCircuit(qr, cr)
# # inicjalizacja wartości qubitów wejściowych (x) na razie randomowa
# initial_state = [[np.sqrt(x[i]), np.sqrt(1-x[i])] for i in range(len(x))]
# # inicjalizacja wartości qubitów wejściowych i bramka Hadamarda
# for i in range(visible):
# initialize_qubit = Initialize(initial_state[i])
# qc.append(initialize_qubit, [i])
# qc.h(i)
# # ciąg bramek CNOT i bramek rotacji R (zależnych od parametrów)
# for i in range(hidden):
# for j in range(visible):
# qc.rz(weight_matrix[j][i], j)
# multi_control_toffoli_gate.mct(qc, [qr[k] for k in range(visible)], qr[visible + i], [qr[i] for i in range(visible + hidden, visible + hidden + ancilla)], mode='basic')
# # bramki Hadamarda na warstwie ukrytej
# for i in range(hidden):
# qc.h(visible + i)
# # pomiar linii visible
# qc.measure(list(range(visible, visible+hidden)), list(range(visible, visible+hidden)))
# ### OBWÓD DRUGĄ STRONĘ
# # wyzerowanie wartości qubitów visible
# for i in range(visible):
# initialize_qubit = Initialize([1, 0])
# qc.append(initialize_qubit, [i])
# # bramka Hadamarda na qubitach hidden
# for i in range(visible, hidden + visible):
# qc.h(i)
# #odwrócone rotacje i CNOTy
# for i in range(hidden):
# for j in range(visible):
# multi_control_toffoli_gate.mct(qc, [qr[k] for k in range(visible, visible + hidden)], qr[j], [qr[k] for k in range(visible + hidden, visible + hidden + ancilla)], mode='basic')
# qc.rz(-weight_matrix[j][hidden - 1 - i], j)
# # bramka Hadamarda i pomiar na qubitach visible
# for i in range(visible):
# qc.h(i)
# qc.measure(list(range(visible)), list(range(visible)))
# EKSPERYMNET Z TESTOWYM UKŁADEM - JUŻ NIEPOTRZEBNY
# # Use Aer's qasm_simulator
# simulator = Aer.get_backend('qasm_simulator')
# # Execute the circuit on the qasm simulator
# job = execute(qc, simulator, shots=1000)
# # Grab results from the job
# result = job.result()
# # Returns counts
# counts = result.get_counts(qc)
# print("\nTotal count for 0 and 1 are:",counts)
# # qc.draw(output='mpl')
# qc.draw()
# # komórka do testowania wieloqubitowej bramki CNOT - JUŻ NIEPOTRZEBNA BO BRAMKA DZIAŁA
# # NIE ZALEŻNA OD WŁAŚCIWEJ SIECI
# # work = ancilla
# def n_control_gate(qc, target, control: list, work: list, gate_type):
# if len(control) - len(work) != 1:
# raise Exception("Wrong number of control or work qubits!")
# qc.toffoli(control[0], control[1], work[0])
# control_left = control[2:]
# for i, c_bit in enumerate(control_left):
# qc.toffoli(c_bit, work[i], work[i+1])
# qc.gate_type(work[-1], target)
# for i, c_bit in reversed(list(enumerate(control_left))):
# qc.toffoli(c_bit, work[i], work[i+1])
# qc.toffoli(control[0], control[1], work[0])
# visible = 2
# hidden = 2
# ancilla = visible - 1
# # qr_visible = QuantumRegister(visible, 'visible')
# # qr_hidden = QuantumRegister(hidden, 'hidden')
# # cr = ClassicalRegister(3, 'c')
# # if visible > 2:
# # anc = QuantumRegister(visible - 2, 'ancilla')
# # qc = QuantumCircuit(qr_visible, qr_hidden, anc, cr)
# # else:
# # qc = QuantumCircuit(qr_visible, qr_hidden, cr)
# # qr_visible = QuantumRegister(visible, 'visible')
# qr = QuantumRegister(visible + hidden + ancilla, 'q')
# cr = ClassicalRegister(3, 'c')
# qc = QuantumCircuit(qr, cr)
# for i in range(visible + hidden):
# initialize_qubit = Initialize([0, 1])
# qc.append(initialize_qubit, [i])
# # initialize_qubit = Initialize([1, 0])
# # qc.append(initialize_qubit, [2])
# # for i in range(hidden):
# # for j in range(visible):
# # qc.rz(weight_matrix[j][i], j)
# print(list(range(visible)) + [visible + 0])
# print(list(range(visible+hidden, visible+hidden+ancilla)))
# # multi_control_multi_target_gate.mcmt(qc, list(range(visible)), [], QuantumCircuit.cx, [visible])
# # print([qr_visible[i] for i in range(visible)])
# # print([anc[i] for i in range(ancilla)])
# # print([qr_hidden[i] for i in range(hidden)])
# for j in range(hidden):
# multi_control_multi_target_gate.mcmt(qc, [qr[i] for i in range(visible)], [qr[i] for i in range(visible + hidden, visible + hidden + ancilla)], QuantumCircuit.cx, [qr[visible + j]])
# # multi_control_multi_target_gate.mcmt(qc, [qr_visible[i] for i in range(visible)], [anc[i] for i in range(ancilla)], QuantumCircuit.cx, [qr_hidden[0]])
# # qc.measure(list(range(visible+hidden)), list(range(visible + hidden)))
# # (qc, list(range(visible)) + [visible + 0], qancilla = 6)
# # Use Aer's qasm_simulator
# simulator = Aer.get_backend('qasm_simulator')
# # Execute the circuit on the qasm simulator
# job = execute(qc, simulator, shots=1000)
# # Grab results from the job
# result = job.result()
# # Returns counts
# counts = result.get_counts(qc)
# print("\nTotal count for 0 and 1 are:",counts)
# qc.draw()
# TO JUŻ NIEPOTRZEBNE - NIE DZIAŁA TEN SPOSÓB Z ARTYKUŁU
# print(weight_matrix, '\n')
# sinus_matrix = np.sin(weight_matrix + np.pi/4)
# print(sinus_matrix, '\n')
# print(sinus_matrix.prod(axis = 0), '\n')
# phi = np.arcsin(sinus_matrix.prod(axis = 0))
# print(phi, '\n')
# psi = phi + np.pi/4
# print(psi, '\n')
# ph = np.sin(psi)**2
# print(ph, '\n')
# # ph_normalized = preprocessing.normalize([ph], norm = 'l1')[0]
# # print(ph_normalized)
def exctract_single_qubit_measurment(dict_of_counts, qubit_range):
# print(dict_of_counts)
# print(len(list(dict_of_counts.keys())[0]))
num_qubits = len(list(dict_of_counts.keys())[0])
# result = np.zeros(len(qubit_range))
result = np.zeros(num_qubits)
# print(result)
for el in dict_of_counts:
for i in range(num_qubits):
# print("i", i)
# print("el[i]", el[i])
if i in qubit_range and el[i] == '1':
result[i] += dict_of_counts[el]
# print(result)
# print(result[qubit_range])
return result[qubit_range]
def create_dataset(dataset_size):
dataset = []
for i in range(dataset_size):
x = np.array([random.choice([0,1]), random.choice([0,1])])
y = 1
if np.array_equal(x, np.array([0,0])):
y = 0
dataset.append({"x": x, "y": y})
return dataset
dataset = create_dataset(4)
print(dataset)
def circuit_function(qc, weight_matrix):
qc.data = []
# inicjalizacja wartości qubitów wejściowych (x)
initial_state = [[np.sqrt(1-x[i]), np.sqrt(x[i])] for i in range(len(x))]
# inicjalizacja wartości qubitów wejściowych i bramka Hadamarda
for i in range(visible):
initialize_qubit = Initialize(initial_state[i])
qc.append(initialize_qubit, [i])
qc.h(i)
# ciąg bramek CNOT i bramek rotacji R (zależnych od parametrów)
for i in range(hidden):
for j in range(visible):
qc.ry(weight_matrix[j][i], j)
multi_control_toffoli_gate.mct(qc, [qr[k] for k in range(visible)], qr[visible + i], [qr[i] for i in range(visible + hidden, visible + hidden + ancilla)], mode='basic')
# bramki Hadamarda na warstwie ukrytej
# for i in range(hidden):
# qc.h(visible + i)
# pomiar linii visible
qc.measure(list(range(visible, visible+hidden)), list(range(hidden)))
#eksperyment:
#symylator
simulator = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator
job = execute(qc, simulator, shots=num_shots)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(qc)
# print(counts)
ph = exctract_single_qubit_measurment(counts, list(range(hidden))) / num_shots
# print("\nProbabilities are:",ph)
return ph[0]
epsilon = 0.01
def update2(ph, expected_ph, weight_matrix, lr):
gradient = []
for i, row in enumerate(weight_matrix):
gradient_row = []
for j, el in enumerate(row):
weight_matrix[i][j] += epsilon
result_plus = circuit_function(qc, weight_matrix)
weight_matrix[i][j] -= 2*epsilon
result_minus = circuit_function(qc, weight_matrix)
weight_matrix[i][j] += epsilon
# result_zero = circuit_function(qc, weight_matrix)
# print("ph", result_zero)
# print("exp_ph", expected_ph)
# print("el final:", el)
# print(result_plus - result_minus)
result = (result_plus - result_minus)/(2*epsilon) * lr * (ph - expected_ph)
gradient_row.append(result)
gradient.append(gradient_row)
# print("gradient", gradient)
weight_matrix = weight_matrix - gradient
return weight_matrix
# update2()
# template do uczenia
import matplotlib.pyplot as plt
%matplotlib inline
def update(exp_ph, ph):
global weight_matrix
# #obliczanie prawdopodobieństwa p(|h>) ze wzoru
# sinus_matrix = np.sin(weight_matrix + np.pi/4)
# phi = np.arcsin(sinus_matrix.prod(axis = 0))
# # print('phi', phi)
# psi = phi + np.pi/4
# # print('psi', psi)
# ph = np.sin(psi)**2
# # print('ph', ph)
#obliczanie gradientu i,k
S = 1/(np.sqrt(1-(np.sin(phi))**2))
# print("S", S)
T = np.sin(phi) * np.sum(1/np.tan(weight_matrix + np.pi/4), axis = 0)
# print("T", T)
# print("sum products", (exp_ph - ph) * ph * np.cos(2*psi) * S * T)
gradient = np.zeros(hidden)
for k in range(hidden):
gradient[k] = np.sum( (exp_ph - ph) * ph * np.cos(2*psi) * S * T[k])
# print("gradient = ", gradient)
# print([gradient] * len(weight_matrix))
weight_matrix = weight_matrix + ([gradient] * len(weight_matrix))
#definicja rozmiaru sieci
visible = 2
hidden = 1
ancilla = visible-1
#definicja wejścia (x)oraz inicjalizacja macierzy wag
# x = np.array([random.uniform(0, 1) for n in range(visible)])
dataset = create_dataset(10)
print(dataset[0]["x"][0])
print(dataset[0]["x"][1])
print([n for n in range(visible)])
weight_matrix = np.random.rand(visible, hidden) * np.pi
#definicja parametrów uczenia
num_shots = 1000
num_epochs = 100
qr = QuantumRegister(visible + hidden + ancilla, 'q')
cr = ClassicalRegister(hidden, 'c')
qc = QuantumCircuit(qr, cr)
cost_function_data = []
lr = 0.05
for epoch in range(num_epochs):
print("epoch: ", epoch)
for i, element in enumerate(dataset):
# print(element)
x = np.array([dataset[i]["x"][n] for n in range(visible)])
exp_ph = dataset[i]["y"]
ph = circuit_function(qc, weight_matrix)
weight_matrix = update2(ph, exp_ph, weight_matrix, lr)
# print("exp_ph", exp_ph, "ph", ph, "weight_matrix", weight_matrix, "cost_function", 0.5 * (ph - exp_ph)**2)
cost_function_data.append(0.5 * (ph - exp_ph)**2)
qc.draw()
plt.xlabel('number of epochs')
plt.ylabel('cost')
plt.plot(cost_function_data)
qc.draw()
|
https://github.com/mareksubocz/QRBM-qiskit
|
mareksubocz
|
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch.autograd import Function
from torchvision import datasets, transforms
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import qiskit
from qiskit.visualization import *
# Concentrating on the first 100 samples
n_samples = 100
X_train = datasets.MNIST(root='./data', train=True, download=True,
transform=transforms.Compose([transforms.ToTensor()]))
# Leaving only labels 0 and 1
idx = np.append(np.where(X_train.targets == 0)[0][:n_samples],
np.where(X_train.targets == 1)[0][:n_samples]
)
idx = np.append(idx,
np.where(X_train.targets == 2)[0][:n_samples]
)
# idx = np.append(idx,
# np.where(X_train.targets == 3)[0][:n_samples]
# )
print(idx)
X_train.data = X_train.data[idx]
X_train.targets = X_train.targets[idx]
train_loader = torch.utils.data.DataLoader(X_train, batch_size=1, shuffle=True)
n_samples_show = 6
data_iter = iter(train_loader)
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
while n_samples_show > 0:
images, targets = data_iter.__next__()
axes[n_samples_show - 1].imshow(images[0].numpy().squeeze(), cmap='gray')
axes[n_samples_show - 1].set_xticks([])
axes[n_samples_show - 1].set_yticks([])
axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item()))
n_samples_show -= 1
n_samples = 50
X_test = datasets.MNIST(root='./data', train=False, download=True,
transform=transforms.Compose([transforms.ToTensor()]))
idx = np.append(np.where(X_test.targets == 0)[0][:n_samples],
np.where(X_test.targets == 1)[0][:n_samples])
idx = np.append(idx,
np.where(X_test.targets == 2)[0][:n_samples]
)
# idx = np.append(idx,
# np.where(X_test.targets == 3)[0][:n_samples]
# )
X_test.data = X_test.data[idx]
X_test.targets = X_test.targets[idx]
test_loader = torch.utils.data.DataLoader(X_test, batch_size=1, shuffle=True)
def exctract_single_qubit_measurment(dict_of_counts, qubit_range):
# print(dict_of_counts)
# print(len(list(dict_of_counts.keys())[0]))
num_qubits = len(list(dict_of_counts.keys())[0])
result = np.zeros(len(qubit_range))
result = np.zeros(num_qubits)
# print(result)
for el in dict_of_counts:
for i in range(num_qubits):
# print("i", i)
# print("el[i]", el[i])
if i in qubit_range and el[i] == '1':
result[i] += dict_of_counts[el]
# print(result)
# print(result[qubit_range])
return result[qubit_range]
class QuantumCircuit:
"""
This class provides a simple interface for interaction
with the quantum circuit
"""
def __init__(self, n_qubits, backend, shots):
# --- Circuit definition ---
self._circuit = qiskit.QuantumCircuit(n_qubits)
self.n_qubits = n_qubits
all_qubits = [i for i in range(n_qubits)]
self.theta = qiskit.circuit.Parameter('theta')
self._circuit.h(all_qubits)
self._circuit.barrier()
self._circuit.ry(self.theta, all_qubits)
self._circuit.measure_all()
# ---------------------------
self.backend = backend
self.shots = shots
def run(self, thetas):
job = qiskit.execute(self._circuit,
self.backend,
shots = self.shots,
parameter_binds = [{self.theta: theta} for theta in thetas])
result = job.result().get_counts(self._circuit)
counts = np.array(list(result.values()))
states = np.array(list(result.keys())).astype(float)
# Compute probabilities for each state
probabilities = counts / self.shots
# Get state expectation
expectation = np.sum(states * probabilities)
# print("states: ", states)
# print("probabilities: ", probabilities)
new_probabilities = exctract_single_qubit_measurment(result, list(range(self.n_qubits)))/self.shots
# print("new_probabilities: ", new_probabilities)
# new_expectation = np.sum(states * new_probabilities)
# print("old expectation", np.array([expectation]))
return new_probabilities
# return np.array([expectation])
simulator = qiskit.Aer.get_backend('qasm_simulator')
circuit = QuantumCircuit(2, simulator, 100)
print('Expected value for rotation pi {}'.format(circuit.run([np.pi])[0]))
circuit._circuit.draw()
class HybridFunction(Function):
""" Hybrid quantum - classical function definition """
@staticmethod
def forward(ctx, input, quantum_circuit, shift):
# print("FORWARD BEGIN")
# print("input: ", input)
""" Forward pass computation """
ctx.shift = shift
ctx.quantum_circuit = quantum_circuit
expectation_z = ctx.quantum_circuit.run(input[0].tolist())
# print("expectation_z: ", expectation_z)
result = torch.tensor([expectation_z])
# print("result", result)
ctx.save_for_backward(input, result)
# print("FORWARD END")
return result
@staticmethod
def backward(ctx, grad_output):
# print("BACKWARD BEGIN")
# print("Grad_output: ", grad_output)
""" Backward pass computation """
input, expectation_z = ctx.saved_tensors
# print("input_list: ", input.tolist())
input_list = np.array(input.tolist())
shift_right = input_list + np.ones(input_list.shape) * ctx.shift
shift_left = input_list - np.ones(input_list.shape) * ctx.shift
gradients = []
for i in range(len(input_list)):
expectation_right = ctx.quantum_circuit.run(shift_right[i])
expectation_left = ctx.quantum_circuit.run(shift_left[i])
gradient = expectation_right - expectation_left
gradients.append(gradient)
# print("HALO")
gradients = np.array([gradients]).T
# print("gradients: ", gradients)
# print("BACKWARD END")
return torch.tensor([gradients]).float() * grad_output.float(), None, None
class Hybrid(nn.Module):
""" Hybrid quantum - classical layer definition """
def __init__(self, backend, shots, shift):
super(Hybrid, self).__init__()
self.quantum_circuit = QuantumCircuit(2, backend, shots)
self.shift = shift
def forward(self, input):
return HybridFunction.apply(input, self.quantum_circuit, self.shift)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=5)
self.conv2 = nn.Conv2d(32, 64, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(6400, 64)
self.fc2 = nn.Linear(64, 2)
self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2)
self.fc3 = nn.Linear(2, 3)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(-1, 6400)
x = F.relu(self.fc1(x))
# print(x)
x = self.fc2(x)
# print("x before hybrid layer", x)
# print(x.size())
x = self.hybrid(x)
# print("x after hybrid layer", x)
# x = F.relu(self.fc3(x.float()))
# print("return: ", torch.cat((x, 1 - x), -1))
x = self.fc3(x.float())
# print(torch.cat((x, 1 - x), -1))
# return torch.cat((x, 1 - x), -1)
# print("softmax: ", F.softmax(x))
# print("argmax: ", torch.argmax(x))
return F.softmax(x)
# return torch.argmax(x)
#
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.01)
loss_func = nn.CrossEntropyLoss()
epochs = 20
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
# print(target)
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list[-1]))
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
n_samples_show = 6
count = 0
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
model.eval()
with torch.no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
if count == n_samples_show:
break
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
axes[count].imshow(data[0].numpy().squeeze(), cmap='gray')
axes[count].set_xticks([])
axes[count].set_yticks([])
axes[count].set_title('Predicted {}'.format(pred.item()))
count += 1
import qiskit
qiskit.__qiskit_version__
|
https://github.com/mareksubocz/QRBM-qiskit
|
mareksubocz
|
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch.autograd import Function
from torchvision import datasets, transforms
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import qiskit
from qiskit.visualization import *
# Concentrating on the first 100 samples
n_samples = 100
X_train = datasets.MNIST(root='./data', train=True, download=True,
transform=transforms.Compose([transforms.ToTensor()]))
# Leaving only labels 0 and 1
idx = np.append(np.where(X_train.targets == 0)[0][:n_samples],
np.where(X_train.targets == 1)[0][:n_samples]
)
# idx = np.append(idx,
# np.where(X_train.targets == 2)[0][:n_samples]
# )
# idx = np.append(idx,
# np.where(X_train.targets == 3)[0][:n_samples]
# )
print(idx)
X_train.data = X_train.data[idx]
X_train.targets = X_train.targets[idx]
train_loader = torch.utils.data.DataLoader(X_train, batch_size=1, shuffle=True)
n_samples_show = 6
data_iter = iter(train_loader)
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
while n_samples_show > 0:
images, targets = data_iter.__next__()
axes[n_samples_show - 1].imshow(images[0].numpy().squeeze(), cmap='gray')
axes[n_samples_show - 1].set_xticks([])
axes[n_samples_show - 1].set_yticks([])
axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item()))
n_samples_show -= 1
n_samples = 50
X_test = datasets.MNIST(root='./data', train=False, download=True,
transform=transforms.Compose([transforms.ToTensor()]))
idx = np.append(np.where(X_test.targets == 0)[0][:n_samples],
np.where(X_test.targets == 1)[0][:n_samples])
# idx = np.append(idx,
# np.where(X_test.targets == 2)[0][:n_samples]
# )
# idx = np.append(idx,
# np.where(X_test.targets == 3)[0][:n_samples]
# )
X_test.data = X_test.data[idx]
X_test.targets = X_test.targets[idx]
test_loader = torch.utils.data.DataLoader(X_test, batch_size=1, shuffle=True)
def exctract_single_qubit_measurment(dict_of_counts, qubit_range):
# print(dict_of_counts)
# print(len(list(dict_of_counts.keys())[0]))
num_qubits = len(list(dict_of_counts.keys())[0])
result = np.zeros(len(qubit_range))
result = np.zeros(num_qubits)
# print(result)
for el in dict_of_counts:
for i in range(num_qubits):
# print("i", i)
# print("el[i]", el[i])
if i in qubit_range and el[i] == '1':
result[i] += dict_of_counts[el]
# print(result)
# print(result[qubit_range])
return result[qubit_range]
class QuantumCircuit:
"""
This class provides a simple interface for interaction
with the quantum circuit
"""
def __init__(self, n_qubits, backend, shots):
# --- Circuit definition ---
self._circuit = qiskit.QuantumCircuit(n_qubits)
self.n_qubits = n_qubits
all_qubits = [i for i in range(n_qubits)]
self.theta = qiskit.circuit.Parameter('theta')
self._circuit.h(all_qubits)
self._circuit.barrier()
self._circuit.ry(self.theta, all_qubits)
self._circuit.measure_all()
# ---------------------------
self.backend = backend
self.shots = shots
def run(self, thetas):
job = qiskit.execute(self._circuit,
self.backend,
shots = self.shots,
parameter_binds = [{self.theta: theta} for theta in thetas])
result = job.result().get_counts(self._circuit)
counts = np.array(list(result.values()))
states = np.array(list(result.keys())).astype(float)
# Compute probabilities for each state
probabilities = counts / self.shots
# Get state expectation
expectation = np.sum(states * probabilities)
# print("states: ", states)
# print("probabilities: ", probabilities)
new_probabilities = exctract_single_qubit_measurment(result, list(range(self.n_qubits)))/self.shots
# print("new_probabilities: ", new_probabilities)
# new_expectation = np.sum(states * new_probabilities)
# print("old expectation", np.array([expectation]))
return new_probabilities
# return np.array([expectation])
simulator = qiskit.Aer.get_backend('qasm_simulator')
circuit = QuantumCircuit(2, simulator, 100)
print('Expected value for rotation pi {}'.format(circuit.run([np.pi])[0]))
circuit._circuit.draw()
class HybridFunction(Function):
""" Hybrid quantum - classical function definition """
@staticmethod
def forward(ctx, input, quantum_circuit, shift):
# print("FORWARD BEGIN")
# print("input: ", input)
""" Forward pass computation """
ctx.shift = shift
ctx.quantum_circuit = quantum_circuit
expectation_z = ctx.quantum_circuit.run(input[0].tolist())
# print("expectation_z: ", expectation_z)
result = torch.tensor([expectation_z])
# print("result", result)
ctx.save_for_backward(input, result)
# print("FORWARD END")
return result
@staticmethod
def backward(ctx, grad_output):
# print("BACKWARD BEGIN")
# print("Grad_output: ", grad_output)
""" Backward pass computation """
input, expectation_z = ctx.saved_tensors
# print("input_list: ", input.tolist())
input_list = np.array(input.tolist())
shift_right = input_list + np.ones(input_list.shape) * ctx.shift
shift_left = input_list - np.ones(input_list.shape) * ctx.shift
gradients = []
for i in range(len(input_list)):
expectation_right = ctx.quantum_circuit.run(shift_right[i])
expectation_left = ctx.quantum_circuit.run(shift_left[i])
gradient = expectation_right - expectation_left
gradients.append(gradient)
# print("HALO")
gradients = np.array([gradients]).T
# print("gradients: ", gradients)
# print("BACKWARD END")
return torch.tensor([gradients]).float() * grad_output.float(), None, None
class Hybrid(nn.Module):
""" Hybrid quantum - classical layer definition """
def __init__(self, backend, shots, shift):
super(Hybrid, self).__init__()
self.quantum_circuit = QuantumCircuit(2, backend, shots)
self.shift = shift
def forward(self, input):
return HybridFunction.apply(input, self.quantum_circuit, self.shift)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=5)
self.conv2 = nn.Conv2d(32, 64, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(6400, 64)
self.fc2 = nn.Linear(64, 2)
self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2)
self.fc3 = nn.Linear(2, 2)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(-1, 6400)
x = F.relu(self.fc1(x))
# print(x.size())
x = self.fc2(x)
# print("x before hybrid layer", x)
# print(x.size())
x = self.hybrid(x)
# print("x after hybrid layer", x)
# x = F.relu(self.fc3(x.float()))
# print("return: ", torch.cat((x, 1 - x), -1))
x = self.fc3(x.float())
# print(torch.cat((x, 1 - x), -1))
# return torch.cat((x, 1 - x), -1)
# print("softmax: ", F.softmax(x))
# print("argmax: ", torch.argmax(x))
return F.softmax(x)
# return torch.argmax(x)
#
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.CrossEntropyLoss()
epochs = 20
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
# print(target)
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list[-1]))
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
n_samples_show = 6
count = 0
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
model.eval()
with torch.no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
if count == n_samples_show:
break
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
axes[count].imshow(data[0].numpy().squeeze(), cmap='gray')
axes[count].set_xticks([])
axes[count].set_yticks([])
axes[count].set_title('Predicted {}'.format(pred.item()))
count += 1
import qiskit
qiskit.__qiskit_version__
|
https://github.com/mareksubocz/QRBM-qiskit
|
mareksubocz
|
from qiskit import IBMQ
# IBMQ.save_account(MY_API_TOKEN)
import qiskit
qiskit.__version__
import scipy
import numpy as np
import random
from sklearn import preprocessing
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.quantum_info.operators import Operator
from qiskit import(QuantumCircuit, execute, Aer)
from qiskit.visualization import plot_histogram
from qiskit.extensions import Initialize # Import the Inititialize function
from qiskit.aqua.circuits.gates import multi_control_toffoli_gate
from qiskit.aqua.circuits.gates import multi_control_multi_target_gate
#definicja rozmiaru sieci
visible = 1
hidden = 1
ancilla = visible-1
#definicja wejścia (x) oraz inicjalizacja macierzy wag
x = np.array([random.uniform(0, 1) for n in range(visible)])
weight_matrix = np.random.rand(visible, hidden) * np.pi
# definicja obwodu (linii qubitów)
# qc = QuantumCircuit(visible + hidden, visible)
qr = QuantumRegister(visible + hidden + ancilla, 'q')
cr = ClassicalRegister(visible + hidden, 'c')
qc = QuantumCircuit(qr, cr)
# inicjalizacja wartości qubitów wejściowych (x) na razie randomowa
initial_state = [[np.sqrt(x[i]), np.sqrt(1-x[i])] for i in range(len(x))]
# inicjalizacja wartości qubitów wejściowych i bramka Hadamarda
for i in range(visible):
initialize_qubit = Initialize(initial_state[i])
qc.append(initialize_qubit, [i])
qc.h(i)
# ciąg bramek CNOT i bramek rotacji R (zależnych od parametrów)
for i in range(hidden):
for j in range(visible):
qc.rz(weight_matrix[j][i], j)
multi_control_toffoli_gate.mct(qc, [qr[k] for k in range(visible)], qr[visible + i], [qr[i] for i in range(visible + hidden, visible + hidden + ancilla)], mode='basic')
# bramki Hadamarda na warstwie ukrytej
for i in range(hidden):
qc.h(visible + i)
# pomiar linii visible
qc.measure(list(range(visible, visible+hidden)), list(range(visible, visible+hidden)))
### OBWÓD DRUGĄ STRONĘ
# wyzerowanie wartości qubitów visible
for i in range(visible):
initialize_qubit = Initialize([1, 0])
qc.append(initialize_qubit, [i])
# bramka Hadamarda na qubitach hidden
for i in range(visible, hidden + visible):
qc.h(i)
#odwrócone rotacje i CNOTy
for i in range(hidden):
for j in range(visible):
multi_control_toffoli_gate.mct(qc, [qr[k] for k in range(visible, visible + hidden)], qr[j], [qr[k] for k in range(visible + hidden, visible + hidden + ancilla)], mode='basic')
qc.rz(-weight_matrix[j][hidden - 1 - i], j)
# bramka Hadamarda i pomiar na qubitach visible
for i in range(visible):
qc.h(i)
qc.measure(list(range(visible)), list(range(visible)))
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator
job = execute(qc, simulator, shots=1000)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(qc)
print("\nTotal count for 0 and 1 are:",counts)
# qc.draw(output='mpl')
qc.draw()
# komórka do testowania wieloqubitowej bramki CNOT
# NIE ZALEŻNA OD WŁAŚCIWEJ SIECI
# work = ancilla
def n_control_gate(qc, target, control: list, work: list, gate_type):
if len(control) - len(work) != 1:
raise Exception("Wrong number of control or work qubits!")
qc.toffoli(control[0], control[1], work[0])
control_left = control[2:]
for i, c_bit in enumerate(control_left):
qc.toffoli(c_bit, work[i], work[i+1])
qc.gate_type(work[-1], target)
for i, c_bit in reversed(list(enumerate(control_left))):
qc.toffoli(c_bit, work[i], work[i+1])
qc.toffoli(control[0], control[1], work[0])
visible = 2
hidden = 2
ancilla = visible - 1
# qr_visible = QuantumRegister(visible, 'visible')
# qr_hidden = QuantumRegister(hidden, 'hidden')
# cr = ClassicalRegister(3, 'c')
# if visible > 2:
# anc = QuantumRegister(visible - 2, 'ancilla')
# qc = QuantumCircuit(qr_visible, qr_hidden, anc, cr)
# else:
# qc = QuantumCircuit(qr_visible, qr_hidden, cr)
# qr_visible = QuantumRegister(visible, 'visible')
qr = QuantumRegister(visible + hidden + ancilla, 'q')
cr = ClassicalRegister(3, 'c')
qc = QuantumCircuit(qr, cr)
for i in range(visible + hidden):
initialize_qubit = Initialize([0, 1])
qc.append(initialize_qubit, [i])
# initialize_qubit = Initialize([1, 0])
# qc.append(initialize_qubit, [2])
# for i in range(hidden):
# for j in range(visible):
# qc.rz(weight_matrix[j][i], j)
print(list(range(visible)) + [visible + 0])
print(list(range(visible+hidden, visible+hidden+ancilla)))
# multi_control_multi_target_gate.mcmt(qc, list(range(visible)), [], QuantumCircuit.cx, [visible])
# print([qr_visible[i] for i in range(visible)])
# print([anc[i] for i in range(ancilla)])
# print([qr_hidden[i] for i in range(hidden)])
for j in range(hidden):
multi_control_multi_target_gate.mcmt(qc, [qr[i] for i in range(visible)], [qr[i] for i in range(visible + hidden, visible + hidden + ancilla)], QuantumCircuit.cx, [qr[visible + j]])
# multi_control_multi_target_gate.mcmt(qc, [qr_visible[i] for i in range(visible)], [anc[i] for i in range(ancilla)], QuantumCircuit.cx, [qr_hidden[0]])
# qc.measure(list(range(visible+hidden)), list(range(visible + hidden)))
# (qc, list(range(visible)) + [visible + 0], qancilla = 6)
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator
job = execute(qc, simulator, shots=1000)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(qc)
print("\nTotal count for 0 and 1 are:",counts)
qc.draw()
print(weight_matrix, '\n')
sinus_matrix = np.sin(weight_matrix + np.pi/4)
print(sinus_matrix, '\n')
print(sinus_matrix.prod(axis = 0), '\n')
phi = np.arcsin(sinus_matrix.prod(axis = 0))
print(phi, '\n')
psi = phi + np.pi/4
print(psi, '\n')
ph = np.sin(psi)**2
print(ph, '\n')
# ph_normalized = preprocessing.normalize([ph], norm = 'l1')[0]
# print(ph_normalized)
def exctract_single_qubit_measurment(dict_of_counts, qubit_range):
num_qubits = int(np.log2(len(counts)))
# result = np.zeros(len(qubit_range))
result = np.zeros(num_qubits)
for el in dict_of_counts:
for i in range(num_qubits):
# print("i", i)
# print("el[i]", el[i])
if i in qubit_range and el[i] == '1':
result[i] += dict_of_counts[el]
# print(result)
# print(result[qubit_range])
return result[qubit_range]
# template do uczenia
def update(exp_ph):
global weight_matrix
#obliczanie prawdopodobieństwa p(|h>) ze wzoru
sinus_matrix = np.sin(weight_matrix + np.pi/4)
phi = np.arcsin(sinus_matrix.prod(axis = 0))
# print('phi', phi)
psi = phi + np.pi/4
# print('psi', psi)
ph = np.sin(psi)**2
# print('ph', ph)
#obliczanie gradientu i,k
S = 1/(np.sqrt(1-(np.sin(phi))**2))
# print("S", S)
T = np.sin(phi) * np.sum(1/np.tan(weight_matrix + np.pi/4), axis = 0)
# print("T", T)
# print("sum products", (exp_ph - ph) * ph * np.cos(2*psi) * S * T)
gradient = np.zeros(hidden)
for k in range(hidden):
gradient[k] = np.sum( (exp_ph - ph) * ph * np.cos(2*psi) * S * T[k])
# print("gradient = ", gradient)
# print([gradient] * len(weight_matrix))
weight_matrix = weight_matrix + ([gradient] * len(weight_matrix))
#definicja rozmiaru sieci
visible = 3
hidden = 2
ancilla = visible-1
#definicja wejścia (x)oraz inicjalizacja macierzy wag
# x = np.array([random.uniform(0, 1) for n in range(visible)])
x = np.array([0.25 for n in range(visible)])
weight_matrix = np.random.rand(visible, hidden) * np.pi
#definicja parametrów uczenia
num_shots = 1000
num_epochs = 100
for epoch in range(num_epochs):
##########################
# definicja obwodu (linii qubitów)
# qc = QuantumCircuit(visible + hidden, visible)
qr = QuantumRegister(visible + hidden + ancilla, 'q')
cr = ClassicalRegister(visible + hidden, 'c')
qc = QuantumCircuit(qr, cr)
# inicjalizacja wartości qubitów wejściowych (x) na razie randomowa
initial_state = [[np.sqrt(x[i]), np.sqrt(1-x[i])] for i in range(len(x))]
# inicjalizacja wartości qubitów wejściowych i bramka Hadamarda
for i in range(visible):
initialize_qubit = Initialize(initial_state[i])
qc.append(initialize_qubit, [i])
qc.h(i)
# ciąg bramek CNOT i bramek rotacji R (zależnych od parametrów)
for i in range(hidden):
for j in range(visible):
qc.rz(weight_matrix[j][i], j)
multi_control_toffoli_gate.mct(qc, [qr[k] for k in range(visible)], qr[visible + i], [qr[i] for i in range(visible + hidden, visible + hidden + ancilla)], mode='basic')
# bramki Hadamarda na warstwie ukrytej
for i in range(hidden):
qc.h(visible + i)
# pomiar linii visible
qc.measure(list(range(visible, visible+hidden)), list(range(visible, visible+hidden)))
### OBWÓD DRUGĄ STRONĘ
# wyzerowanie wartości qubitów visible
for i in range(visible):
initialize_qubit = Initialize([1, 0])
qc.append(initialize_qubit, [i])
# bramka Hadamarda na qubitach hidden
for i in range(visible, hidden + visible):
qc.h(i)
#odwrócone rotacje i CNOTy
for i in range(hidden):
for j in range(visible):
multi_control_toffoli_gate.mct(qc, [qr[k] for k in range(visible, visible + hidden)], qr[j], [qr[k] for k in range(visible + hidden, visible + hidden + ancilla)], mode='basic')
qc.rz(-weight_matrix[j][hidden - 1 - i], j)
# bramka Hadamarda i pomiar na qubitach visible
for i in range(visible):
qc.h(i)
qc.measure(list(range(visible)), list(range(visible)))
#################################
#eksperyment:
#symylator
simulator = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator
job = execute(qc, simulator, shots=num_shots)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(qc)
exp_ph = exctract_single_qubit_measurment(counts, list(range(visible, visible + hidden))) / num_shots
# print("\nTotal count for hidden qubits '1' measurments are:",exctract_single_qubit_measurment(counts))
print("\nProbabilities are:",exp_ph)
# print("\nTotal count for 0 and 1 are:",counts)
print(weight_matrix)
qc.draw()
update(exp_ph)
|
https://github.com/mareksubocz/QRBM-qiskit
|
mareksubocz
|
from qiskit import IBMQ
# IBMQ.save_account(MY_API_TOKEN)
import qiskit
qiskit.__version__
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info.operators import Operator
from qiskit import(QuantumCircuit, execute, Aer)
from qiskit.visualization import plot_histogram
from qiskit.extensions import Initialize # Import the Inititialize function
theta = np.pi / 6
x = 0.25
qc = QuantumCircuit(2,2)
initial_state = [np.sqrt(x), np.sqrt(1-x)]
initialize_qubit = Initialize(initial_state)
qc.append(initialize_qubit, [0])
qc.h(0)
# qc.unitary(Rz(0), [0], label='Rz')
qc.rz(theta, 0)
qc.cx(0,1)
qc.h(1)
# Map the quantum measurement to the classical bits
qc.measure([0], [0])
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator
job = execute(qc, simulator, shots=1000)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(qc)
print("\nTotal count for 0 and 1 are:",counts)
qc.draw()
|
https://github.com/mareksubocz/QRBM-qiskit
|
mareksubocz
|
from qiskit import IBMQ
# IBMQ.save_account(MY_API_TOKEN)
import qiskit
qiskit.__version__
import scipy
import numpy as np
import random
from sklearn import preprocessing
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.quantum_info.operators import Operator
from qiskit import(QuantumCircuit, execute, Aer)
from qiskit.visualization import plot_histogram
from qiskit.extensions import Initialize # Import the Inititialize function
from qiskit.aqua.circuits.gates import multi_control_toffoli_gate
from qiskit.aqua.circuits.gates import multi_control_multi_target_gate
import torch
from torch.autograd import Function
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
import timeit
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['image.cmap'] = 'gray'
import pandas as pd
from skimage import data, color
from skimage.transform import rescale, resize, downscale_local_mean
from skimage import img_as_bool
import cv2 as cv
def exctract_single_qubit_measurment(dict_of_counts, qubit_range):
# print(dict_of_counts)
# print(len(list(dict_of_counts.keys())[0]))
num_qubits = len(list(dict_of_counts.keys())[0])
# result = np.zeros(len(qubit_range))
result = np.zeros(num_qubits)
# print(result)
for el in dict_of_counts:
for i in range(num_qubits):
# print("i", i)
# print("el[i]", el[i])
if i in qubit_range and el[i] == '1':
result[i] += dict_of_counts[el]
# print(result)
# print(result[qubit_range])
return result[qubit_range]
# Wczytywanie danych inną metodą
# Concentrating on the first 100 samples
n_samples = 100
X_train = datasets.MNIST(root='./data', train=True, download=True,
transform=transforms.Compose([transforms.ToTensor()]))
# Leaving only labels 0 and 1
idx = np.append(np.where(X_train.targets == 0)[0][:n_samples],
np.where(X_train.targets == 1)[0][:n_samples])
X_train.data = X_train.data[idx]
X_train.targets = X_train.targets[idx]
train_loader = torch.utils.data.DataLoader(X_train, batch_size=1, shuffle=True)
n_samples_show = 6
data_iter = iter(train_loader)
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
while n_samples_show > 0:
images, targets = data_iter.__next__()
axes[n_samples_show - 1].imshow(images[0].numpy().squeeze(), cmap='gray')
axes[n_samples_show - 1].set_xticks([])
axes[n_samples_show - 1].set_yticks([])
axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item()))
n_samples_show -= 1
n_samples = 50
X_test = datasets.MNIST(root='./data', train=False, download=True,
transform=transforms.Compose([transforms.ToTensor()]))
idx = np.append(np.where(X_test.targets == 0)[0][:n_samples],
np.where(X_test.targets == 1)[0][:n_samples])
X_test.data = X_test.data[idx]
X_test.targets = X_test.targets[idx]
test_loader = torch.utils.data.DataLoader(X_test, batch_size=1, shuffle=True)
class QMLCircuit():
def __init__(self, visible, hidden, num_shots=1000):
self.visible = visible
self.hidden = hidden
self.ancilla = visible-1
self.qr = QuantumRegister((self.visible + self.hidden + self.ancilla), 'q')
self.cr = ClassicalRegister(self.hidden, 'c')
self.qc = QuantumCircuit(self.qr, self.cr)
self.num_shots = num_shots
# def run(self, thetas):
def circuit_function(self, x, weight_matrix):
self.qc.data = []
# print("x: ",x)
# print("x[0]: ", x[0])
# inicjalizacja wartości qubitów wejściowych (x)
initial_state = [[np.sqrt(1-x[i]*x[i]), x[i]] for i in range(len(x))]
# inicjalizacja wartości qubitów wejściowych i bramka Hadamarda
for i in range(visible):
initialize_qubit = Initialize(initial_state[i])
self.qc.append(initialize_qubit, [i])
self.qc.h(i)
# ciąg bramek CNOT i bramek rotacji R (zależnych od parametrów)
for i in range(self.hidden):
for j in range(self.visible):
self.qc.ry(weight_matrix[j][i], j)
# print([self.qr[k] for k in range(self.visible)])
# print(self.qr[self.visible + i])
# print([self.qr[i] for i in range(self.visible + self.hidden, self.visible + self.hidden + self.ancilla)])
multi_control_toffoli_gate.mct(self.qc, [self.qr[k] for k in range(self.visible)], self.qr[self.visible + i], [self.qr[i] for i in range(self.visible + self.hidden, self.visible + self.hidden + self.ancilla)], mode='basic')
# pomiar linii visible
self.qc.measure(list(range(self.visible, self.visible+self.hidden)), list(range(self.hidden)))
#eksperyment:
simulator = Aer.get_backend('qasm_simulator')
job = execute(self.qc, simulator, shots=self.num_shots)
result = job.result()
counts = result.get_counts(self.qc)
ph = exctract_single_qubit_measurment(counts, list(range(self.hidden))) / self.num_shots
# print("\nProbabilities are:",ph)
return ph
visible = 2
hidden = 2
QMLC = QMLCircuit(visible, hidden, 1000)
#definicja wejścia (x)oraz inicjalizacja macierzy wag
x = np.array([random.uniform(0, 1) for n in range(visible)])
weight_matrix = np.random.rand(visible, hidden) * np.pi
ph = QMLC.circuit_function(x, weight_matrix)
print("ph: ", ph)
QMLC.qc.draw()
# global weight_matrix
# weight_matrix = nn.Parameter(torch.tensor(np.random.rand(visible, hidden) * np.pi))
# print("self.weight_matrix: ", weight_matrix)
class QFunction(Function):
""" Hybrid quantum - classical function definition """
@staticmethod
def forward(ctx, input, weight_matrix, QMLC, epsilon):
""" Forward pass computation """
print("FORWARD BEGIN")
ctx.epsilon = epsilon
ctx.QMLC = QMLC
ctx.weight_matrix = weight_matrix
print("input from forward: ", input)
print("weight_matrix: ", ctx.weight_matrix)
wm = ctx.weight_matrix.tolist()
print("wm: ", wm)
ph = ctx.QMLC.circuit_function(input.tolist()[0], wm)
result = torch.tensor([ph])
print("result: ", result)
ctx.save_for_backward(input, result)
print("FORWARD END")
return result
@staticmethod
def backward(ctx, grad_output):
print("BACKWARD BEGIN")
print("grad_output: ", grad_output)
input, ph = ctx.saved_tensors
input_list = np.array(input.tolist())
wm = ctx.weight_matrix.tolist()
# print("wm: ", wm)
# print(len(wm))
# print(len(wm[0]))
gradient = []
# wyliczam część gradientu dy/dw
for i in range(len(wm)):
gradient_row = []
for j in range(len(wm[0])):
wm[i][j] += ctx.epsilon
result_plus = ctx.QMLC.circuit_function(input_list.tolist()[0], wm)
print(wm)
wm[i][j] -= 2*ctx.epsilon
result_minus = ctx.QMLC.circuit_function(input_list.tolist()[0], wm)
print(wm)
wm[i][j] += ctx.epsilon
result_0 = ctx.QMLC.circuit_function(input_list.tolist()[0], wm)
print(wm)
# print("exp_ph", expected_ph)
# print(result_plus - result_minus)
dydw = (result_plus - result_minus)/(2*ctx.epsilon)
djdy = (result_0 - grad_output.tolist())
lr = 0.05
print("dydw: ", dydw)
print("djdy: ", djdy)
result = djdy * dydw * lr
# print("result: ", result)
gradient_row.append(np.sum(result))
gradient.append(gradient_row)
# print("gradient: ", gradient)
gradient = np.array(gradient)
# print("gradient size: ", gradient)
# print("wm size: ", wm)
wm -= gradient
# print("self.weight_matrix: ", wm)
# print(torch.tensor(gradient).float() * grad_output.float(), None, None)
# print("BACKWARD END")
ret = np.zeros((len(wm), 1)).T
# print(ret)
return torch.tensor(ret).float(), None, None, None
class QuantumLayer(nn.Module):
""" Hybrid quantum - classical layer definition """
def __init__(self, visible, hidden, backend, shots, epsilon):
super(QuantumLayer, self).__init__()
self.visible = visible
self.hidden = hidden
self.QMLC = QMLCircuit(self.visible, self.hidden, 1000)
self.epsilon = epsilon
# self.weight_matrix = nn.Parameter(torch.randn(visible, hidden))
# self.weight_matrix = np.random.rand(visible, hidden) * np.pi
self.weight_matrix = nn.Parameter(torch.tensor(np.random.rand(visible, hidden) * np.pi))
print("self.weight_matrix: ", self.weight_matrix)
def forward(self, input):
return QFunction.apply(input, self.weight_matrix, self.QMLC, self.epsilon)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=5)
self.conv2 = nn.Conv2d(32, 64, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(6400, 64)
self.fc2 = nn.Linear(64, 2)
self.quantum = QuantumLayer(2, 2, qiskit.Aer.get_backend('qasm_simulator'), 1000, 0.01)
self.fc3 = nn.Linear(2, 2)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(-1, 6400)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = F.softmax(x)
# print("softmax x: ", x)
x = self.quantum(x)
# print("x after quantum: ", x)
# print("x after quantum: ", x.size())
x = self.fc3(x.float())
# print("x after fc3: ", x.size())
# print("x after fc3: ", x)
return F.log_softmax(x)
# return x
# trenowanie modelu
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 20
loss_list = []
model.train()
for epoch in range(epochs):
print("epoch: ", epoch)
print("weight_matrix: ", weight_matrix)
# print("wm: ", weight_matrix)
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
# target = target.float() # for MSELoss() function
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list[-1]))
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
n_samples_show = 6
count = 0
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
model.eval()
with torch.no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
if count == n_samples_show:
break
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
axes[count].imshow(data[0].numpy().squeeze(), cmap='gray')
axes[count].set_xticks([])
axes[count].set_yticks([])
axes[count].set_title('Predicted {}'.format(pred.item()))
count += 1
# nie trzeba odpalać STARE FUNKCJE
epsilon = 0.01
def update(ph, expected_ph, weight_matrix, lr):
gradient = []
for i, row in enumerate(weight_matrix):
gradient_row = []
for j, el in enumerate(row):
weight_matrix[i][j] += epsilon
result_plus = circuit_function(qc, weight_matrix)
weight_matrix[i][j] -= 2*epsilon
result_minus = circuit_function(qc, weight_matrix)
weight_matrix[i][j] += epsilon
# result_zero = circuit_function(qc, weight_matrix)
# print("ph", result_zero)
# print("exp_ph", expected_ph)
# print("el final:", el)
# print(result_plus - result_minus)
result = (result_plus - result_minus)/(2*epsilon) * lr * (ph - expected_ph)
gradient_row.append(result)
gradient.append(gradient_row)
# print("gradient", gradient)
weight_matrix = weight_matrix - gradient
return weight_matrix
def create_dataset(dataset_size):
dataset = []
for i in range(dataset_size):
x = np.array([random.choice([0,1]), random.choice([0,1])])
y = 1
if np.array_equal(x, np.array([0,0])) or np.array_equal(x, np.array([1,1])):
y = 0
dataset.append({"x": x, "y": y})
return dataset
dataset = create_dataset(4)
print(dataset)
# template do uczenia
import matplotlib.pyplot as plt
%matplotlib inline
#definicja rozmiaru sieci
visible = 2
hidden = 1
ancilla = visible-1
#definicja wejścia (x)oraz inicjalizacja macierzy wag
# x = np.array([random.uniform(0, 1) for n in range(visible)])
dataset = create_dataset(10)
print(dataset[0]["x"][0])
print(dataset[0]["x"][1])
print([n for n in range(visible)])
weight_matrix = np.random.rand(visible, hidden) * np.pi
#definicja parametrów uczenia
num_shots = 1000
num_epochs = 100
qr = QuantumRegister(visible + hidden + ancilla, 'q')
cr = ClassicalRegister(hidden, 'c')
qc = QuantumCircuit(qr, cr)
cost_function_data = []
lr = 0.05
for epoch in range(num_epochs):
print("epoch: ", epoch)
for i, element in enumerate(dataset):
# print(element)
x = np.array([dataset[i]["x"][n] for n in range(visible)])
exp_ph = dataset[i]["y"]
ph = circuit_function(qc, weight_matrix)
weight_matrix = update(ph, exp_ph, weight_matrix, lr)
# print("exp_ph", exp_ph, "ph", ph, "weight_matrix", weight_matrix, "cost_function", 0.5 * (ph - exp_ph)**2)
cost_function_data.append(0.5 * (ph - exp_ph)**2)
qc.draw()
plt.xlabel('number of epochs')
plt.ylabel('cost')
plt.plot(cost_function_data)
for i in range(len(dataset)):
x = np.array([dataset[i]["x"][n] for n in range(visible)])
exp_ph = dataset[i]["y"]
ph = circuit_function(qc, weight_matrix)
print(ph)
print(exp_ph, "\n")
qc.draw()
ph = circuit_function(qc, weight_matrix)
print(ph)
|
https://github.com/mareksubocz/QRBM-qiskit
|
mareksubocz
|
from qiskit import IBMQ
# IBMQ.save_account(MY_API_TOKEN)
import qiskit
qiskit.__version__
import scipy
import numpy as np
import random
from sklearn import preprocessing
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.quantum_info.operators import Operator
from qiskit import(QuantumCircuit, execute, Aer)
from qiskit.visualization import plot_histogram
from qiskit.extensions import Initialize # Import the Inititialize function
from qiskit.aqua.circuits.gates import multi_control_toffoli_gate
from qiskit.aqua.circuits.gates import multi_control_multi_target_gate
import torch
from torch.autograd import Function
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
import timeit
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['image.cmap'] = 'gray'
import pandas as pd
from skimage import data, color
from skimage.transform import rescale, resize, downscale_local_mean
from skimage import img_as_bool
import cv2 as cv
image_height = 14
image_width = 14
len_x = image_height * image_width
len_y = 0
mnist_dataset = pd.read_csv('../data/mnist_train.csv')
X_train = mnist_dataset.values[:,1:]
img = np.resize(X_train[1], (28, 28))
def random_image(dataset):
return random.choice(dataset)
X_train = mnist_dataset.values[:,1:]
X_train2 = mnist_dataset.values[:,:]
# print(mnist_dataset.values[:,0])
X_train3 = mnist_dataset.values[np.where(mnist_dataset.values[:,0] < 2), 1:]
labels =mnist_dataset.values[np.where(mnist_dataset.values[:,0] < 2), 0]
# print(labels)
# print(X_train3)
image = random_image(X_train3[0])
print(len(X_train3[0]))
imgs = np.resize(X_train3[0], (len(X_train3[0]), 28, 28)) / 255
print(len(imgs))
plt.imshow(imgs[0])
plt.show()
# print([img for img in imgs)
images_resized = [resize(img, (14, 14), anti_aliasing=True) for img in imgs]
# print(images_resized)
plt.imshow(images_resized[8])
plt.show()
# print(image_resized)
# # img = np.array(data).reshape(image_height, -1)
# print(len(X_train[0]))
# # plt.imshow(np.resize(X_train[0], (28, 28)))
# plt.show()
plt.imshow(images_resized[7])
plt.show()
plt.imshow(images_resized[8])
plt.show()
plt.imshow(images_resized[9])
plt.show()
images_normalized = [cv.normalize(image_resized, image_resized, 0, 255, cv.NORM_MINMAX) for image_resized in images_resized]
print(len(images_normalized))
plt.imshow(images_normalized[0])
plt.show()
data = [np.where(image_resized > 0.1, 1, 0) for image_resized in images_resized]
print(len(data))
print(data[0])
plt.imshow(data[0])
plt.show()
# data = np.reshape(data, (image_height*image_height))
data = [x.flatten().tolist() for x in data]
# len_y = len(X_train3[0])
print(data[0])
def exctract_single_qubit_measurment(dict_of_counts, qubit_range):
# print(dict_of_counts)
# print(len(list(dict_of_counts.keys())[0]))
num_qubits = len(list(dict_of_counts.keys())[0])
# result = np.zeros(len(qubit_range))
result = np.zeros(num_qubits)
# print(result)
for el in dict_of_counts:
for i in range(num_qubits):
# print("i", i)
# print("el[i]", el[i])
if i in qubit_range and el[i] == '1':
result[i] += dict_of_counts[el]
# print(result)
# print(result[qubit_range])
return result[qubit_range]
# TUTAJ ZACZYNAM KOD
class QMLCircuit():
def __init__(self, visible, hidden, num_shots=1000):
self.visible = visible
self.hidden = hidden
self.ancilla = visible-1
self.qr = QuantumRegister((self.visible + self.hidden + self.ancilla), 'q')
self.cr = ClassicalRegister(self.hidden, 'c')
self.qc = QuantumCircuit(self.qr, self.cr)
self.num_shots = num_shots
# def run(self, thetas):
def circuit_function(self, x, weight_matrix):
self.qc.data = []
# inicjalizacja wartości qubitów wejściowych (x)
initial_state = [[np.sqrt(1-x[i]), np.sqrt(x[i])] for i in range(len(x))]
# inicjalizacja wartości qubitów wejściowych i bramka Hadamarda
for i in range(visible):
initialize_qubit = Initialize(initial_state[i])
self.qc.append(initialize_qubit, [i])
self.qc.h(i)
# ciąg bramek CNOT i bramek rotacji R (zależnych od parametrów)
for i in range(self.hidden):
for j in range(self.visible):
self.qc.ry(weight_matrix[j][i], j)
print([self.qr[k] for k in range(self.visible)])
print(self.qr[self.visible + i])
print([self.qr[i] for i in range(self.visible + self.hidden, self.visible + self.hidden + self.ancilla)])
multi_control_toffoli_gate.mct(self.qc, [self.qr[k] for k in range(self.visible)], self.qr[self.visible + i], [self.qr[i] for i in range(self.visible + self.hidden, self.visible + self.hidden + self.ancilla)], mode='basic')
# pomiar linii visible
self.qc.measure(list(range(visible, visible+hidden)), list(range(hidden)))
#eksperyment:
simulator = Aer.get_backend('qasm_simulator')
job = execute(self.qc, simulator, shots=self.num_shots)
result = job.result()
counts = result.get_counts(self.qc)
ph = exctract_single_qubit_measurment(counts, list(range(self.hidden))) / self.num_shots
# print("\nProbabilities are:",ph)
return ph
visible = 2
hidden = 1
QMLC = QMLCircuit(visible, hidden, 1000)
#definicja wejścia (x)oraz inicjalizacja macierzy wag
x = np.array([random.uniform(0, 1) for n in range(visible)])
weight_matrix = np.random.rand(visible, hidden) * np.pi
print(QMLC.circuit_function(x, weight_matrix))
QMLC.qc.draw()
class QFunction(Function):
""" Hybrid quantum - classical function definition """
@staticmethod
def forward(ctx, input, QMLC, epsilon):
""" Forward pass computation """
ctx.epsilon = epsilon
ctx.QMLC = QMLC
print(input)
ph = ctx.QMLC(input[0].tolist())
result = torch.tensor([ph])
ctx.save_for_backward(input, result)
return result
@staticmethod
def backward(ctx, grad_output):
# def update(ph, expected_ph, weight_matrix, lr):
input, ph = ctx.saved_tensors
input_list = np.array(input.tolist())
gradients = []
gradient_row = []
for j, el in enumerate(row):
weight_matrix[i][j] += epsilon
result_plus = circuit_function(qc, weight_matrix)
weight_matrix[i][j] -= 2*epsilon
result_minus = circuit_function(qc, weight_matrix)
weight_matrix[i][j] += epsilon
# result_zero = circuit_function(qc, weight_matrix)
# print("ph", result_zero)
# print("exp_ph", expected_ph)
# print("el final:", el)
# print(result_plus - result_minus)
result = (result_plus - result_minus)/(2*epsilon) * lr * (ph - expected_ph)
gradient_row.append(result)
gradient.append(gradient_row)
# print("gradient", gradient)
weight_matrix = weight_matrix - gradient
return weight_matrix
""" Backward pass computation """
input, ph = ctx.saved_tensors
input_list = np.array(input.tolist())
shift_right = input_list + np.ones(input_list.shape) * ctx.epsilon
shift_left = input_list - np.ones(input_list.shape) * ctx.epsilon
gradients = []
for i in range(len(input_list)):
expectation_right = ctx.quantum_circuit.run(shift_right[i])
expectation_left = ctx.quantum_circuit.run(shift_left[i])
gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left])
gradients.append(gradient)
gradients = np.array([gradients]).T
return torch.tensor([gradients]).float() * grad_output.float(), None, None
class QuantumLayer(nn.Module):
""" Hybrid quantum - classical layer definition """
def __init__(self, backend, shots, epsilon):
super(QuantumLayer, self).__init__()
self.QMLC = QMLCircuit(1, 1, 1000)
self.epsilon = epsilon
def forward(self, input):
return QFunction.apply(input, self.QMLC, self.epsilon)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=5)
self.conv2 = nn.Conv2d(32, 64, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(256, 64)
self.fc2 = nn.Linear(64, 1)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(-1, 256)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return torch.cat((x, 1 - x), -1)
# Concentrating on the first 100 samples
n_samples = 100
X_train = datasets.MNIST(root='./data', train=True, download=True,
transform=transforms.Compose([transforms.ToTensor()]))
# Leaving only labels 0 and 1
idx = np.append(np.where(X_train.targets == 0)[0][:n_samples],
np.where(X_train.targets == 1)[0][:n_samples])
X_train.data = X_train.data[idx]
X_train.targets = X_train.targets[idx]
train_loader = torch.utils.data.DataLoader(X_train, batch_size=1, shuffle=True)
n_samples_show = 6
data_iter = iter(train_loader)
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
while n_samples_show > 0:
images, targets = data_iter.__next__()
axes[n_samples_show - 1].imshow(images[0].numpy().squeeze(), cmap='gray')
axes[n_samples_show - 1].set_xticks([])
axes[n_samples_show - 1].set_yticks([])
axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item()))
n_samples_show -= 1
n_samples = 50
X_test = datasets.MNIST(root='./data', train=False, download=True,
transform=transforms.Compose([transforms.ToTensor()]))
idx = np.append(np.where(X_test.targets == 0)[0][:n_samples],
np.where(X_test.targets == 1)[0][:n_samples])
X_test.data = X_test.data[idx]
X_test.targets = X_test.targets[idx]
test_loader = torch.utils.data.DataLoader(X_test, batch_size=1, shuffle=True)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 20
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
print(i for i in enumerate(train_loader))
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list[-1]))
for epoch in range(epochs):
total_loss = []
print(i for i in enumerate(train_loader))
for batch_idx, something in enumerate(train_loader):
print(batch_idx)
print(something)
print(something)
class QuantumCircuit:
"""
This class provides a simple interface for interaction
with the quantum circuit
"""
def __init__(self, visible, hidden, backend, shots):
# --- Circuit definition ---
self.qc = qiskit.QuantumCircuit(visible + hidden)
all_qubits = [i for i in range(visible+hidden)]
self.theta = qiskit.circuit.Parameter('theta')
self._circuit.h(all_qubits)
self._circuit.barrier()
self._circuit.ry(self.theta, all_qubits)
self._circuit.measure_all()
# ---------------------------
self.backend = backend
self.shots = shots
def run(self, thetas):
job = qiskit.execute(self._circuit,
self.backend,
shots = self.shots,
parameter_binds = [{self.theta: theta} for theta in thetas])
result = job.result().get_counts(self._circuit)
counts = np.array(list(result.values()))
states = np.array(list(result.keys())).astype(float)
# Compute probabilities for each state
probabilities = counts / self.shots
# Get state expectation
expectation = np.sum(states * probabilities)
return np.array([expectation])
simulator = qiskit.Aer.get_backend('qasm_simulator')
circuit = QuantumCircuit(1, 1, simulator, 100)
print('Expected value for rotation pi {}'.format(circuit.run([np.pi])[0]))
circuit._circuit.draw()
epsilon = 0.01
def update(ph, expected_ph, weight_matrix, lr):
gradient = []
for i, row in enumerate(weight_matrix):
gradient_row = []
for j, el in enumerate(row):
weight_matrix[i][j] += epsilon
result_plus = circuit_function(qc, weight_matrix)
weight_matrix[i][j] -= 2*epsilon
result_minus = circuit_function(qc, weight_matrix)
weight_matrix[i][j] += epsilon
# result_zero = circuit_function(qc, weight_matrix)
# print("ph", result_zero)
# print("exp_ph", expected_ph)
# print("el final:", el)
# print(result_plus - result_minus)
result = (result_plus - result_minus)/(2*epsilon) * lr * (ph - expected_ph)
gradient_row.append(result)
gradient.append(gradient_row)
# print("gradient", gradient)
weight_matrix = weight_matrix - gradient
return weight_matrix
# class QuantumCircuit:
# """
# This class provides a simple interface for interaction
# with the quantum circuit
# """
# def __init__(self, n_qubits, backend, shots):
# # --- Circuit definition ---
# self._circuit = qiskit.QuantumCircuit(n_qubits)
# all_qubits = [i for i in range(n_qubits)]
# self.theta = qiskit.circuit.Parameter('theta')
# self._circuit.h(all_qubits)
# self._circuit.barrier()
# self._circuit.ry(self.theta, all_qubits)
# self._circuit.measure_all()
# # ---------------------------
# self.backend = backend
# self.shots = shots
# def run(self, thetas): #MOJE circuit_funcion()
# job = qiskit.execute(self._circuit,
# self.backend,
# shots = self.shots,
# parameter_binds = [{self.theta: theta} for theta in thetas])
# result = job.result().get_counts(self._circuit)
# counts = np.array(list(result.values()))
# states = np.array(list(result.keys())).astype(float)
# # Compute probabilities for each state
# probabilities = counts / self.shots
# # Get state expectation
# expectation = np.sum(states * probabilities)
# return np.array([expectation])
class QuantumFunction(Function):
""" Hybrid quantum - classical function definition """
@staticmethod
def forward(ctx, input, quantum_circuit, shift):
""" Forward pass computation """
ctx.shift = shift
ctx.quantum_circuit = quantum_circuit
ph = ctx.quantum_circuit.run(input[0].tolist())
result = torch.tensor([expectation_z])
ctx.save_for_backward(input, result)
return result
@staticmethod
def backward(ctx, grad_output):
""" Backward pass computation """
input, expectation_z = ctx.saved_tensors
input_list = np.array(input.tolist())
shift_right = input_list + np.ones(input_list.shape) * ctx.shift
shift_left = input_list - np.ones(input_list.shape) * ctx.shift
gradients = []
for i in range(len(input_list)):
expectation_right = ctx.quantum_circuit.run(shift_right[i])
expectation_left = ctx.quantum_circuit.run(shift_left[i])
gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left])
gradients.append(gradient)
gradients = np.array([gradients]).T
return torch.tensor([gradients]).float() * grad_output.float(), None, None
class QuantumLayer(nn.Module):
""" Hybrid quantum - classical layer definition """
def __init__(self, backend, shots, shift):
super(QuantumLayer, self).__init__()
self.quantum_circuit = QuantumCircuit(1, backend, shots)
self.shift = shift
def forward(self, input):
return QuantumFunction.apply(input, self.quantum_circuit, self.shift)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=5)
self.conv2 = nn.Conv2d(32, 64, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(256, 64)
self.fc2 = nn.Linear(64, 1)
self.quantum_layer = Quantum_Layer()
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(-1, 256)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.quantum_layer(x)
return torch.cat((x, 1 - x), -1)
net = Net()
print(net)
def exctract_single_qubit_measurment(dict_of_counts, qubit_range):
# print(dict_of_counts)
# print(len(list(dict_of_counts.keys())[0]))
num_qubits = len(list(dict_of_counts.keys())[0])
# result = np.zeros(len(qubit_range))
result = np.zeros(num_qubits)
# print(result)
for el in dict_of_counts:
for i in range(num_qubits):
# print("i", i)
# print("el[i]", el[i])
if i in qubit_range and el[i] == '1':
result[i] += dict_of_counts[el]
# print(result)
# print(result[qubit_range])
return result[qubit_range]
def create_dataset(dataset_size):
dataset = []
for i in range(dataset_size):
x = np.array([random.choice([0,1]), random.choice([0,1])])
y = 1
if np.array_equal(x, np.array([0,0])) or np.array_equal(x, np.array([1,1])):
y = 0
dataset.append({"x": x, "y": y})
return dataset
dataset = create_dataset(4)
print(dataset)
class QuantumCircuit():
def __init__(self, visible=1, hidden=1, num_shots=1000):
self._visible = visible
self._hidden = hidden
print(self._visible + self._hidden + ancilla)
qr = QuantumRegister((self._visible + self._hidden), 'q')
cr = ClassicalRegister(self._hidden, 'c')
self._qc = QuantumCircuit(qr, cr)
self._num_shots = num_shots
# def run(self, thetas):
def circuit_function(qc, x, weight_matrix):
qc.data = []
# inicjalizacja wartości qubitów wejściowych (x)
initial_state = [[np.sqrt(1-x[i]), np.sqrt(x[i])] for i in range(len(x))]
# inicjalizacja wartości qubitów wejściowych i bramka Hadamarda
for i in range(visible):
initialize_qubit = Initialize(initial_state[i])
qc.append(initialize_qubit, [i])
qc.h(i)
# ciąg bramek CNOT i bramek rotacji R (zależnych od parametrów)
for i in range(hidden):
for j in range(visible):
qc.ry(weight_matrix[j][i], j)
multi_control_toffoli_gate.mct(qc, [qr[k] for k in range(visible)], qr[visible + i], [qr[i] for i in range(visible + hidden, visible + hidden + ancilla)], mode='basic')
# pomiar linii visible
qc.measure(list(range(visible, visible+hidden)), list(range(hidden)))
#eksperyment:
simulator = Aer.get_backend('qasm_simulator')
job = execute(qc, simulator, shots=num_shots)
result = job.result()
counts = result.get_counts(qc)
ph = exctract_single_qubit_measurment(counts, list(range(hidden))) / num_shots
# print("\nProbabilities are:",ph)
return ph[0]
epsilon = 0.01
def update(ph, expected_ph, weight_matrix, lr):
gradient = []
for i, row in enumerate(weight_matrix):
gradient_row = []
for j, el in enumerate(row):
weight_matrix[i][j] += epsilon
result_plus = circuit_function(qc, weight_matrix)
weight_matrix[i][j] -= 2*epsilon
result_minus = circuit_function(qc, weight_matrix)
weight_matrix[i][j] += epsilon
# result_zero = circuit_function(qc, weight_matrix)
# print("ph", result_zero)
# print("exp_ph", expected_ph)
# print("el final:", el)
# print(result_plus - result_minus)
result = (result_plus - result_minus)/(2*epsilon) * lr * (ph - expected_ph)
gradient_row.append(result)
gradient.append(gradient_row)
# print("gradient", gradient)
weight_matrix = weight_matrix - gradient
return weight_matrix
visible = 2
hidden = 1
ancilla = visible-1
num_shots = 1000
qc = QuantumCircuit(visible, hidden, 1000)
# template do uczenia
import matplotlib.pyplot as plt
%matplotlib inline
#definicja rozmiaru sieci
visible = 2
hidden = 1
ancilla = visible-1
#definicja wejścia (x)oraz inicjalizacja macierzy wag
# x = np.array([random.uniform(0, 1) for n in range(visible)])
dataset = create_dataset(10)
print(dataset[0]["x"][0])
print(dataset[0]["x"][1])
print([n for n in range(visible)])
weight_matrix = np.random.rand(visible, hidden) * np.pi
#definicja parametrów uczenia
num_shots = 1000
num_epochs = 100
qr = QuantumRegister(visible + hidden + ancilla, 'q')
cr = ClassicalRegister(hidden, 'c')
qc = QuantumCircuit(qr, cr)
cost_function_data = []
lr = 0.05
for epoch in range(num_epochs):
print("epoch: ", epoch)
for i, element in enumerate(dataset):
# print(element)
x = np.array([dataset[i]["x"][n] for n in range(visible)])
exp_ph = dataset[i]["y"]
ph = circuit_function(qc, weight_matrix)
weight_matrix = update(ph, exp_ph, weight_matrix, lr)
# print("exp_ph", exp_ph, "ph", ph, "weight_matrix", weight_matrix, "cost_function", 0.5 * (ph - exp_ph)**2)
cost_function_data.append(0.5 * (ph - exp_ph)**2)
qc.draw()
plt.xlabel('number of epochs')
plt.ylabel('cost')
plt.plot(cost_function_data)
for i in range(len(dataset)):
x = np.array([dataset[i]["x"][n] for n in range(visible)])
exp_ph = dataset[i]["y"]
ph = circuit_function(qc, weight_matrix)
print(ph)
print(exp_ph, "\n")
qc.draw()
ph = circuit_function(qc, weight_matrix)
print(ph)
|
https://github.com/mareksubocz/QRBM-qiskit
|
mareksubocz
|
from qiskit import IBMQ
# IBMQ.save_account(MY_API_TOKEN)
import qiskit
qiskit.__version__
import scipy
import numpy as np
import random
from sklearn import preprocessing
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.quantum_info.operators import Operator
from qiskit import(QuantumCircuit, execute, Aer)
from qiskit.visualization import plot_histogram
from qiskit.extensions import Initialize # Import the Inititialize function
from qiskit.aqua.circuits.gates import multi_control_toffoli_gate
from qiskit.aqua.circuits.gates import multi_control_multi_target_gate
import torch
from torch.autograd import Function
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
import timeit
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['image.cmap'] = 'gray'
import pandas as pd
from skimage import data, color
from skimage.transform import rescale, resize, downscale_local_mean
from skimage import img_as_bool
import cv2 as cv
def exctract_single_qubit_measurment(dict_of_counts, qubit_range):
num_qubits = len(list(dict_of_counts.keys())[0])
result = np.zeros(num_qubits)
for el in dict_of_counts:
for i in range(num_qubits):
if i in qubit_range and el[i] == '1':
result[i] += dict_of_counts[el]
return result[qubit_range]
class QMLCircuit():
def __init__(self, visible, hidden, num_shots=1000):
self.visible = visible
self.hidden = hidden
self.ancilla = visible-1
self.qr = QuantumRegister((self.visible + self.hidden + self.ancilla), 'q')
self.cr = ClassicalRegister(self.hidden, 'c')
self.qc = QuantumCircuit(self.qr, self.cr)
self.num_shots = num_shots
# def run(self, thetas):
def circuit_function(self, x, weight_matrix):
self.qc.data = []
# inicjalizacja wartości qubitów wejściowych (x)
initial_state = [[np.sqrt(1-x[i]), np.sqrt(x[i])] for i in range(len(x))]
print('dlugosc initial_state: ', len(initial_state))
# inicjalizacja wartości qubitów wejściowych i bramka Hadamarda
for i in range(visible):
print('i vis: ', i)
initialize_qubit = Initialize(initial_state[i])
self.qc.append(initialize_qubit, [i])
self.qc.h(i)
# ciąg bramek CNOT i bramek rotacji R (zależnych od parametrów)
for i in range(self.hidden):
print('i hid: ', i)
for j in range(self.visible):
print('j vis: ', j)
self.qc.ry(weight_matrix[j][i], j)
print([self.qr[k] for k in range(self.visible)])
print(self.qr[self.visible + i])
print([self.qr[i] for i in range(self.visible + self.hidden, self.visible + self.hidden + self.ancilla)])
multi_control_toffoli_gate.mct(self.qc, [self.qr[k] for k in range(self.visible)], self.qr[self.visible + i], [self.qr[i] for i in range(self.visible + self.hidden, self.visible + self.hidden + self.ancilla)], mode='basic')
# pomiar linii visible
self.qc.measure(list(range(visible, visible+hidden)), list(range(hidden)))
#eksperyment:
simulator = Aer.get_backend('qasm_simulator')
job = execute(self.qc, simulator, shots=self.num_shots)
result = job.result()
counts = result.get_counts(self.qc)
ph = exctract_single_qubit_measurment(counts, list(range(self.hidden))) / self.num_shots
# print("\nProbabilities are:",ph)
return ph
visible = 2
hidden = 1
QMLC = QMLCircuit(visible, hidden, 1000)
#definicja wejścia (x)oraz inicjalizacja macierzy wag
x = np.array([random.uniform(0, 1) for n in range(visible)])
weight_matrix = np.random.rand(visible, hidden) * np.pi
print(QMLC.circuit_function(x, weight_matrix))
QMLC.qc.draw()
##Na razie zostawiam na później
class QFunction(Function):
""" Hybrid quantum - classical function definition """
@staticmethod
def forward(ctx, input, QMLC, epsilon):
""" Forward pass computation """
ctx.epsilon = epsilon
ctx.QMLC = QMLC
print(input)
ph = ctx.QMLC(input[0].tolist())
result = torch.tensor([ph])
ctx.save_for_backward(input, result)
return result
@staticmethod
def backward(ctx, grad_output):
# def update(ph, expected_ph, weight_matrix, lr):
input, ph = ctx.saved_tensors
input_list = np.array(input.tolist())
gradients = []
gradient_row = []
for j, el in enumerate(row):
weight_matrix[i][j] += epsilon
result_plus = circuit_function(qc, weight_matrix)
weight_matrix[i][j] -= 2*epsilon
result_minus = circuit_function(qc, weight_matrix)
weight_matrix[i][j] += epsilon
# result_zero = circuit_function(qc, weight_matrix)
# print("ph", result_zero)
# print("exp_ph", expected_ph)
# print("el final:", el)
# print(result_plus - result_minus)
result = (result_plus - result_minus)/(2*epsilon) * lr * (ph - expected_ph)
gradient_row.append(result)
gradient.append(gradient_row)
# print("gradient", gradient)
weight_matrix = weight_matrix - gradient
return weight_matrix
""" Backward pass computation """
input, ph = ctx.saved_tensors
input_list = np.array(input.tolist())
shift_right = input_list + np.ones(input_list.shape) * ctx.epsilon
shift_left = input_list - np.ones(input_list.shape) * ctx.epsilon
gradients = []
for i in range(len(input_list)):
expectation_right = ctx.quantum_circuit.run(shift_right[i])
expectation_left = ctx.quantum_circuit.run(shift_left[i])
gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left])
gradients.append(gradient)
gradients = np.array([gradients]).T
return torch.tensor([gradients]).float() * grad_output.float(), None, None
class QuantumLayer(nn.Module):
""" Hybrid quantum - classical layer definition """
def __init__(self, backend, shots, epsilon):
super(QuantumLayer, self).__init__()
self.QMLC = QMLCircuit(1, 1, 1000)
self.epsilon = epsilon
def forward(self, input):
return QFunction.apply(input, self.QMLC, self.epsilon)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=5)
self.conv2 = nn.Conv2d(32, 64, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(6400, 64)
self.fc2 = nn.Linear(64, 1)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(-1, 6400)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return torch.cat((x, 1 - x), -1)
# Wczytywanie danych inną metodą
# Concentrating on the first 100 samples
n_samples = 100
X_train = datasets.MNIST(root='./data', train=True, download=True,
transform=transforms.Compose([transforms.ToTensor()]))
# Leaving only labels 0 and 1
idx = np.append(np.where(X_train.targets == 0)[0][:n_samples],
np.where(X_train.targets == 1)[0][:n_samples])
X_train.data = X_train.data[idx]
X_train.targets = X_train.targets[idx]
train_loader = torch.utils.data.DataLoader(X_train, batch_size=1, shuffle=True)
n_samples_show = 6
data_iter = iter(train_loader)
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
while n_samples_show > 0:
images, targets = data_iter.__next__()
axes[n_samples_show - 1].imshow(images[0].numpy().squeeze(), cmap='gray')
axes[n_samples_show - 1].set_xticks([])
axes[n_samples_show - 1].set_yticks([])
axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item()))
n_samples_show -= 1
n_samples = 50
X_test = datasets.MNIST(root='./data', train=False, download=True,
transform=transforms.Compose([transforms.ToTensor()]))
idx = np.append(np.where(X_test.targets == 0)[0][:n_samples],
np.where(X_test.targets == 1)[0][:n_samples])
X_test.data = X_test.data[idx]
X_test.targets = X_test.targets[idx]
test_loader = torch.utils.data.DataLoader(X_test, batch_size=1, shuffle=True)
# trenowanie modelu
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 20
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
print(i for i in enumerate(train_loader))
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list[-1]))
# nie trzeba odpalać STARE FUNKCJE
epsilon = 0.01
def update(ph, expected_ph, weight_matrix, lr):
gradient = []
for i, row in enumerate(weight_matrix):
gradient_row = []
for j, el in enumerate(row):
weight_matrix[i][j] += epsilon
result_plus = circuit_function(qc, weight_matrix)
weight_matrix[i][j] -= 2*epsilon
result_minus = circuit_function(qc, weight_matrix)
weight_matrix[i][j] += epsilon
# result_zero = circuit_function(qc, weight_matrix)
# print("ph", result_zero)
# print("exp_ph", expected_ph)
# print("el final:", el)
# print(result_plus - result_minus)
result = (result_plus - result_minus)/(2*epsilon) * lr * (ph - expected_ph)
gradient_row.append(result)
gradient.append(gradient_row)
# print("gradient", gradient)
weight_matrix = weight_matrix - gradient
return weight_matrix
def create_dataset(dataset_size):
dataset = []
for i in range(dataset_size):
x = np.array([random.choice([0,1]), random.choice([0,1])])
y = 1
if np.array_equal(x, np.array([0,0])) or np.array_equal(x, np.array([1,1])):
y = 0
dataset.append({"x": x, "y": y})
return dataset
dataset = create_dataset(4)
print(dataset)
# template do uczenia
import matplotlib.pyplot as plt
%matplotlib inline
#definicja rozmiaru sieci
visible = 2
hidden = 1
ancilla = visible-1
#definicja wejścia (x)oraz inicjalizacja macierzy wag
# x = np.array([random.uniform(0, 1) for n in range(visible)])
dataset = create_dataset(10)
print(dataset[0]["x"][0])
print(dataset[0]["x"][1])
print([n for n in range(visible)])
weight_matrix = np.random.rand(visible, hidden) * np.pi
#definicja parametrów uczenia
num_shots = 1000
num_epochs = 100
QMLC = QMLCircuit(visible, hidden, 1000)
qr = QuantumRegister(visible + hidden + ancilla, 'q')
cr = ClassicalRegister(hidden, 'c')
qc = QuantumCircuit(qr, cr)
cost_function_data = []
lr = 0.05
for epoch in range(num_epochs):
print("epoch: ", epoch)
# qc.data = []
# initial_state = [[np.sqrt(1-x[i]), np.sqrt(x[i])] for i in range(len(x))]
# for i in range(visible):
# print('i vis: ', i)
# initialize_qubit = Initialize(initial_state[i])
# qc.append(initialize_qubit, [i])
# qc.h(i)
for i, element in enumerate(dataset):
# print(element)
x = np.array([dataset[i]["x"][n] for n in range(visible)])
exp_ph = dataset[i]["y"]
ph = QMLC.circuit_function(qc, weight_matrix)
weight_matrix = update(ph, exp_ph, weight_matrix, lr)
# print("exp_ph", exp_ph, "ph", ph, "weight_matrix", weight_matrix, "cost_function", 0.5 * (ph - exp_ph)**2)
cost_function_data.append(0.5 * (ph - exp_ph)**2)
qc.draw()
plt.xlabel('number of epochs')
plt.ylabel('cost')
plt.plot(cost_function_data)
for i in range(len(dataset)):
x = np.array([dataset[i]["x"][n] for n in range(visible)])
exp_ph = dataset[i]["y"]
ph = circuit_function(qc, weight_matrix)
print(ph)
print(exp_ph, "\n")
qc.draw()
ph = circuit_function(qc, weight_matrix)
print(ph)
|
https://github.com/sathayen/qiskit-docker
|
sathayen
|
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit import Aer
from qiskit import execute
from qiskit.tools.visualization import circuit_drawer, plot_histogram
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.measure(qr, cr)
# Draw the circuit
circuit_drawer(qc)
# Print qasm
qc_qasm = qc.qasm()
print(qc_qasm)
# Run the circuit
job = execute(qc, backend = Aer.get_backend('qasm_simulator'), shots=1024)
# get status
job.status
# get results
result = job.result()
counts = result.get_counts()
print("Probability = ", counts['00']/1024)
|
https://github.com/sathayen/qiskit-docker
|
sathayen
|
# Creating quantum circuits
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit import execute, Aer
from qiskit.tools.visualization import circuit_drawer, plot_histogram
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.x(qr[0])
qc.measure(qr, cr)
circuit_drawer(qc)
# Run the circuit
job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=1024)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
print("Counts dictionary:", counts )
print("Probability = ", counts['01']/1024)
|
https://github.com/sathayen/qiskit-docker
|
sathayen
|
# Creating quantum circuits
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit import execute, Aer
from qiskit.tools.visualization import circuit_drawer, plot_histogram
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
# Apply a single H gate
qc.h(qr)
qc.measure(qr, cr)
circuit_drawer(qc)
# Create a backend object
local_simulator = Aer.get_backend('qasm_simulator')
# Run the circuit
job = execute(qc, backend=local_simulator, shots=100)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
print(counts)
qc2 = QuantumCircuit(qr, cr)
qc2.h(qr)
qc2.h(qr)
qc2.measure(qr, cr)
circuit_drawer(qc2)
# Run the circuit with 2 H gates applied in succession
job = execute(qc2, backend=local_simulator, shots=100)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
print(counts)
|
https://github.com/sathayen/qiskit-docker
|
sathayen
|
# Creating quantum circuits
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit import execute, Aer
from qiskit.tools.visualization import circuit_drawer, plot_histogram
qr = QuantumRegister(5)
cr = ClassicalRegister(5)
qc = QuantumCircuit(qr, cr)
qc.x(qr[0])
qc.cx(qr[0], qr[1])
qc.measure(qr, cr)
circuit_drawer(qc)
# Run the circuit
job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=1024)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
print("Counts dictionary:", counts )
print("Probability = ", counts['00011']/1024)
|
https://github.com/sathayen/qiskit-docker
|
sathayen
|
# Creating quantum circuits
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit import execute
from qiskit.tools.visualization import circuit_drawer, plot_histogram
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
# Apply a single H gate
qc.h(qr)
qc.measure(qr, cr)
circuit_drawer(qc)
import os
from qiskit import Aer
# Print the local simulator backends
print("Local simulator backends: ")
Aer.backends()
from qiskit import IBMQ
# Save your credeintials on disk. Need to be done only once.
IBMQ.save_account(os.getenv('QX_API_TOKEN'))
#IBMQ.save_account("PUT_YOUR_API_TOKEN_HERE")
# Alternatively, you can only "enable" the credentials, for this session only:
# IBMQ.enable_account("PUT_YOUR_API_TOKEN_HERE")
IBMQ.load_accounts()
print("Available online backends: ")
IBMQ.backends()
# Run the circuit using local simulator
local_simulator = Aer.get_backend("qasm_simulator")
job = execute(qc, backend=local_simulator, shots=100)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
print(counts)
# Run the circuit using the cloud simulator
online_simulator = IBMQ.get_backend("ibmq_qasm_simulator")
job = execute(qc, backend=online_simulator)
result_cloud = job.result()
counts = result.get_counts()
plot_histogram(counts)
print(counts)
|
https://github.com/sathayen/qiskit-docker
|
sathayen
|
# Creating quantum circuits
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.tools.visualization import circuit_drawer
qr = QuantumRegister(5)
cr = ClassicalRegister(5)
qc = QuantumCircuit(qr, cr)
def swap_gate(q_swap, q1, q2):
q_swap.cx(q1, q2)
q_swap.cx(q2, q1)
q_swap.cx(q1, q2)
#q_swap.measure(qr2, cr2)
#circuit_drawer(q_swap)
swap_gate(qc, qr[3], qr[4])
qc.measure(qr, cr)
circuit_drawer(qc)
|
https://github.com/sathayen/qiskit-docker
|
sathayen
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, Aer, IBMQ
from qiskit.tools.visualization import plot_histogram , circuit_drawer
qr = QuantumRegister(16)
cr = ClassicalRegister(16)
qc = QuantumCircuit(qr, cr)
import bitarray
s1 = ";)"
s2 = "8)"
b1 = bitarray.bitarray()
b1.fromstring(s1)
b2 = bitarray.bitarray()
b2.fromstring(s2)
# print the bit sequences
print("b1 =", b1)
print("b2 =", b2)
# qr[0] ----> qr[15]
# 0011 1011 0010 1001" # s1 bit sequence
# 0011 1000 0010 1001" #s2 bit sequence
# Notice the difference between s1 and s2 -- bits 7 (qr[6]) and 8 (qr[7]) are different.
# 11 (s1)
# 00 (s2)
# All other bits are identical
# First take care of all other qubits -- APPLY x gates for appropriate qubits
# YOUR CODE HERE:
# We want both qr[6],qr[7] as 00 or 11 to get either 8 or ; respectively.
# Apply a controlled-NOT gate between 6 and 7 , so that when qubit 6 is "1", 7 also becomes 1
# YOUR CODE HERE:
# MEASURE:
# DRAW Circuit
# SET THE API:
# EXECUTE ON REMOTE BACKEND:
# Results:
result.status()
stats = result.result().get_counts()
plot_histogram(stats)
|
https://github.com/soultanis/Quantum-SAT-Solver
|
soultanis
|
# Import the Qiskit SDK.
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import available_backends, execute, Aer
from qiskit.tools.visualization import plot_histogram, circuit_drawer, plot_state
# Define the number of n-qbits.
n = 6
# Create a Quantum Register with n-qbits.
q = QuantumRegister(n)
# Create a Classical Register with n-bits.
c = ClassicalRegister(n)
# Create a Quantum Circuit
qc = QuantumCircuit(q, c)
# Init with |1>
qc.x(q[0])
qc.x(q[1])
# Add H-gate to get superposition.
qc.h(q[0])
qc.h(q[1])
# Apply the oracle 11.
qc.cx(q[0],q[1],q[2])
qc.x(q[0])
qc.x(q[1])
qc.cx(q[0],q[1],q[3])
qc.x(q[0])
qc.x(q[1])
qc.x(q[0])
qc.cx(q[0],q[4])
qc.x(q[0])
qc.x(q[2])
qc.x(q[3])
qc.x(q[4])
qc.x(q[5])
qc.cx(q[2],q[3],q[4],q[5])
qc.x(q[2])
qc.x(q[3])
qc.x(q[4])
qc.x(q[5])
qc.z(q[5])
qc.x(q[2])
qc.x(q[3])
qc.x(q[4])
qc.x(q[5])
qc.cx(q[2],q[3],q[4],q[5])
qc.x(q[2])
qc.x(q[3])
qc.x(q[4])
qc.x(q[5])
qc.x(q[0])
qc.cx(q[0],q[4])
qc.x(q[0])
qc.x(q[0])
qc.x(q[1])
qc.cx(q[0],q[1],q[3])
qc.x(q[0])
qc.x(q[1])
qc.cx(q[0],q[1],q[2])
# Apply the grover-algorithm 11
# Measure qubit to bit. .
qc.measure(q, c)
# Get Aer backend.
backend_sim = Aer.get_backend('qasm_simulator')
# Compile and run the Quantum circuit on a simulator backend.
sim_result1 = execute(qc, backend_sim, shots=1000).result()
counts1 = sim_result1.get_counts(qc)
# Show the results as text and plot.
print("Simulation: ", sim_result1)
print("Output: ", counts1)
plot_histogram(counts1)
circuit_drawer(qc)
|
https://github.com/soultanis/Quantum-SAT-Solver
|
soultanis
|
import grover_test as gt
# Simulator-Backend
# output = gt.build_and_run(3, [1])
# IBMQ-Backend
output = gt.build_and_run(2, [1], real=True, online=True)
print(output)
|
https://github.com/soultanis/Quantum-SAT-Solver
|
soultanis
|
import pylab
import numpy as np
from qiskit.providers.ibmq import least_busy
from qiskit import LegacySimulators, execute, IBMQ, Aer
from qiskit.tools.visualization import plot_histogram
from qiskit_aqua import QuantumInstance
from qiskit_aqua import run_algorithm
from qiskit_aqua.algorithms import Grover
from qiskit_aqua.components.oracles import SAT
satProblem = '3sat2-3.cnf'
with open(satProblem, 'r') as f:
sat_cnf = f.read()
print(sat_cnf)
sat_oracle = SAT(sat_cnf)
algorithm = Grover(sat_oracle)
backend = Aer.get_backend('qasm_simulator')
algorithm = Grover(sat_oracle)
result = algorithm.run(backend)
print(result['result'])
plot_histogram(result['measurements'])
params = {
'problem': {'name': 'search'},
'algorithm': {
'name': 'Grover'
},
'oracle': {
'name': 'SAT',
'cnf': sat_cnf
},
'backend': {
'shots': 100
}
}
result_dict = run_algorithm(params, backend=backend)
plot_histogram(result_dict['measurements'])
# Authenticate for access to remote backends
try:
import Qconfig
IBMQ.load_accounts()
except:
print("""WARNING: There's no connection with the API for remote backends.
Have you initialized a file with your personal token?
For now, there's only access to local simulator backends...""")
backend = least_busy(IBMQ.backends(simulator=False))
algorithm = Grover(sat_oracle)
result = algorithm.run(backend)
print(result['result'])
|
https://github.com/soultanis/Quantum-SAT-Solver
|
soultanis
|
import pylab
import numpy as np
from qiskit.providers.ibmq import least_busy
from qiskit import LegacySimulators, execute, IBMQ, Aer
from qiskit.tools.visualization import plot_histogram
from qiskit_aqua import QuantumInstance
from qiskit_aqua import run_algorithm
from qiskit_aqua.algorithms import Grover
from qiskit_aqua.components.oracles import SAT
m = 2
n = 2
satProblem = '3SATm-n\\3sat' + str(m) + '-' + str(n) + '.cnf'
with open(satProblem, 'r') as f:
sat_cnf = f.read()
print(sat_cnf)
sat_oracle = SAT(sat_cnf)
algorithm = Grover(sat_oracle)
sim_backend = Aer.get_backend('qasm_simulator')
result = algorithm.run(sim_backend)
print(result['result'])
plot_histogram(result['measurements'])
# Authenticate for access to remote backends
try:
import Qconfig
IBMQ.load_accounts()
except:
print("""WARNING: There's no connection with the API for remote backends.
Have you initialized a file with your personal token?
For now, there's only access to local simulator backends...""")
ibmq_backend = least_busy(IBMQ.backends(simulator=False))
result = algorithm.run(ibmq_backend)
print(result['result'])
plot_histogram(result['measurements'])
params = {
'problem': {'name': 'search'},
'algorithm': {
'name': 'Grover'
},
'oracle': {
'name': 'SAT',
'cnf': sat_cnf
},
'backend': {
'shots': 100
}
}
result_dict = run_algorithm(params, backend=backend)
plot_histogram(result_dict['measurements'])
from __future__ import print_function
def even_ones(s):
# Two states:
# - 0 (even number of ones seen so far)
# - 1 (odd number of ones seen so far)
rules = {(0, '0'): 0,
(0, '1'): 1,
(1, '0'): 1,
(1, '1'): 0}
# There are 0 (which is an even number) ones in the empty
# string so we start with state = 0.
state = 0
for c in s:
state = rules[state, c]
return state == 0
# Example usage:
s = "100110"
print('Output for {} = {}'.format(s, even_ones(s)))
|
https://github.com/soultanis/Quantum-SAT-Solver
|
soultanis
|
# Import the Qiskit SDK.
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import available_backends, execute, Aer
from qiskit.tools.visualization import plot_histogram, circuit_drawer, plot_state
# Define the number of n-qbits.
n = 6
# Create a Quantum Register with n-qbits.
q = QuantumRegister(n)
# Create a Classical Register with n-bits.
c = ClassicalRegister(n)
# Create a Quantum Circuit
qc = QuantumCircuit(q, c)
# Init with |1>
qc.x(q[0])
qc.x(q[1])
# Add H-gate to get superposition.
qc.h(q[0])
qc.h(q[1])
# Apply the oracle 11.
qc.cx(q[0],q[1],q[2])
qc.x(q[0])
qc.x(q[1])
qc.cx(q[0],q[1],q[3])
qc.x(q[0])
qc.x(q[1])
qc.x(q[0])
qc.cx(q[0],q[4])
qc.x(q[0])
qc.x(q[2])
qc.x(q[3])
qc.x(q[4])
qc.x(q[5])
qc.cx(q[2],q[3],q[4],q[5])
qc.x(q[2])
qc.x(q[3])
qc.x(q[4])
qc.x(q[5])
qc.z(q[5])
qc.x(q[2])
qc.x(q[3])
qc.x(q[4])
qc.x(q[5])
qc.cx(q[2],q[3],q[4],q[5])
qc.x(q[2])
qc.x(q[3])
qc.x(q[4])
qc.x(q[5])
qc.x(q[0])
qc.cx(q[0],q[4])
qc.x(q[0])
qc.x(q[0])
qc.x(q[1])
qc.cx(q[0],q[1],q[3])
qc.x(q[0])
qc.x(q[1])
qc.cx(q[0],q[1],q[2])
# Apply the grover-algorithm 11
# Measure qubit to bit. .
qc.measure(q, c)
# Get Aer backend.
backend_sim = Aer.get_backend('qasm_simulator')
# Compile and run the Quantum circuit on a simulator backend.
sim_result1 = execute(qc, backend_sim, shots=1000).result()
counts1 = sim_result1.get_counts(qc)
# Show the results as text and plot.
print("Simulation: ", sim_result1)
print("Output: ", counts1)
plot_histogram(counts1)
circuit_drawer(qc)
|
https://github.com/soultanis/Quantum-SAT-Solver
|
soultanis
|
import pylab
import numpy as np
from qiskit.providers.ibmq import least_busy
from qiskit import LegacySimulators, execute, IBMQ, Aer
from qiskit.tools.visualization import plot_histogram
from qiskit_aqua import QuantumInstance
from qiskit_aqua import run_algorithm
from qiskit_aqua.algorithms import Grover
from qiskit_aqua.components.oracles import SAT
m = 4
n = 5
satProblem = 'examples\\3sat' + str(m) + '-' + str(n) + '.cnf'
with open(satProblem, 'r') as f:
sat_cnf = f.read()
print(sat_cnf)
sat_oracle = SAT(sat_cnf)
algorithm = Grover(sat_oracle)
sim_backend = Aer.get_backend('qasm_simulator')
result = algorithm.run(sim_backend)
print(result['result'])
plot_histogram(result['measurements'])
# figsize = (15,12),
# bar_labels = False)
# Authenticate for access to remote backends
try:
import Qconfig
IBMQ.load_accounts()
except:
print("""WARNING: There's no connection with the API for remote backends.
Have you initialized a file with your personal token?
For now, there's only access to local simulator backends...""")
ibmq_backend = least_busy(IBMQ.backends(simulator=False))
result = algorithm.run(ibmq_backend)
print(result['result'])
plot_histogram(result['measurements'])
params = {
'problem': {'name': 'search'},
'algorithm': {
'name': 'Grover'
},
'oracle': {
'name': 'SAT',
'cnf': sat_cnf
},
'backend': {
'shots': 100
}
}
result_dict = run_algorithm(params, backend=backend)
plot_histogram(result_dict['measurements'])
from __future__ import print_function
def even_ones(s):
# Two states:
# - 0 (even number of ones seen so far)
# - 1 (odd number of ones seen so far)
rules = {(0, '0'): 0,
(0, '1'): 1,
(1, '0'): 1,
(1, '1'): 0}
# There are 0 (which is an even number) ones in the empty
# string so we start with state = 0.
state = 0
for c in s:
state = rules[state, c]
return state == 0
# Example usage:
s = "100110"
print('Output for {} = {}'.format(s, even_ones(s)))
|
https://github.com/soultanis/Quantum-SAT-Solver
|
soultanis
|
#setup.py
import numpy as np
from scipy.linalg import expm
from qiskit.extensions import UnitaryGate
from qiskit.circuit.add_control import add_control
from qiskit import Aer
import circuit
import hhl
import tools
#참고 논문 :Low Complexity Quantum Matrix Inversion A기gorithm for non-Hermitian Matrices
def main(A,b,backend,shots,t,n_l,delta):
#Check if Hermitian
if np.allclose(A,A.T) == False:
print("Given A matrice is not Hermitian.")
print("Given Matrices will be transformed into Hermitian formation.")
A = np.vstack((np.hstack((np.zeros_like(A),A)),np.hstack((A.T, np.zeros_like(A))))) # Hermitian의 꼴로 바꿈
b = np.hstack((b,np.zeros_like((np.shape(A)[0]-np.shape(b)[0],1))))
#A의 shape와 동일한 zero array를 생성하고, A의 왼쪽에 배치, horizontal 방향도 마찬가지.
i = complex(0,1) #complex(real part, imaginary part)
U = expm(i*A*t) #여기서 A가 행렬로 주어졌기 때문에, 행렬을 exp에 올리기 위해서는 expm이라는 scipy 패키지가 필요함.
U_gate = UnitaryGate(U) #위에서 구성한 U라는 행렬로써 Unitary gate를 구성할 수 있음. (4*4) 행렬
CU = add_control(U_gate,1,ctrl_state=None, label="CU")
#CU라는 게이트 이름을 label에 저장
#control 되는 경우의 state를 지정 -> 해당사항 없음
#두번째 인자는 컨트롤 큐빗의 개수를 지정함.
n_b = int(np.log2(U.shape[0]))
#Ax =b의 꼴이고, b는 4*1의 shape이므로, A의 행의 개수와 동일함. 따라서, U의 행렬의 행의 개수와 동일함.
#행의 개수에 log2를 취하면 필요한 n_b의 값을 구할 수 있음.
My_HHL_result = hhl.My_HHL(CU,b,n_l,n_b,backend,delta,shots,A,details = True,chevyshev = False)
print("\n")
qiskit_result = hhl.qiskit_HHL(A,b,backend)
print("\n")
classical_result = hhl.classical_HHL(A,b)
print("\n")
#For normalized answer
print("<Un - normalized Case Comparision>")
print('Qiskit Error : {0}'.format(np.linalg.norm(qiskit_result[1]-classical_result[1])))
print('My HHL Error : {0}'.format(np.linalg.norm(My_HHL_result[1]-classical_result[1])))
print("\n")
print("<Normalized Case Comparision>")
print('Qiskit Error : {0}'.format(np.linalg.norm(qiskit_result[0]-classical_result[0])))
print('My HHL Error : {0}'.format(np.linalg.norm(My_HHL_result[0]-classical_result[0])))
if __name__ == "__main__":
#setups
A = np.array([[2,-1],[1,4]]) #non-Hermitian인 경우의 행렬에 대한 저장
b = np.array([1,1])
backend = Aer.get_backend('aer_simulator')
shots = 8192
t = np.pi*2/16
n_l = 3 #QPE 상에서 n_ㅣ는 하다마드로 초기화 되는 부분
delta = 1/16*(2**(n_l-1))
main(A,b,backend,shots,t,n_l,delta)
|
https://github.com/soultanis/Quantum-SAT-Solver
|
soultanis
|
"""
Solves SAT instance by reading from stdin using Qiskit framework from IBM.
For text recognition as input you have to set the path to your lib.
"""
import pylab
import numpy as np
from sys import stdin
import argparse
from argparse import ArgumentParser
from argparse import FileType
from PIL import Image
import pytesseract
from qiskit.providers.ibmq import least_busy
from qiskit import LegacySimulators, execute, IBMQ, Aer
from qiskit.tools.visualization import plot_histogram
from qiskit_aqua import QuantumInstance
from qiskit_aqua import run_algorithm
from qiskit_aqua.algorithms import Grover
from qiskit_aqua.components.oracles import SAT
# from qiskit_aqua.components.oracles import LogicalExpressionOracle
def grover_solution(m, n, hr, i):
# normal parser
if m and n is not None:
satProblem = 'examples\\3sat' + m + '-' + n + '.cnf'
with open(satProblem, 'r') as f:
sat_cnf = f.read()
print(sat_cnf)
# hand recognition parser: still needs to be implemented
elif hr:
# tesseract parser
pass
else:
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
i_read = pytesseract.image_to_string(Image.open(i.name), lang='eng')
print(i_read)
sat_oracle = SAT(sat_cnf)
algorithm = Grover(sat_oracle)
backend = Aer.get_backend('qasm_simulator')
algorithm = Grover(sat_oracle)
result = algorithm.run(backend)
print(result['result'])
plot_histogram(result['measurements'])
def main():
args = parse_args()
grover_solution(args.variable, args.equation,
args.hand_recognition, args.file_input)
def parse_args():
parser = ArgumentParser(
description='Quantum SAT solver with Grovers algorithm')
parser.add_argument('-m',
'--variable',
help='the number of variable for the SAT-Problem from examples')
parser.add_argument('-n',
'--equation',
help='the number of equation for the SAT-Problem from examples')
parser.add_argument('-hr',
'--hand_recognition',
action='store_true',
help='set to true, if your file is handwritten (still needs to be implemented)')
parser.add_argument('-i',
'--file_input',
type=FileType('r'),
help='read from given file instead of stdin',)
return parser.parse_args()
if __name__ == "__main__":
main()
'''
print('Type the number of m variables and on the next line the number of n equations for the SAT-Problem:')
m = input()
n = input()
print('You set the SAT-Problem with ' + m +
' variables and ' + n + ' equations.')
(m, n)
parser.add_argument('-i',
'--input',
help='read from given file instead of stdin',
type=FileType('r'),
default=stdin)
parser.add_argument('-o',
'--output',
help='write to given file instead of default stdout',
type=FileType('w'),
default=stdout)
'''
|
https://github.com/ranaarp/Qiskit-Meetup-content
|
ranaarp
|
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
# IBMQ.save_account('your account id')
provider = IBMQ.load_account()
q = QuantumRegister(7)
c = ClassicalRegister(4)
qc = QuantumCircuit(q, c)
# initialize in a superposition of all possible states
qc.x(q[4])
qc.h(q[0:5])
qc.barrier(q)
qc.barrier(q)
# build oracle. ex: to find 1010 state
qc.x(q[1])
qc.x(q[3])
qc.barrier(q)
qc.mct([q[0], q[1], q[2], q[3]], q[4], q[5:7]) # control qubits, target qubit, ancilla qubits = number of control qubits - 2
qc.barrier(q)
qc.x(q[1])
qc.x(q[3])
qc.barrier(q)
qc.barrier(q)
qc.h(q[0:4])
qc.barrier(q)
qc.x(q[0:4])
qc.barrier(q)
qc.h(q[3])
qc.barrier(q)
qc.mct([q[0], q[1], q[2]], q[3], q[5:6])
qc.barrier(q)
qc.h(q[3])
qc.barrier(q)
qc.x(q[0:4])
qc.barrier(q)
qc.h(q[0:4])
qc.barrier(q)
qc.measure(q[0:4], c[0:4])
qc.draw(output='mpl')
# in the output drawing
# running and getting results
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
# backend = provider.get_backend('ibmq_qasm_simulator')
# job = execute(qc, backend=backend, shots=8000, seed_simulator=12345, backend_options={"fusion_enable":True})
result = job.result()
count = result.get_counts()
print(count)
# the code snippet below can be used to retreive your job in case your jupyter notebook loses connection with IBMQ servers before completion of the job
# backend = provider.get_backend('ibmq_qasm_simulator')
# job = backend.retrieve_job('enter your job id here. it can be found in your IBM Q Experience dashboard')
# counts = job.result().get_counts()
# print(counts)
plot_histogram(count)
# the answer may seem inverted, i.e, 0101 is actually state 1010. that's just the notation used by qiskit.
|
https://github.com/ranaarp/Qiskit-Meetup-content
|
ranaarp
|
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
def phase_oracle(circuit, register):
circuit.cz(register[0], register[1])
qr = QuantumRegister(2)
oracleCircuit = QuantumCircuit(qr)
phase_oracle(oracleCircuit, qr)
oracleCircuit.draw(output="mpl")
def inversion_about_average(circuit, register):
"""Apply inversion about the average step of Grover's algorithm."""
circuit.h(register)
circuit.x(register)
circuit.h(register[1])
circuit.cx(register[0], register[1])
circuit.h(register[1])
circuit.x(register)
circuit.h(register)
qAverage = QuantumCircuit(qr)
inversion_about_average(qAverage, qr)
qAverage.draw(output='mpl')
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
groverCircuit = QuantumCircuit(qr,cr)
groverCircuit.h(qr)
phase_oracle(groverCircuit, qr)
inversion_about_average(groverCircuit, qr)
groverCircuit.measure(qr,cr)
groverCircuit.draw(output="mpl")
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(groverCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device
# These are compatible with QisKit v0.11.x
# IBMQ.load_accounts()
# IBMQ.backends()
# backend_lb = least_busy(IBMQ.backends(simulator=False))
# print("Least busy backend: ", backend_lb)
# Updated to run on QisKit v0.12.0
IBMQ.load_account()
provider = IBMQ.get_provider(group='open')
backend_lb = least_busy(provider.backends(simulator=False, operational=True))
print("Least busy backend: ", backend_lb)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
backend = backend_lb
shots = 1024
job_exp = execute(groverCircuit, backend=backend, shots=shots)
job_monitor(job_exp, interval = 2)
# get the results from the computation
results = job_exp.result()
answer = results.get_counts(groverCircuit)
plot_histogram(answer)
# Initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# Importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# Import basic plot tools
from qiskit.tools.visualization import plot_histogram
def phase_oracle(circuit, register,oracle_register):
circuit.h(oracle_register)
circuit.ccx(register[0], register[1],oracle_register)
circuit.h(oracle_register)
qr = QuantumRegister(3)
oracleCircuit = QuantumCircuit(qr)
oracleCircuit.x(qr[2])
phase_oracle(oracleCircuit, qr,qr[2])
oracleCircuit.draw(output="mpl")
def inversion_about_average(circuit, register):
"""Apply inversion about the average step of Grover's algorithm."""
circuit.h(register)
circuit.x(register)
circuit.h(register[1])
circuit.cx(register[0], register[1])
circuit.h(register[1])
circuit.x(register)
circuit.h(register)
qAverage = QuantumCircuit(qr)
inversion_about_average(qAverage, qr[0:2])
qAverage.draw(output='mpl')
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
groverCircuit = QuantumCircuit(qr,cr)
groverCircuit.h(qr[0:2])
groverCircuit.x(qr[2])
phase_oracle(groverCircuit, qr,qr[2])
inversion_about_average(groverCircuit, qr[0:2])
groverCircuit.measure(qr,cr)
groverCircuit.draw(output="mpl")
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(groverCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
def phase_oracle(circuit, register):
circuit.x(register[0])
circuit.cz(register[0], register[1])
circuit.x(register[0])
qr = QuantumRegister(2)
oracleCircuit = QuantumCircuit(qr)
phase_oracle(oracleCircuit, qr)
oracleCircuit.draw(output="mpl")
def inversion_about_average(circuit, register):
"""Apply inversion about the average step of Grover's algorithm."""
circuit.h(register)
circuit.x(register)
circuit.h(register[1])
circuit.cx(register[0], register[1])
circuit.h(register[1])
circuit.x(register)
circuit.h(register)
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
groverCircuit = QuantumCircuit(qr,cr)
groverCircuit.h(qr)
phase_oracle(groverCircuit, qr)
inversion_about_average(groverCircuit, qr)
groverCircuit.measure(qr,cr)
groverCircuit.draw(output="mpl")
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(groverCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
def phase_oracle(circuit, register,oracle_register):
circuit.h(oracle_register)
circuit.x(register[0])
circuit.ccx(register[0], register[1],oracle_register)
circuit.x(register[0])
circuit.h(oracle_register)
qr = QuantumRegister(3)
oracleCircuit = QuantumCircuit(qr)
oracleCircuit.x(qr[2])
phase_oracle(oracleCircuit, qr,qr[2])
oracleCircuit.draw(output="mpl")
def inversion_about_average(circuit, register):
"""Apply inversion about the average step of Grover's algorithm."""
circuit.h(register)
circuit.x(register)
circuit.h(register[1])
circuit.cx(register[0], register[1])
circuit.h(register[1])
circuit.x(register)
circuit.h(register)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
groverCircuit = QuantumCircuit(qr,cr)
groverCircuit.h(qr[0:2])
groverCircuit.x(qr[2])
phase_oracle(groverCircuit, qr,qr[2])
inversion_about_average(groverCircuit, qr[0:2])
groverCircuit.measure(qr,cr)
groverCircuit.draw(output="mpl")
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(groverCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/ranaarp/Qiskit-Meetup-content
|
ranaarp
|
import numpy as np
from qiskit import BasicAer
from qiskit.visualization import plot_histogram
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import Grover
from qiskit.aqua.components.oracles import LogicalExpressionOracle, TruthTableOracle
input_3sat = '''
c example DIMACS-CNF 3-SAT
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
'''
oracle = LogicalExpressionOracle(input_3sat)
grover = Grover(oracle)
backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
result = grover.run(quantum_instance)
print(result['result'])
plot_histogram(result['measurement'])
# Load our saved IBMQ accounts and get the ibmq_16_melbourne backend
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_16_melbourne')
from qiskit.compiler import transpile
# transpile the circuit for ibmq_16_melbourne
grover_compiled = transpile(result['circuit'], backend=backend, optimization_level=3)
print('gates = ', grover_compiled.count_ops())
print('depth = ', grover_compiled.depth())
import qiskit
qiskit.__qiskit_version__
|
https://github.com/ranaarp/Qiskit-Meetup-content
|
ranaarp
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute
IBMQ.load_account()
q = QuantumRegister(3)
qc = QuantumCircuit(q)
#cutedge checker
def ccheck(a, b, c):
qc.cx(q[a], q[c])
qc.cx(q[b], q[c])
qc.h(q[0])
qc.h(q[1])
ccheck(0,1,2)
qc.draw(output='mpl')
q = QuantumRegister(8)
qc = QuantumCircuit(q)
#half adder
#inputs: a,b
#outputs: the sum output s and carry output c
def hadder(a,b,s,c):
#XOR
qc.cx(q[b], q[s])
qc.cx(q[a], q[s])
#AND
qc.ccx(q[a], q[b], q[c])
qc.h(q[0:3])
ccheck(0,1,3)
ccheck(1,2,4)
hadder(3,4,6,5)
qc.draw(output='mpl')
#create an oracle
q = QuantumRegister(8)
c = ClassicalRegister(1)
qc = QuantumCircuit(q,c)
qc.h(q[0:3])
ccheck(0,1,3)
ccheck(1,2,4)
hadder(3,4,6,5)
qc.cx(q[5],q[7])
qc.measure(q[7], c[0])
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=100000)
result = job.result()
count =result.get_counts()
print(count)
qc.draw(output='mpl')
q = QuantumRegister(8)
c = ClassicalRegister(7)
qc = QuantumCircuit(q,c)
#inverse operations
def iccheck(a, b, c):
qc.cx(q[b], q[c])
qc.cx(q[a], q[c])
def ihadder(a,b,s,c):
qc.ccx(q[a], q[b], q[c])
qc.cx(q[a], q[s])
qc.cx(q[b], q[s])
qc.h(q[0:3])
qc.x(q[7])
qc.h(q[7])
ccheck(0,1,3)
ccheck(1,2,4)
hadder(3,4,6,5)
qc.cx(q[5],q[7])
ihadder(3,4,6,5)
iccheck(1,2,4)
iccheck(0,1,3)
qc.barrier()
qc.measure(q[0:7], c[0:7])
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
result = job.result()
count =result.get_counts()
print(count)
qc.draw(output='mpl')
q = QuantumRegister(8)
c = ClassicalRegister(3)
qc = QuantumCircuit(q,c)
#diffusion operations
def diffusion(a,b,c):
qc.h(q[a])
qc.h(q[b])
qc.h(q[c])
qc.x(q[a])
qc.x(q[b])
qc.x(q[c])
qc.h(q[c])
qc.ccx(q[a],q[b], q[c])
qc.h(q[c])
qc.x(q[a])
qc.x(q[b])
qc.x(q[c])
qc.h(q[a])
qc.h(q[b])
qc.h(q[c])
#initialization
qc.h(q[0:3])
qc.x(q[7])
qc.h(q[7])
qc.barrier()
#oracle part
ccheck(0,1,3)
ccheck(1,2,4)
hadder(3,4,6,5)
qc.cx(q[5],q[7])
ihadder(3,4,6,5)
iccheck(1,2,4)
iccheck(0,1,3)
qc.barrier()
#diffusion part
diffusion(0,1,2)
qc.barrier()
qc.measure(q[0:3], c[0:3])
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=10000)
result = job.result()
count =result.get_counts()
print(count)
qc.draw(output='mpl')
#from qiskit.aqua.circuits.gates import mct
q = QuantumRegister(11)
c = ClassicalRegister(4)
qc = QuantumCircuit(q,c)
ite = 2 #number of iteration
#initialization
qc.h(q[0:4])
qc.x(q[8])
qc.h(q[8])
qc.barrier()
for i in range(ite):
#oracle part
ccheck(0,1,4)
ccheck(0,2,5)
ccheck(0,3,6)
qc.mct([q[4],q[5],q[6]], q[8] , [q[7]], mode='basic')
iccheck(0,3,6)
iccheck(0,2,5)
iccheck(0,1,4)
qc.barrier()
#diffusion part
qc.h(q[0:4])
qc.barrier()
qc.x(q[0:4])
qc.barrier()
qc.h(q[3])
qc.mct([q[0],q[1],q[2]], q[3] , [q[7]], mode='basic')
qc.h(q[3])
qc.barrier()
qc.x(q[0:4])
qc.barrier()
qc.h(q[0:4])
qc.barrier()
qc.measure(q[0:4], c[0:4])
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=10000)
result = job.result()
count =result.get_counts()
print(count)
qc.draw(output='mpl')
# the measurement results for each quantum state will be shown in reverse order. (i.e. 1000 -> 0001, 0111-> 1110)
#Decompose the circuit by using the Unroller
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Unroller
pass_ = Unroller(['u3', 'cx'])
pm = PassManager(pass_)
new_circuit = pm.run(qc)
new_circuit.draw(output='mpl')
#show elementary gate counts
new_circuit.count_ops()
#create output text file with the gate counts
import json
dct = new_circuit.count_ops()
with open('wk3_output.txt', 'w') as f:
f.write(json.dumps(dct))
|
https://github.com/tula3and/random-question-generator
|
tula3and
|
from qiskit import *
# from qiskit import IBMQ
# IBMQ.save_account('<API Token>')
# provider = IBMQ.load_account()
# backend = IBMQ.get_provider(hub='ibm-q-kaist', group='internal', project='default').backends.ibmq_manhattan
backend = Aer.get_backend('qasm_simulator')
q = QuantumRegister(48)
c = ClassicalRegister(48)
circuit = QuantumCircuit(q,c)
circuit.h(q)
for i in range(47):
circuit.cx(q[i], q[47])
circuit.measure(q,c)
import string
table = string.ascii_uppercase + string.ascii_lowercase + string.digits
def hash8():
hash_result = ''
result = execute(circuit, backend, shots=1).result()
count = result.get_counts(circuit)
bits = max(count, key=lambda i: count[i])
start = 0
end = 6
while (end <= 48):
rand = int(bits[start:end], 2) % len(table)
start += 6
end += 6
hash_result += table[rand]
return hash_result
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
p = 0.2
import numpy as np
from qiskit.circuit import QuantumCircuit
class BernoulliA(QuantumCircuit):
"""A circuit representing the Bernoulli A operator."""
def __init__(self, probability):
super().__init__(1) # circuit on 1 qubit
theta_p = 2 * np.arcsin(np.sqrt(probability))
self.ry(theta_p, 0)
class BernoulliQ(QuantumCircuit):
"""A circuit representing the Bernoulli Q operator."""
def __init__(self, probability):
super().__init__(1) # circuit on 1 qubit
self._theta_p = 2 * np.arcsin(np.sqrt(probability))
self.ry(2 * self._theta_p, 0)
def power(self, k):
# implement the efficient power of Q
q_k = QuantumCircuit(1)
q_k.ry(2 * k * self._theta_p, 0)
return q_k
A = BernoulliA(p)
Q = BernoulliQ(p)
from qiskit.algorithms import EstimationProblem
problem = EstimationProblem(
state_preparation=A, # A operator
grover_operator=Q, # Q operator
objective_qubits=[0], # the "good" state Psi1 is identified as measuring |1> in qubit 0
)
from qiskit.primitives import Sampler
sampler = Sampler()
from qiskit.algorithms import AmplitudeEstimation
ae = AmplitudeEstimation(
num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy
sampler=sampler,
)
ae_result = ae.estimate(problem)
print(ae_result.estimation)
import matplotlib.pyplot as plt
# plot estimated values
gridpoints = list(ae_result.samples.keys())
probabilities = list(ae_result.samples.values())
plt.bar(gridpoints, probabilities, width=0.5 / len(probabilities))
plt.axvline(p, color="r", ls="--")
plt.xticks(size=15)
plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15)
plt.title("Estimated Values", size=15)
plt.ylabel("Probability", size=15)
plt.xlabel(r"Amplitude $a$", size=15)
plt.ylim((0, 1))
plt.grid()
plt.show()
print("Interpolated MLE estimator:", ae_result.mle)
ae_circuit = ae.construct_circuit(problem)
ae_circuit.decompose().draw(
"mpl", style="iqx"
) # decompose 1 level: exposes the Phase estimation circuit!
from qiskit import transpile
basis_gates = ["h", "ry", "cry", "cx", "ccx", "p", "cp", "x", "s", "sdg", "y", "t", "cz"]
transpile(ae_circuit, basis_gates=basis_gates, optimization_level=2).draw("mpl", style="iqx")
from qiskit.algorithms import IterativeAmplitudeEstimation
iae = IterativeAmplitudeEstimation(
epsilon_target=0.01, # target accuracy
alpha=0.05, # width of the confidence interval
sampler=sampler,
)
iae_result = iae.estimate(problem)
print("Estimate:", iae_result.estimation)
iae_circuit = iae.construct_circuit(problem, k=3)
iae_circuit.draw("mpl", style="iqx")
from qiskit.algorithms import MaximumLikelihoodAmplitudeEstimation
mlae = MaximumLikelihoodAmplitudeEstimation(
evaluation_schedule=3, # log2 of the maximal Grover power
sampler=sampler,
)
mlae_result = mlae.estimate(problem)
print("Estimate:", mlae_result.estimation)
from qiskit.algorithms import FasterAmplitudeEstimation
fae = FasterAmplitudeEstimation(
delta=0.01, # target accuracy
maxiter=3, # determines the maximal power of the Grover operator
sampler=sampler,
)
fae_result = fae.estimate(problem)
print("Estimate:", fae_result.estimation)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.result import QuasiDistribution
from qiskit_aer.primitives import Sampler
from qiskit_finance.applications.optimization import PortfolioOptimization
from qiskit_finance.data_providers import RandomDataProvider
from qiskit_optimization.algorithms import MinimumEigenOptimizer
import numpy as np
import matplotlib.pyplot as plt
import datetime
# set number of assets (= number of qubits)
num_assets = 4
seed = 123
# Generate expected return and covariance matrix from (random) time-series
stocks = [("TICKER%s" % i) for i in range(num_assets)]
data = RandomDataProvider(
tickers=stocks,
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=seed,
)
data.run()
mu = data.get_period_return_mean_vector()
sigma = data.get_period_return_covariance_matrix()
# plot sigma
plt.imshow(sigma, interpolation="nearest")
plt.show()
q = 0.5 # set risk factor
budget = num_assets // 2 # set budget
penalty = num_assets # set parameter to scale the budget penalty term
portfolio = PortfolioOptimization(
expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget
)
qp = portfolio.to_quadratic_program()
qp
def print_result(result):
selection = result.x
value = result.fval
print("Optimal: selection {}, value {:.4f}".format(selection, value))
eigenstate = result.min_eigen_solver_result.eigenstate
probabilities = (
eigenstate.binary_probabilities()
if isinstance(eigenstate, QuasiDistribution)
else {k: np.abs(v) ** 2 for k, v in eigenstate.to_dict().items()}
)
print("\n----------------- Full result ---------------------")
print("selection\tvalue\t\tprobability")
print("---------------------------------------------------")
probabilities = sorted(probabilities.items(), key=lambda x: x[1], reverse=True)
for k, v in probabilities:
x = np.array([int(i) for i in list(reversed(k))])
value = portfolio.to_quadratic_program().objective.evaluate(x)
print("%10s\t%.4f\t\t%.4f" % (x, value, v))
exact_mes = NumPyMinimumEigensolver()
exact_eigensolver = MinimumEigenOptimizer(exact_mes)
result = exact_eigensolver.solve(qp)
print_result(result)
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 1234
cobyla = COBYLA()
cobyla.set_options(maxiter=500)
ry = TwoLocal(num_assets, "ry", "cz", reps=3, entanglement="full")
vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla)
vqe = MinimumEigenOptimizer(vqe_mes)
result = vqe.solve(qp)
print_result(result)
algorithm_globals.random_seed = 1234
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(qp)
print_result(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Import requisite modules
import math
import datetime
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Import Qiskit packages
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit_aer.primitives import Sampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
# The data providers of stock-market data
from qiskit_finance.data_providers import RandomDataProvider
from qiskit_finance.applications.optimization import PortfolioDiversification
# Generate a pairwise time-series similarity matrix
seed = 123
stocks = ["TICKER1", "TICKER2"]
n = len(stocks)
data = RandomDataProvider(
tickers=stocks,
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=seed,
)
data.run()
rho = data.get_similarity_matrix()
q = 1 # q less or equal than n
class ClassicalOptimizer:
def __init__(self, rho, n, q):
self.rho = rho
self.n = n # number of inner variables
self.q = q # number of required selection
def compute_allowed_combinations(self):
f = math.factorial
return int(f(self.n) / f(self.q) / f(self.n - self.q))
def cplex_solution(self):
# refactoring
rho = self.rho
n = self.n
q = self.q
my_obj = list(rho.reshape(1, n**2)[0]) + [0.0 for x in range(0, n)]
my_ub = [1 for x in range(0, n**2 + n)]
my_lb = [0 for x in range(0, n**2 + n)]
my_ctype = "".join(["I" for x in range(0, n**2 + n)])
my_rhs = (
[q]
+ [1 for x in range(0, n)]
+ [0 for x in range(0, n)]
+ [0.1 for x in range(0, n**2)]
)
my_sense = (
"".join(["E" for x in range(0, 1 + n)])
+ "".join(["E" for x in range(0, n)])
+ "".join(["L" for x in range(0, n**2)])
)
try:
my_prob = cplex.Cplex()
self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs)
my_prob.solve()
except CplexError as exc:
print(exc)
return
x = my_prob.solution.get_values()
x = np.array(x)
cost = my_prob.solution.get_objective_value()
return x, cost
def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs):
n = self.n
prob.objective.set_sense(prob.objective.sense.minimize)
prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype)
prob.set_log_stream(None)
prob.set_error_stream(None)
prob.set_warning_stream(None)
prob.set_results_stream(None)
rows = []
col = [x for x in range(n**2, n**2 + n)]
coef = [1 for x in range(0, n)]
rows.append([col, coef])
for ii in range(0, n):
col = [x for x in range(0 + n * ii, n + n * ii)]
coef = [1 for x in range(0, n)]
rows.append([col, coef])
for ii in range(0, n):
col = [ii * n + ii, n**2 + ii]
coef = [1, -1]
rows.append([col, coef])
for ii in range(0, n):
for jj in range(0, n):
col = [ii * n + jj, n**2 + jj]
coef = [1, -1]
rows.append([col, coef])
prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs)
# Instantiate the classical optimizer class
classical_optimizer = ClassicalOptimizer(rho, n, q)
# Compute the number of feasible solutions:
print("Number of feasible combinations= " + str(classical_optimizer.compute_allowed_combinations()))
# Compute the total number of possible combinations (feasible + unfeasible)
print("Total number of combinations= " + str(2 ** (n * (n + 1))))
# Visualize the solution
def visualize_solution(xc, yc, x, C, n, K, title_str):
plt.figure()
plt.scatter(xc, yc, s=200)
for i in range(len(xc)):
plt.annotate(i, (xc[i] + 0.015, yc[i]), size=16, color="r")
plt.grid()
for ii in range(n**2, n**2 + n):
if x[ii] > 0:
plt.plot(xc[ii - n**2], yc[ii - n**2], "r*", ms=20)
for ii in range(0, n**2):
if x[ii] > 0:
iy = ii // n
ix = ii % n
plt.plot([xc[ix], xc[iy]], [yc[ix], yc[iy]], "C2")
plt.title(title_str + " cost = " + str(int(C * 100) / 100.0))
plt.show()
from qiskit.utils import algorithm_globals
class QuantumOptimizer:
def __init__(self, rho, n, q):
self.rho = rho
self.n = n
self.q = q
self.pdf = PortfolioDiversification(similarity_matrix=rho, num_assets=n, num_clusters=q)
self.qp = self.pdf.to_quadratic_program()
# Obtains the least eigenvalue of the Hamiltonian classically
def exact_solution(self):
exact_mes = NumPyMinimumEigensolver()
exact_eigensolver = MinimumEigenOptimizer(exact_mes)
result = exact_eigensolver.solve(self.qp)
return self.decode_result(result)
def vqe_solution(self):
algorithm_globals.random_seed = 100
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
ry = TwoLocal(n, "ry", "cz", reps=5, entanglement="full")
vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla)
vqe = MinimumEigenOptimizer(vqe_mes)
result = vqe.solve(self.qp)
return self.decode_result(result)
def qaoa_solution(self):
algorithm_globals.random_seed = 1234
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(self.qp)
return self.decode_result(result)
def decode_result(self, result, offset=0):
quantum_solution = 1 - (result.x)
ground_level = self.qp.objective.evaluate(result.x)
return quantum_solution, ground_level
# Instantiate the quantum optimizer class with parameters:
quantum_optimizer = QuantumOptimizer(rho, n, q)
# Check if the binary representation is correct. This requires CPLEX
try:
import cplex
# warnings.filterwarnings('ignore')
quantum_solution, quantum_cost = quantum_optimizer.exact_solution()
print(quantum_solution, quantum_cost)
classical_solution, classical_cost = classical_optimizer.cplex_solution()
print(classical_solution, classical_cost)
if np.abs(quantum_cost - classical_cost) < 0.01:
print("Binary formulation is correct")
else:
print("Error in the formulation of the Hamiltonian")
except Exception as ex:
print(ex)
ground_state, ground_level = quantum_optimizer.exact_solution()
print(ground_state)
classical_cost = 1.000779571614484 # obtained from the CPLEX solution
try:
if np.abs(ground_level - classical_cost) < 0.01:
print("Ising Hamiltonian in Z basis is correct")
else:
print("Error in the Ising Hamiltonian formulation")
except Exception as ex:
print(ex)
vqe_state, vqe_level = quantum_optimizer.vqe_solution()
print(vqe_state, vqe_level)
try:
if np.linalg.norm(ground_state - vqe_state) < 0.01:
print("SamplingVQE produces the same solution as the exact eigensolver.")
else:
print(
"SamplingVQE does not produce the same solution as the exact eigensolver, but that is to be expected."
)
except Exception as ex:
print(ex)
xc, yc = data.get_coordinates()
visualize_solution(xc, yc, ground_state, ground_level, n, q, "Classical")
visualize_solution(xc, yc, vqe_state, vqe_level, n, q, "VQE")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import QuantumCircuit
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit.circuit.library import LinearAmplitudeFunction
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import LogNormalDistribution
# number of qubits to represent the uncertainty
num_uncertainty_qubits = 3
# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity
# resulting parameters for log-normal distribution
mu = (r - 0.5 * vol**2) * T + np.log(S)
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2 / 2)
variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3 * stddev)
high = mean + 3 * stddev
# construct A operator for QAE for the payoff function by
# composing the uncertainty model and the objective
uncertainty_model = LogNormalDistribution(
num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high)
)
# plot probability distribution
x = uncertainty_model.values
y = uncertainty_model.probabilities
plt.bar(x, y, width=0.2)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.grid()
plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15)
plt.ylabel("Probability ($\%$)", size=15)
plt.show()
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price = 1.896
# set the approximation scaling for the payoff function
c_approx = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [low, strike_price]
slopes = [0, 1]
offsets = [0, 0]
f_min = 0
f_max = high - strike_price
european_call_objective = LinearAmplitudeFunction(
num_uncertainty_qubits,
slopes,
offsets,
domain=(low, high),
image=(f_min, f_max),
breakpoints=breakpoints,
rescaling_factor=c_approx,
)
# construct A operator for QAE for the payoff function by
# composing the uncertainty model and the objective
num_qubits = european_call_objective.num_qubits
european_call = QuantumCircuit(num_qubits)
european_call.append(uncertainty_model, range(num_uncertainty_qubits))
european_call.append(european_call_objective, range(num_qubits))
# draw the circuit
european_call.draw()
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = uncertainty_model.values
y = np.maximum(0, x - strike_price)
plt.plot(x, y, "ro-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value (normalized to the [0, 1] interval)
exact_value = np.dot(uncertainty_model.probabilities, y)
exact_delta = sum(uncertainty_model.probabilities[x >= strike_price])
print("exact expected value:\t%.4f" % exact_value)
print("exact delta value: \t%.4f" % exact_delta)
european_call.draw()
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=european_call,
objective_qubits=[3],
post_processing=european_call_objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % exact_value)
print("Estimated value: \t%.4f" % (result.estimation_processed))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
from qiskit_finance.applications.estimation import EuropeanCallPricing
european_call_pricing = EuropeanCallPricing(
num_state_qubits=num_uncertainty_qubits,
strike_price=strike_price,
rescaling_factor=c_approx,
bounds=(low, high),
uncertainty_model=uncertainty_model,
)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = european_call_pricing.to_estimation_problem()
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % exact_value)
print("Estimated value: \t%.4f" % (european_call_pricing.interpret(result)))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
from qiskit_finance.applications.estimation import EuropeanCallDelta
european_call_delta = EuropeanCallDelta(
num_state_qubits=num_uncertainty_qubits,
strike_price=strike_price,
bounds=(low, high),
uncertainty_model=uncertainty_model,
)
european_call_delta._objective.decompose().draw()
european_call_delta_circ = QuantumCircuit(european_call_delta._objective.num_qubits)
european_call_delta_circ.append(uncertainty_model, range(num_uncertainty_qubits))
european_call_delta_circ.append(
european_call_delta._objective, range(european_call_delta._objective.num_qubits)
)
european_call_delta_circ.draw()
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = european_call_delta.to_estimation_problem()
# construct amplitude estimation
ae_delta = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_delta = ae_delta.estimate(problem)
conf_int = np.array(result_delta.confidence_interval_processed)
print("Exact delta: \t%.4f" % exact_delta)
print("Esimated value: \t%.4f" % european_call_delta.interpret(result_delta))
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit.circuit.library import LinearAmplitudeFunction
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import LogNormalDistribution
# number of qubits to represent the uncertainty
num_uncertainty_qubits = 3
# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity
# resulting parameters for log-normal distribution
mu = (r - 0.5 * vol**2) * T + np.log(S)
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2 / 2)
variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3 * stddev)
high = mean + 3 * stddev
# construct A operator for QAE for the payoff function by
# composing the uncertainty model and the objective
uncertainty_model = LogNormalDistribution(
num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high)
)
# plot probability distribution
x = uncertainty_model.values
y = uncertainty_model.probabilities
plt.bar(x, y, width=0.2)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.grid()
plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15)
plt.ylabel("Probability ($\%$)", size=15)
plt.show()
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price = 2.126
# set the approximation scaling for the payoff function
rescaling_factor = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [low, strike_price]
slopes = [-1, 0]
offsets = [strike_price - low, 0]
f_min = 0
f_max = strike_price - low
european_put_objective = LinearAmplitudeFunction(
num_uncertainty_qubits,
slopes,
offsets,
domain=(low, high),
image=(f_min, f_max),
breakpoints=breakpoints,
rescaling_factor=rescaling_factor,
)
# construct A operator for QAE for the payoff function by
# composing the uncertainty model and the objective
european_put = european_put_objective.compose(uncertainty_model, front=True)
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = uncertainty_model.values
y = np.maximum(0, strike_price - x)
plt.plot(x, y, "ro-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value (normalized to the [0, 1] interval)
exact_value = np.dot(uncertainty_model.probabilities, y)
exact_delta = -sum(uncertainty_model.probabilities[x <= strike_price])
print("exact expected value:\t%.4f" % exact_value)
print("exact delta value: \t%.4f" % exact_delta)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=european_put,
objective_qubits=[num_uncertainty_qubits],
post_processing=european_put_objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % exact_value)
print("Estimated value: \t%.4f" % (result.estimation_processed))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
# setup piecewise linear objective fcuntion
breakpoints = [low, strike_price]
slopes = [0, 0]
offsets = [1, 0]
f_min = 0
f_max = 1
european_put_delta_objective = LinearAmplitudeFunction(
num_uncertainty_qubits,
slopes,
offsets,
domain=(low, high),
image=(f_min, f_max),
breakpoints=breakpoints,
)
# construct circuit for payoff function
european_put_delta = european_put_delta_objective.compose(uncertainty_model, front=True)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=european_put_delta, objective_qubits=[num_uncertainty_qubits]
)
# construct amplitude estimation
ae_delta = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_delta = ae_delta.estimate(problem)
conf_int = -np.array(result_delta.confidence_interval)[::-1]
print("Exact delta: \t%.4f" % exact_delta)
print("Esimated value: \t%.4f" % -result_delta.estimation)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit.circuit.library import LinearAmplitudeFunction
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import LogNormalDistribution
# number of qubits to represent the uncertainty
num_uncertainty_qubits = 3
# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity
# resulting parameters for log-normal distribution
mu = (r - 0.5 * vol**2) * T + np.log(S)
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2 / 2)
variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3 * stddev)
high = mean + 3 * stddev
# construct circuit for uncertainty model
uncertainty_model = LogNormalDistribution(
num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high)
)
# plot probability distribution
x = uncertainty_model.values
y = uncertainty_model.probabilities
plt.bar(x, y, width=0.2)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.grid()
plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15)
plt.ylabel("Probability ($\%$)", size=15)
plt.show()
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price_1 = 1.438
strike_price_2 = 2.584
# set the approximation scaling for the payoff function
rescaling_factor = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [low, strike_price_1, strike_price_2]
slopes = [0, 1, 0]
offsets = [0, 0, strike_price_2 - strike_price_1]
f_min = 0
f_max = strike_price_2 - strike_price_1
bull_spread_objective = LinearAmplitudeFunction(
num_uncertainty_qubits,
slopes,
offsets,
domain=(low, high),
image=(f_min, f_max),
breakpoints=breakpoints,
rescaling_factor=rescaling_factor,
)
# construct A operator for QAE for the payoff function by
# composing the uncertainty model and the objective
bull_spread = bull_spread_objective.compose(uncertainty_model, front=True)
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = uncertainty_model.values
y = np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1)
plt.plot(x, y, "ro-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value (normalized to the [0, 1] interval)
exact_value = np.dot(uncertainty_model.probabilities, y)
exact_delta = sum(
uncertainty_model.probabilities[np.logical_and(x >= strike_price_1, x <= strike_price_2)]
)
print("exact expected value:\t%.4f" % exact_value)
print("exact delta value: \t%.4f" % exact_delta)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=bull_spread,
objective_qubits=[num_uncertainty_qubits],
post_processing=bull_spread_objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % exact_value)
print("Estimated value:\t%.4f" % result.estimation_processed)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
# setup piecewise linear objective fcuntion
breakpoints = [low, strike_price_1, strike_price_2]
slopes = [0, 0, 0]
offsets = [0, 1, 0]
f_min = 0
f_max = 1
bull_spread_delta_objective = LinearAmplitudeFunction(
num_uncertainty_qubits,
slopes,
offsets,
domain=(low, high),
image=(f_min, f_max),
breakpoints=breakpoints,
) # no approximation necessary, hence no rescaling factor
# construct the A operator by stacking the uncertainty model and payoff function together
bull_spread_delta = bull_spread_delta_objective.compose(uncertainty_model, front=True)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=bull_spread_delta, objective_qubits=[num_uncertainty_qubits]
)
# construct amplitude estimation
ae_delta = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_delta = ae_delta.estimate(problem)
conf_int = np.array(result_delta.confidence_interval)
print("Exact delta: \t%.4f" % exact_delta)
print("Estimated value:\t%.4f" % result_delta.estimation)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
%matplotlib inline
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit.circuit.library import WeightedAdder, LinearAmplitudeFunction
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import LogNormalDistribution
# number of qubits per dimension to represent the uncertainty
num_uncertainty_qubits = 2
# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity
# resulting parameters for log-normal distribution
mu = (r - 0.5 * vol**2) * T + np.log(S)
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2 / 2)
variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3 * stddev)
high = mean + 3 * stddev
# map to higher dimensional distribution
# for simplicity assuming dimensions are independent and identically distributed)
dimension = 2
num_qubits = [num_uncertainty_qubits] * dimension
low = low * np.ones(dimension)
high = high * np.ones(dimension)
mu = mu * np.ones(dimension)
cov = sigma**2 * np.eye(dimension)
# construct circuit
u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=list(zip(low, high)))
# plot PDF of uncertainty model
x = [v[0] for v in u.values]
y = [v[1] for v in u.values]
z = u.probabilities
# z = map(float, z)
# z = list(map(float, z))
resolution = np.array([2**n for n in num_qubits]) * 1j
grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]]
grid_z = griddata((x, y), z, (grid_x, grid_y))
plt.figure(figsize=(10, 8))
ax = plt.axes(projection="3d")
ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral)
ax.set_xlabel("Spot Price $S_T^1$ (\$)", size=15)
ax.set_ylabel("Spot Price $S_T^2$ (\$)", size=15)
ax.set_zlabel("Probability (\%)", size=15)
plt.show()
# determine number of qubits required to represent total loss
weights = []
for n in num_qubits:
for i in range(n):
weights += [2**i]
# create aggregation circuit
agg = WeightedAdder(sum(num_qubits), weights)
n_s = agg.num_sum_qubits
n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price = 3.5
# map strike price from [low, high] to {0, ..., 2^n-1}
max_value = 2**n_s - 1
low_ = low[0]
high_ = high[0]
mapped_strike_price = (
(strike_price - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1)
)
# set the approximation scaling for the payoff function
c_approx = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [0, mapped_strike_price]
slopes = [0, 1]
offsets = [0, 0]
f_min = 0
f_max = 2 * (2**num_uncertainty_qubits - 1) - mapped_strike_price
basket_objective = LinearAmplitudeFunction(
n_s,
slopes,
offsets,
domain=(0, max_value),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
# define overall multivariate problem
qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution
qr_obj = QuantumRegister(1, "obj") # to encode the function values
ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum
ar = AncillaRegister(max(n_aux, basket_objective.num_ancillas), "work") # additional qubits
objective_index = u.num_qubits
basket_option = QuantumCircuit(qr_state, qr_obj, ar_sum, ar)
basket_option.append(u, qr_state)
basket_option.append(agg, qr_state[:] + ar_sum[:] + ar[:n_aux])
basket_option.append(basket_objective, ar_sum[:] + qr_obj[:] + ar[: basket_objective.num_ancillas])
print(basket_option.draw())
print("objective qubit index", objective_index)
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = np.linspace(sum(low), sum(high))
y = np.maximum(0, x - strike_price)
plt.plot(x, y, "r-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Sum of Spot Prices ($S_T^1 + S_T^2)$", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value
sum_values = np.sum(u.values, axis=1)
exact_value = np.dot(
u.probabilities[sum_values >= strike_price],
sum_values[sum_values >= strike_price] - strike_price,
)
print("exact expected value:\t%.4f" % exact_value)
num_state_qubits = basket_option.num_qubits - basket_option.num_ancillas
print("state qubits: ", num_state_qubits)
transpiled = transpile(basket_option, basis_gates=["u", "cx"])
print("circuit width:", transpiled.width())
print("circuit depth:", transpiled.depth())
basket_option_measure = basket_option.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(basket_option_measure)
# evaluate the result
value = 0
probabilities = job.result().quasi_dists[0].binary_probabilities()
for i, prob in probabilities.items():
if prob > 1e-4 and i[-num_state_qubits:][0] == "1":
value += prob
# map value to original range
mapped_value = (
basket_objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_)
)
print("Exact Operator Value: %.4f" % value)
print("Mapped Operator value: %.4f" % mapped_value)
print("Exact Expected Payoff: %.4f" % exact_value)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=basket_option,
objective_qubits=[objective_index],
post_processing=basket_objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = (
np.array(result.confidence_interval_processed)
/ (2**num_uncertainty_qubits - 1)
* (high_ - low_)
)
print("Exact value: \t%.4f" % exact_value)
print(
"Estimated value: \t%.4f"
% (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_))
)
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
%matplotlib inline
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile
from qiskit.circuit.library import IntegerComparator, WeightedAdder, LinearAmplitudeFunction
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import LogNormalDistribution
# number of qubits per dimension to represent the uncertainty
num_uncertainty_qubits = 2
# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity
# resulting parameters for log-normal distribution
mu = (r - 0.5 * vol**2) * T + np.log(S)
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2 / 2)
variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3 * stddev)
high = mean + 3 * stddev
# map to higher dimensional distribution
# for simplicity assuming dimensions are independent and identically distributed)
dimension = 2
num_qubits = [num_uncertainty_qubits] * dimension
low = low * np.ones(dimension)
high = high * np.ones(dimension)
mu = mu * np.ones(dimension)
cov = sigma**2 * np.eye(dimension)
# construct circuit
u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=(list(zip(low, high))))
# plot PDF of uncertainty model
x = [v[0] for v in u.values]
y = [v[1] for v in u.values]
z = u.probabilities
# z = map(float, z)
# z = list(map(float, z))
resolution = np.array([2**n for n in num_qubits]) * 1j
grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]]
grid_z = griddata((x, y), z, (grid_x, grid_y))
plt.figure(figsize=(10, 8))
ax = plt.axes(projection="3d")
ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral)
ax.set_xlabel("Spot Price $S_1$ (\$)", size=15)
ax.set_ylabel("Spot Price $S_2$ (\$)", size=15)
ax.set_zlabel("Probability (\%)", size=15)
plt.show()
# determine number of qubits required to represent total loss
weights = []
for n in num_qubits:
for i in range(n):
weights += [2**i]
# create aggregation circuit
agg = WeightedAdder(sum(num_qubits), weights)
n_s = agg.num_sum_qubits
n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price_1 = 3
strike_price_2 = 4
# set the barrier threshold
barrier = 2.5
# map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1}
max_value = 2**n_s - 1
low_ = low[0]
high_ = high[0]
mapped_strike_price_1 = (
(strike_price_1 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1)
)
mapped_strike_price_2 = (
(strike_price_2 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1)
)
mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1)
# condition and condition result
conditions = []
barrier_thresholds = [2] * dimension
n_aux_conditions = 0
for i in range(dimension):
# target dimension of random distribution and corresponding condition (which is required to be True)
comparator = IntegerComparator(num_qubits[i], mapped_barrier[i] + 1, geq=False)
n_aux_conditions = max(n_aux_conditions, comparator.num_ancillas)
conditions += [comparator]
# set the approximation scaling for the payoff function
c_approx = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2]
slopes = [0, 1, 0]
offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1]
f_min = 0
f_max = mapped_strike_price_2 - mapped_strike_price_1
objective = LinearAmplitudeFunction(
n_s,
slopes,
offsets,
domain=(0, max_value),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
# define overall multivariate problem
qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution
qr_obj = QuantumRegister(1, "obj") # to encode the function values
ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum
ar_cond = AncillaRegister(len(conditions) + 1, "conditions")
ar = AncillaRegister(
max(n_aux, n_aux_conditions, objective.num_ancillas), "work"
) # additional qubits
objective_index = u.num_qubits
# define the circuit
asian_barrier_spread = QuantumCircuit(qr_state, qr_obj, ar_cond, ar_sum, ar)
# load the probability distribution
asian_barrier_spread.append(u, qr_state)
# apply the conditions
for i, cond in enumerate(conditions):
state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))]
asian_barrier_spread.append(cond, state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas])
# aggregate the conditions on a single qubit
asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1])
# apply the aggregation function controlled on the condition
asian_barrier_spread.append(agg.control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux])
# apply the payoff function
asian_barrier_spread.append(objective, ar_sum[:] + qr_obj[:] + ar[: objective.num_ancillas])
# uncompute the aggregation
asian_barrier_spread.append(
agg.inverse().control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux]
)
# uncompute the conditions
asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1])
for j, cond in enumerate(reversed(conditions)):
i = len(conditions) - j - 1
state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))]
asian_barrier_spread.append(
cond.inverse(), state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas]
)
print(asian_barrier_spread.draw())
print("objective qubit index", objective_index)
# plot exact payoff function
plt.figure(figsize=(7, 5))
x = np.linspace(sum(low), sum(high))
y = (x <= 5) * np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1)
plt.plot(x, y, "r-")
plt.grid()
plt.title("Payoff Function (for $S_1 = S_2$)", size=15)
plt.xlabel("Sum of Spot Prices ($S_1 + S_2)$", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# plot contour of payoff function with respect to both time steps, including barrier
plt.figure(figsize=(7, 5))
z = np.zeros((17, 17))
x = np.linspace(low[0], high[0], 17)
y = np.linspace(low[1], high[1], 17)
for i, x_ in enumerate(x):
for j, y_ in enumerate(y):
z[i, j] = np.minimum(
np.maximum(0, x_ + y_ - strike_price_1), strike_price_2 - strike_price_1
)
if x_ > barrier or y_ > barrier:
z[i, j] = 0
plt.title("Payoff Function", size=15)
plt.contourf(x, y, z)
plt.colorbar()
plt.xlabel("Spot Price $S_1$", size=15)
plt.ylabel("Spot Price $S_2$", size=15)
plt.xticks(size=15)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value
sum_values = np.sum(u.values, axis=1)
payoff = np.minimum(np.maximum(sum_values - strike_price_1, 0), strike_price_2 - strike_price_1)
leq_barrier = [np.max(v) <= barrier for v in u.values]
exact_value = np.dot(u.probabilities[leq_barrier], payoff[leq_barrier])
print("exact expected value:\t%.4f" % exact_value)
num_state_qubits = asian_barrier_spread.num_qubits - asian_barrier_spread.num_ancillas
print("state qubits: ", num_state_qubits)
transpiled = transpile(asian_barrier_spread, basis_gates=["u", "cx"])
print("circuit width:", transpiled.width())
print("circuit depth:", transpiled.depth())
asian_barrier_spread_measure = asian_barrier_spread.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(asian_barrier_spread_measure)
# evaluate the result
value = 0
probabilities = job.result().quasi_dists[0].binary_probabilities()
for i, prob in probabilities.items():
if prob > 1e-4 and i[-num_state_qubits:][0] == "1":
value += prob
# map value to original range
mapped_value = objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_)
print("Exact Operator Value: %.4f" % value)
print("Mapped Operator value: %.4f" % mapped_value)
print("Exact Expected Payoff: %.4f" % exact_value)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=asian_barrier_spread,
objective_qubits=[objective_index],
post_processing=objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}))
result = ae.estimate(problem)
conf_int = (
np.array(result.confidence_interval_processed)
/ (2**num_uncertainty_qubits - 1)
* (high_ - low_)
)
print("Exact value: \t%.4f" % exact_value)
print(
"Estimated value:\t%.4f"
% (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_))
)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import QuantumCircuit
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import NormalDistribution
# can be used in case a principal component analysis has been done to derive the uncertainty model, ignored in this example.
A = np.eye(2)
b = np.zeros(2)
# specify the number of qubits that are used to represent the different dimenions of the uncertainty model
num_qubits = [2, 2]
# specify the lower and upper bounds for the different dimension
low = [0, 0]
high = [0.12, 0.24]
mu = [0.12, 0.24]
sigma = 0.01 * np.eye(2)
# construct corresponding distribution
bounds = list(zip(low, high))
u = NormalDistribution(num_qubits, mu, sigma, bounds)
# plot contour of probability density function
x = np.linspace(low[0], high[0], 2 ** num_qubits[0])
y = np.linspace(low[1], high[1], 2 ** num_qubits[1])
z = u.probabilities.reshape(2 ** num_qubits[0], 2 ** num_qubits[1])
plt.contourf(x, y, z)
plt.xticks(x, size=15)
plt.yticks(y, size=15)
plt.grid()
plt.xlabel("$r_1$ (%)", size=15)
plt.ylabel("$r_2$ (%)", size=15)
plt.colorbar()
plt.show()
# specify cash flow
cf = [1.0, 2.0]
periods = range(1, len(cf) + 1)
# plot cash flow
plt.bar(periods, cf)
plt.xticks(periods, size=15)
plt.yticks(size=15)
plt.grid()
plt.xlabel("periods", size=15)
plt.ylabel("cashflow ($)", size=15)
plt.show()
# estimate real value
cnt = 0
exact_value = 0.0
for x1 in np.linspace(low[0], high[0], pow(2, num_qubits[0])):
for x2 in np.linspace(low[1], high[1], pow(2, num_qubits[1])):
prob = u.probabilities[cnt]
for t in range(len(cf)):
# evaluate linear approximation of real value w.r.t. interest rates
exact_value += prob * (
cf[t] / pow(1 + b[t], t + 1)
- (t + 1) * cf[t] * np.dot(A[:, t], np.asarray([x1, x2])) / pow(1 + b[t], t + 2)
)
cnt += 1
print("Exact value: \t%.4f" % exact_value)
# specify approximation factor
c_approx = 0.125
# create fixed income pricing application
from qiskit_finance.applications.estimation import FixedIncomePricing
fixed_income = FixedIncomePricing(
num_qubits=num_qubits,
pca_matrix=A,
initial_interests=b,
cash_flow=cf,
rescaling_factor=c_approx,
bounds=bounds,
uncertainty_model=u,
)
fixed_income._objective.draw()
fixed_income_circ = QuantumCircuit(fixed_income._objective.num_qubits)
# load probability distribution
fixed_income_circ.append(u, range(u.num_qubits))
# apply function
fixed_income_circ.append(fixed_income._objective, range(fixed_income._objective.num_qubits))
fixed_income_circ.draw()
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
# construct amplitude estimation
problem = fixed_income.to_estimation_problem()
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % exact_value)
print("Estimated value: \t%.4f" % (fixed_income.interpret(result)))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import IntegerComparator
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
# set problem parameters
n_z = 2
z_max = 2
z_values = np.linspace(-z_max, z_max, 2**n_z)
p_zeros = [0.15, 0.25]
rhos = [0.1, 0.05]
lgd = [1, 2]
K = len(p_zeros)
alpha = 0.05
from qiskit_finance.circuit.library import GaussianConditionalIndependenceModel as GCI
u = GCI(n_z, z_max, p_zeros, rhos)
u.draw()
u_measure = u.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(u_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# analyze uncertainty circuit and determine exact solutions
p_z = np.zeros(2**n_z)
p_default = np.zeros(K)
values = []
probabilities = []
num_qubits = u.num_qubits
for i, prob in binary_probabilities.items():
# extract value of Z and corresponding probability
i_normal = int(i[-n_z:], 2)
p_z[i_normal] += prob
# determine overall default probability for k
loss = 0
for k in range(K):
if i[K - k - 1] == "1":
p_default[k] += prob
loss += lgd[k]
values += [loss]
probabilities += [prob]
values = np.array(values)
probabilities = np.array(probabilities)
expected_loss = np.dot(values, probabilities)
losses = np.sort(np.unique(values))
pdf = np.zeros(len(losses))
for i, v in enumerate(losses):
pdf[i] += sum(probabilities[values == v])
cdf = np.cumsum(pdf)
i_var = np.argmax(cdf >= 1 - alpha)
exact_var = losses[i_var]
exact_cvar = np.dot(pdf[(i_var + 1) :], losses[(i_var + 1) :]) / sum(pdf[(i_var + 1) :])
print("Expected Loss E[L]: %.4f" % expected_loss)
print("Value at Risk VaR[L]: %.4f" % exact_var)
print("P[L <= VaR[L]]: %.4f" % cdf[exact_var])
print("Conditional Value at Risk CVaR[L]: %.4f" % exact_cvar)
# plot loss PDF, expected loss, var, and cvar
plt.bar(losses, pdf)
plt.axvline(expected_loss, color="green", linestyle="--", label="E[L]")
plt.axvline(exact_var, color="orange", linestyle="--", label="VaR(L)")
plt.axvline(exact_cvar, color="red", linestyle="--", label="CVaR(L)")
plt.legend(fontsize=15)
plt.xlabel("Loss L ($)", size=15)
plt.ylabel("probability (%)", size=15)
plt.title("Loss Distribution", size=20)
plt.xticks(size=15)
plt.yticks(size=15)
plt.show()
# plot results for Z
plt.plot(z_values, p_z, "o-", linewidth=3, markersize=8)
plt.grid()
plt.xlabel("Z value", size=15)
plt.ylabel("probability (%)", size=15)
plt.title("Z Distribution", size=20)
plt.xticks(size=15)
plt.yticks(size=15)
plt.show()
# plot results for default probabilities
plt.bar(range(K), p_default)
plt.xlabel("Asset", size=15)
plt.ylabel("probability (%)", size=15)
plt.title("Individual Default Probabilities", size=20)
plt.xticks(range(K), size=15)
plt.yticks(size=15)
plt.grid()
plt.show()
# add Z qubits with weight/loss 0
from qiskit.circuit.library import WeightedAdder
agg = WeightedAdder(n_z + K, [0] * n_z + lgd)
from qiskit.circuit.library import LinearAmplitudeFunction
# define linear objective function
breakpoints = [0]
slopes = [1]
offsets = [0]
f_min = 0
f_max = sum(lgd)
c_approx = 0.25
objective = LinearAmplitudeFunction(
agg.num_sum_qubits,
slope=slopes,
offset=offsets,
# max value that can be reached by the qubit register (will not always be reached)
domain=(0, 2**agg.num_sum_qubits - 1),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
# define the registers for convenience and readability
qr_state = QuantumRegister(u.num_qubits, "state")
qr_sum = QuantumRegister(agg.num_sum_qubits, "sum")
qr_carry = QuantumRegister(agg.num_carry_qubits, "carry")
qr_obj = QuantumRegister(1, "objective")
# define the circuit
state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A")
# load the random variable
state_preparation.append(u.to_gate(), qr_state)
# aggregate
state_preparation.append(agg.to_gate(), qr_state[:] + qr_sum[:] + qr_carry[:])
# linear objective function
state_preparation.append(objective.to_gate(), qr_sum[:] + qr_obj[:])
# uncompute aggregation
state_preparation.append(agg.to_gate().inverse(), qr_state[:] + qr_sum[:] + qr_carry[:])
# draw the circuit
state_preparation.draw()
state_preparation_measure = state_preparation.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(state_preparation_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# evaluate the result
value = 0
for i, prob in binary_probabilities.items():
if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1":
value += prob
print("Exact Expected Loss: %.4f" % expected_loss)
print("Exact Operator Value: %.4f" % value)
print("Mapped Operator value: %.4f" % objective.post_processing(value))
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=state_preparation,
objective_qubits=[len(qr_state)],
post_processing=objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
# print results
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % expected_loss)
print("Estimated value:\t%.4f" % result.estimation_processed)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
# set x value to estimate the CDF
x_eval = 2
comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False)
comparator.draw()
def get_cdf_circuit(x_eval):
# define the registers for convenience and readability
qr_state = QuantumRegister(u.num_qubits, "state")
qr_sum = QuantumRegister(agg.num_sum_qubits, "sum")
qr_carry = QuantumRegister(agg.num_carry_qubits, "carry")
qr_obj = QuantumRegister(1, "objective")
qr_compare = QuantumRegister(1, "compare")
# define the circuit
state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A")
# load the random variable
state_preparation.append(u, qr_state)
# aggregate
state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:])
# comparator objective function
comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False)
state_preparation.append(comparator, qr_sum[:] + qr_obj[:] + qr_carry[:])
# uncompute aggregation
state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:])
return state_preparation
state_preparation = get_cdf_circuit(x_eval)
state_preparation.draw()
state_preparation_measure = state_preparation.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(state_preparation_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# evaluate the result
var_prob = 0
for i, prob in binary_probabilities.items():
if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1":
var_prob += prob
print("Operator CDF(%s)" % x_eval + " = %.4f" % var_prob)
print("Exact CDF(%s)" % x_eval + " = %.4f" % cdf[x_eval])
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_state)])
# construct amplitude estimation
ae_cdf = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_cdf = ae_cdf.estimate(problem)
# print results
conf_int = np.array(result_cdf.confidence_interval)
print("Exact value: \t%.4f" % cdf[x_eval])
print("Estimated value:\t%.4f" % result_cdf.estimation)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
def run_ae_for_cdf(x_eval, epsilon=0.01, alpha=0.05, simulator="aer_simulator"):
# construct amplitude estimation
state_preparation = get_cdf_circuit(x_eval)
problem = EstimationProblem(
state_preparation=state_preparation, objective_qubits=[len(qr_state)]
)
ae_var = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_var = ae_var.estimate(problem)
return result_var.estimation
def bisection_search(
objective, target_value, low_level, high_level, low_value=None, high_value=None
):
"""
Determines the smallest level such that the objective value is still larger than the target
:param objective: objective function
:param target: target value
:param low_level: lowest level to be considered
:param high_level: highest level to be considered
:param low_value: value of lowest level (will be evaluated if set to None)
:param high_value: value of highest level (will be evaluated if set to None)
:return: dictionary with level, value, num_eval
"""
# check whether low and high values are given and evaluated them otherwise
print("--------------------------------------------------------------------")
print("start bisection search for target value %.3f" % target_value)
print("--------------------------------------------------------------------")
num_eval = 0
if low_value is None:
low_value = objective(low_level)
num_eval += 1
if high_value is None:
high_value = objective(high_level)
num_eval += 1
# check if low_value already satisfies the condition
if low_value > target_value:
return {
"level": low_level,
"value": low_value,
"num_eval": num_eval,
"comment": "returned low value",
}
elif low_value == target_value:
return {"level": low_level, "value": low_value, "num_eval": num_eval, "comment": "success"}
# check if high_value is above target
if high_value < target_value:
return {
"level": high_level,
"value": high_value,
"num_eval": num_eval,
"comment": "returned low value",
}
elif high_value == target_value:
return {
"level": high_level,
"value": high_value,
"num_eval": num_eval,
"comment": "success",
}
# perform bisection search until
print("low_level low_value level value high_level high_value")
print("--------------------------------------------------------------------")
while high_level - low_level > 1:
level = int(np.round((high_level + low_level) / 2.0))
num_eval += 1
value = objective(level)
print(
"%2d %.3f %2d %.3f %2d %.3f"
% (low_level, low_value, level, value, high_level, high_value)
)
if value >= target_value:
high_level = level
high_value = value
else:
low_level = level
low_value = value
# return high value after bisection search
print("--------------------------------------------------------------------")
print("finished bisection search")
print("--------------------------------------------------------------------")
return {"level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success"}
# run bisection search to determine VaR
objective = lambda x: run_ae_for_cdf(x)
bisection_result = bisection_search(
objective, 1 - alpha, min(losses) - 1, max(losses), low_value=0, high_value=1
)
var = bisection_result["level"]
print("Estimated Value at Risk: %2d" % var)
print("Exact Value at Risk: %2d" % exact_var)
print("Estimated Probability: %.3f" % bisection_result["value"])
print("Exact Probability: %.3f" % cdf[exact_var])
# define linear objective
breakpoints = [0, var]
slopes = [0, 1]
offsets = [0, 0] # subtract VaR and add it later to the estimate
f_min = 0
f_max = 3 - var
c_approx = 0.25
cvar_objective = LinearAmplitudeFunction(
agg.num_sum_qubits,
slopes,
offsets,
domain=(0, 2**agg.num_sum_qubits - 1),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
cvar_objective.draw()
# define the registers for convenience and readability
qr_state = QuantumRegister(u.num_qubits, "state")
qr_sum = QuantumRegister(agg.num_sum_qubits, "sum")
qr_carry = QuantumRegister(agg.num_carry_qubits, "carry")
qr_obj = QuantumRegister(1, "objective")
qr_work = QuantumRegister(cvar_objective.num_ancillas - len(qr_carry), "work")
# define the circuit
state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, qr_work, name="A")
# load the random variable
state_preparation.append(u, qr_state)
# aggregate
state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:])
# linear objective function
state_preparation.append(cvar_objective, qr_sum[:] + qr_obj[:] + qr_carry[:] + qr_work[:])
# uncompute aggregation
state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:])
state_preparation_measure = state_preparation.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(state_preparation_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# evaluate the result
value = 0
for i, prob in binary_probabilities.items():
if prob > 1e-6 and i[-(len(qr_state) + 1)] == "1":
value += prob
# normalize and add VaR to estimate
value = cvar_objective.post_processing(value)
d = 1.0 - bisection_result["value"]
v = value / d if d != 0 else 0
normalized_value = v + var
print("Estimated CVaR: %.4f" % normalized_value)
print("Exact CVaR: %.4f" % exact_cvar)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=state_preparation,
objective_qubits=[len(qr_state)],
post_processing=cvar_objective.post_processing,
)
# construct amplitude estimation
ae_cvar = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_cvar = ae_cvar.estimate(problem)
# print results
d = 1.0 - bisection_result["value"]
v = result_cvar.estimation_processed / d if d != 0 else 0
print("Exact CVaR: \t%.4f" % exact_cvar)
print("Estimated CVaR:\t%.4f" % (v + var))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
import numpy as np
from qiskit.circuit import ParameterVector
from qiskit.circuit.library import TwoLocal
from qiskit.quantum_info import Statevector
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.applications.estimation import EuropeanCallPricing
from qiskit_finance.circuit.library import NormalDistribution
# Set upper and lower data values
bounds = np.array([0.0, 7.0])
# Set number of qubits used in the uncertainty model
num_qubits = 3
# Load the trained circuit parameters
g_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225]
# Set an initial state for the generator circuit
init_dist = NormalDistribution(num_qubits, mu=1.0, sigma=1.0, bounds=bounds)
# construct the variational form
var_form = TwoLocal(num_qubits, "ry", "cz", entanglement="circular", reps=1)
# keep a list of the parameters so we can associate them to the list of numerical values
# (otherwise we need a dictionary)
theta = var_form.ordered_parameters
# compose the generator circuit, this is the circuit loading the uncertainty model
g_circuit = init_dist.compose(var_form)
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price = 2
# set the approximation scaling for the payoff function
c_approx = 0.25
# Evaluate trained probability distribution
values = [
bounds[0] + (bounds[1] - bounds[0]) * x / (2**num_qubits - 1) for x in range(2**num_qubits)
]
uncertainty_model = g_circuit.assign_parameters(dict(zip(theta, g_params)))
amplitudes = Statevector.from_instruction(uncertainty_model).data
x = np.array(values)
y = np.abs(amplitudes) ** 2
# Sample from target probability distribution
N = 100000
log_normal = np.random.lognormal(mean=1, sigma=1, size=N)
log_normal = np.round(log_normal)
log_normal = log_normal[log_normal <= 7]
log_normal_samples = []
for i in range(8):
log_normal_samples += [np.sum(log_normal == i)]
log_normal_samples = np.array(log_normal_samples / sum(log_normal_samples))
# Plot distributions
plt.bar(x, y, width=0.2, label="trained distribution", color="royalblue")
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.grid()
plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15)
plt.ylabel("Probability ($\%$)", size=15)
plt.plot(
log_normal_samples,
"-o",
color="deepskyblue",
label="target distribution",
linewidth=4,
markersize=12,
)
plt.legend(loc="best")
plt.show()
# Evaluate payoff for different distributions
payoff = np.array([0, 0, 0, 1, 2, 3, 4, 5])
ep = np.dot(log_normal_samples, payoff)
print("Analytically calculated expected payoff w.r.t. the target distribution: %.4f" % ep)
ep_trained = np.dot(y, payoff)
print("Analytically calculated expected payoff w.r.t. the trained distribution: %.4f" % ep_trained)
# Plot exact payoff function (evaluated on the grid of the trained uncertainty model)
x = np.array(values)
y_strike = np.maximum(0, x - strike_price)
plt.plot(x, y_strike, "ro-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# construct circuit for payoff function
european_call_pricing = EuropeanCallPricing(
num_qubits,
strike_price=strike_price,
rescaling_factor=c_approx,
bounds=bounds,
uncertainty_model=uncertainty_model,
)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = european_call_pricing.to_estimation_problem()
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % ep_trained)
print("Estimated value: \t%.4f" % (result.estimation_processed))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
%matplotlib inline
from qiskit_finance import QiskitFinanceError
from qiskit_finance.data_providers import *
import datetime
import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
data = RandomDataProvider(
tickers=["TICKER1", "TICKER2"],
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=1,
)
data.run()
means = data.get_mean_vector()
print("Means:")
print(means)
rho = data.get_similarity_matrix()
print("A time-series similarity measure:")
print(rho)
plt.imshow(rho)
plt.show()
cov = data.get_covariance_matrix()
print("A covariance matrix:")
print(cov)
plt.imshow(cov)
plt.show()
print("The underlying evolution of stock prices:")
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
for (cnt, s) in enumerate(data._tickers):
print(s)
print(data._data[cnt])
data = RandomDataProvider(
tickers=["CompanyA", "CompanyB", "CompanyC"],
start=datetime.datetime(2015, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=1,
)
data.run()
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
stocks = ["GOOG", "AAPL"]
token = "REPLACE-ME"
if token != "REPLACE-ME":
try:
wiki = WikipediaDataProvider(
token=token,
tickers=stocks,
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
)
wiki.run()
except QiskitFinanceError as ex:
print(ex)
print("Error retrieving data.")
if token != "REPLACE-ME":
if wiki._data:
if wiki._n <= 1:
print(
"Not enough wiki data to plot covariance or time-series similarity. Please use at least two tickers."
)
else:
rho = wiki.get_similarity_matrix()
print("A time-series similarity measure:")
print(rho)
plt.imshow(rho)
plt.show()
cov = wiki.get_covariance_matrix()
print("A covariance matrix:")
print(cov)
plt.imshow(cov)
plt.show()
else:
print("No wiki data loaded.")
if token != "REPLACE-ME":
if wiki._data:
print("The underlying evolution of stock prices:")
for (cnt, s) in enumerate(stocks):
plt.plot(wiki._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
for (cnt, s) in enumerate(stocks):
print(s)
print(wiki._data[cnt])
else:
print("No wiki data loaded.")
token = "REPLACE-ME"
if token != "REPLACE-ME":
try:
nasdaq = DataOnDemandProvider(
token=token,
tickers=["GOOG", "AAPL"],
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 2),
)
nasdaq.run()
for (cnt, s) in enumerate(nasdaq._tickers):
plt.plot(nasdaq._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
except QiskitFinanceError as ex:
print(ex)
print("Error retrieving data.")
token = "REPLACE-ME"
if token != "REPLACE-ME":
try:
lse = ExchangeDataProvider(
token=token,
tickers=["AEO", "ABBY", "ADIG", "ABF", "AEP", "AAL", "AGK", "AFN", "AAS", "AEFS"],
stockmarket=StockMarket.LONDON,
start=datetime.datetime(2018, 1, 1),
end=datetime.datetime(2018, 12, 31),
)
lse.run()
for (cnt, s) in enumerate(lse._tickers):
plt.plot(lse._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
except QiskitFinanceError as ex:
print(ex)
print("Error retrieving data.")
try:
data = YahooDataProvider(
tickers=["MSFT", "AAPL", "GOOG"],
start=datetime.datetime(2021, 1, 1),
end=datetime.datetime(2021, 12, 31),
)
data.run()
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend(loc="upper center", bbox_to_anchor=(0.5, 1.1), ncol=3)
plt.xticks(rotation=90)
plt.show()
except QiskitFinanceError as ex:
data = None
print(ex)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
p = 0.2
import numpy as np
from qiskit.circuit import QuantumCircuit
class BernoulliA(QuantumCircuit):
"""A circuit representing the Bernoulli A operator."""
def __init__(self, probability):
super().__init__(1) # circuit on 1 qubit
theta_p = 2 * np.arcsin(np.sqrt(probability))
self.ry(theta_p, 0)
class BernoulliQ(QuantumCircuit):
"""A circuit representing the Bernoulli Q operator."""
def __init__(self, probability):
super().__init__(1) # circuit on 1 qubit
self._theta_p = 2 * np.arcsin(np.sqrt(probability))
self.ry(2 * self._theta_p, 0)
def power(self, k):
# implement the efficient power of Q
q_k = QuantumCircuit(1)
q_k.ry(2 * k * self._theta_p, 0)
return q_k
A = BernoulliA(p)
Q = BernoulliQ(p)
from qiskit.algorithms import EstimationProblem
problem = EstimationProblem(
state_preparation=A, # A operator
grover_operator=Q, # Q operator
objective_qubits=[0], # the "good" state Psi1 is identified as measuring |1> in qubit 0
)
from qiskit.primitives import Sampler
sampler = Sampler()
from qiskit.algorithms import AmplitudeEstimation
ae = AmplitudeEstimation(
num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy
sampler=sampler,
)
ae_result = ae.estimate(problem)
print(ae_result.estimation)
import matplotlib.pyplot as plt
# plot estimated values
gridpoints = list(ae_result.samples.keys())
probabilities = list(ae_result.samples.values())
plt.bar(gridpoints, probabilities, width=0.5 / len(probabilities))
plt.axvline(p, color="r", ls="--")
plt.xticks(size=15)
plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15)
plt.title("Estimated Values", size=15)
plt.ylabel("Probability", size=15)
plt.xlabel(r"Amplitude $a$", size=15)
plt.ylim((0, 1))
plt.grid()
plt.show()
print("Interpolated MLE estimator:", ae_result.mle)
ae_circuit = ae.construct_circuit(problem)
ae_circuit.decompose().draw(
"mpl", style="iqx"
) # decompose 1 level: exposes the Phase estimation circuit!
from qiskit import transpile
basis_gates = ["h", "ry", "cry", "cx", "ccx", "p", "cp", "x", "s", "sdg", "y", "t", "cz"]
transpile(ae_circuit, basis_gates=basis_gates, optimization_level=2).draw("mpl", style="iqx")
from qiskit.algorithms import IterativeAmplitudeEstimation
iae = IterativeAmplitudeEstimation(
epsilon_target=0.01, # target accuracy
alpha=0.05, # width of the confidence interval
sampler=sampler,
)
iae_result = iae.estimate(problem)
print("Estimate:", iae_result.estimation)
iae_circuit = iae.construct_circuit(problem, k=3)
iae_circuit.draw("mpl", style="iqx")
from qiskit.algorithms import MaximumLikelihoodAmplitudeEstimation
mlae = MaximumLikelihoodAmplitudeEstimation(
evaluation_schedule=3, # log2 of the maximal Grover power
sampler=sampler,
)
mlae_result = mlae.estimate(problem)
print("Estimate:", mlae_result.estimation)
from qiskit.algorithms import FasterAmplitudeEstimation
fae = FasterAmplitudeEstimation(
delta=0.01, # target accuracy
maxiter=3, # determines the maximal power of the Grover operator
sampler=sampler,
)
fae_result = fae.estimate(problem)
print("Estimate:", fae_result.estimation)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.result import QuasiDistribution
from qiskit_aer.primitives import Sampler
from qiskit_finance.applications.optimization import PortfolioOptimization
from qiskit_finance.data_providers import RandomDataProvider
from qiskit_optimization.algorithms import MinimumEigenOptimizer
import numpy as np
import matplotlib.pyplot as plt
import datetime
# set number of assets (= number of qubits)
num_assets = 4
seed = 123
# Generate expected return and covariance matrix from (random) time-series
stocks = [("TICKER%s" % i) for i in range(num_assets)]
data = RandomDataProvider(
tickers=stocks,
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=seed,
)
data.run()
mu = data.get_period_return_mean_vector()
sigma = data.get_period_return_covariance_matrix()
# plot sigma
plt.imshow(sigma, interpolation="nearest")
plt.show()
q = 0.5 # set risk factor
budget = num_assets // 2 # set budget
penalty = num_assets # set parameter to scale the budget penalty term
portfolio = PortfolioOptimization(
expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget
)
qp = portfolio.to_quadratic_program()
qp
def print_result(result):
selection = result.x
value = result.fval
print("Optimal: selection {}, value {:.4f}".format(selection, value))
eigenstate = result.min_eigen_solver_result.eigenstate
probabilities = (
eigenstate.binary_probabilities()
if isinstance(eigenstate, QuasiDistribution)
else {k: np.abs(v) ** 2 for k, v in eigenstate.to_dict().items()}
)
print("\n----------------- Full result ---------------------")
print("selection\tvalue\t\tprobability")
print("---------------------------------------------------")
probabilities = sorted(probabilities.items(), key=lambda x: x[1], reverse=True)
for k, v in probabilities:
x = np.array([int(i) for i in list(reversed(k))])
value = portfolio.to_quadratic_program().objective.evaluate(x)
print("%10s\t%.4f\t\t%.4f" % (x, value, v))
exact_mes = NumPyMinimumEigensolver()
exact_eigensolver = MinimumEigenOptimizer(exact_mes)
result = exact_eigensolver.solve(qp)
print_result(result)
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 1234
cobyla = COBYLA()
cobyla.set_options(maxiter=500)
ry = TwoLocal(num_assets, "ry", "cz", reps=3, entanglement="full")
vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla)
vqe = MinimumEigenOptimizer(vqe_mes)
result = vqe.solve(qp)
print_result(result)
algorithm_globals.random_seed = 1234
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(qp)
print_result(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Import requisite modules
import math
import datetime
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Import Qiskit packages
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit_aer.primitives import Sampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
# The data providers of stock-market data
from qiskit_finance.data_providers import RandomDataProvider
from qiskit_finance.applications.optimization import PortfolioDiversification
# Generate a pairwise time-series similarity matrix
seed = 123
stocks = ["TICKER1", "TICKER2"]
n = len(stocks)
data = RandomDataProvider(
tickers=stocks,
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=seed,
)
data.run()
rho = data.get_similarity_matrix()
q = 1 # q less or equal than n
class ClassicalOptimizer:
def __init__(self, rho, n, q):
self.rho = rho
self.n = n # number of inner variables
self.q = q # number of required selection
def compute_allowed_combinations(self):
f = math.factorial
return int(f(self.n) / f(self.q) / f(self.n - self.q))
def cplex_solution(self):
# refactoring
rho = self.rho
n = self.n
q = self.q
my_obj = list(rho.reshape(1, n**2)[0]) + [0.0 for x in range(0, n)]
my_ub = [1 for x in range(0, n**2 + n)]
my_lb = [0 for x in range(0, n**2 + n)]
my_ctype = "".join(["I" for x in range(0, n**2 + n)])
my_rhs = (
[q]
+ [1 for x in range(0, n)]
+ [0 for x in range(0, n)]
+ [0.1 for x in range(0, n**2)]
)
my_sense = (
"".join(["E" for x in range(0, 1 + n)])
+ "".join(["E" for x in range(0, n)])
+ "".join(["L" for x in range(0, n**2)])
)
try:
my_prob = cplex.Cplex()
self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs)
my_prob.solve()
except CplexError as exc:
print(exc)
return
x = my_prob.solution.get_values()
x = np.array(x)
cost = my_prob.solution.get_objective_value()
return x, cost
def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs):
n = self.n
prob.objective.set_sense(prob.objective.sense.minimize)
prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype)
prob.set_log_stream(None)
prob.set_error_stream(None)
prob.set_warning_stream(None)
prob.set_results_stream(None)
rows = []
col = [x for x in range(n**2, n**2 + n)]
coef = [1 for x in range(0, n)]
rows.append([col, coef])
for ii in range(0, n):
col = [x for x in range(0 + n * ii, n + n * ii)]
coef = [1 for x in range(0, n)]
rows.append([col, coef])
for ii in range(0, n):
col = [ii * n + ii, n**2 + ii]
coef = [1, -1]
rows.append([col, coef])
for ii in range(0, n):
for jj in range(0, n):
col = [ii * n + jj, n**2 + jj]
coef = [1, -1]
rows.append([col, coef])
prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs)
# Instantiate the classical optimizer class
classical_optimizer = ClassicalOptimizer(rho, n, q)
# Compute the number of feasible solutions:
print("Number of feasible combinations= " + str(classical_optimizer.compute_allowed_combinations()))
# Compute the total number of possible combinations (feasible + unfeasible)
print("Total number of combinations= " + str(2 ** (n * (n + 1))))
# Visualize the solution
def visualize_solution(xc, yc, x, C, n, K, title_str):
plt.figure()
plt.scatter(xc, yc, s=200)
for i in range(len(xc)):
plt.annotate(i, (xc[i] + 0.015, yc[i]), size=16, color="r")
plt.grid()
for ii in range(n**2, n**2 + n):
if x[ii] > 0:
plt.plot(xc[ii - n**2], yc[ii - n**2], "r*", ms=20)
for ii in range(0, n**2):
if x[ii] > 0:
iy = ii // n
ix = ii % n
plt.plot([xc[ix], xc[iy]], [yc[ix], yc[iy]], "C2")
plt.title(title_str + " cost = " + str(int(C * 100) / 100.0))
plt.show()
from qiskit.utils import algorithm_globals
class QuantumOptimizer:
def __init__(self, rho, n, q):
self.rho = rho
self.n = n
self.q = q
self.pdf = PortfolioDiversification(similarity_matrix=rho, num_assets=n, num_clusters=q)
self.qp = self.pdf.to_quadratic_program()
# Obtains the least eigenvalue of the Hamiltonian classically
def exact_solution(self):
exact_mes = NumPyMinimumEigensolver()
exact_eigensolver = MinimumEigenOptimizer(exact_mes)
result = exact_eigensolver.solve(self.qp)
return self.decode_result(result)
def vqe_solution(self):
algorithm_globals.random_seed = 100
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
ry = TwoLocal(n, "ry", "cz", reps=5, entanglement="full")
vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla)
vqe = MinimumEigenOptimizer(vqe_mes)
result = vqe.solve(self.qp)
return self.decode_result(result)
def qaoa_solution(self):
algorithm_globals.random_seed = 1234
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(self.qp)
return self.decode_result(result)
def decode_result(self, result, offset=0):
quantum_solution = 1 - (result.x)
ground_level = self.qp.objective.evaluate(result.x)
return quantum_solution, ground_level
# Instantiate the quantum optimizer class with parameters:
quantum_optimizer = QuantumOptimizer(rho, n, q)
# Check if the binary representation is correct. This requires CPLEX
try:
import cplex
# warnings.filterwarnings('ignore')
quantum_solution, quantum_cost = quantum_optimizer.exact_solution()
print(quantum_solution, quantum_cost)
classical_solution, classical_cost = classical_optimizer.cplex_solution()
print(classical_solution, classical_cost)
if np.abs(quantum_cost - classical_cost) < 0.01:
print("Binary formulation is correct")
else:
print("Error in the formulation of the Hamiltonian")
except Exception as ex:
print(ex)
ground_state, ground_level = quantum_optimizer.exact_solution()
print(ground_state)
classical_cost = 1.000779571614484 # obtained from the CPLEX solution
try:
if np.abs(ground_level - classical_cost) < 0.01:
print("Ising Hamiltonian in Z basis is correct")
else:
print("Error in the Ising Hamiltonian formulation")
except Exception as ex:
print(ex)
vqe_state, vqe_level = quantum_optimizer.vqe_solution()
print(vqe_state, vqe_level)
try:
if np.linalg.norm(ground_state - vqe_state) < 0.01:
print("SamplingVQE produces the same solution as the exact eigensolver.")
else:
print(
"SamplingVQE does not produce the same solution as the exact eigensolver, but that is to be expected."
)
except Exception as ex:
print(ex)
xc, yc = data.get_coordinates()
visualize_solution(xc, yc, ground_state, ground_level, n, q, "Classical")
visualize_solution(xc, yc, vqe_state, vqe_level, n, q, "VQE")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import QuantumCircuit
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit.circuit.library import LinearAmplitudeFunction
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import LogNormalDistribution
# number of qubits to represent the uncertainty
num_uncertainty_qubits = 3
# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity
# resulting parameters for log-normal distribution
mu = (r - 0.5 * vol**2) * T + np.log(S)
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2 / 2)
variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3 * stddev)
high = mean + 3 * stddev
# construct A operator for QAE for the payoff function by
# composing the uncertainty model and the objective
uncertainty_model = LogNormalDistribution(
num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high)
)
# plot probability distribution
x = uncertainty_model.values
y = uncertainty_model.probabilities
plt.bar(x, y, width=0.2)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.grid()
plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15)
plt.ylabel("Probability ($\%$)", size=15)
plt.show()
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price = 1.896
# set the approximation scaling for the payoff function
c_approx = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [low, strike_price]
slopes = [0, 1]
offsets = [0, 0]
f_min = 0
f_max = high - strike_price
european_call_objective = LinearAmplitudeFunction(
num_uncertainty_qubits,
slopes,
offsets,
domain=(low, high),
image=(f_min, f_max),
breakpoints=breakpoints,
rescaling_factor=c_approx,
)
# construct A operator for QAE for the payoff function by
# composing the uncertainty model and the objective
num_qubits = european_call_objective.num_qubits
european_call = QuantumCircuit(num_qubits)
european_call.append(uncertainty_model, range(num_uncertainty_qubits))
european_call.append(european_call_objective, range(num_qubits))
# draw the circuit
european_call.draw()
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = uncertainty_model.values
y = np.maximum(0, x - strike_price)
plt.plot(x, y, "ro-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value (normalized to the [0, 1] interval)
exact_value = np.dot(uncertainty_model.probabilities, y)
exact_delta = sum(uncertainty_model.probabilities[x >= strike_price])
print("exact expected value:\t%.4f" % exact_value)
print("exact delta value: \t%.4f" % exact_delta)
european_call.draw()
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=european_call,
objective_qubits=[3],
post_processing=european_call_objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % exact_value)
print("Estimated value: \t%.4f" % (result.estimation_processed))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
from qiskit_finance.applications.estimation import EuropeanCallPricing
european_call_pricing = EuropeanCallPricing(
num_state_qubits=num_uncertainty_qubits,
strike_price=strike_price,
rescaling_factor=c_approx,
bounds=(low, high),
uncertainty_model=uncertainty_model,
)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = european_call_pricing.to_estimation_problem()
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % exact_value)
print("Estimated value: \t%.4f" % (european_call_pricing.interpret(result)))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
from qiskit_finance.applications.estimation import EuropeanCallDelta
european_call_delta = EuropeanCallDelta(
num_state_qubits=num_uncertainty_qubits,
strike_price=strike_price,
bounds=(low, high),
uncertainty_model=uncertainty_model,
)
european_call_delta._objective.decompose().draw()
european_call_delta_circ = QuantumCircuit(european_call_delta._objective.num_qubits)
european_call_delta_circ.append(uncertainty_model, range(num_uncertainty_qubits))
european_call_delta_circ.append(
european_call_delta._objective, range(european_call_delta._objective.num_qubits)
)
european_call_delta_circ.draw()
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = european_call_delta.to_estimation_problem()
# construct amplitude estimation
ae_delta = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_delta = ae_delta.estimate(problem)
conf_int = np.array(result_delta.confidence_interval_processed)
print("Exact delta: \t%.4f" % exact_delta)
print("Esimated value: \t%.4f" % european_call_delta.interpret(result_delta))
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit.circuit.library import LinearAmplitudeFunction
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import LogNormalDistribution
# number of qubits to represent the uncertainty
num_uncertainty_qubits = 3
# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity
# resulting parameters for log-normal distribution
mu = (r - 0.5 * vol**2) * T + np.log(S)
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2 / 2)
variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3 * stddev)
high = mean + 3 * stddev
# construct A operator for QAE for the payoff function by
# composing the uncertainty model and the objective
uncertainty_model = LogNormalDistribution(
num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high)
)
# plot probability distribution
x = uncertainty_model.values
y = uncertainty_model.probabilities
plt.bar(x, y, width=0.2)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.grid()
plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15)
plt.ylabel("Probability ($\%$)", size=15)
plt.show()
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price = 2.126
# set the approximation scaling for the payoff function
rescaling_factor = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [low, strike_price]
slopes = [-1, 0]
offsets = [strike_price - low, 0]
f_min = 0
f_max = strike_price - low
european_put_objective = LinearAmplitudeFunction(
num_uncertainty_qubits,
slopes,
offsets,
domain=(low, high),
image=(f_min, f_max),
breakpoints=breakpoints,
rescaling_factor=rescaling_factor,
)
# construct A operator for QAE for the payoff function by
# composing the uncertainty model and the objective
european_put = european_put_objective.compose(uncertainty_model, front=True)
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = uncertainty_model.values
y = np.maximum(0, strike_price - x)
plt.plot(x, y, "ro-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value (normalized to the [0, 1] interval)
exact_value = np.dot(uncertainty_model.probabilities, y)
exact_delta = -sum(uncertainty_model.probabilities[x <= strike_price])
print("exact expected value:\t%.4f" % exact_value)
print("exact delta value: \t%.4f" % exact_delta)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=european_put,
objective_qubits=[num_uncertainty_qubits],
post_processing=european_put_objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % exact_value)
print("Estimated value: \t%.4f" % (result.estimation_processed))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
# setup piecewise linear objective fcuntion
breakpoints = [low, strike_price]
slopes = [0, 0]
offsets = [1, 0]
f_min = 0
f_max = 1
european_put_delta_objective = LinearAmplitudeFunction(
num_uncertainty_qubits,
slopes,
offsets,
domain=(low, high),
image=(f_min, f_max),
breakpoints=breakpoints,
)
# construct circuit for payoff function
european_put_delta = european_put_delta_objective.compose(uncertainty_model, front=True)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=european_put_delta, objective_qubits=[num_uncertainty_qubits]
)
# construct amplitude estimation
ae_delta = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_delta = ae_delta.estimate(problem)
conf_int = -np.array(result_delta.confidence_interval)[::-1]
print("Exact delta: \t%.4f" % exact_delta)
print("Esimated value: \t%.4f" % -result_delta.estimation)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit.circuit.library import LinearAmplitudeFunction
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import LogNormalDistribution
# number of qubits to represent the uncertainty
num_uncertainty_qubits = 3
# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity
# resulting parameters for log-normal distribution
mu = (r - 0.5 * vol**2) * T + np.log(S)
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2 / 2)
variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3 * stddev)
high = mean + 3 * stddev
# construct circuit for uncertainty model
uncertainty_model = LogNormalDistribution(
num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high)
)
# plot probability distribution
x = uncertainty_model.values
y = uncertainty_model.probabilities
plt.bar(x, y, width=0.2)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.grid()
plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15)
plt.ylabel("Probability ($\%$)", size=15)
plt.show()
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price_1 = 1.438
strike_price_2 = 2.584
# set the approximation scaling for the payoff function
rescaling_factor = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [low, strike_price_1, strike_price_2]
slopes = [0, 1, 0]
offsets = [0, 0, strike_price_2 - strike_price_1]
f_min = 0
f_max = strike_price_2 - strike_price_1
bull_spread_objective = LinearAmplitudeFunction(
num_uncertainty_qubits,
slopes,
offsets,
domain=(low, high),
image=(f_min, f_max),
breakpoints=breakpoints,
rescaling_factor=rescaling_factor,
)
# construct A operator for QAE for the payoff function by
# composing the uncertainty model and the objective
bull_spread = bull_spread_objective.compose(uncertainty_model, front=True)
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = uncertainty_model.values
y = np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1)
plt.plot(x, y, "ro-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value (normalized to the [0, 1] interval)
exact_value = np.dot(uncertainty_model.probabilities, y)
exact_delta = sum(
uncertainty_model.probabilities[np.logical_and(x >= strike_price_1, x <= strike_price_2)]
)
print("exact expected value:\t%.4f" % exact_value)
print("exact delta value: \t%.4f" % exact_delta)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=bull_spread,
objective_qubits=[num_uncertainty_qubits],
post_processing=bull_spread_objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % exact_value)
print("Estimated value:\t%.4f" % result.estimation_processed)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
# setup piecewise linear objective fcuntion
breakpoints = [low, strike_price_1, strike_price_2]
slopes = [0, 0, 0]
offsets = [0, 1, 0]
f_min = 0
f_max = 1
bull_spread_delta_objective = LinearAmplitudeFunction(
num_uncertainty_qubits,
slopes,
offsets,
domain=(low, high),
image=(f_min, f_max),
breakpoints=breakpoints,
) # no approximation necessary, hence no rescaling factor
# construct the A operator by stacking the uncertainty model and payoff function together
bull_spread_delta = bull_spread_delta_objective.compose(uncertainty_model, front=True)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=bull_spread_delta, objective_qubits=[num_uncertainty_qubits]
)
# construct amplitude estimation
ae_delta = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_delta = ae_delta.estimate(problem)
conf_int = np.array(result_delta.confidence_interval)
print("Exact delta: \t%.4f" % exact_delta)
print("Estimated value:\t%.4f" % result_delta.estimation)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
%matplotlib inline
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit.circuit.library import WeightedAdder, LinearAmplitudeFunction
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import LogNormalDistribution
# number of qubits per dimension to represent the uncertainty
num_uncertainty_qubits = 2
# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity
# resulting parameters for log-normal distribution
mu = (r - 0.5 * vol**2) * T + np.log(S)
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2 / 2)
variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3 * stddev)
high = mean + 3 * stddev
# map to higher dimensional distribution
# for simplicity assuming dimensions are independent and identically distributed)
dimension = 2
num_qubits = [num_uncertainty_qubits] * dimension
low = low * np.ones(dimension)
high = high * np.ones(dimension)
mu = mu * np.ones(dimension)
cov = sigma**2 * np.eye(dimension)
# construct circuit
u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=list(zip(low, high)))
# plot PDF of uncertainty model
x = [v[0] for v in u.values]
y = [v[1] for v in u.values]
z = u.probabilities
# z = map(float, z)
# z = list(map(float, z))
resolution = np.array([2**n for n in num_qubits]) * 1j
grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]]
grid_z = griddata((x, y), z, (grid_x, grid_y))
plt.figure(figsize=(10, 8))
ax = plt.axes(projection="3d")
ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral)
ax.set_xlabel("Spot Price $S_T^1$ (\$)", size=15)
ax.set_ylabel("Spot Price $S_T^2$ (\$)", size=15)
ax.set_zlabel("Probability (\%)", size=15)
plt.show()
# determine number of qubits required to represent total loss
weights = []
for n in num_qubits:
for i in range(n):
weights += [2**i]
# create aggregation circuit
agg = WeightedAdder(sum(num_qubits), weights)
n_s = agg.num_sum_qubits
n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price = 3.5
# map strike price from [low, high] to {0, ..., 2^n-1}
max_value = 2**n_s - 1
low_ = low[0]
high_ = high[0]
mapped_strike_price = (
(strike_price - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1)
)
# set the approximation scaling for the payoff function
c_approx = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [0, mapped_strike_price]
slopes = [0, 1]
offsets = [0, 0]
f_min = 0
f_max = 2 * (2**num_uncertainty_qubits - 1) - mapped_strike_price
basket_objective = LinearAmplitudeFunction(
n_s,
slopes,
offsets,
domain=(0, max_value),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
# define overall multivariate problem
qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution
qr_obj = QuantumRegister(1, "obj") # to encode the function values
ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum
ar = AncillaRegister(max(n_aux, basket_objective.num_ancillas), "work") # additional qubits
objective_index = u.num_qubits
basket_option = QuantumCircuit(qr_state, qr_obj, ar_sum, ar)
basket_option.append(u, qr_state)
basket_option.append(agg, qr_state[:] + ar_sum[:] + ar[:n_aux])
basket_option.append(basket_objective, ar_sum[:] + qr_obj[:] + ar[: basket_objective.num_ancillas])
print(basket_option.draw())
print("objective qubit index", objective_index)
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = np.linspace(sum(low), sum(high))
y = np.maximum(0, x - strike_price)
plt.plot(x, y, "r-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Sum of Spot Prices ($S_T^1 + S_T^2)$", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value
sum_values = np.sum(u.values, axis=1)
exact_value = np.dot(
u.probabilities[sum_values >= strike_price],
sum_values[sum_values >= strike_price] - strike_price,
)
print("exact expected value:\t%.4f" % exact_value)
num_state_qubits = basket_option.num_qubits - basket_option.num_ancillas
print("state qubits: ", num_state_qubits)
transpiled = transpile(basket_option, basis_gates=["u", "cx"])
print("circuit width:", transpiled.width())
print("circuit depth:", transpiled.depth())
basket_option_measure = basket_option.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(basket_option_measure)
# evaluate the result
value = 0
probabilities = job.result().quasi_dists[0].binary_probabilities()
for i, prob in probabilities.items():
if prob > 1e-4 and i[-num_state_qubits:][0] == "1":
value += prob
# map value to original range
mapped_value = (
basket_objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_)
)
print("Exact Operator Value: %.4f" % value)
print("Mapped Operator value: %.4f" % mapped_value)
print("Exact Expected Payoff: %.4f" % exact_value)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=basket_option,
objective_qubits=[objective_index],
post_processing=basket_objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = (
np.array(result.confidence_interval_processed)
/ (2**num_uncertainty_qubits - 1)
* (high_ - low_)
)
print("Exact value: \t%.4f" % exact_value)
print(
"Estimated value: \t%.4f"
% (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_))
)
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
%matplotlib inline
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile
from qiskit.circuit.library import IntegerComparator, WeightedAdder, LinearAmplitudeFunction
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import LogNormalDistribution
# number of qubits per dimension to represent the uncertainty
num_uncertainty_qubits = 2
# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity
# resulting parameters for log-normal distribution
mu = (r - 0.5 * vol**2) * T + np.log(S)
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2 / 2)
variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3 * stddev)
high = mean + 3 * stddev
# map to higher dimensional distribution
# for simplicity assuming dimensions are independent and identically distributed)
dimension = 2
num_qubits = [num_uncertainty_qubits] * dimension
low = low * np.ones(dimension)
high = high * np.ones(dimension)
mu = mu * np.ones(dimension)
cov = sigma**2 * np.eye(dimension)
# construct circuit
u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=(list(zip(low, high))))
# plot PDF of uncertainty model
x = [v[0] for v in u.values]
y = [v[1] for v in u.values]
z = u.probabilities
# z = map(float, z)
# z = list(map(float, z))
resolution = np.array([2**n for n in num_qubits]) * 1j
grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]]
grid_z = griddata((x, y), z, (grid_x, grid_y))
plt.figure(figsize=(10, 8))
ax = plt.axes(projection="3d")
ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral)
ax.set_xlabel("Spot Price $S_1$ (\$)", size=15)
ax.set_ylabel("Spot Price $S_2$ (\$)", size=15)
ax.set_zlabel("Probability (\%)", size=15)
plt.show()
# determine number of qubits required to represent total loss
weights = []
for n in num_qubits:
for i in range(n):
weights += [2**i]
# create aggregation circuit
agg = WeightedAdder(sum(num_qubits), weights)
n_s = agg.num_sum_qubits
n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price_1 = 3
strike_price_2 = 4
# set the barrier threshold
barrier = 2.5
# map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1}
max_value = 2**n_s - 1
low_ = low[0]
high_ = high[0]
mapped_strike_price_1 = (
(strike_price_1 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1)
)
mapped_strike_price_2 = (
(strike_price_2 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1)
)
mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1)
# condition and condition result
conditions = []
barrier_thresholds = [2] * dimension
n_aux_conditions = 0
for i in range(dimension):
# target dimension of random distribution and corresponding condition (which is required to be True)
comparator = IntegerComparator(num_qubits[i], mapped_barrier[i] + 1, geq=False)
n_aux_conditions = max(n_aux_conditions, comparator.num_ancillas)
conditions += [comparator]
# set the approximation scaling for the payoff function
c_approx = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2]
slopes = [0, 1, 0]
offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1]
f_min = 0
f_max = mapped_strike_price_2 - mapped_strike_price_1
objective = LinearAmplitudeFunction(
n_s,
slopes,
offsets,
domain=(0, max_value),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
# define overall multivariate problem
qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution
qr_obj = QuantumRegister(1, "obj") # to encode the function values
ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum
ar_cond = AncillaRegister(len(conditions) + 1, "conditions")
ar = AncillaRegister(
max(n_aux, n_aux_conditions, objective.num_ancillas), "work"
) # additional qubits
objective_index = u.num_qubits
# define the circuit
asian_barrier_spread = QuantumCircuit(qr_state, qr_obj, ar_cond, ar_sum, ar)
# load the probability distribution
asian_barrier_spread.append(u, qr_state)
# apply the conditions
for i, cond in enumerate(conditions):
state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))]
asian_barrier_spread.append(cond, state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas])
# aggregate the conditions on a single qubit
asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1])
# apply the aggregation function controlled on the condition
asian_barrier_spread.append(agg.control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux])
# apply the payoff function
asian_barrier_spread.append(objective, ar_sum[:] + qr_obj[:] + ar[: objective.num_ancillas])
# uncompute the aggregation
asian_barrier_spread.append(
agg.inverse().control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux]
)
# uncompute the conditions
asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1])
for j, cond in enumerate(reversed(conditions)):
i = len(conditions) - j - 1
state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))]
asian_barrier_spread.append(
cond.inverse(), state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas]
)
print(asian_barrier_spread.draw())
print("objective qubit index", objective_index)
# plot exact payoff function
plt.figure(figsize=(7, 5))
x = np.linspace(sum(low), sum(high))
y = (x <= 5) * np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1)
plt.plot(x, y, "r-")
plt.grid()
plt.title("Payoff Function (for $S_1 = S_2$)", size=15)
plt.xlabel("Sum of Spot Prices ($S_1 + S_2)$", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# plot contour of payoff function with respect to both time steps, including barrier
plt.figure(figsize=(7, 5))
z = np.zeros((17, 17))
x = np.linspace(low[0], high[0], 17)
y = np.linspace(low[1], high[1], 17)
for i, x_ in enumerate(x):
for j, y_ in enumerate(y):
z[i, j] = np.minimum(
np.maximum(0, x_ + y_ - strike_price_1), strike_price_2 - strike_price_1
)
if x_ > barrier or y_ > barrier:
z[i, j] = 0
plt.title("Payoff Function", size=15)
plt.contourf(x, y, z)
plt.colorbar()
plt.xlabel("Spot Price $S_1$", size=15)
plt.ylabel("Spot Price $S_2$", size=15)
plt.xticks(size=15)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value
sum_values = np.sum(u.values, axis=1)
payoff = np.minimum(np.maximum(sum_values - strike_price_1, 0), strike_price_2 - strike_price_1)
leq_barrier = [np.max(v) <= barrier for v in u.values]
exact_value = np.dot(u.probabilities[leq_barrier], payoff[leq_barrier])
print("exact expected value:\t%.4f" % exact_value)
num_state_qubits = asian_barrier_spread.num_qubits - asian_barrier_spread.num_ancillas
print("state qubits: ", num_state_qubits)
transpiled = transpile(asian_barrier_spread, basis_gates=["u", "cx"])
print("circuit width:", transpiled.width())
print("circuit depth:", transpiled.depth())
asian_barrier_spread_measure = asian_barrier_spread.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(asian_barrier_spread_measure)
# evaluate the result
value = 0
probabilities = job.result().quasi_dists[0].binary_probabilities()
for i, prob in probabilities.items():
if prob > 1e-4 and i[-num_state_qubits:][0] == "1":
value += prob
# map value to original range
mapped_value = objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_)
print("Exact Operator Value: %.4f" % value)
print("Mapped Operator value: %.4f" % mapped_value)
print("Exact Expected Payoff: %.4f" % exact_value)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=asian_barrier_spread,
objective_qubits=[objective_index],
post_processing=objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}))
result = ae.estimate(problem)
conf_int = (
np.array(result.confidence_interval_processed)
/ (2**num_uncertainty_qubits - 1)
* (high_ - low_)
)
print("Exact value: \t%.4f" % exact_value)
print(
"Estimated value:\t%.4f"
% (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_))
)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import QuantumCircuit
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import NormalDistribution
# can be used in case a principal component analysis has been done to derive the uncertainty model, ignored in this example.
A = np.eye(2)
b = np.zeros(2)
# specify the number of qubits that are used to represent the different dimenions of the uncertainty model
num_qubits = [2, 2]
# specify the lower and upper bounds for the different dimension
low = [0, 0]
high = [0.12, 0.24]
mu = [0.12, 0.24]
sigma = 0.01 * np.eye(2)
# construct corresponding distribution
bounds = list(zip(low, high))
u = NormalDistribution(num_qubits, mu, sigma, bounds)
# plot contour of probability density function
x = np.linspace(low[0], high[0], 2 ** num_qubits[0])
y = np.linspace(low[1], high[1], 2 ** num_qubits[1])
z = u.probabilities.reshape(2 ** num_qubits[0], 2 ** num_qubits[1])
plt.contourf(x, y, z)
plt.xticks(x, size=15)
plt.yticks(y, size=15)
plt.grid()
plt.xlabel("$r_1$ (%)", size=15)
plt.ylabel("$r_2$ (%)", size=15)
plt.colorbar()
plt.show()
# specify cash flow
cf = [1.0, 2.0]
periods = range(1, len(cf) + 1)
# plot cash flow
plt.bar(periods, cf)
plt.xticks(periods, size=15)
plt.yticks(size=15)
plt.grid()
plt.xlabel("periods", size=15)
plt.ylabel("cashflow ($)", size=15)
plt.show()
# estimate real value
cnt = 0
exact_value = 0.0
for x1 in np.linspace(low[0], high[0], pow(2, num_qubits[0])):
for x2 in np.linspace(low[1], high[1], pow(2, num_qubits[1])):
prob = u.probabilities[cnt]
for t in range(len(cf)):
# evaluate linear approximation of real value w.r.t. interest rates
exact_value += prob * (
cf[t] / pow(1 + b[t], t + 1)
- (t + 1) * cf[t] * np.dot(A[:, t], np.asarray([x1, x2])) / pow(1 + b[t], t + 2)
)
cnt += 1
print("Exact value: \t%.4f" % exact_value)
# specify approximation factor
c_approx = 0.125
# create fixed income pricing application
from qiskit_finance.applications.estimation import FixedIncomePricing
fixed_income = FixedIncomePricing(
num_qubits=num_qubits,
pca_matrix=A,
initial_interests=b,
cash_flow=cf,
rescaling_factor=c_approx,
bounds=bounds,
uncertainty_model=u,
)
fixed_income._objective.draw()
fixed_income_circ = QuantumCircuit(fixed_income._objective.num_qubits)
# load probability distribution
fixed_income_circ.append(u, range(u.num_qubits))
# apply function
fixed_income_circ.append(fixed_income._objective, range(fixed_income._objective.num_qubits))
fixed_income_circ.draw()
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
# construct amplitude estimation
problem = fixed_income.to_estimation_problem()
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % exact_value)
print("Estimated value: \t%.4f" % (fixed_income.interpret(result)))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import IntegerComparator
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
# set problem parameters
n_z = 2
z_max = 2
z_values = np.linspace(-z_max, z_max, 2**n_z)
p_zeros = [0.15, 0.25]
rhos = [0.1, 0.05]
lgd = [1, 2]
K = len(p_zeros)
alpha = 0.05
from qiskit_finance.circuit.library import GaussianConditionalIndependenceModel as GCI
u = GCI(n_z, z_max, p_zeros, rhos)
u.draw()
u_measure = u.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(u_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# analyze uncertainty circuit and determine exact solutions
p_z = np.zeros(2**n_z)
p_default = np.zeros(K)
values = []
probabilities = []
num_qubits = u.num_qubits
for i, prob in binary_probabilities.items():
# extract value of Z and corresponding probability
i_normal = int(i[-n_z:], 2)
p_z[i_normal] += prob
# determine overall default probability for k
loss = 0
for k in range(K):
if i[K - k - 1] == "1":
p_default[k] += prob
loss += lgd[k]
values += [loss]
probabilities += [prob]
values = np.array(values)
probabilities = np.array(probabilities)
expected_loss = np.dot(values, probabilities)
losses = np.sort(np.unique(values))
pdf = np.zeros(len(losses))
for i, v in enumerate(losses):
pdf[i] += sum(probabilities[values == v])
cdf = np.cumsum(pdf)
i_var = np.argmax(cdf >= 1 - alpha)
exact_var = losses[i_var]
exact_cvar = np.dot(pdf[(i_var + 1) :], losses[(i_var + 1) :]) / sum(pdf[(i_var + 1) :])
print("Expected Loss E[L]: %.4f" % expected_loss)
print("Value at Risk VaR[L]: %.4f" % exact_var)
print("P[L <= VaR[L]]: %.4f" % cdf[exact_var])
print("Conditional Value at Risk CVaR[L]: %.4f" % exact_cvar)
# plot loss PDF, expected loss, var, and cvar
plt.bar(losses, pdf)
plt.axvline(expected_loss, color="green", linestyle="--", label="E[L]")
plt.axvline(exact_var, color="orange", linestyle="--", label="VaR(L)")
plt.axvline(exact_cvar, color="red", linestyle="--", label="CVaR(L)")
plt.legend(fontsize=15)
plt.xlabel("Loss L ($)", size=15)
plt.ylabel("probability (%)", size=15)
plt.title("Loss Distribution", size=20)
plt.xticks(size=15)
plt.yticks(size=15)
plt.show()
# plot results for Z
plt.plot(z_values, p_z, "o-", linewidth=3, markersize=8)
plt.grid()
plt.xlabel("Z value", size=15)
plt.ylabel("probability (%)", size=15)
plt.title("Z Distribution", size=20)
plt.xticks(size=15)
plt.yticks(size=15)
plt.show()
# plot results for default probabilities
plt.bar(range(K), p_default)
plt.xlabel("Asset", size=15)
plt.ylabel("probability (%)", size=15)
plt.title("Individual Default Probabilities", size=20)
plt.xticks(range(K), size=15)
plt.yticks(size=15)
plt.grid()
plt.show()
# add Z qubits with weight/loss 0
from qiskit.circuit.library import WeightedAdder
agg = WeightedAdder(n_z + K, [0] * n_z + lgd)
from qiskit.circuit.library import LinearAmplitudeFunction
# define linear objective function
breakpoints = [0]
slopes = [1]
offsets = [0]
f_min = 0
f_max = sum(lgd)
c_approx = 0.25
objective = LinearAmplitudeFunction(
agg.num_sum_qubits,
slope=slopes,
offset=offsets,
# max value that can be reached by the qubit register (will not always be reached)
domain=(0, 2**agg.num_sum_qubits - 1),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
# define the registers for convenience and readability
qr_state = QuantumRegister(u.num_qubits, "state")
qr_sum = QuantumRegister(agg.num_sum_qubits, "sum")
qr_carry = QuantumRegister(agg.num_carry_qubits, "carry")
qr_obj = QuantumRegister(1, "objective")
# define the circuit
state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A")
# load the random variable
state_preparation.append(u.to_gate(), qr_state)
# aggregate
state_preparation.append(agg.to_gate(), qr_state[:] + qr_sum[:] + qr_carry[:])
# linear objective function
state_preparation.append(objective.to_gate(), qr_sum[:] + qr_obj[:])
# uncompute aggregation
state_preparation.append(agg.to_gate().inverse(), qr_state[:] + qr_sum[:] + qr_carry[:])
# draw the circuit
state_preparation.draw()
state_preparation_measure = state_preparation.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(state_preparation_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# evaluate the result
value = 0
for i, prob in binary_probabilities.items():
if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1":
value += prob
print("Exact Expected Loss: %.4f" % expected_loss)
print("Exact Operator Value: %.4f" % value)
print("Mapped Operator value: %.4f" % objective.post_processing(value))
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=state_preparation,
objective_qubits=[len(qr_state)],
post_processing=objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
# print results
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % expected_loss)
print("Estimated value:\t%.4f" % result.estimation_processed)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
# set x value to estimate the CDF
x_eval = 2
comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False)
comparator.draw()
def get_cdf_circuit(x_eval):
# define the registers for convenience and readability
qr_state = QuantumRegister(u.num_qubits, "state")
qr_sum = QuantumRegister(agg.num_sum_qubits, "sum")
qr_carry = QuantumRegister(agg.num_carry_qubits, "carry")
qr_obj = QuantumRegister(1, "objective")
qr_compare = QuantumRegister(1, "compare")
# define the circuit
state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A")
# load the random variable
state_preparation.append(u, qr_state)
# aggregate
state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:])
# comparator objective function
comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False)
state_preparation.append(comparator, qr_sum[:] + qr_obj[:] + qr_carry[:])
# uncompute aggregation
state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:])
return state_preparation
state_preparation = get_cdf_circuit(x_eval)
state_preparation.draw()
state_preparation_measure = state_preparation.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(state_preparation_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# evaluate the result
var_prob = 0
for i, prob in binary_probabilities.items():
if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1":
var_prob += prob
print("Operator CDF(%s)" % x_eval + " = %.4f" % var_prob)
print("Exact CDF(%s)" % x_eval + " = %.4f" % cdf[x_eval])
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_state)])
# construct amplitude estimation
ae_cdf = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_cdf = ae_cdf.estimate(problem)
# print results
conf_int = np.array(result_cdf.confidence_interval)
print("Exact value: \t%.4f" % cdf[x_eval])
print("Estimated value:\t%.4f" % result_cdf.estimation)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
def run_ae_for_cdf(x_eval, epsilon=0.01, alpha=0.05, simulator="aer_simulator"):
# construct amplitude estimation
state_preparation = get_cdf_circuit(x_eval)
problem = EstimationProblem(
state_preparation=state_preparation, objective_qubits=[len(qr_state)]
)
ae_var = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_var = ae_var.estimate(problem)
return result_var.estimation
def bisection_search(
objective, target_value, low_level, high_level, low_value=None, high_value=None
):
"""
Determines the smallest level such that the objective value is still larger than the target
:param objective: objective function
:param target: target value
:param low_level: lowest level to be considered
:param high_level: highest level to be considered
:param low_value: value of lowest level (will be evaluated if set to None)
:param high_value: value of highest level (will be evaluated if set to None)
:return: dictionary with level, value, num_eval
"""
# check whether low and high values are given and evaluated them otherwise
print("--------------------------------------------------------------------")
print("start bisection search for target value %.3f" % target_value)
print("--------------------------------------------------------------------")
num_eval = 0
if low_value is None:
low_value = objective(low_level)
num_eval += 1
if high_value is None:
high_value = objective(high_level)
num_eval += 1
# check if low_value already satisfies the condition
if low_value > target_value:
return {
"level": low_level,
"value": low_value,
"num_eval": num_eval,
"comment": "returned low value",
}
elif low_value == target_value:
return {"level": low_level, "value": low_value, "num_eval": num_eval, "comment": "success"}
# check if high_value is above target
if high_value < target_value:
return {
"level": high_level,
"value": high_value,
"num_eval": num_eval,
"comment": "returned low value",
}
elif high_value == target_value:
return {
"level": high_level,
"value": high_value,
"num_eval": num_eval,
"comment": "success",
}
# perform bisection search until
print("low_level low_value level value high_level high_value")
print("--------------------------------------------------------------------")
while high_level - low_level > 1:
level = int(np.round((high_level + low_level) / 2.0))
num_eval += 1
value = objective(level)
print(
"%2d %.3f %2d %.3f %2d %.3f"
% (low_level, low_value, level, value, high_level, high_value)
)
if value >= target_value:
high_level = level
high_value = value
else:
low_level = level
low_value = value
# return high value after bisection search
print("--------------------------------------------------------------------")
print("finished bisection search")
print("--------------------------------------------------------------------")
return {"level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success"}
# run bisection search to determine VaR
objective = lambda x: run_ae_for_cdf(x)
bisection_result = bisection_search(
objective, 1 - alpha, min(losses) - 1, max(losses), low_value=0, high_value=1
)
var = bisection_result["level"]
print("Estimated Value at Risk: %2d" % var)
print("Exact Value at Risk: %2d" % exact_var)
print("Estimated Probability: %.3f" % bisection_result["value"])
print("Exact Probability: %.3f" % cdf[exact_var])
# define linear objective
breakpoints = [0, var]
slopes = [0, 1]
offsets = [0, 0] # subtract VaR and add it later to the estimate
f_min = 0
f_max = 3 - var
c_approx = 0.25
cvar_objective = LinearAmplitudeFunction(
agg.num_sum_qubits,
slopes,
offsets,
domain=(0, 2**agg.num_sum_qubits - 1),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
cvar_objective.draw()
# define the registers for convenience and readability
qr_state = QuantumRegister(u.num_qubits, "state")
qr_sum = QuantumRegister(agg.num_sum_qubits, "sum")
qr_carry = QuantumRegister(agg.num_carry_qubits, "carry")
qr_obj = QuantumRegister(1, "objective")
qr_work = QuantumRegister(cvar_objective.num_ancillas - len(qr_carry), "work")
# define the circuit
state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, qr_work, name="A")
# load the random variable
state_preparation.append(u, qr_state)
# aggregate
state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:])
# linear objective function
state_preparation.append(cvar_objective, qr_sum[:] + qr_obj[:] + qr_carry[:] + qr_work[:])
# uncompute aggregation
state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:])
state_preparation_measure = state_preparation.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(state_preparation_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# evaluate the result
value = 0
for i, prob in binary_probabilities.items():
if prob > 1e-6 and i[-(len(qr_state) + 1)] == "1":
value += prob
# normalize and add VaR to estimate
value = cvar_objective.post_processing(value)
d = 1.0 - bisection_result["value"]
v = value / d if d != 0 else 0
normalized_value = v + var
print("Estimated CVaR: %.4f" % normalized_value)
print("Exact CVaR: %.4f" % exact_cvar)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=state_preparation,
objective_qubits=[len(qr_state)],
post_processing=cvar_objective.post_processing,
)
# construct amplitude estimation
ae_cvar = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_cvar = ae_cvar.estimate(problem)
# print results
d = 1.0 - bisection_result["value"]
v = result_cvar.estimation_processed / d if d != 0 else 0
print("Exact CVaR: \t%.4f" % exact_cvar)
print("Estimated CVaR:\t%.4f" % (v + var))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
import numpy as np
from qiskit.circuit import ParameterVector
from qiskit.circuit.library import TwoLocal
from qiskit.quantum_info import Statevector
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.applications.estimation import EuropeanCallPricing
from qiskit_finance.circuit.library import NormalDistribution
# Set upper and lower data values
bounds = np.array([0.0, 7.0])
# Set number of qubits used in the uncertainty model
num_qubits = 3
# Load the trained circuit parameters
g_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225]
# Set an initial state for the generator circuit
init_dist = NormalDistribution(num_qubits, mu=1.0, sigma=1.0, bounds=bounds)
# construct the variational form
var_form = TwoLocal(num_qubits, "ry", "cz", entanglement="circular", reps=1)
# keep a list of the parameters so we can associate them to the list of numerical values
# (otherwise we need a dictionary)
theta = var_form.ordered_parameters
# compose the generator circuit, this is the circuit loading the uncertainty model
g_circuit = init_dist.compose(var_form)
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price = 2
# set the approximation scaling for the payoff function
c_approx = 0.25
# Evaluate trained probability distribution
values = [
bounds[0] + (bounds[1] - bounds[0]) * x / (2**num_qubits - 1) for x in range(2**num_qubits)
]
uncertainty_model = g_circuit.assign_parameters(dict(zip(theta, g_params)))
amplitudes = Statevector.from_instruction(uncertainty_model).data
x = np.array(values)
y = np.abs(amplitudes) ** 2
# Sample from target probability distribution
N = 100000
log_normal = np.random.lognormal(mean=1, sigma=1, size=N)
log_normal = np.round(log_normal)
log_normal = log_normal[log_normal <= 7]
log_normal_samples = []
for i in range(8):
log_normal_samples += [np.sum(log_normal == i)]
log_normal_samples = np.array(log_normal_samples / sum(log_normal_samples))
# Plot distributions
plt.bar(x, y, width=0.2, label="trained distribution", color="royalblue")
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.grid()
plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15)
plt.ylabel("Probability ($\%$)", size=15)
plt.plot(
log_normal_samples,
"-o",
color="deepskyblue",
label="target distribution",
linewidth=4,
markersize=12,
)
plt.legend(loc="best")
plt.show()
# Evaluate payoff for different distributions
payoff = np.array([0, 0, 0, 1, 2, 3, 4, 5])
ep = np.dot(log_normal_samples, payoff)
print("Analytically calculated expected payoff w.r.t. the target distribution: %.4f" % ep)
ep_trained = np.dot(y, payoff)
print("Analytically calculated expected payoff w.r.t. the trained distribution: %.4f" % ep_trained)
# Plot exact payoff function (evaluated on the grid of the trained uncertainty model)
x = np.array(values)
y_strike = np.maximum(0, x - strike_price)
plt.plot(x, y_strike, "ro-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# construct circuit for payoff function
european_call_pricing = EuropeanCallPricing(
num_qubits,
strike_price=strike_price,
rescaling_factor=c_approx,
bounds=bounds,
uncertainty_model=uncertainty_model,
)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = european_call_pricing.to_estimation_problem()
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % ep_trained)
print("Estimated value: \t%.4f" % (result.estimation_processed))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.