repo
stringclasses 900
values | file
stringclasses 754
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/derek-wang-ibm/coding-with-qiskit
|
derek-wang-ibm
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit.classical import expr
def get_dynamic_CNOT_circuit(num_qubit):
"""
(1) 1D chain of nearest neighbors
(2) 0th qubit is the control, and the last qubit (num_qubit-1) is the target
(3) The control qubit starts in the + state
"""
num_ancilla = num_qubit - 2
num_ancilla_pair = int(num_ancilla / 2)
qr = QuantumRegister(num_qubit)
cr1 = ClassicalRegister(num_ancilla_pair, name="cr1") # The parity-controlled X gate
cr2 = ClassicalRegister(num_ancilla - num_ancilla_pair, name="cr2") # The parity-controlled Z gate
cr3 = ClassicalRegister(2, name="cr3") # For the final measurements on the control and target qubits
qc = QuantumCircuit(qr, cr1, cr2, cr3)
# Initialize the control qubit
qc.h(0)
qc.barrier()
# Entangle the contorl qubit and the first ancilla qubit
qc.cx(0,1)
# Create Bell pairs on ancilla qubits
# The first ancilla qubit in index 1
for i in range(num_ancilla_pair):
qc.h(2+2*i)
qc.cx(2+2*i, 2+2*i+1)
# Prepare Bell pairs on staggered ancilla and data qubits
for i in range(num_ancilla_pair+1):
qc.cx(1+2*i, 1+2*i+1)
for i in range(1, num_ancilla_pair+2):
qc.h(2*i-1)
# Measurement on alternating ancilla qubits starting with the first one
# Keep track of the parity for eventual conditional Z gate
for i in range(1, num_ancilla_pair+2):
qc.measure(2*i - 1, cr2[i-1])
if i == 1:
parity_control = expr.lift(cr2[i-1])
else:
parity_control = expr.bit_xor(cr2[i-1], parity_control)
# Measurement on staggered alternating ancilla qubits starting with the second
# Keep track of the parity of eventual conditional X gate
for i in range(num_ancilla_pair):
qc.measure(2*i + 2, cr1[i])
if i == 0:
parity_target = expr.lift(cr1[i])
else:
parity_target = expr.bit_xor(cr1[i], parity_target)
with qc.if_test(parity_control):
qc.z(0)
with qc.if_test(parity_target):
qc.x(-1)
# Final measurements on the control and target qubits
qc.measure(0, cr3[0])
qc.measure(-1, cr3[1])
return qc
qc = get_dynamic_CNOT_circuit(num_qubit=7)
qc.draw(output='mpl')
max_num_qubit = 41
qc_list = []
num_qubit_list = list(range(7, max_num_qubit+1, 2))
for num_qubit in num_qubit_list:
qc_list.append(get_dynamic_CNOT_circuit(num_qubit))
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = service.backend(name='ibm_cusco')
pm = generate_preset_pass_manager(optimization_level=1, backend=backend)
qc_transpiled_list = pm.run(qc_list)
from qiskit_ibm_runtime import SamplerV2 as Sampler
sampler = Sampler(backend=backend)
job = sampler.run(qc_transpiled_list)
print(job.job_id())
import matplotlib.pyplot as plt
from qiskit_ibm_runtime import QiskitRuntimeService
job_id = 'crbf06rc90400089gk8g' # Cusco, documentation provider, max_qubit=41, new image
service = QiskitRuntimeService()
job = service.job(job_id)
result = job.result()
list_Bell = []
list_other = []
for i in range(0, len(qc_list)):
data = result[i].data
counts = data.cr3.get_counts()
total_counts = data.cr3.num_shots
prob_Bell = (counts['00'] + counts['11']) / total_counts
list_Bell.append(prob_Bell)
list_other.append(1-prob_Bell)
plt.plot(num_qubit_list, list_Bell, '--o', label='00 or 11')
plt.plot(num_qubit_list, list_other, '-.^', label='other')
plt.xlabel('Number of qubits')
plt.ylabel('Probability')
plt.legend()
|
https://github.com/derek-wang-ibm/coding-with-qiskit
|
derek-wang-ibm
|
from qiskit import QuantumCircuit, transpile
qc = QuantumCircuit(2)
qc.reset(0)
qc.x(0)
qc.cx(0, 1)
qc.reset(0)
qc.reset(0)
qc.h(0)
qc.draw(output='mpl')
qc_basic_transpile = transpile(qc, optimization_level=3)
qc_basic_transpile.draw(output='mpl', style='iqp')
from qiskit.transpiler.passes.optimization.remove_reset_in_zero_state import RemoveResetInZeroState
from qiskit.converters import circuit_to_dag, dag_to_circuit
remove_reset = RemoveResetInZeroState()
remove_reset(qc).draw('mpl')
from dynacir.dynacir_passes import CollectResets
collect_resets = CollectResets()
circuit_with_less_resets = collect_resets(qc)
circuit_with_less_resets.draw(output='mpl')
!pip install git+https://github.com/derek-wang-ibm/dynacir.git
from qiskit.transpiler.preset_passmanagers.plugin import list_stage_plugins
print(list_stage_plugins("optimization"))
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
pm = generate_preset_pass_manager(optimization_level=3, optimization_method="dynacir"
)
qc_dynacir = pm.run(qc)
qc_dynacir.draw(output='mpl', style='iqp')
|
https://github.com/qiskit-community/qiskit_rng
|
qiskit-community
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# (C) Copyright CQC 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the Programs
# directory of this source 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.
"""Module for random number generator."""
import logging
import pickle
import uuid
import os
from itertools import product
from typing import List, Tuple, Callable, Optional, Any, Union
from qiskit import QuantumCircuit, transpile, assemble
from qiskit.providers.basebackend import BaseBackend
from qiskit.providers.basejob import BaseJob
from qiskit.providers.ibmq.ibmqbackend import IBMQBackend
from qiskit.providers.ibmq.managed.ibmqjobmanager import IBMQJobManager, ManagedJobSet
from qiskit.providers.ibmq.accountprovider import AccountProvider
from .generator_job import GeneratorJob
from .utils import generate_wsr
try:
from qiskit.providers.backend import Backend
HAS_V2_BACKEND = True
except ImportError:
HAS_V2_BACKEND = False
logger = logging.getLogger(__name__)
class Generator:
"""Class for generating random numbers.
You can use the :meth:`sample` method to run quantum circuits on a backend
to generate random bits. When the circuit jobs finish and their results
processed, you can examine the generated random bits as well as the
bell values. An example of this flow::
from qiskit import IBMQ
from qiskit_rng import Generator
provider = IBMQ.load_account()
generator = Generator(backend=provider.backends.ibmq_valencia)
output = generator.sample(num_raw_bits=1024).block_until_ready()
print("Mermin correlator value is {}".format(output.mermin_correlator))
print("first 8 raw bits are {}".format(output.raw_bits[:8]))
Note that due to the way the circuits are constructed and executed, the resulting
size of ``raw_bits`` might be slightly larger than the input ``num_raw_bits``.
The bits generated by the :meth:`sample` method are only weakly random. You
will need to apply a randomness extractor to this output in order to obtain
a more uniformly distributed string of random bits.
"""
_file_prefix = "qiskit_rng"
_job_tag = 'qiskit_rng'
def __init__(
self,
backend: BaseBackend,
wsr_generator: Optional[Callable] = None,
noise_model: Any = None,
save_local: bool = False
) -> None:
"""Generator constructor.
Args:
backend: Backend to use for generating random numbers.
wsr_generator: Function used to generate WSR. It must take the
number of bits as the input and a list of random bits (0s and 1s)
as the output. If ``None``, :func:`qiskit_rng.generate_wsr` is used.
noise_model: Noise model to use. Only applicable if `backend` is a
simulator.
save_local: If ``True``, the generated WSR and other metadata is
saved into a pickle file in the local directory. The file can
be used to recover and resume a sampling if needed.
The file name will be in the format of
``qiskit_rng_<backend>_<num_raw_bits>_<id>``.
The file will be deleted automatically when the corresponding
:meth:`GeneratorJob.block_until_ready()` method is invoked.
Only supported if `backend` is an ``IBMQBackend``.
"""
self.backend = backend
self.job_manager = IBMQJobManager()
self.wsr_generator = wsr_generator or generate_wsr
self.noise_model = noise_model
self.save_local = save_local
def sample(
self,
num_raw_bits: int
) -> GeneratorJob:
"""Use the target system to generate raw bit strings.
Args:
num_raw_bits: Number of raw bits to sample. Note that the raw
bits are only weakly random and needs to go through extraction
to generate highly random output.
Returns:
A :class:`GeneratorJob` instance that contains all the information
needed to extract randomness.
Raises:
ValueError: If an input argument is invalid.
"""
if not isinstance(self.backend, BaseBackend) and \
(HAS_V2_BACKEND and not isinstance(self.backend, Backend)):
raise ValueError("Backend needs to be a Qiskit `BaseBackend` or `Backend` instance.")
max_shots = self.backend.configuration().max_shots
num_raw_bits_qubit = int((num_raw_bits + 2)/3)
if num_raw_bits_qubit <= max_shots:
shots = num_raw_bits_qubit
num_circuits = 1
else:
num_circuits = int((num_raw_bits_qubit + max_shots - 1)/max_shots)
shots = int((num_raw_bits_qubit + num_circuits - 1)/num_circuits)
logger.debug("Using %s circuits with %s shots each", num_circuits, shots)
initial_wsr = self.wsr_generator(num_circuits * 3)
wsr_bits = self._get_wsr(num_circuits, initial_wsr)
circuits = self._generate_all_circuits(num_circuits, wsr_bits)
job = self._run_circuits(circuits, shots)
saved_fn = None
if self.save_local and isinstance(self.backend, IBMQBackend):
saved_fn = self._save_local(num_raw_bits, wsr_bits, job, shots)
return GeneratorJob(
initial_wsr=initial_wsr,
wsr=wsr_bits,
job=job,
shots=shots,
saved_fn=saved_fn
)
def _run_circuits(
self,
circuits: List[QuantumCircuit],
shots: int
) -> Union[ManagedJobSet, BaseJob]:
"""Run circuits on a backend.
Args:
circuits: Circuits to run.
shots: Number of shots.
Returns:
An IBMQ managed job set or a job.
"""
transpiled = transpile(circuits, backend=self.backend, optimization_level=2)
transpiled = [transpiled] if not isinstance(transpiled, list) else transpiled
if isinstance(self.backend, IBMQBackend):
job = self.job_manager.run(transpiled, backend=self.backend, shots=shots,
job_tags=[self._job_tag], memory=True)
logger.info("Jobs submitted to %s. Job set ID is %s.", self.backend, job.job_set_id())
else:
job = self.backend.run(assemble(transpiled, backend=self.backend, shots=shots,
memory=True, noise_model=self.noise_model))
logger.info("Jobs submitted to %s. Job ID is %s.", self.backend, job.job_id())
return job
def _get_wsr(self, num_circuits: int, initial_wsr: List[int]) -> List:
"""Obtain the weak source of randomness bits used to generate circuits.
Args:
num_circuits: Number of circuits.
initial_wsr: Raw WSR bits used to generate the output WSR.
Returns:
A list the size of `num_circuits`. Each element in the
list is another list of 3 binary numbers.
For example,
[ [1, 0, 0], [0, 1, 1], [1, 1, 0], ...]
"""
output_wsr = []
for i in range(num_circuits):
output_wsr.append(
[int(initial_wsr[3*i]), int(initial_wsr[3*i+1]), int(initial_wsr[3*i+2])])
return output_wsr
def _generate_circuit(self, label: Tuple[int, int, int]) -> QuantumCircuit:
"""Generate a circuit based on the input label.
The size of the input label determines the number of qubits.
An ``sdg`` is added to the circuit for the qubit if the corresponding
label value is a ``1``.
Args:
label: Label used to determine how the circuit is to be constructed.
A tuple of 1s and 0s.
Returns:
Constructed circuit.
"""
num_qubit = len(label)
qc = QuantumCircuit(num_qubit, num_qubit)
qc.h(0)
for i in range(1, num_qubit):
qc.cx(0, i)
qc.s(0)
qc.barrier()
for i in range(num_qubit):
if label[i] == 1:
qc.sdg(i)
for i in range(num_qubit):
qc.h(i)
qc.measure(qc.qregs[0], qc.cregs[0])
return qc
def _generate_all_circuits(self, num_circuits: int, wsr_bits: List) -> List[QuantumCircuit]:
"""Generate all circuits based on input WSR bits.
Args:
num_circuits: Number of circuits to generate.
wsr_bits: WSR bits used to determine which circuits to use.
Returns:
A list of generated circuits.
"""
# Generate 3-qubit circuits for each of the 8 permutations.
num_qubits = 3
labels = list(product([0, 1], repeat=num_qubits))
# Generate base circuits.
circuits = []
for label in labels:
circuits.append(self._generate_circuit(label))
# Construct final circuits using input WSR bits.
final_circuits = []
for i in range(num_circuits):
wsr_set = wsr_bits[i] # Get the 3-bit value.
final_circuits.append(circuits[labels.index(tuple(wsr_set))])
return final_circuits
def _save_local(
self,
num_raw_bits: int,
wsr_bits: List,
job: Union[ManagedJobSet, BaseJob],
shots: int
) -> str:
"""Save context information for the sampling.
Args:
num_raw_bits: Number of raw bits requested.
wsr_bits: WSR bits to save.
job: Job whose ID is to be saved.
shots: Number of shots.
Returns:
Name of the file with saved data.
"""
file_prefix = "{}_{}_{}_".format(
self._file_prefix, self.backend.name(), num_raw_bits)
file_name = file_prefix + str(uuid.uuid4())[:4]
while os.path.exists(file_name):
file_name = file_prefix + str(uuid.uuid4())[:4]
data = {"wsr": wsr_bits, "shots": shots}
if isinstance(job, ManagedJobSet):
data["job_id"] = job.job_set_id()
data["job_type"] = "jobset"
else:
data["job_id"] = job.job_id()
data["job_type"] = "job"
with open(file_name, 'wb') as file:
pickle.dump(data, file)
return file_name
@classmethod
def recover(cls, file_name: str, provider: AccountProvider) -> GeneratorJob:
"""Recover a previously saved sampling run.
Args:
file_name: Name of the file containing saved context.
provider: Provider used to do the sampling.
Returns:
Recovered output of the original :meth:`sample` call.
"""
with open(file_name, 'rb') as file:
data = pickle.load(file)
job_id = data['job_id']
job_type = data['job_type']
if job_type == "jobset":
job = IBMQJobManager().retrieve_job_set(job_id, provider)
else:
job = provider.backends.retrieve_job(job_id)
return GeneratorJob(
initial_wsr=[],
wsr=data['wsr'],
job=job,
shots=data["shots"],
saved_fn=file_name
)
|
https://github.com/pratjz/IBM-Qiskit-Certification-Exam-Prep
|
pratjz
|
import numpy as np
from qiskit import *
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.quantum_info import Statevector
# Load your IBM Quantum account(s)
provider = IBMQ.load_account()
# here we create the four bell states
# This statevector object do not need simulation to get the information
bell1 = QuantumCircuit(2)
bell1.h(0)
bell1.cx(0,1)
sv = Statevector.from_label('00') # here .from_label() is used, we could also use .from_int(), for more check docs!
sv_ev1 = sv.evolve(bell1) # then evolve this initial state through the circuit, What is evolve ?
sv_ev1.draw('latex')
bell2 = QuantumCircuit(2)
bell2.h(0)
bell2.cx(0,1)
bell2.z(0)
sv_ev2 = sv.evolve(bell2)
sv_ev2.draw('latex')
bell3 = QuantumCircuit(2)
bell3.h(0)
bell3.x(1)
bell3.cx(0,1)
sv_ev3 = sv.evolve(bell3)
sv_ev3.draw('latex')
bell4 = QuantumCircuit(2)
bell4.h(0)
bell4.x(1)
bell4.cx(0,1)
bell4.z(1)
sv_ev4 = sv.evolve(bell4)
sv_ev4.draw('latex')
# the Statevector object can be drawn on a qsphere
# with the .draw() method by changing the call from 'latex' to 'qsphere'
sv_ev1.draw('qsphere')
sv_ev2.draw('qsphere')
sv_ev3.draw('qsphere')
sv_ev4.draw('qsphere')
# What is GHZ State ? (Greenberger–Horne–Zeilinger state)
ghz = QuantumCircuit(3)
ghz.h(0)
ghz.cx([0,0],[1,2]) # using []s notation we can apply 2 cx gates in same statement
ghz.draw() # or use 'mpl' or 'text', leaving blank default uses mpl
sv = Statevector.from_int(0,2**3) # what is from _int ?
sv_ev = sv.evolve(ghz)
sv_ev.draw('latex')
sv = Statevector.from_label('000') #doing the same with .from_label()
sv_ev = sv.evolve(ghz)
sv_ev.draw('latex')
sv_ev.draw('qsphere')
# we can also plot hinton directly!, What is Hinton ? is similar to city graph but flat & represent matrix density distribution
sv_ev.draw('hinton')
# BasicAer has 3 main simulators:
# 1-'qasm_simulator'
# 2-'statevector_simulator'
# 3-'unitary_simulator'
BasicAer.backends()
backend_sv = BasicAer.get_backend('statevector_simulator') # get the statevector_simulator
job = execute(ghz, backend_sv, shots=1024) # specify job, which circuit to execute and how many times/shots
result = job.result() # results from the job
sv_ev2 = result.get_statevector(ghz) # get statevector from the result
# this way of getting the statevector does not have the method '.draw()' in order to visualize you need plotting functions directly
plot_state_city(sv_ev2, title='my_city',color=['red','blue'])
plot_state_hinton(sv_ev2, title='my_hinton')
plot_state_qsphere(sv_ev2)
plot_state_paulivec(sv_ev2)
plot_bloch_multivector(sv_ev2)
# The multivector as we saw plots a state coming from a circuit
# whereas the bloch_vector needs coordinate specifications the coordinates can be cartesian, or spherical
plot_bloch_vector([1,1,1]) # here for [x,y,z]; x=Tr[Xρ] and similar for y and z
q_a = QuantumRegister(1,'q_a')
q_b = QuantumRegister(1, 'q_b')
qc = QuantumCircuit(q_a, q_b)
qc.h(0)
qc.z(0)
qc.draw()
qc.measure_all() # measure_all() will create a barrier & classical register for a circuit that doesn't have one
#NOTE: this also means, if your circuit already had a classical register, it would create another one!
#so measure_all() is usually used for circuits that do not have a classical register
qasm_sim = BasicAer.get_backend('qasm_simulator')
result = execute(qc, qasm_sim).result()
counts = result.get_counts()
plot_histogram(counts)
meas = QuantumCircuit(3,3)
meas.barrier()
meas.measure([0,1,2],[0,1,2]) # here we measure respective quantum registers into respective classical registers, the ordering is important!
meas.draw('mpl')
circ = meas.compose(ghz,range(3),front=True) # compose to extend the circuit the front=True gets GHZ before the measure
circ.draw()
backend = BasicAer.get_backend('qasm_simulator')
circ = transpile(circ, backend)
job = backend.run(circ, shots=1024) #notice here we use .run instead of execute most usually we employ 'execute' though because it is more flexible
result = job.result()
counts = result.get_counts()
print(counts) #now, we could also just print our counts in an un-spectacular way compared to plotting the histograms!
import qiskit.tools.jupyter
#%qiskit_job_watcher #this creates a pop up of your jobs
from qiskit.tools import job_monitor
#quito = provider.get_backend('ibmq_quito') # to call a real backend QPU, we use 'provider' object instead of BasicAer you can check which backends are available for you too!
#job = execute(circ, quito)
#job_monitor(job)
#result = job.result()
#counts = result.get_counts()
#plot_histogram(counts)
from qiskit.quantum_info import Operator
U = Operator(ghz) # we can turn our ghz circuit from above into an operator!
U.data
# this is very similar to getting the Statevector object directly,
# if needed we can round all these numbers by using np.around and specify how many decimals we want
np.around(U.data, 3)
backend_uni = BasicAer.get_backend('unitary_simulator')
U = execute(ghz,backend_uni).result().get_unitary(decimals=3)
U
from qiskit_textbook.tools import array_to_latex
array_to_latex(U, pretext="\\text{Statevector} = ")
q = QuantumRegister(2,'q_reg')
c = ClassicalRegister(2,'c_reg')
qc = QuantumCircuit(q,c)
qc.h(q[0:2])
qc.cx(q[0], q[1])
qc.draw('mpl')
U_bell = Operator(qc)
np.around(U_bell.data,3) # rounding decimal places
a = 1/np.sqrt(3) # we can define a state ourselves, we could also get a random state,
desired_state = [a,np.sqrt(1-a**2)] # state is defined such that it is a valid one!
q_reg = QuantumRegister(2,'q')
qc = QuantumCircuit(q_reg)
qc.initialize(desired_state,1)
qc.draw('mpl')
decomp = qc.decompose()
decomp.draw() #but what is this |0> ? It is a reset! Meaning that initialize as a whole is NOT a Gate!
#It is irreversible because it has a reset! check docs for more
c_reg = ClassicalRegister(1,'c')
meas = QuantumCircuit(q_reg, c_reg)
meas.measure(0,0)
circ = meas.compose(qc, range(2), front=True)
circ.draw('mpl')
#squaring the amplitudes
alpha_squared = 0.577 ** 2
beta_squared = 0.816 ** 2
print(alpha_squared, beta_squared, alpha_squared+beta_squared)
back = BasicAer.get_backend('qasm_simulator')
job = execute(circ, back, shots=1000)
counts = job.result().get_counts()
print(counts)
plot_histogram(counts,title='test_title')
# state_fidelity
back_sv = BasicAer.get_backend('statevector_simulator')
result = execute(qc, back_sv).result()
qc_sv = result.get_statevector(qc)
qc_sv
from qiskit.quantum_info import state_fidelity
state_fidelity(desired_state, qc_sv)
# this compares the statevector we got from simulation vs the state we wanted to initialize
# here we see they match perfectly, as expected because it is a simulator on actual hardware they may not have matched so perfectly
# average_gate_fidelity
from qiskit.circuit.library import XGate
from qiskit.quantum_info import Operator, average_gate_fidelity, process_fidelity
op_a = Operator(XGate())
op_b = np.exp(1j / 2) * op_a
# these differ only by a phase so the gate and process fidelities are expected to be 1
a = average_gate_fidelity(op_a,op_b)
a
# process_fidelity
b = process_fidelity(op_a, op_b)
a == b
back_uni = BasicAer.get_backend('unitary_simulator')
job = execute(qc, back_uni)
result = job.result()
U_qc = result.get_unitary(decimals=3)
U_qc
qc = QuantumCircuit(3)
qc.mct([0,1],2) # What does it do ?
qc.cx(0,2)
qc.h(1)
qc.z(0)
qc.draw('mpl')
qc_gate = qc.to_gate()
qc_gate.name = 'my_gate_ϕ' # optionally we can give it a name!
circ = QuantumCircuit(3)
circ.append(qc_gate, [0,1,2])
circ.draw('mpl')
circ_decomp = circ.decompose() # decompose it back!
circ_decomp.draw('mpl')
from qiskit.circuit.library import HGate
ch = HGate().control(2) # specify how many controls we want
qc = QuantumCircuit(3)
qc.append(ch, [0,1,2]) # the [a,b,c] correspond to controls and target respectively
qc.draw('mpl')
# another little more complex example
circ = QuantumCircuit(4)
circ.h(range(2))
circ.cx(0,1)
circ.cx(0,3)
circ.crz(np.pi/2,0,2)
my_gate = circ.to_gate().control(2) #this
qc = QuantumCircuit(6)
qc.append(my_gate, [0,5,1,2,3,4])
qc.draw()
circ = qc.decompose()
circ.draw()
# Again simpler circuit!
qc = QuantumCircuit(3)
qc.mct([0,1],2)
qc.cx(0,2)
qc.h(1)
qc.z(0)
trans = transpile(qc, basis_gates = ['u3','cx','s'])
trans.draw('mpl')
q_a = QuantumRegister(2, 'q_a')
q_b = QuantumRegister(4, 'q_b')
c_a = ClassicalRegister(2,'c_a')
c_b = ClassicalRegister(4,'c_b')
qc = QuantumCircuit(q_a, q_b,c_a, c_b)
qc.x(0)
qc.h(1)
qc.cx(0,1)
qc.barrier()
qc.cz(0,1)
qc.cx(0,4)
qc.h(3)
qc.h(4)
qc.barrier()
qc.x(3)
qc.ccx(0,3,5)
qc.barrier()
qc.measure(q_a, c_a)
qc.measure(q_b, c_b)
qc.draw()
#Now look at all the crazy things we can do with the .draw() method! Who would've imagined!
qc.draw(reverse_bits=True, plot_barriers=False,scale=0.5, style = {'backgroundcolor': 'gray'})
from qiskit.tools.visualization import circuit_drawer
circuit_drawer(qc, output='text') # circuit_drawer is also there
qc = QuantumCircuit(3,3)
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
qc.barrier()
qc.measure([0,1,2],[0,1,2])
qc.draw()
qasm_str = qc.qasm() #returning a qasm string, THIS SIMPLE
qasm_str
circ = QuantumCircuit.from_qasm_str(qasm_str) #you got to be kidding!
circ.draw() #you can also read a file directly with .from_qasm_file('path'), check out docs!
#what do you think the circuit depth of this picture is?
#hint: not 2
circ = QuantumCircuit(3)
circ.h(0)
circ.x(1)
circ.h(2)
circ.draw()
circ.depth()
qc =QuantumCircuit(3,3)
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
qc.h(2)
qc.barrier()
qc.cx(2,0)
qc.barrier()
print(qc.depth()) # Barriers do not count for depth
qiskit.__version__
%qiskit_version_table
# # this will give all the information on all the hardware available
# import qiskit.tools.jupyter
# %qiskit_backend_overview
from qiskit.visualization import plot_gate_map
backend = provider.get_backend('ibmq_manila')
plot_gate_map(backend, plot_directed=True)
plot_error_map(backend)
qc = QuantumCircuit(3)
qc.measure_all()
sim = BasicAer.get_backend('qasm_simulator')
couple_map = [[0,1],[1,2]] # specify some linear connection
job = execute(qc, sim, shots=1000, coupling_map=couple_map)
result = job.result()
counts = result.get_counts()
print(counts)
#Answer is D
qc.draw('mpl',filename='test.png') ## check the folder where the notebook is located
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector.from_instruction(qc)
state.draw('latex')
plot_state_paulivec(state, color=['midnightblue','green','orange'],title="New PauliVec plot")
qc = QuantumCircuit(3)
qc.x(0)
qc.y(1)
qc.cx(0,1)
qc.ccx(0,1,2)
backend = Aer.get_backend('statevector_simulator')
result = execute(qc, backend).result()
output = result.get_statevector()
output.draw('latex')
plot_state_paulivec(output, title = 'MY CITY', color = ['red','green'])
# 21) Which one of the following output results are correct when the given code is executed?
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q,c)
qc.h(q[0])
qc.x(q[1])
qc.h(q[1])
sim = Aer.get_backend('unitary_simulator')
job = execute(qc, sim)
unitary = job.result().get_unitary()
unitary
from qiskit_textbook.tools import array_to_latex
array_to_latex(unitary, pretext="\\text{Statevector} = ")
# 22) Which one of the following output results are correct when the given code is executed?
qc = QuantumCircuit(2,2)
qc.h(0)
qc.z(1)
backend = Aer.get_backend('statevector_simulator')
job = execute(qc, backend)
statevector = job.result().get_statevector()
print(statevector)
array_to_latex(statevector, pretext="\\text{Statevector} = ")
# 37) When executed, which one of the following codes produces the given image?
qc = QuantumCircuit(2,2)
qc.x(0)
qc.h(1)
qc.crz(np.pi,0,1)
qc.measure([0,1],[0,1])
#qc.draw('mpl')
#qc.draw()
#qc.draw('latex')
qc.draw('text')
# 42) Which one of the following codes will create a random circuit?
from qiskit.circuit.random import random_circuit
#circ = random_circuit(2, 2, reset=reset, measure=True)
#circ = random_circuit(2, 2,conditional=True, measurement=measure)
circ = random_circuit(2, 2, measure=False)
#circ = random_circuit(2, 2, max_operands=True)
circ.draw()
# 17) Which operator is the O/P of the following circuit?
qc = QuantumCircuit(2)
qc.x(0)
qc.cx(0,1)
op = Operator(qc)
array_to_latex(op, pretext="\\text{Operator} = ")
# Q Given this code, which two inserted code fragments result in the state vector represented by this Bloch sphere?
qc = QuantumCircuit(1,1)
qc.h(0)
#qc.rx(np.pi/4,0)
#qc.ry(-np.pi/4,0)
qc.rz(-np.pi/4,0)
#qc.ry(np.pi,0)
simulator = Aer.get_backend('statevector_simulator')
job = execute(qc, simulator)
result = job.result()
outputstate = result.get_statevector(qc)
plot_bloch_multivector(outputstate)
qc = QuantumCircuit(2)
qc.mct([0],1)
qc.draw()
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.x(q[0])
qc.h(q[0])
style = {'backgroundcolor': 'lightgreen'}
qc.draw(output='mpl', style=style, scale=3.5, plot_barriers=False, reverse_bits=False)
qc = QuantumCircuit(1)
qc.h(0)
qc.x(0)
qc.ry(np.pi/2,0)
qc.rx(-np.pi/2,0)
qc.x(0)
simulator = Aer.get_backend('statevector_simulator')
job = execute(qc, simulator)
result = job.result()
outputstate = result.get_statevector(qc)
plot_bloch_multivector(outputstate)
qc = QuantumCircuit(3)
qc.x(0)
qc.y(1)
qc.cx(0,1)
qc.ccx(0,1,2)
backend = Aer.get_backend('statevector_simulator')
result = execute(qc, backend).result()
output = result.get_statevector()
plot_state_paulivec(output, title = 'MY CITY', color = ['red','green'])
array_to_latex(output, pretext="\\text{Operator} = ")
output
qc = QuantumCircuit(3,3)
qc.h(0)
qc.cx(0,1)
qc.cry(np.pi,0,1)
qc.barrier()
qc.cx(0,2)
qc.rz(np.pi/3,1)
qc.ccx(0,2,1)
qc.measure_all()
qc.draw('mpl', scale=1, reverse_bits=True)
qc = QuantumCircuit(2,2)
qc.x(0)
qc.cx(1,0)
qc.h(1)
qc.measure(range(2),range(2))
backend = Aer.get_backend('qasm_simulator')
result = execute(qc, backend).result()
counts1 = result.get_counts()
counts2 = result.get_counts()
legend = counts1, counts2
plot_histogram([counts1,counts2], legend=legend, title = 'HISTOGRAM')
qc = QuantumCircuit(2,2)
qc.h(0)
qc.cx(0,1)
qc.cx(1,0)
backend = BasicAer.get_backend('statevector_simulator')
job = execute(qc, backend, shots=1024)
result = job.result()
sv = result.get_statevector(qc)
plot_state_qsphere(sv)
qc = QuantumCircuit(3,3)
qc.h(0)
qc.x(1)
qc.ccx(0,2,1)
qc.measure(range(3),range(3))
backend = Aer.get_backend('qasm_simulator')
result = execute(qc, backend).result()
counts = result.get_counts()
plot_histogram(counts)
q = QuantumRegister(2,'hello')
c = QuantumRegister(2,'hey')
qc = QuantumCircuit(q,c)
qc.x([0,1])
qc.h(3)
qc.cz(0,1)
qc.draw()
qc= QuantumCircuit(1,1)
pi = np.pi
qc.z(0) #4
qc.t(0) #5
qc.sdg(0) #2
qc.h(0) #3
qc.x(0) #1
simulator = Aer.get_backend('statevector_simulator')
job = execute(qc, simulator)
result = job.result()
outputstate = result.get_statevector(qc)
plot_bloch_multivector(outputstate)
array_to_latex(statevector, pretext="\\text{Operator} = ")
cords=[1,1,1]
#cords=[0,1,0]
#cords=[1,0,0]
#cords=[0,0,1]
plot_bloch_vector(cords, title='Image')
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.x(q[1])
qc.h(q[1])
sim = Aer.get_backend('unitary_simulator')
job = execute(qc, sim)
unitary = job.result().get_unitary()
array_to_latex(unitary, pretext="\\text{Operator} = ")
qc = QuantumCircuit(3,3)
qc.h(0)
qc.cx(0,1)
qc.cry(pi,0,1)
qc.barrier()
qc.cx(0,2)
qc.rz(pi/3,1)
qc.ccx(0,2,1)
qc.measure_all()
qc.draw('mpl', scale=1, reverse_bits=True)
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""
QmlHadamardNeighborClassifier
===============================
.. currentmodule:: dc_qiskit_qml.distance_based.hadamard._QmlHadamardNeighborClassifier
Implementing the Hadamard distance & majority based classifier (http://stacks.iop.org/0295-5075/119/i=6/a=60002).
.. autosummary::
:nosignatures:
QmlHadamardNeighborClassifier
AsyncPredictJob
More details:
QmlHadamardNeighborClassifier
###############################
.. autoclass:: QmlHadamardNeighborClassifier
:members:
AsyncPredictJob
##################
.. autoclass:: AsyncPredictJob
:members:
"""
import itertools
import logging
from typing import List, Union, Optional, Iterable, Sized
import numpy as np
import qiskit
from qiskit.circuit import QuantumCircuit
from qiskit.providers import BackendV2, JobV1
from qiskit.qobj import QasmQobj
from qiskit.transpiler import CouplingMap
from sklearn.base import ClassifierMixin, TransformerMixin
from dc_qiskit_qml.QiskitOptions import QiskitOptions
from ...encoding_maps import EncodingMap
log = logging.getLogger(__name__)
class CompactHadamardClassifier(ClassifierMixin, TransformerMixin):
"""
The Hadamard distance & majority based classifier implementing sci-kit learn's mechanism of fit/predict
"""
def __init__(self, encoding_map, backend, shots=1024, coupling_map=None,
basis_gates=None, theta=None, options=None):
# type: (EncodingMap, BackendV2, int, CouplingMap, List[str], Optional[float], Optional[QiskitOptions]) -> None
"""
Create the classifier
:param encoding_map: a classical feature map to apply to every training and testing sample before building
the circuit
:param classifier_circuit_factory: the circuit building factory class
:param backend: the qiskit backend to do the compilation & computation on
:param shots: *deprecated* use options. the amount of shots for the experiment
:param coupling_map: *deprecated* use options. if given overrides the backend's coupling map, useful when using the simulator
:param basis_gates: *deprecated* use options. if given overrides the backend's basis gates, useful for the simulator
:param theta: an advanced feature that generalizes the "Hadamard" gate as a rotation with this angle
:param options: the options for transpilation & executions with qiskit.
"""
self.encoding_map = encoding_map # type: EncodingMap
self.basis_gates = basis_gates # type: List[str]
self.shots = shots # type: int
self.backend = backend # type: BackendV2
self.coupling_map = coupling_map # type: CouplingMap
self._X = np.asarray([]) # type: np.ndarray
self._y = np.asarray([]) # type: np.ndarray
self.last_predict_X = None
self.last_predict_label = None
self.last_predict_probability = [] # type: List[float]
self._last_predict_circuits = [] # type: List[QuantumCircuit]
self.last_predict_p_acc = [] # type: List[float]
self.theta = np.pi / 2 if theta is None else theta # type: float
if options is not None:
self.options = options # type: QiskitOptions
else:
self.options = QiskitOptions()
self.options.basis_gates = basis_gates
self.options.coupling_map = coupling_map
self.options.shots = shots
def transform(self, X, y='deprecated', copy=None):
return X
def fit(self, X, y):
# type: (QmlHadamardNeighborClassifier, Iterable) -> QmlHadamardNeighborClassifier
"""
Internal fit method just saves the train sample set
:param X: array_like, training sample
"""
self._X = np.asarray(X)
self._y = y
log.debug("Setting training data:")
for x, y in zip(self._X, self._y):
log.debug("%s: %s", x, y)
return self
def _create_circuits(self, unclassified_input):
# type: (Iterable) -> None
"""
Creates the circuits to be executed on the quantum computer
:param unclassified_input: array like, the input set
"""
self._last_predict_circuits = []
for index, x in enumerate(unclassified_input):
log.info("Creating state for input %d: %s.", index, x)
circuit_name = 'qml_hadamard_index_%d' % index
X_input = self.encoding_map.map(x)
X_train_0 = [self.encoding_map.map(s) for s, l in zip(self._X, self._y) if l == 0]
X_train_1 = [self.encoding_map.map(s) for s, l in zip(self._X, self._y) if l == 1]
full_data = list(itertools.zip_longest([X_train_0, X_train_1], fillvalue=None))
# all_batches = max(len(X_train_0), len(X_train_1))
#
# index_no =
#
# ancilla = QuantumRegister(ancilla_qubits_needed, "a")
# index = QuantumRegister(index_of_samples_qubits_needed, "i")
# data = QuantumRegister(sample_space_dimensions_qubits_needed, "f^S")
# clabel = ClassicalRegister(label_qubits_needed, "l^c")
qc = QuantumCircuit()
self._last_predict_circuits.append(qc)
def predict_qasm_only(self, X):
# type: (Union[Sized, Iterable]) -> QasmQobj
"""
Instead of predicting straight away returns the Qobj, the command object for executing
the experiment
:param X: array like, unclassified input set
:return: the compiled Qobj ready for execution!
"""
self.last_predict_X = X
self.last_predict_label = []
self._last_predict_circuits = []
self.last_predict_probability = []
self.last_predict_p_acc = []
log.info("Creating circuits (#%d inputs)..." % len(X))
self._create_circuits(X)
log.info("Compiling circuits...")
transpiled_qc = qiskit.transpile(
self._last_predict_circuits,
backend=self.backend,
coupling_map=self.options.coupling_map,
basis_gates=self.options.basis_gates,
backend_properties=self.options.backend_properties,
initial_layout=self.options.initial_layout,
seed_transpiler=self.options.seed_transpiler,
optimization_level=self.options.optimization_level
) # type: List[QuantumCircuit]
qobj = qiskit.assemble(transpiled_qc,
backend=self.backend,
shots=self.options.shots,
qobj_id=self.options.qobj_id,
qobj_header=self.options.qobj_header,
memory=self.options.memory,
max_credits=self.options.max_credits,
seed_simulator=self.options.seed_simulator,
default_qubit_los=self.options.default_qubit_los,
default_meas_los=self.options.default_meas_los,
schedule_los=self.options.schedule_los,
meas_level=self.options.meas_level,
meas_return=self.options.meas_return,
memory_slots=self.options.memory_slots,
memory_slot_size=self.options.memory_slot_size,
rep_time=self.options.rep_time,
parameter_binds=self.options.parameter_binds,
**self.options.run_config
)
return qobj
def predict(self, X, do_async=False):
# type: (QmlHadamardNeighborClassifier, Union[Sized, Iterable], bool) -> Union[Optional[List[int]], 'AsyncPredictJob']
"""
Predict the class labels of the unclassified input set!
:param X: array like, the unclassified input set
:param do_async: if True return a wrapped job, it is handy for reading out the prediction results from a real processor
:return: depending on the input either the prediction on class labels or a wrapper object for an async task
"""
qobj = self.predict_qasm_only(X)
log.info("Executing circuits...")
job = self.backend.run(qobj) # type: JobV1
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""
QmlHadamardNeighborClassifier
===============================
.. currentmodule:: dc_qiskit_qml.distance_based.hadamard._QmlHadamardNeighborClassifier
Implementing the Hadamard distance & majority based classifier (http://stacks.iop.org/0295-5075/119/i=6/a=60002).
.. autosummary::
:nosignatures:
QmlHadamardNeighborClassifier
AsyncPredictJob
More details:
QmlHadamardNeighborClassifier
###############################
.. autoclass:: QmlHadamardNeighborClassifier
:members:
AsyncPredictJob
##################
.. autoclass:: AsyncPredictJob
:members:
"""
import logging
import time
from typing import List, Union, Optional, Iterable, Sized
import numpy as np
import qiskit
from qiskit.circuit import QuantumCircuit
from qiskit.providers import JobStatus, BackendV2, JobV1
from qiskit.qobj import QasmQobj
from qiskit.result import Result
from qiskit.result.models import ExperimentResult
from qiskit.transpiler import CouplingMap
from sklearn.base import ClassifierMixin, TransformerMixin
from dc_qiskit_qml.QiskitOptions import QiskitOptions
from .state import QmlStateCircuitBuilder
from .state._measurement_outcome import MeasurementOutcome
from ...encoding_maps import EncodingMap
log = logging.getLogger(__name__)
class QmlHadamardNeighborClassifier(ClassifierMixin, TransformerMixin):
"""
The Hadamard distance & majority based classifier implementing sci-kit learn's mechanism of fit/predict
"""
def __init__(self, encoding_map, classifier_circuit_factory, backend, shots=1024, coupling_map=None,
basis_gates=None, theta=None, options=None):
# type: (EncodingMap, QmlStateCircuitBuilder, BackendV2, int, CouplingMap, List[str], Optional[float], Optional[QiskitOptions]) -> None
"""
Create the classifier
:param encoding_map: a classical feature map to apply to every training and testing sample before building
the circuit
:param classifier_circuit_factory: the circuit building factory class
:param backend: the qiskit backend to do the compilation & computation on
:param shots: *deprecated* use options. the amount of shots for the experiment
:param coupling_map: *deprecated* use options. if given overrides the backend's coupling map, useful when using the simulator
:param basis_gates: *deprecated* use options. if given overrides the backend's basis gates, useful for the simulator
:param theta: an advanced feature that generalizes the "Hadamard" gate as a rotation with this angle
:param options: the options for transpilation & executions with qiskit.
"""
self.encoding_map = encoding_map # type: EncodingMap
self.basis_gates = basis_gates # type: List[str]
self.shots = shots # type: int
self.backend = backend # type: BackendV2
self.coupling_map = coupling_map # type: CouplingMap
self._X = np.asarray([]) # type: np.ndarray
self._y = np.asarray([]) # type: np.ndarray
self.last_predict_X = None
self.last_predict_label = None
self.last_predict_probability = [] # type: List[float]
self._last_predict_circuits = [] # type: List[QuantumCircuit]
self.last_predict_p_acc = [] # type: List[float]
self.classifier_state_factory = classifier_circuit_factory # type: QmlStateCircuitBuilder
self.theta = np.pi / 2 if theta is None else theta # type: float
if options is not None:
self.options = options # type: QiskitOptions
else:
self.options = QiskitOptions()
self.options.basis_gates = basis_gates
self.options.coupling_map = coupling_map
self.options.shots = shots
def transform(self, X, y='deprecated', copy=None):
return X
def fit(self, X, y):
# type: (QmlHadamardNeighborClassifier, Iterable) -> QmlHadamardNeighborClassifier
"""
Internal fit method just saves the train sample set
:param X: array_like, training sample
"""
self._X = np.asarray(X)
self._y = y
log.debug("Setting training data:")
for x, y in zip(self._X, self._y):
log.debug("%s: %s", x, y)
return self
def _create_circuits(self, unclassified_input):
# type: (QmlHadamardNeighborClassifier, Iterable) -> None
"""
Creates the circuits to be executed on the quantum computer
:param unclassified_input: array like, the input set
"""
self._last_predict_circuits = []
if self.classifier_state_factory is None:
raise Exception("Classifier state factory is not set!")
for index, x in enumerate(unclassified_input):
log.info("Creating state for input %d: %s.", index, x)
circuit_name = 'qml_hadamard_index_%d' % index
X_input = self.encoding_map.map(x)
X_train = [self.encoding_map.map(s) for s in self._X]
qc = self.classifier_state_factory.build_circuit(circuit_name=circuit_name, X_train=X_train,
y_train=self._y, X_input=X_input) # type: QuantumCircuit
ancillary = [q for q in qc.qregs if q.name == 'a'][0]
qlabel = [q for q in qc.qregs if q.name == 'l^q'][0]
clabel = [q for q in qc.cregs if q.name == 'l^c'][0]
branch = [q for q in qc.cregs if q.name == 'b'][0]
# Classifier
# Instead of a Hadamard gate we want this to be parametrized
# use comments for now to toggle!
# standard.h(qc, ancillary)
# Must be minus, as the IBMQX gate is implemented this way!
qc.ry(-self.theta, ancillary)
qc.z(ancillary)
# Make sure measurements aren't shifted around
# This would have some consequences as no gates
# are allowed after a measurement.
qc.barrier()
# The correct label is on ancillary branch |0>!
qc.measure(ancillary[0], branch[0])
qc.measure(qlabel, clabel)
self._last_predict_circuits.append(qc)
@staticmethod
def _extract_measurement_answer_from_index(index, result):
# type: (int, Result) -> List[MeasurementOutcome]
# Aggregate Counts
experiment = None # type: Optional[ExperimentResult]
experiment_names = [
experiment.header.name
for experiment in result.results
if experiment.header and 'qml_hadamard_index_%d' % index in experiment.header.name
]
counts = {} # type: dict
for name in experiment_names:
c = result.get_counts(name) # type: dict
for k, v in c.items():
if k not in counts:
counts[k] = v
else:
counts[k] += v
log.debug(counts)
answer = [
MeasurementOutcome(label=int(k.split(' ')[-1], 2), branch=int(k.split(' ')[-2], 2), count=v)
for k, v in counts.items()
]
return answer
def _read_result(self, test_size, result):
# type: (QmlHadamardNeighborClassifier, int, Result) -> Optional[List[int]]
"""
The logic to read out the classification from the result
:param test_size: the input set size
:param result: the qiskit result object holding the results from the experiment execution
:return: if there is a result, will return it as a list of class labels
"""
self.last_predict_label = []
self.last_predict_probability = []
for index in range(test_size):
answer = QmlHadamardNeighborClassifier._extract_measurement_answer_from_index(index, result)
log.info(answer)
answer_branch = [e for e in answer if self.classifier_state_factory.is_classifier_branch(e.branch)]
if len(answer_branch) == 0:
return None
p_acc = sum([e.count for e in answer_branch]) / self.shots
sum_of_all = sum([e.count for e in answer_branch])
predicted_answer = max(answer_branch, key=lambda e: e.count)
log.debug(predicted_answer)
predict_label = predicted_answer.label
probability = predicted_answer.count / sum_of_all
self.last_predict_label.append(predict_label)
self.last_predict_probability.append(probability)
self.last_predict_p_acc.append(p_acc)
return self.last_predict_label
def predict_qasm_only(self, X):
# type: (QmlHadamardNeighborClassifier, Union[Sized, Iterable]) -> QasmQobj
"""
Instead of predicting straight away returns the Qobj, the command object for executing
the experiment
:param X: array like, unclassified input set
:return: the compiled Qobj ready for execution!
"""
self.last_predict_X = X
self.last_predict_label = []
self._last_predict_circuits = []
self.last_predict_probability = []
self.last_predict_p_acc = []
log.info("Creating circuits (#%d inputs)..." % len(X))
self._create_circuits(X)
log.info("Compiling circuits...")
transpiled_qc = qiskit.transpile(
self._last_predict_circuits,
backend=self.backend,
coupling_map=self.options.coupling_map,
basis_gates=self.options.basis_gates,
backend_properties=self.options.backend_properties,
initial_layout=self.options.initial_layout,
seed_transpiler=self.options.seed_transpiler,
optimization_level=self.options.optimization_level
) # type: List[QuantumCircuit]
qobj = qiskit.assemble(transpiled_qc,
backend=self.backend,
shots=self.options.shots,
qobj_id=self.options.qobj_id,
qobj_header=self.options.qobj_header,
memory=self.options.memory,
max_credits=self.options.max_credits,
seed_simulator=self.options.seed_simulator,
default_qubit_los=self.options.default_qubit_los,
default_meas_los=self.options.default_meas_los,
schedule_los=self.options.schedule_los,
meas_level=self.options.meas_level,
meas_return=self.options.meas_return,
memory_slots=self.options.memory_slots,
memory_slot_size=self.options.memory_slot_size,
rep_time=self.options.rep_time,
parameter_binds=self.options.parameter_binds,
**self.options.run_config
)
return qobj
def predict(self, X, do_async=False):
# type: (QmlHadamardNeighborClassifier, Union[Sized, Iterable], bool) -> Union[Optional[List[int]], 'AsyncPredictJob']
"""
Predict the class labels of the unclassified input set!
:param X: array like, the unclassified input set
:param do_async: if True return a wrapped job, it is handy for reading out the prediction results from a real processor
:return: depending on the input either the prediction on class labels or a wrapper object for an async task
"""
qobj = self.predict_qasm_only(X)
log.info("Executing circuits...")
job = self.backend.run(qobj) # type: JobV1
async_job = AsyncPredictJob(X, job, self) # type: AsyncPredictJob
if do_async:
return async_job
job.result()
while not job.status() == JobStatus.DONE:
if job.status() == JobStatus.CANCELLED:
break
log.debug("Waiting for job...")
time.sleep(10)
if job.status() == JobStatus.DONE:
log.info("Circuits Executed!")
return async_job.predict_result()
else:
log.error("Circuits not executed!")
log.error(job.status)
return None
def predict_async(self, X):
# type: (QmlHadamardNeighborClassifier, any) -> 'AsyncPredictJob'
"""
Same as predict(self, X, do_aysnc=True)
:param X: unclassified input set
:return: Wrapper for a Job
"""
return self.predict(X, do_async=True)
def predict_sync(self, X):
# type: (QmlHadamardNeighborClassifier, any) -> Optional[List[int]]
"""
Same as predict(self, X, do_aysnc=False)
:param X: unclassified input set
:return: List of class labels
"""
return self.predict(X, do_async=False)
@staticmethod
def p_acc_theory(X_train, y_train, X_test):
# type: (List[np.ndarray], Iterable, np.ndarray) -> float
"""
Computes the branch acceptance probability
:param X_train: training set (list of numpy arrays shape (n,1)
:param y_train: Class labels of training set
:param X_test: Unclassified input vector (shape (n,1))
:return: branch acceptance probability P_acc
"""
M = len(X_train)
p_acc = sum([np.linalg.norm(X_train[i] + X_test) ** 2 for i, e in enumerate(y_train)]) / (4 * M)
return p_acc
@staticmethod
def p_label_theory(X_train, y_train, X_test, label):
# type: (List[np.ndarray], Iterable, np.ndarray, int) -> float
"""
Computes the label's probability
:param X_train: training set
:param y_train: Class labels of training set
:param X_test: Unclassified input vector (shape: (n,1))
:param label: The label to test
:return: probability of class label
"""
M = len(X_train)
p_acc = QmlHadamardNeighborClassifier.p_acc_theory(X_train, y_train, X_test)
p_label = sum([np.linalg.norm(X_train[i] + X_test) ** 2
for i, e in enumerate(y_train) if e == label]) / (4 * p_acc * M)
return p_label
class AsyncPredictJob(object):
"""
Wrapper for a qiskit BaseJob and classification experiments
"""
def __init__(self, input, job, qml):
# type: (AsyncPredictJob, Sized, JobV1, QmlHadamardNeighborClassifier) -> None
"""
Constructs a new Wrapper
:param input: the unclassified input data set
:param job: the qiskit BaseJob running the experiment
:param qml: the classifier
"""
self.input = input # type: Sized
self.job = job # type: JobV1
self.qml = qml # type: QmlHadamardNeighborClassifier
def predict_result(self):
# type: () -> Optional[List[int]]
"""
Returns the prediction result if it exists
:return: a list of class labels or None
"""
if self.job.status() == JobStatus.DONE:
log.info("Circuits Executed!")
return self.qml._read_result(len(self.input), self.job.result())
else:
log.error("Circuits not executed!")
log.error(self.job.status)
return None
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""
QmlBinaryDataStateCircuitBuilder
=======================================
.. currentmodule:: dc_qiskit_qml.distance_based.hadamard.state._QmlBinaryDataStateCircuitBuilder
.. autosummary::
:nosignatures:
QmlBinaryDataStateCircuitBuilder
QmlBinaryDataStateCircuitBuilder
#########################################
.. autoclass:: QmlBinaryDataStateCircuitBuilder
:members:
"""
import logging
from math import sqrt
from typing import List
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.dagcircuit import DAGNode
from scipy import sparse
from . import QmlStateCircuitBuilder
from .cnot import CCXFactory
log = logging.getLogger('QubitEncodingClassifierStateCircuit')
class QmlBinaryDataStateCircuitBuilder(QmlStateCircuitBuilder):
"""
From binary training and testing data creates the quantum state vector and applies a quantum algorithm to create a circuit.
"""
def __init__(self, ccx_factory, do_optimizations = True):
# type: (QmlBinaryDataStateCircuitBuilder, CCXFactory, bool) -> None
"""
Creates the uniform amplitude state circuit builder
:param ccx_factory: The multiple-controlled X-gate factory to be used
"""
self.do_optimizations = do_optimizations
self.ccx_factory = ccx_factory # type:CCXFactory
def build_circuit(self, circuit_name, X_train, y_train, X_input):
# type: (QmlBinaryDataStateCircuitBuilder, str, List[sparse.dok_matrix], any, sparse.dok_matrix) -> QuantumCircuit
"""
Build a circuit that encodes the training (samples/labels) and input data sets into a quantum circuit.
Sample data must be given as a binary (sparse) vector, i.e. each vector's entry must be either 0.0 or 1.0.
It may also be given already normed to unit length instead of binary.
:param circuit_name: The name of the quantum circuit
:param X_train: The training data set
:param y_train: the training class label data set
:param X_input: the unclassified input data vector
:return: The circuit containing the gates to encode the input data
"""
log.debug("Preparing state.")
log.debug("Raw Input Vector: %s" % X_input)
# map the training samples and test input to unit length
def normalizer(x):
# type: (sparse.dok_matrix) -> sparse.dok_matrix
norm = sqrt(sum([abs(e)**2 for e in x.values()]))
for k in x.keys():
x[k] = x[k]/norm
return x
X_train = [normalizer(x) for x in X_train]
X_input = normalizer(X_input)
# Calculate dimensions and qubit usage
count_of_samples, sample_space_dimension = len(X_train), max([s.get_shape()[0] for s in X_train + [X_input]])
count_of_distinct_classes = len(set(y_train))
index_of_samples_qubits_needed = (count_of_samples - 1).bit_length()
sample_space_dimensions_qubits_needed = (sample_space_dimension - 1).bit_length()
ancilla_qubits_needed = 1
label_qubits_needed = (count_of_distinct_classes - 1).bit_length() if count_of_distinct_classes > 1 else 1
log.info("Qubit map: index=%d, ancillary=%d, feature=%d, label=%d", index_of_samples_qubits_needed,
ancilla_qubits_needed, sample_space_dimensions_qubits_needed, label_qubits_needed)
# Create Registers
ancilla = QuantumRegister(ancilla_qubits_needed, "a")
index = QuantumRegister(index_of_samples_qubits_needed, "i")
data = QuantumRegister(sample_space_dimensions_qubits_needed, "f^S")
qlabel = QuantumRegister(label_qubits_needed, "l^q")
clabel = ClassicalRegister(label_qubits_needed, "l^c")
branch = ClassicalRegister(1, "b")
# Create the Circuit
qc = QuantumCircuit(ancilla, index, data, qlabel, clabel, branch, name=circuit_name)
# ======================
# Build the circuit now
# ======================
# Superposition on ancilla & index
qc.h(ancilla)
qc.h(index)
# Create multi-CNOTs
# First on the sample, then the input and finally the label
ancilla_and_index_regs = [ancilla[i] for i in range(ancilla.size)] + [index[i] for i in range(index.size)]
for index_sample, (sample, label) in enumerate(zip(X_train, y_train)):
cnot_type_sample = (index_sample << 1) + 0
cnot_type_input = (index_sample << 1) + 1
# The sample will be encoded
for basis_vector_index, _ in sample.keys():
bit_string = "{:b}".format(basis_vector_index)
for i, v in enumerate(reversed(bit_string)):
if v == "1":
self.ccx_factory.ccx(qc,
cnot_type_sample,
ancilla_and_index_regs,
data[i])
# Label will be encoded
bit_string = "{:b}".format(label)
for i, v in enumerate(reversed(bit_string)):
if v == "1":
self.ccx_factory.ccx(qc,
cnot_type_sample,
ancilla_and_index_regs,
qlabel[i])
# The input will be encoded
for basis_vector_index, _ in X_input.keys():
bit_string = "{:b}".format(basis_vector_index)
for i, v in enumerate(reversed(bit_string)):
if v == "1":
self.ccx_factory.ccx(qc, cnot_type_input, ancilla_and_index_regs, data[i])
# Label will be encoded
bit_string = "{:b}".format(label)
for i, v in enumerate(reversed(bit_string)):
if v == "1":
self.ccx_factory.ccx(qc, cnot_type_input, ancilla_and_index_regs, qlabel[i])
stop = False
while not stop and self.do_optimizations:
dag = circuit_to_dag(qc)
dag.remove_all_ops_named("barrier")
gates = dag.named_nodes("ccx", "cx", "x") # type: List[DAGNode]
removable_nodes = []
for ccx_gate in gates:
successor = list(dag.successors(ccx_gate)) # type: List[DAGNode]
if len(successor) == 1:
if successor[0].name == ccx_gate.name:
removable_nodes.append(successor[0])
removable_nodes.append(ccx_gate)
print(end='')
for n in removable_nodes:
dag.remove_op_node(n)
if len(removable_nodes) > 0:
qc = dag_to_circuit(dag)
else:
stop = True
return qc
def is_classifier_branch(self, branch_value):
# type: (QmlBinaryDataStateCircuitBuilder, int) -> bool
"""
The branch of quantum state bearing the classification is defined to be 0.
This functions checks this.
:param branch_value: The measurement of the branch
:return: True is the measured branch is 0, False if not
"""
return branch_value == 0
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""
QmlGenericStateCircuitBuilder
==============================
.. currentmodule:: dc_qiskit_qml.distance_based.hadamard.state._QmlGenericStateCircuitBuilder
The generic state circuit builder classically computes the necessary quantum state vector (sparse) and will use a
state preparing quantum routine that takes the state vector and creates a circuit. This state preparing quantum routine
must implement :py:class:`QmlSparseVectorFactory`.
.. autosummary::
:nosignatures:
QmlGenericStateCircuitBuilder
QmlGenericStateCircuitBuilder
##############################
.. autoclass:: QmlGenericStateCircuitBuilder
:members:
"""
import logging
from typing import List, Optional
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from scipy import sparse
from ._QmlStateCircuitBuilder import QmlStateCircuitBuilder
from .sparsevector import QmlSparseVectorStatePreparation
log = logging.getLogger('QmlGenericStateCircuitBuilder')
class RegisterSizes:
count_of_samples: int
index_of_samples_qubits: int
sample_space_dimensions_qubits: int
ancilla_qubits: int
label_qubits: int
total_qubits: int
def __init__(self, count_of_samples, index_of_samples_qubits, sample_space_dimensions_qubits,
ancilla_qubits, label_qubits, total_qubits):
# type: (int, int, int, int, int, int) -> None
self.count_of_samples = count_of_samples
self.index_of_samples_qubits = index_of_samples_qubits
self.sample_space_dimensions_qubits = sample_space_dimensions_qubits
self.ancilla_qubits = ancilla_qubits
self.label_qubits = label_qubits
self.total_qubits = total_qubits
class QmlGenericStateCircuitBuilder(QmlStateCircuitBuilder):
"""
From generic training and testing data creates the quantum state vector and applies a quantum algorithm to create
a circuit.
"""
def __init__(self, state_preparation):
# type: (QmlGenericStateCircuitBuilder, QmlSparseVectorStatePreparation) -> None
"""
Create a new object, use the state preparation routine
:param state_preparation: The quantum state preparation routine to encode the quantum state
"""
self.state_preparation = state_preparation
self._last_state_vector = None # type: sparse.dok_matrix
@staticmethod
def get_binary_representation(sample_index, sample_label, entry_index, is_input, register_sizes):
# type: (int, int, int, bool, RegisterSizes) -> str
"""
Computes the binary representation of the quantum state as `str` given indices and qubit lengths
:param sample_index: the training data sample index
:param sample_label: the training data label
:param entry_index: the data sample vector index
:param is_input: True if the we encode the input instead of the training vector
:param register_sizes: qubits needed for the all registers
:return: binary representation of which the quantum state being addressed
"""
sample_index_b = "{0:b}".format(sample_index).zfill(register_sizes.index_of_samples_qubits)
sample_label_b = "{0:b}".format(sample_label).zfill(register_sizes.label_qubits)
ancillary_b = '0' if is_input else '1'
entry_index_b = "{0:b}".format(entry_index).zfill(register_sizes.sample_space_dimensions_qubits)
# Here we compose the qubit, the ordering will be essential
# However keep in mind, that the order is LSB
qubit_composition = [
sample_label_b,
entry_index_b,
sample_index_b,
ancillary_b
]
return "".join(qubit_composition)
@staticmethod
def _get_register_sizes(X_train, y_train):
# type: (List[sparse.dok_matrix], np.ndarray) -> RegisterSizes
count_of_samples, sample_space_dimension = len(X_train), X_train[0].get_shape()[0]
count_of_distinct_classes = len(set(y_train))
index_of_samples_qubits_needed = (count_of_samples - 1).bit_length()
sample_space_dimensions_qubits_needed = (sample_space_dimension - 1).bit_length()
ancilla_qubits_needed = 1
label_qubits_needed = (count_of_distinct_classes - 1).bit_length() if count_of_distinct_classes > 1 else 1
total_qubits_needed = (index_of_samples_qubits_needed + ancilla_qubits_needed
+ sample_space_dimensions_qubits_needed + label_qubits_needed)
return RegisterSizes(
count_of_samples,
index_of_samples_qubits_needed,
sample_space_dimensions_qubits_needed,
ancilla_qubits_needed,
label_qubits_needed,
total_qubits_needed
)
@staticmethod
def assemble_state_vector(X_train, y_train, X_input):
# type: (List[sparse.dok_matrix], any, sparse.dok_matrix) -> sparse.dok_matrix
"""
This method assembles the state vector for given data. The X data for training (which is a list of sparse
vectors) is encoded into a sub-space, in the other orthogonal sub-space the same input is encoded everywhere.
Also, the label is encoded.
A note: this method is used in conjunction with a generic state preparation, and this may not be the most
efficient way.
:param X_train: The training data set
:param y_train: the training class label data set
:param X_input: the unclassified input data vector
:return: The
"""
register_sizes = QmlGenericStateCircuitBuilder._get_register_sizes(X_train, y_train)
state_vector = sparse.dok_matrix((2 ** register_sizes.total_qubits, 1), dtype=complex) # type: sparse.dok_matrix
factor = 2 * register_sizes.count_of_samples * 1.0
for index_sample, (sample, label) in enumerate(zip(X_train, y_train)):
for (i, j), sample_i in sample.items():
qubit_state = QmlGenericStateCircuitBuilder.get_binary_representation(
index_sample, label, i, is_input=False, register_sizes=register_sizes
)
state_index = int(qubit_state, 2)
log.debug("Sample Entry: %s (%d): %.2f.", qubit_state, state_index, sample_i)
state_vector[state_index, 0] = sample_i
for (i, j), input_i in X_input.items():
qubit_state = QmlGenericStateCircuitBuilder.get_binary_representation(
index_sample, label, i, is_input=True, register_sizes=register_sizes
)
state_index = int(qubit_state, 2)
log.debug("Input Entry: %s (%d): %.2f.", qubit_state, state_index, input_i)
state_vector[state_index, 0] = input_i
state_vector = state_vector * (1 / np.sqrt(factor))
return state_vector
def build_circuit(self, circuit_name, X_train, y_train, X_input):
# type: (QmlGenericStateCircuitBuilder, str, List[sparse.dok_matrix], any, sparse.dok_matrix) -> QuantumCircuit
"""
Build a circuit that encodes the training (samples/labels) and input data sets into a quantum circuit.
It does so by iterating through the training data set with labels and constructs upon sample index and
vector position the to be modified amplitude. The state vector is stored into a sparse matrix of
shape (n,1) which is stored and can be accessed through :py:func:`get_last_state_vector` for
debugging purposes.
Then the routine uses a :py:class:`QmlSparseVectorStatePreparation` routine to encode the calculated state
vector into a quantum circuit.
:param circuit_name: The name of the quantum circuit
:param X_train: The training data set
:param y_train: the training class label data set
:param X_input: the unclassified input data vector
:return: The circuit containing the gates to encode the input data
"""
log.debug("Preparing state.")
log.debug("Raw Input Vector: %s" % X_input)
register_sizes = QmlGenericStateCircuitBuilder._get_register_sizes(X_train, y_train)
log.info("Qubit map: index=%d, ancillary=%d, feature=%d, label=%d", register_sizes.index_of_samples_qubits,
register_sizes.ancilla_qubits, register_sizes.sample_space_dimensions_qubits,
register_sizes.label_qubits)
ancilla = QuantumRegister(register_sizes.ancilla_qubits, "a")
index = QuantumRegister(register_sizes.index_of_samples_qubits, "i")
data = QuantumRegister(register_sizes.sample_space_dimensions_qubits, "f^S")
qlabel = QuantumRegister(register_sizes.label_qubits, "l^q")
clabel = ClassicalRegister(register_sizes.label_qubits, "l^c")
branch = ClassicalRegister(1, "b")
qc = QuantumCircuit(ancilla, index, data, qlabel, clabel, branch, name=circuit_name) # type: QuantumCircuit
self._last_state_vector = QmlGenericStateCircuitBuilder.assemble_state_vector(X_train, y_train, X_input)
return self.state_preparation.prepare_state(qc, self._last_state_vector)
def is_classifier_branch(self, branch_value):
# type: (QmlGenericStateCircuitBuilder, int) -> bool
"""
As each state preparation algorithm uses a unique layout. Here the :py:class:`QmlSparseVectorFactory`
is asked how the branch for post selection can be identified.
:param branch_value: The measurement of the branch
:return: True is the branch is containing the classification, False if not
"""
return self.state_preparation.is_classifier_branch(branch_value)
def get_last_state_vector(self):
# type: (QmlGenericStateCircuitBuilder) -> Optional[sparse.dok_matrix]
"""
From the last call of :py:func:`build_circuit` the computed (sparse) state vector.
:return: a sparse vector (shape (n,0)) if present
"""
return self._last_state_vector
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""
QmlStateCircuitBuilder
==============================
.. currentmodule:: dc_qiskit_qml.distance_based.hadamard.state._QmlStateCircuitBuilder
This is the abstract base class to implement a custom state circuit builder which takes the classification
training data samples and labels and one to be classified sample and outputs the circuit that creates the necessary
quantum state than then can be used to apply the :py:class:`QmlHadamardNeighborClassifier`.
.. autosummary::
:nosignatures:
QmlStateCircuitBuilder
QmlStateCircuitBuilder
##############################
.. autoclass:: QmlStateCircuitBuilder
:members:
"""
import abc
from typing import List
from qiskit import QuantumCircuit
from scipy import sparse
class QmlStateCircuitBuilder(object):
"""
Interface class for creating a quantum circuit from a sparse quantum state vector.
"""
@abc.abstractmethod
def build_circuit(self, circuit_name, X_train, y_train, X_input):
# type: (QmlStateCircuitBuilder, str, List[sparse.dok_matrix], any, sparse.dok_matrix) -> QuantumCircuit
"""
Build a circuit that encodes the training (samples/labels) and input data sets into a quantum circuit
:param circuit_name: The name of the quantum circuit
:param X_train: The training data set
:param y_train: the training class label data set
:param X_input: the unclassified input data vector
:return: The circuit containing the gates to encode the input data
"""
pass
@abc.abstractmethod
def is_classifier_branch(self, branch_value):
# type: (QmlStateCircuitBuilder, int) -> bool
"""
As each state preparation algorithm uses a unique layout. The classifier has the correct classification
probabilities only on the correct branch of the ancilla qubit. However each state preparation may have
different methods making it necessary to query specific logic to assess what value must be given after the
branch qubit measurement.
:param branch_value: The measurement of the branch
:return: True is the branch is containing the classification, False if not
"""
pass
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""
CCXFactory
============
.. currentmodule:: dc_qiskit_qml.distance_based.hadamard.state.cnot._CCXFactory
This class is the abstract base class for the multiple-controlled X-gates (short ccx) that are primarily used
for binary input data of the classifier.
.. autosummary::
:nosignatures:
CCXFactory
CCXFactory
#############
.. autoclass:: CCXFactory
:members:
"""
import abc
from typing import List, Union, Tuple
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.register import Register
class CCXFactory(object):
"""
Abstract base class for using a multi-ccx gate within the context of the classifier
"""
@abc.abstractmethod
def ccx(self, qc, conditial_case, control_qubits, tgt):
# type: (CCXFactory, QuantumCircuit, int, Union[List[Tuple[Register, int]], QuantumRegister], Union[Tuple[Register, int], QuantumRegister]) ->QuantumCircuit
"""
This method applies to a quantum circuit on the control qubits the desired controlled operation on the target
if the quantum state coincides with the (binary representation of the) conditional case.
This abstract method must be implemented in order to be used by the
:py:class:`_QmlUniformAmplitudeStateCircuitBuilder` and so that the correct state for the classifier can be
applied.
:param qc: the circuit to apply this operation to
:param conditial_case: an integer whose binary representation signifies the branch to controll on
:param control_qubits: the qubits that hold the desired conditional case
:param tgt: the target to be applied the controlled X gate on
:return: the circuit after application of the gate
"""
pass
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""
CCXMöttönen
============
.. currentmodule:: dc_qiskit_qml.distance_based.hadamard.state.cnot._CCXMöttönen
This module implements a :py:class:`CCXFactory` to create a multi-controlled X-gate (or NOT gate) to a circuit
using the uniform rotations as described by Möttönen et al. (http://dl.acm.org/citation.cfm?id=2011670.2011675).
.. autosummary::
:nosignatures:
CCXMöttönen
CCXMöttönen
#############
.. autoclass:: CCXMöttönen
:members:
"""
import logging
from typing import List, Union, Tuple
from dc_qiskit_algorithms.UniformRotation import ccx_uni_rot
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.register import Register
from . import CCXFactory
log = logging.getLogger(__name__)
class CCXMottonen(CCXFactory):
"""
cc-X gate implemented via the uniform rotation scheme (Möttönen et al. 2005)
"""
def ccx(self, qc, conditial_case, control_qubits, tgt):
# type: (CCXFactory, QuantumCircuit, int, Union[List[Tuple[Register, int]], QuantumRegister], Union[Tuple[Register, int], QuantumRegister]) ->QuantumCircuit
"""
Using the Möttönen uniform rotation, one can create multi-controlled NOT gate
(along with other arbitrary rotations). The routine has exponential (w.r.t. number of qubits) gate usage.
:param qc: the circuit to apply this operation to
:param conditial_case: an integer whose binary representation signifies the branch to controll on
:param control_qubits: the qubits that hold the desired conditional case
:param tgt: the target to be applied the controlled X gate on
:return: the circuit after application of the gate
"""
ccx_uni_rot(qc, conditial_case, control_qubits, tgt)
return qc
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""
CCXToffoli
============
.. currentmodule:: dc_qiskit_qml.distance_based.hadamard.state.cnot._CCXToffoli
This module implements a :py:class:`CCXFactory` to create a multi-controlled X-gate (or NOT gate) to a circuit
using the Toffoli gate cascade on ancillary qubits described by Nielsen & Chuang (https://doi.org/10.1017/CBO9780511976667).
Its advantage is that it doesn't need expnential gates w.r.t. to the controlled qubit count, however, its downside is
that it needs auxiliary qubits. It depends strongly on the use case whether to use this or the algorithm by
Möttönen et al. as implemented by :py:class:`CCXMöttönen`.
.. autosummary::
:nosignatures:
CCXToffoli
CCXToffoli
#############
.. autoclass:: CCXToffoli
:members:
"""
import logging
from typing import List, Union, Tuple
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.register import Register
from . import CCXFactory
log = logging.getLogger(__name__)
class CCXToffoli(CCXFactory):
"""
cc-X gate implemented via the Toffoli cascade with auxiliary qubits.
"""
def ccx(self, qc, conditial_case, control_qubits, tgt):
# type:(CCXToffoli, QuantumCircuit, int, List[Tuple[Register, int]], Union[Tuple[Register, int], QuantumRegister]) -> QuantumCircuit
"""
Using the Toffoli gate cascade on auxiliary qubits, one can create multi-controlled NOT gate. The routine
needs to add an auxiliary register called ``
ccx_ancilla`` which also will be re-used if multiple calls
of this routine are done within the same circuit. As the cascade is always 'undone', the ancilla register
is left to the ground state.
:param qc: the circuit to apply this operation to
:param conditial_case: an integer whose binary representation signifies the branch to controll on
:param control_qubits: the qubits that hold the desired conditional case
:param tgt: the target to be applied the controlled X gate on
:return: the circuit after application of the gate
"""
# Prepare conditional case
bit_string = "{:b}".format(conditial_case).zfill(len(control_qubits))
for i, b in enumerate(reversed(bit_string)):
if b == '0':
qc.x(control_qubits[i])
qc.barrier()
if len(control_qubits) == 1: # This is just the normal CNOT
qc.cx(control_qubits[0], tgt)
elif len(control_qubits) == 2: # This is the simple Toffoli
qc.ccx(control_qubits[0], control_qubits[1], tgt)
else:
# Create ancilla qubit or take the one that is already there
if 'ccx_ancilla' not in [q.name for q in qc.qregs]:
ccx_ancilla = QuantumRegister(len(control_qubits) - 1, 'ccx_ancilla') # type: QuantumRegister
qc.add_register(ccx_ancilla)
else:
ccx_ancilla = [q for q in qc.qregs if q.name == 'ccx_ancilla'][0] # type: QuantumRegister
# Algorithm
qc.ccx(control_qubits[0], control_qubits[1], ccx_ancilla[0])
for i in range(1, ccx_ancilla.size):
qc.ccx(control_qubits[i], ccx_ancilla[i - 1], ccx_ancilla[i])
qc.ccx(control_qubits[-1], ccx_ancilla[ccx_ancilla.size - 1], tgt)
for i in reversed(range(1, ccx_ancilla.size)):
qc.ccx(control_qubits[i], ccx_ancilla[i - 1], ccx_ancilla[i])
qc.ccx(control_qubits[0], control_qubits[1], ccx_ancilla[0])
qc.barrier()
# Undo the conditional case
for i, b in enumerate(reversed(bit_string)):
if b == '0':
qc.x(control_qubits[i])
return qc
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""
MöttönenStatePreparation
==========================
.. currentmodule:: dc_qiskit_qml.distance_based.hadamard.state.sparsevector._MöttönenStatePreparation
.. autosummary::
:nosignatures:
MöttönenStatePreparation
MöttönenStatePreparation
#########################
.. autoclass:: MöttönenStatePreparation
:members:
"""
from dc_qiskit_algorithms.MottonenStatePreparation import state_prep_möttönen
from qiskit import QuantumCircuit
from scipy import sparse
from ._QmlSparseVectorStatePreparation import QmlSparseVectorStatePreparation
class MottonenStatePreparation(QmlSparseVectorStatePreparation):
def prepare_state(self, qc, state_vector):
# type: (QmlSparseVectorStatePreparation, QuantumCircuit, sparse.dok_matrix) -> QuantumCircuit
"""
Apply the Möttönen state preparation routine on a quantum circuit using the given state vector.
The quantum circuit's quantum registers must be able to hold the state vector. Also it is expected
that the registers are initialized to the ground state ´´|0>´´ each.
:param qc: the quantum circuit to be used
:param state_vector: the (complex) state vector of unit length to be prepared
:return: the quantum circuit
"""
qregs = qc.qregs
# State Prep
register = [reg[i] for reg in qregs for i in range(0, reg.size)]
state_prep_möttönen(qc, state_vector, register)
return qc
def is_classifier_branch(self, branch_value):
# type: (QmlSparseVectorStatePreparation, int) -> bool
"""
The classifier will be directly usable if the branch label is 0.
:param branch_value: the branch measurement value
:return: True if the branch measurement was 0
"""
return branch_value == 0
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""
MöttönenStatePreparation
==========================
.. currentmodule:: dc_qiskit_qml.distance_based.hadamard.state.sparsevector._MöttönenStatePreparation
.. autosummary::
:nosignatures:
MöttönenStatePreparation
MöttönenStatePreparation
#########################
.. autoclass:: MöttönenStatePreparation
:members:
"""
from qiskit import QuantumCircuit
from scipy import sparse
from ._QmlSparseVectorStatePreparation import QmlSparseVectorStatePreparation
class QiskitNativeStatePreparation(QmlSparseVectorStatePreparation):
def prepare_state(self, qc, state_vector):
# type: (QmlSparseVectorStatePreparation, QuantumCircuit, sparse.dok_matrix) -> QuantumCircuit
"""
Apply the Möttönen state preparation routine on a quantum circuit using the given state vector.
The quantum circuit's quantum registers must be able to hold the state vector. Also it is expected
that the registers are initialized to the ground state ´´|0>´´ each.
:param qc: the quantum circuit to be used
:param state_vector: the (complex) state vector of unit length to be prepared
:return: the quantum circuit
"""
qregs = qc.qregs
# State Prep
register = [reg[i] for reg in qregs for i in range(0, reg.size)]
state = state_vector.toarray()[:,0]
qc.initialize(state, register)
return qc
def is_classifier_branch(self, branch_value):
# type: (QmlSparseVectorStatePreparation, int) -> bool
"""
The classifier will be directly usable if the branch label is 0.
:param branch_value: the branch measurement value
:return: True if the branch measurement was 0
"""
return branch_value == 0
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import List
import numpy as np
from scipy import sparse
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from dc_qiskit_algorithms import FFQramDb
from dc_qiskit_algorithms.FlipFlopQuantumRam import add_vector
from ._QmlSparseVectorStatePreparation import QmlSparseVectorStatePreparation
class FFQRAMStateVectorRoutine(QmlSparseVectorStatePreparation):
def prepare_state(self, qc, state_vector):
# type: (FFQRAMStateVectorRoutine, QuantumCircuit, sparse.dok_matrix) -> QuantumCircuit
cregs_new = [reg for reg in qc.cregs if reg.name != "b"] # type: List[ClassicalRegister]
branch_old = [reg for reg in qc.cregs if reg.name == "b"][0] # type: ClassicalRegister
branch = ClassicalRegister(name=branch_old.name, size=2)
ffqram_reg = QuantumRegister(1, "ffqram_reg")
qc_result = QuantumCircuit(*qc.qregs, ffqram_reg, *cregs_new, branch, name=qc.name)
bus = [reg[i] for reg in qc.qregs for i in range(reg.size)]
# Create DB
db = FFQramDb()
# TODO: make it take a sparse matrix too!
add_vector(db, list([np.real(e[0]) for e in state_vector.toarray()]))
# State Prep
for r in bus:
qc_result.h(r)
db.add_to_circuit(qc_result, bus, ffqram_reg[0])
qc_result.barrier()
qc_result.measure(ffqram_reg[0], branch[1])
return qc_result
def is_classifier_branch(self, branch_value):
return branch_value == 2
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""
QmlSparseVectorStatePreparation
================================
.. currentmodule:: dc_qiskit_qml.distance_based.hadamard.state.sparsevector._QmlSparseVectorStatePreparation
This is the abstract base class that needs to be implemented for any routine that takes a sparse state vector
and encodes it into a quantum circuit that produces this quantum state.
.. autosummary::
:nosignatures:
QmlSparseVectorStatePreparation
QmlSparseVectorStatePreparation
#################################
.. autoclass:: QmlSparseVectorStatePreparation
:members:
"""
import abc
from qiskit import QuantumCircuit
from scipy import sparse
class QmlSparseVectorStatePreparation(object):
@abc.abstractmethod
def prepare_state(self, qc, state_vector):
# type: (QmlSparseVectorStatePreparation, QuantumCircuit, sparse.dok_matrix) -> QuantumCircuit
"""
Given a sparse quantum state apply a quantum algorithm (gates) to the given circuit to produce the
desired quantum state.
:param qc: the quantum circuit to be used
:param state_vector: the (complex) state vector of unit length to be prepared
:return: the quantum circuit
"""
pass
@abc.abstractmethod
def is_classifier_branch(self, branch_value):
# type: (QmlSparseVectorStatePreparation, int) -> bool
"""
The state preparation logic is done in this class, therefore it knows what value the branch measurement
must have in order to know if we can get classification numbers.
:param branch_value: the branch measurement value
:return: True if the branch measurement was 0
"""
pass
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
import qiskit
from qiskit_aer.backends.aerbackend import AerBackend
from dc_qiskit_qml.encoding_maps import NormedAmplitudeEncoding
from dc_qiskit_qml.distance_based.hadamard import QmlHadamardNeighborClassifier
from dc_qiskit_qml.distance_based.hadamard.state import QmlGenericStateCircuitBuilder
from dc_qiskit_qml.distance_based.hadamard.state.sparsevector import MottonenStatePreparation
initial_state_builder = QmlGenericStateCircuitBuilder(MottonenStatePreparation())
encoding_map = NormedAmplitudeEncoding()
execution_backend: AerBackend = qiskit.Aer.get_backend('qasm_simulator')
qml = QmlHadamardNeighborClassifier(backend=execution_backend,
shots=8192,
classifier_circuit_factory=initial_state_builder,
encoding_map=encoding_map)
from sklearn.datasets import load_iris
import numpy as np
import matplotlib.pyplot as plt
X, y = load_iris(return_X_y=True)
X = np.asarray([x[0:2] for x, yy in zip(X, y) if yy != 2])
y = np.asarray([yy for x, yy in zip(X, y) if yy != 2])
figure = plt.figure(figsize=(5,3.5), num=2)
sub1 = figure.subplots(nrows=1, ncols=1)
class_0_data = np.asarray([X[i] for i in range(len(X)) if y[i] == 0])
class_1_data = np.asarray([X[i] for i in range(len(X)) if y[i] == 1])
class_0 = sub1.scatter(class_0_data[:,0], class_0_data[:,1], color='red', marker='x', s=50)
class_1 = sub1.scatter(class_1_data[:,0], class_1_data[:,1], color='blue', marker='x', s=50)
sub1.plot([np.cos(x) for x in np.arange(0, 2*np.pi + 0.1, 0.1)], [np.sin(x) for x in np.arange(0, 2*np.pi + 0.1, 0.1)],
color='black', linewidth=1)
sub1.set_title("Iris Data")
sub1.legend([class_0, class_1], ["Class 1", "Class 2"])
sub1.axvline(color='gray')
sub1.axhline(color='gray')
from sklearn.preprocessing import StandardScaler, Normalizer
from sklearn.pipeline import Pipeline
pipeline = Pipeline([
('scaler', StandardScaler()),
('l2norm', Normalizer(norm='l2', copy=True)),
('qml', qml)
])
_X = pipeline.fit_transform(X, y)
figure = plt.figure(figsize=(5,5), num=2)
sub1 = figure.subplots(nrows=1, ncols=1)
class_0_data = np.asarray([_X[i] for i in range(len(X)) if y[i] == 0])
class_1_data = np.asarray([_X[i] for i in range(len(X)) if y[i] == 1])
class_0 = sub1.scatter(class_0_data[:,0], class_0_data[:,1], color='red', marker='x', s=50)
class_1 = sub1.scatter(class_1_data[:,0], class_1_data[:,1], color='blue', marker='x', s=50)
sub1.plot([np.cos(x) for x in np.arange(0, 2*np.pi, 0.1)], [np.sin(x) for x in np.arange(0, 2*np.pi, 0.1)],
color='black', linewidth=1)
sub1.set_title("Iris Data")
sub1.legend([class_0, class_1], ["Class 1", "Class 2"])
sub1.axvline(color='gray')
sub1.axhline(color='gray')
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.10, random_state=42)
_X_train = pipeline.fit_transform(X_train, y_train)
_X_test = pipeline.transform(X_test)
figure = plt.figure(figsize=(10,4.5), num=2)
sub1, sub2 = figure.subplots(nrows=1, ncols=2)
class_0_data = np.asarray([_X_train[i] for i in range(len(X_train)) if y_train[i] == 0])
class_1_data = np.asarray([_X_train[i] for i in range(len(X_train)) if y_train[i] == 1])
class_0 = sub1.scatter(class_0_data[:,0], class_0_data[:,1], color='red', marker='x', s=50)
class_1 = sub1.scatter(class_1_data[:,0], class_1_data[:,1], color='blue', marker='x', s=50)
sub1.plot([np.cos(x) for x in np.arange(0, 2*np.pi, 0.1)], [np.sin(x) for x in np.arange(0, 2*np.pi, 0.1)],
color='black', linewidth=1)
sub1.set_title("Training data")
sub1.legend([class_0, class_1], ["Class 1", "Class 2"])
sub1.axvline(color='gray')
sub1.axhline(color='gray')
class_0_data_test = np.asarray([_X_test[i] for i in range(len(X_test)) if y_test[i] == 0])
class_1_data_test = np.asarray([_X_test[i] for i in range(len(X_test)) if y_test[i] == 1])
class_0 = sub2.scatter(class_0_data_test[:,0], class_0_data_test[:,1], color='red', marker='x', s=50)
class_1 = sub2.scatter(class_1_data_test[:,0], class_1_data_test[:,1], color='blue', marker='x', s=50)
sub2.plot([np.cos(x) for x in np.arange(0, 2*np.pi, 0.1)], [np.sin(x) for x in np.arange(0, 2*np.pi, 0.1)],
color='black', linewidth=1)
sub2.set_title("Testing data")
sub2.legend([class_0, class_1], ["Class 1", "Class 2"])
sub2.axvline(color='gray')
sub2.axhline(color='gray')
len(X_train), np.ceil(np.log2(len(X_train)))
pipeline.fit(X_train, y_train)
prediction = pipeline.predict(X_test)
list(zip(prediction, y_test))
"Test Accuracy: {}".format(
sum([1 if p == t else 0 for p, t in zip(prediction, y_test)])/len(prediction)
)
prediction_train = pipeline.predict(X_train)
"Train Accuracy: {}".format(
sum([1 if p == t else 0 for p, t in zip(prediction_train, y_train)])/len(prediction_train)
)
list(zip(prediction_train, y_train))
for i in range(len(X_test)):
acc = QmlHadamardNeighborClassifier.p_acc_theory(X_train, y_train, X_test[i])
print(f"{qml.last_predict_p_acc[i]:.4f} ~~ {acc:.4f}")
for i in range(len(X_test)):
label = QmlHadamardNeighborClassifier.p_label_theory(X_train, y_train, X_test[i], prediction[i])
print(f"{qml.last_predict_probability[i]:.4f} ~~ {label:.4f}")
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
import qiskit
from qiskit_aer import Aer, QasmSimulator
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Decompose
from dc_qiskit_qml import QiskitOptions
from dc_qiskit_qml.encoding_maps import NormedAmplitudeEncoding
from dc_qiskit_qml.distance_based.hadamard import QmlHadamardNeighborClassifier
from dc_qiskit_qml.distance_based.hadamard.state import QmlGenericStateCircuitBuilder
from dc_qiskit_qml.distance_based.hadamard.state.sparsevector import MottonenStatePreparation
from dc_qiskit_algorithms.MottonenStatePreparation import MottonenStatePreparationGate
initial_state_builder = QmlGenericStateCircuitBuilder(MottonenStatePreparation())
execution_backend: QasmSimulator = Aer.get_backend('qasm_simulator')
options = QiskitOptions(shots=8192,optimization_level=3)
qml = QmlHadamardNeighborClassifier(
backend=execution_backend,
classifier_circuit_factory=initial_state_builder,
encoding_map=NormedAmplitudeEncoding(),
options=options
)
import numpy as np
from sklearn.preprocessing import StandardScaler, Normalizer
from sklearn.pipeline import Pipeline
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
X = np.asarray([x[0:2] for x, y in zip(X, y) if y != 2])
y = np.asarray([y for x, y in zip(X, y) if y != 2])
X_train = X[[33, 85]]
y_train = y[[33, 85]]
X_test = X[[28, 36]]
y_test = y[[28, 36]]
pipeline = Pipeline([
('scaler', StandardScaler()),
('l2norm', Normalizer(norm='l2', copy=True)),
('qml', qml)
])
import matplotlib.pyplot as plt
_X = pipeline.fit_transform(X, y)
_X_train = pipeline.transform(X_train)
_X_test = pipeline.transform(X_test)
plt.scatter(
_X[:,0], _X[:,1],
color=['red' if yy == 0 else 'blue' for yy in y],
s=20)
plt.scatter(
_X_train[:,0], _X_train[:,1],
color=['red' if yy == 0 else 'blue' for yy in y_train],
marker='x', s=200)
plt.scatter(
_X_test[:,0], _X_test[:,1],
color=['red' if yy == 0 else 'blue' for yy in y_test],
marker='o', s=200)
plt.xlim([-1.2,1.2])
plt.ylim([-1.2,1.2])
plt.show()
pipeline.fit(X_train, y_train)
pipeline.predict(X_test), y_test
qml._last_predict_circuits[0].draw(output="mpl", fold=-1)
PassManager([Decompose(MottonenStatePreparationGate)]).run(qml._last_predict_circuits[0]).draw(fold=-1, output="mpl")
qiskit.transpile(
circuits=qml._last_predict_circuits[0],
basis_gates=['cx', 'u1', 'u2', 'u3'],
optimization_level=0
).draw(fold=-1, output="mpl")
qiskit.transpile(
circuits=qml._last_predict_circuits[0],
basis_gates=['cx', 'u1', 'u2', 'u3'],
optimization_level=3
).draw(fold=-1, output="mpl")
X_train = X[45:61]
y_train = y[45:61]
X_test = X[[33, 63]]
y_test = y[[33, 63]]
_X = pipeline.fit_transform(X, y)
_X_train = pipeline.transform(X_train)
_X_test = pipeline.transform(X_test)
plt.scatter(
_X[:,0], _X[:,1],
color=['red' if yy == 0 else 'blue' for yy in y], s=10)
plt.scatter(
_X_train[:,0], _X_train[:,1],
color=['red' if yy == 0 else 'blue' for yy in y_train],
marker='x', s=200)
plt.scatter(
_X_test[:,0], _X_test[:,1],
color=['red' if yy == 0 else 'blue' for yy in y_test],
marker='o', s=200)
plt.show()
pipeline.fit(X_train, y_train)
pipeline.predict(X_test), y_test
qml._last_predict_circuits[0].draw(fold=-1, output="mpl")
PassManager([Decompose(MottonenStatePreparationGate)]).run(qml._last_predict_circuits[0]).draw(fold=-1, output="mpl")
qiskit.transpile(circuits=qml._last_predict_circuits[0], optimization_level=0, backend=execution_backend).draw(fold=120, output="mpl")
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
import qiskit
import numpy as np
X_train = np.asarray([[1.0, 1.0], [-1.0, 1.0], [-1.0, -1.0], [1.0, -1.0]])
y_train = [0, 1, 0, 1]
X_test = np.asarray([[0.2, 0.4], [0.4, -0.8]])
y_test = [0, 1]
from dc_qiskit_qml.encoding_maps import EncodingMap
import scipy.sparse as sparse
class MyEncodingMap(EncodingMap):
def map(self, input_vector: list) -> sparse.dok_matrix:
result = sparse.dok_matrix((4,1))
index = 0
if input_vector[0] > 0 and input_vector[1] > 0:
index = 0
if input_vector[0] < 0 < input_vector[1]:
index = 1
if input_vector[0] < 0 and input_vector[1] < 0:
index = 2
if input_vector[0] > 0 > input_vector[1]:
index = 3
result[index, 0] = 1.0
return result
encoding_map = MyEncodingMap()
import matplotlib.pyplot as plt
plt.scatter(
X_train[:,0], X_train[:,1],
color=['red' if yy == 0 else 'blue' for yy in y_train],
marker='x', s=200)
plt.scatter(
X_test[:,0], X_test[:,1],
color=['red' if yy == 0 else 'blue' for yy in y_test],
marker='o', s=200)
plt.hlines(0.0, -1.0, 1.0)
plt.vlines(0.0, -1.0, 1.0)
plt.show()
from qiskit_aer.backends.aerbackend import AerBackend
from dc_qiskit_qml.distance_based.hadamard import QmlHadamardNeighborClassifier
from dc_qiskit_qml.distance_based.hadamard.state import QmlBinaryDataStateCircuitBuilder
from dc_qiskit_qml.distance_based.hadamard.state.cnot import CCXToffoli
initial_state_builder = QmlBinaryDataStateCircuitBuilder(CCXToffoli(), do_optimizations=False)
execution_backend: AerBackend = qiskit.Aer.get_backend('qasm_simulator')
qml = QmlHadamardNeighborClassifier(backend=execution_backend,
shots=8192,
encoding_map=encoding_map,
classifier_circuit_factory=initial_state_builder)
qml.fit(X_train, y_train)
qml.predict(X_test), y_test
qml._last_predict_circuits[0].draw(output='mpl', fold=-1)
initial_state_builder = QmlBinaryDataStateCircuitBuilder(CCXToffoli(), do_optimizations=True)
execution_backend: AerBackend = qiskit.Aer.get_backend('qasm_simulator')
qml = QmlHadamardNeighborClassifier(backend=execution_backend,
shots=8192,
encoding_map=encoding_map,
classifier_circuit_factory=initial_state_builder)
qml.fit(X_train, y_train)
qml.predict(X_test), y_test
qml._last_predict_circuits[0].draw(output='mpl', fold=-1)
from qiskit_ibm_provider import IBMProvider, IBMBackend
provider : IBMProvider = IBMProvider()
ibm_brisbane: IBMBackend = provider.get_backend('ibm_brisbane')
transpiled_qc = qiskit.transpile(qml._last_predict_circuits[0], backend=ibm_brisbane)
qobj = qiskit.assemble(transpiled_qc, backend=ibm_brisbane)
print("Number of gates: {}.\n".format(len(transpiled_qc.data)))
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
import qiskit
import numpy as np
X_train = np.asarray([[1.0, 1.0], [-1.0, 1.0], [-1.0, -1.0], [1.0, -1.0]])
y_train = [0, 1, 0, 1]
X_test = np.asarray([[0.2, 0.4], [0.4, -0.8]])
y_test = [0, 1]
import matplotlib.pyplot as plt
plt.scatter(
X_train[:,0], X_train[:,1],
color=['red' if yy == 0 else 'blue' for yy in y_train],
marker='x', s=200)
plt.scatter(
X_test[:,0], X_test[:,1],
color=['red' if yy == 0 else 'blue' for yy in y_test],
marker='o', s=200)
plt.hlines(0.0, -1.0, 1.0)
plt.vlines(0.0, -1.0, 1.0)
plt.show()
from dc_qiskit_qml.encoding_maps import EncodingMap
import scipy.sparse as sparse
class MyEncodingMap(EncodingMap):
def map(self, input_vector: list) -> sparse.dok_matrix:
result = sparse.dok_matrix((4,1))
index = 0
if input_vector[0] > 0 and input_vector[1] > 0:
index = 0
if input_vector[0] < 0 < input_vector[1]:
index = 1
if input_vector[0] < 0 and input_vector[1] < 0:
index = 2
if input_vector[0] > 0 > input_vector[1]:
index = 3
result[index, 0] = 1.0
return result
encoding_map = MyEncodingMap()
list(zip(X_train, [encoding_map.map(x).keys() for x in X_train]))
list(zip(X_test, [encoding_map.map(x).keys() for x in X_test]))
from qiskit_aer.backends.aerbackend import AerBackend
from dc_qiskit_qml.distance_based.hadamard import QmlHadamardNeighborClassifier
from dc_qiskit_qml.distance_based.hadamard.state import QmlBinaryDataStateCircuitBuilder
from dc_qiskit_qml.distance_based.hadamard.state.cnot import CCXToffoli
initial_state_builder = QmlBinaryDataStateCircuitBuilder(CCXToffoli(), do_optimizations=True)
execution_backend: AerBackend = qiskit.Aer.get_backend('qasm_simulator')
qml = QmlHadamardNeighborClassifier(backend=execution_backend,
shots=8192,
encoding_map=encoding_map,
classifier_circuit_factory=initial_state_builder)
qml.fit(X_train, y_train)
qml.predict(X_test), y_test
qiskit.IBMQ.load_account()
qiskit.IBMQ.get_provider().backends()
qiskit.Aer.backends()
b16 = qiskit.IBMQ.get_provider().get_backend('ibmq_16_melbourne')
b16.status()
execution_backend = b16
qml = QmlHadamardNeighborClassifier(backend=execution_backend,
shots=8192,
encoding_map=encoding_map,
classifier_circuit_factory=initial_state_builder)
qml.fit(X_train, y_train)
async_qml_job = qml.predict_async(X_test)
async_qml_job.job.status(), async_qml_job.job.job_id()
async_qml_job.predict_result(), y_test
qml.last_predict_probability, qml.last_predict_p_acc
qml._last_predict_circuits[0].draw(output='mpl')
from dc_qiskit_qml.distance_based.hadamard.state.cnot import CCXMottonen
initial_state_builder = QmlBinaryDataStateCircuitBuilder(CCXMottonen())
execution_backend: AerBackend = qiskit.Aer.get_backend('qasm_simulator')
qml = QmlHadamardNeighborClassifier(backend=execution_backend,
shots=8192,
encoding_map=encoding_map,
classifier_circuit_factory=initial_state_builder)
qml.fit(X_train, y_train)
qml.predict(X_test), y_test
qml._last_predict_circuits[0].draw(output='mpl', fold=-1)
execution_backend = b16
qml = QmlHadamardNeighborClassifier(backend=execution_backend,
shots=8192,
encoding_map=encoding_map,
classifier_circuit_factory=initial_state_builder)
qml.fit(X_train, y_train)
async_qml_job.job.status(), async_qml_job.job.job_id()
qml.last_predict_probability, qml.last_predict_p_acc
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
import qiskit
from qiskit_aer.backends.aerbackend import AerBackend
from dc_qiskit_qml.encoding_maps import NormedAmplitudeEncoding
from dc_qiskit_qml.distance_based.hadamard import QmlHadamardNeighborClassifier
from dc_qiskit_qml.distance_based.hadamard.state import QmlGenericStateCircuitBuilder
from dc_qiskit_qml.distance_based.hadamard.state.sparsevector import QiskitNativeStatePreparation
initial_state_builder = QmlGenericStateCircuitBuilder(QiskitNativeStatePreparation())
execution_backend: AerBackend = qiskit.Aer.get_backend('qasm_simulator')
qml = QmlHadamardNeighborClassifier(backend=execution_backend,
shots=8192,
classifier_circuit_factory=initial_state_builder,
encoding_map=NormedAmplitudeEncoding())
import numpy as np
from sklearn.preprocessing import StandardScaler, Normalizer
from sklearn.pipeline import Pipeline
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
X, y = load_wine(return_X_y=True)
X_train = X[[33, 88, 144]]
y_train = y[[33, 88, 144]]
X_test = X[[28, 140]]
y_test = y[[28, 140]]
pipeline = Pipeline([
('scaler', StandardScaler()),
('pca2', PCA(n_components=2)),
('l2norm', Normalizer(norm='l2', copy=True)),
('qml', qml)
])
import matplotlib.pyplot as plt
_X = pipeline.fit_transform(X, y)
_X_train = pipeline.transform(X_train)
_X_test = pipeline.transform(X_test)
colors = ['red', 'blue', 'green', 'orange']
plt.scatter(
_X[:,0], _X[:,1],
color=[colors[yy] for yy in y])
plt.scatter(
_X_train[:,0], _X_train[:,1],
color=[colors[yy] for yy in y_train],
marker='x', s=200)
plt.scatter(
_X_test[:,0], _X_test[:,1],
color=[colors[yy] for yy in y_test],
marker='o', s=200)
plt.show()
pipeline.fit(X_train, y_train)
pipeline.predict(X_test), y_test
qml._last_predict_circuits[0].draw(output='mpl', fold=-1)
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
import qiskit
from qiskit_aer.backends.aerbackend import AerBackend
from dc_qiskit_qml.encoding_maps import NormedAmplitudeEncoding
from dc_qiskit_qml.distance_based.hadamard import QmlHadamardNeighborClassifier
from dc_qiskit_qml.distance_based.hadamard.state import QmlGenericStateCircuitBuilder
from dc_qiskit_qml.distance_based.hadamard.state.sparsevector import MottonenStatePreparation
initial_state_builder = QmlGenericStateCircuitBuilder(MottonenStatePreparation())
execution_backend: AerBackend = qiskit.Aer.get_backend('qasm_simulator')
qml = QmlHadamardNeighborClassifier(backend=execution_backend,
shots=8192,
classifier_circuit_factory=initial_state_builder,
encoding_map=NormedAmplitudeEncoding())
from sklearn.preprocessing import StandardScaler, Normalizer
from sklearn.pipeline import Pipeline
from sklearn.datasets import load_wine
X, y = load_wine(return_X_y=True)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.10, random_state=42)
pipeline = Pipeline([
('scaler', StandardScaler()),
('l2norm', Normalizer(norm='l2', copy=True)),
('qml', qml)
])
pipeline.fit(X_train, y_train)
prediction = pipeline.predict(X_test)
prediction
"Test Accuracy: {}".format(
sum([1 if p == t else 0 for p, t in zip(prediction, y_test)])/len(prediction)
)
prediction_train = pipeline.predict(X_train)
"Train Accuracy: {}".format(
sum([1 if p == t else 0 for p, t in zip(prediction_train, y_train)])/len(prediction_train)
)
import matplotlib.pyplot as plt
colors = ['red', 'blue', 'green', 'orange']
plt.scatter(
pipeline.transform(X_train[:,0]), pipeline.transform(X_train[:,1]),
color=[colors[yy] for yy in y_train],
marker='.', s=50)
plt.show()
plt.scatter(
pipeline.transform(X_test[:,0]), pipeline.transform(X_test[:,1]),
color=[colors[yy] for yy in prediction],
marker='.', s=50)
plt.show()
plt.scatter(
pipeline.transform(X_test[:,0]), pipeline.transform(X_test[:,1]),
color=[colors[yy] for yy in y_test],
marker='.', s=20)
plt.show()
_X_train = pipeline.transform(X_train)
_X_test = pipeline.transform(X_test)
for i in range(len(_X_test)):
p_acc_theory = QmlHadamardNeighborClassifier.p_acc_theory(X_train, y_train, X_test[i])
print(f"{qml.last_predict_p_acc[i]:.4f} ~~ {p_acc_theory:.4f}")
for i in range(len(X_test)):
p_label_theory = QmlHadamardNeighborClassifier.p_label_theory(X_train, y_train, X_test[i], prediction[i])
print(f"{qml.last_predict_probability[i]:.4f} ~~ {p_label_theory:.4f}")
print(qml._last_predict_circuits[0].qasm())
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
import qiskit
from qiskit_aer.backends.aerbackend import AerBackend
from dc_qiskit_qml.encoding_maps import NormedAmplitudeEncoding
from dc_qiskit_qml.distance_based.hadamard import QmlHadamardNeighborClassifier
from dc_qiskit_qml.distance_based.hadamard.state import QmlGenericStateCircuitBuilder
from dc_qiskit_qml.distance_based.hadamard.state.sparsevector import MottonenStatePreparation
initial_state_builder = QmlGenericStateCircuitBuilder(MottonenStatePreparation())
execution_backend: AerBackend = qiskit.Aer.get_backend('qasm_simulator')
qml = QmlHadamardNeighborClassifier(backend=execution_backend,
shots=8192,
classifier_circuit_factory=initial_state_builder,
encoding_map=NormedAmplitudeEncoding())
import numpy as np
from sklearn.preprocessing import StandardScaler, Normalizer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.10, random_state=42)
pipeline = Pipeline([
('scaler', StandardScaler()),
('pca2', PCA(n_components=2)),
('l2norm', Normalizer(norm='l2', copy=True)),
('qml', qml)
])
import matplotlib.pyplot as plt
_X = pipeline.fit_transform(X, y)
figure = plt.figure(figsize=(5,5), num=2)
sub1 = figure.subplots(nrows=1, ncols=1)
class_0_data = np.asarray([_X[i] for i in range(len(_X)) if y[i] == 0])
class_1_data = np.asarray([_X[i] for i in range(len(_X)) if y[i] == 1])
class_2_data = np.asarray([_X[i] for i in range(len(_X)) if y[i] == 2])
class_0 = sub1.scatter(class_0_data[:,0], class_0_data[:,1], color='red', marker='x', s=50)
class_1 = sub1.scatter(class_1_data[:,0], class_1_data[:,1], color='blue', marker='x', s=50)
class_2 = sub1.scatter(class_2_data[:,0], class_2_data[:,1], color='green', marker='x', s=50)
sub1.plot([np.cos(x) for x in np.arange(0, 2*np.pi, 0.1)], [np.sin(x) for x in np.arange(0, 2*np.pi, 0.1)],
color='black', linewidth=1)
sub1.set_title("Iris Data")
sub1.legend([class_0, class_1, class_2], ["Class 1", "Class 2", "Class 3"])
sub1.axvline(color='gray')
sub1.axhline(color='gray')
_X_train = pipeline.transform(X_train)
_X_test = pipeline.transform(X_test)
figure = plt.figure(figsize=(10,4.5), num=2)
sub1, sub2 = figure.subplots(nrows=1, ncols=2)
class_0_data = np.asarray([_X_train[i] for i in range(len(_X_train)) if y_train[i] == 0])
class_1_data = np.asarray([_X_train[i] for i in range(len(_X_train)) if y_train[i] == 1])
class_2_data = np.asarray([_X_train[i] for i in range(len(_X_train)) if y_train[i] == 2])
class_0 = sub1.scatter(class_0_data[:,0], class_0_data[:,1], color='red', marker='x', s=50)
class_1 = sub1.scatter(class_1_data[:,0], class_1_data[:,1], color='blue', marker='x', s=50)
class_2 = sub1.scatter(class_2_data[:,0], class_2_data[:,1], color='green', marker='x', s=50)
sub1.plot([np.cos(x) for x in np.arange(0, 2*np.pi, 0.1)], [np.sin(x) for x in np.arange(0, 2*np.pi, 0.1)],
color='black', linewidth=1)
sub1.set_title("Training data")
sub1.legend([class_0, class_1, class_2], ["Class 1", "Class 2", "Class 3"])
sub1.axvline(color='gray')
sub1.axhline(color='gray')
class_0_data_test = np.asarray([_X_test[i] for i in range(len(_X_test)) if y_test[i] == 0])
class_1_data_test = np.asarray([_X_test[i] for i in range(len(_X_test)) if y_test[i] == 1])
class_2_data_test = np.asarray([_X_test[i] for i in range(len(_X_test)) if y_test[i] == 2])
class_0 = sub2.scatter(class_0_data_test[:,0], class_0_data_test[:,1], color='red', marker='x', s=50)
class_1 = sub2.scatter(class_1_data_test[:,0], class_1_data_test[:,1], color='blue', marker='x', s=50)
class_2 = sub2.scatter(class_2_data_test[:,0], class_2_data_test[:,1], color='green', marker='x', s=50)
sub2.plot([np.cos(x) for x in np.arange(0, 2*np.pi, 0.1)], [np.sin(x) for x in np.arange(0, 2*np.pi, 0.1)],
color='black', linewidth=1)
sub2.set_title("Testing data")
sub2.legend([class_0, class_1, class_2], ["Class 1", "Class 2", "Class 3"])
sub2.axvline(color='gray')
sub2.axhline(color='gray')
pipeline.fit(X_train, y_train)
prediction = pipeline.predict(X_test)
prediction
"Test Accuracy: {}".format(
sum([1 if p == t else 0 for p, t in zip(prediction, y_test)])/len(prediction)
)
prediction_train = pipeline.predict(X_train)
"Train Accuracy: {}".format(
sum([1 if p == t else 0 for p, t in zip(prediction_train, y_train)])/len(prediction_train)
)
for i in range(len(_X_test)):
p_acc_theory = QmlHadamardNeighborClassifier.p_acc_theory(_X_train, y_train, _X_test[i])
print(f"{qml.last_predict_p_acc[i]:.4f} ~~ {p_acc_theory:.4f}")
for i in range(len(_X_test)):
p_label_theory = QmlHadamardNeighborClassifier.p_label_theory(_X_train, y_train, _X_test[i], prediction[i])
print(f"{qml.last_predict_probability[i]:.4f} ~~ {p_label_theory:.4f}")
print(qml._last_predict_circuits[0].qasm())
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018, Carsten Blank.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
import logging
import unittest
import numpy
import qiskit
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, Normalizer
from dc_qiskit_qml.distance_based.compact_hadamard.compact_hadamard_classifier import CompactHadamardClassifier
from dc_qiskit_qml.encoding_maps import NormedAmplitudeEncoding
logging.basicConfig(format=logging.BASIC_FORMAT, level='INFO')
log = logging.getLogger(__name__)
class FullIris(unittest.TestCase):
def test(self):
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
X = numpy.asarray([x for x, yy in zip(X, y) if yy != 2])
y = numpy.asarray([yy for x, yy in zip(X, y) if yy != 2])
preprocessing_pipeline = Pipeline([
('scaler', StandardScaler()),
('l2norm', Normalizer(norm='l2', copy=True))
])
X = preprocessing_pipeline.fit_transform(X, y)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.10, random_state=42)
execution_backend = qiskit.Aer.get_backend('qasm_simulator') # type: BaseBackend
qml = CompactHadamardClassifier(backend=execution_backend,
shots=8192,
encoding_map=NormedAmplitudeEncoding())
qml.fit(X_train, y_train)
prediction = qml.predict(X_test)
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018, Carsten Blank.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
import logging
import sys
import unittest
from typing import Dict
import numpy as np
import qiskit
from qiskit import QuantumCircuit, ClassicalRegister
from qiskit.providers import BackendV2
from scipy import sparse
from dc_qiskit_qml.distance_based.hadamard.state import QmlBinaryDataStateCircuitBuilder
from dc_qiskit_qml.distance_based.hadamard.state.cnot import CCXMottonen, CCXToffoli
from dc_qiskit_qml.encoding_maps import EncodingMap
from dc_qiskit_qml.encoding_maps import FixedLengthQubitEncoding
logger = logging.getLogger()
logger.level = logging.DEBUG
stream_handler = logging.StreamHandler(sys.stderr)
stream_handler.setFormatter(logging._defaultFormatter)
logger.addHandler(stream_handler)
def extract_gate_info(qc, index):
# type: (QuantumCircuit, int) -> list
return [qc.data[index][0].name, qc.data[index][0].params, str(qc.data[index][1][-1])]
class QubitEncodingClassifierStateCircuitTests(unittest.TestCase):
def test_one(self):
encoding_map = FixedLengthQubitEncoding(4, 4)
X_train = [
[4.4, -9.53],
[18.42, 1.0]
]
y_train = [0, 1]
input = [2.043, 13.84]
X_train_in_encoded_space = [encoding_map.map(x) for x in X_train]
X_train_in_encoded_space_qubit_notation = [["{:b}".format(i).zfill(2 * 9) for i, _ in elem.keys()] for elem in
X_train_in_encoded_space]
input_in_feature_space = encoding_map.map(input)
input_in_feature_space_qubit_notation = ["{:b}".format(i).zfill(2 * 9) for i, _ in
input_in_feature_space.keys()]
logger.info("Training samples in encoded space: {}".format(X_train_in_encoded_space_qubit_notation))
logger.info("Input sample in encoded space: {}".format(input_in_feature_space_qubit_notation))
circuit = QmlBinaryDataStateCircuitBuilder(CCXMottonen())
qc = circuit.build_circuit('test', X_train=X_train_in_encoded_space, y_train=y_train, X_input=input_in_feature_space)
self.assertIsNotNone(qc)
self.assertIsNotNone(qc.data)
self.assertEqual(30, len(qc.data))
self.assertListEqual(["h"], [qc.data[0][0].name])
self.assertListEqual(["h"], [qc.data[1][0].name])
self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(18, 'f^S'), 3)"], extract_gate_info(qc, 2))
self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(18, 'f^S'), 4)"], extract_gate_info(qc, 3))
self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(18, 'f^S'), 7)"], extract_gate_info(qc, 4))
self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(18, 'f^S'), 8)"], extract_gate_info(qc, 5))
self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(18, 'f^S'), 10)"], extract_gate_info(qc, 6))
self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(18, 'f^S'), 11)"], extract_gate_info(qc, 7))
self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(18, 'f^S'), 15)"], extract_gate_info(qc, 8))
self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(18, 'f^S'), 0)"], extract_gate_info(qc, 9))
self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(18, 'f^S'), 2)"], extract_gate_info(qc, 10))
self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(18, 'f^S'), 3)"], extract_gate_info(qc, 11))
self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(18, 'f^S'), 4)"], extract_gate_info(qc, 12))
self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(18, 'f^S'), 6)"], extract_gate_info(qc, 13))
self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(18, 'f^S'), 7)"], extract_gate_info(qc, 14))
self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(18, 'f^S'), 14)"], extract_gate_info(qc, 15))
self.assertListEqual(["ccx_uni_rot", [2], "Qubit(QuantumRegister(18, 'f^S'), 4)"], extract_gate_info(qc, 16))
self.assertListEqual(["ccx_uni_rot", [2], "Qubit(QuantumRegister(18, 'f^S'), 10)"], extract_gate_info(qc, 17))
self.assertListEqual(["ccx_uni_rot", [2], "Qubit(QuantumRegister(18, 'f^S'), 11)"], extract_gate_info(qc, 18))
self.assertListEqual(["ccx_uni_rot", [2], "Qubit(QuantumRegister(18, 'f^S'), 13)"], extract_gate_info(qc, 19))
self.assertListEqual(["ccx_uni_rot", [2], "Qubit(QuantumRegister(18, 'f^S'), 16)"], extract_gate_info(qc, 20))
self.assertListEqual(["ccx_uni_rot", [2], "Qubit(QuantumRegister(1, 'l^q'), 0)"], extract_gate_info(qc, 21))
self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(18, 'f^S'), 0)"], extract_gate_info(qc, 22))
self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(18, 'f^S'), 2)"], extract_gate_info(qc, 23))
self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(18, 'f^S'), 3)"], extract_gate_info(qc, 24))
self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(18, 'f^S'), 4)"], extract_gate_info(qc, 25))
self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(18, 'f^S'), 6)"], extract_gate_info(qc, 26))
self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(18, 'f^S'), 7)"], extract_gate_info(qc, 27))
self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(18, 'f^S'), 14)"], extract_gate_info(qc, 28))
self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(1, 'l^q'), 0)"], extract_gate_info(qc, 29))
def test_two(self):
encoding_map = FixedLengthQubitEncoding(2, 2)
X_train = [
[4.4, -9.53],
[18.42, 1.0]
]
y_train = [0, 1]
input = [2.043, 13.84]
X_train_in_encoded_space = [encoding_map.map(x) for x in X_train]
X_train_in_encoded_space_qubit_notation = [["{:b}".format(i).zfill(2*5) for i, _ in elem.keys()] for elem in X_train_in_encoded_space]
input_in_feature_space = encoding_map.map(input)
input_in_feature_space_qubit_notation = ["{:b}".format(i).zfill(2*5) for i, _ in input_in_feature_space.keys()]
logger.info("Training samples in encoded space: {}".format(X_train_in_encoded_space_qubit_notation))
logger.info("Input sample in encoded space: {}".format(input_in_feature_space_qubit_notation))
circuit = QmlBinaryDataStateCircuitBuilder(CCXMottonen())
qc = circuit.build_circuit('test', X_train=X_train_in_encoded_space, y_train=y_train, X_input=input_in_feature_space)
self.assertIsNotNone(qc)
self.assertIsNotNone(qc.data)
self.assertEqual(len(qc.data), 22)
self.assertListEqual(["h"], [qc.data[0][0].name])
self.assertListEqual(["h"], [qc.data[1][0].name])
self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(10, 'f^S'), 1)"], extract_gate_info(qc, 2))
self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(10, 'f^S'), 3)"], extract_gate_info(qc, 3))
self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(10, 'f^S'), 4)"], extract_gate_info(qc, 4))
self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(10, 'f^S'), 5)"], extract_gate_info(qc, 5))
self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(10, 'f^S'), 8)"], extract_gate_info(qc, 6))
self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(10, 'f^S'), 0)"], extract_gate_info(qc, 7))
self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(10, 'f^S'), 1)"], extract_gate_info(qc, 8))
self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(10, 'f^S'), 2)"], extract_gate_info(qc, 9))
self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(10, 'f^S'), 3)"], extract_gate_info(qc, 10))
self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(10, 'f^S'), 8)"], extract_gate_info(qc, 11))
self.assertListEqual(["ccx_uni_rot", [2], "Qubit(QuantumRegister(10, 'f^S'), 2)"], extract_gate_info(qc, 12))
self.assertListEqual(["ccx_uni_rot", [2], "Qubit(QuantumRegister(10, 'f^S'), 5)"], extract_gate_info(qc, 13))
self.assertListEqual(["ccx_uni_rot", [2], "Qubit(QuantumRegister(10, 'f^S'), 8)"], extract_gate_info(qc, 14))
self.assertListEqual(["ccx_uni_rot", [2], "Qubit(QuantumRegister(1, 'l^q'), 0)"], extract_gate_info(qc, 15))
self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(10, 'f^S'), 0)"], extract_gate_info(qc, 16))
self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(10, 'f^S'), 1)"], extract_gate_info(qc, 17))
self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(10, 'f^S'), 2)"], extract_gate_info(qc, 18))
self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(10, 'f^S'), 3)"], extract_gate_info(qc, 19))
self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(10, 'f^S'), 8)"], extract_gate_info(qc, 20))
self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(1, 'l^q'), 0)"], extract_gate_info(qc, 21))
qregs = qc.qregs
cregs = [ClassicalRegister(qr.size, 'c' + qr.name) for qr in qregs]
qc2 = QuantumCircuit(*qregs, *cregs, name='test2')
qc2.data = qc.data
for i in range(len(qregs)):
qc2.measure(qregs[i], cregs[i])
execution_backend = qiskit.Aer.get_backend('qasm_simulator') # type: BackendV2
job = qiskit.execute(qc2, execution_backend, shots=8192)
counts = job.result().get_counts() # type: dict
self.assertListEqual(sorted(counts.keys()), sorted(['0 0100111010 0 0', '0 0100001111 0 1', '1 0100100100 1 0', '1 0100001111 1 1']))
def test_three(self):
encoding_map = FixedLengthQubitEncoding(4, 4)
X_train = [
[4.4, -9.53],
[18.42, 1.0]
]
y_train = [0, 1]
input = [2.043, 13.84]
X_train_in_encoded_space = [encoding_map.map(x) for x in X_train]
X_train_in_encoded_space_qubit_notation = [["{:b}".format(i).zfill(2 * 9) for i, _ in elem.keys()] for elem in
X_train_in_encoded_space]
input_in_feature_space = encoding_map.map(input)
input_in_feature_space_qubit_notation = ["{:b}".format(i).zfill(2 * 9) for i, _ in
input_in_feature_space.keys()]
logger.info("Training samples in encoded space: {}".format(X_train_in_encoded_space_qubit_notation))
logger.info("Input sample in encoded space: {}".format(input_in_feature_space_qubit_notation))
circuit = QmlBinaryDataStateCircuitBuilder(CCXToffoli())
qc = circuit.build_circuit('test', X_train=X_train_in_encoded_space, y_train=y_train, X_input=input_in_feature_space)
self.assertIsNotNone(qc)
self.assertIsNotNone(qc.data)
# TODO: adjust ASAP
# self.assertEqual(36, len(qc.data))
#
# self.assertListEqual(["h"], [qc.data[0].name])
# self.assertListEqual(["h"], [qc.data[1].name])
#
# self.assertListEqual(["x", [], "(QuantumRegister(1, 'a'), 0)"], extract_gate_info(qc, 2))
# self.assertListEqual(["x", [], "(QuantumRegister(1, 'i'), 0)"], extract_gate_info(qc, 3))
#
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 3)"], extract_gate_info(qc, 4))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 4)"], extract_gate_info(qc, 5))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 7)"], extract_gate_info(qc, 6))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 8)"], extract_gate_info(qc, 7))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 10)"], extract_gate_info(qc, 8))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 11)"], extract_gate_info(qc, 9))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 15)"], extract_gate_info(qc, 10))
#
# self.assertListEqual(["x", [], "(QuantumRegister(1, 'a'), 0)"], extract_gate_info(qc, 11))
#
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 0)"], extract_gate_info(qc, 12))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 2)"], extract_gate_info(qc, 13))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 3)"], extract_gate_info(qc, 14))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 4)"], extract_gate_info(qc, 15))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 6)"], extract_gate_info(qc, 16))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 7)"], extract_gate_info(qc, 17))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 14)"], extract_gate_info(qc, 18))
#
# self.assertListEqual(["x", [], "(QuantumRegister(1, 'i'), 0)"], extract_gate_info(qc, 19))
#
# self.assertListEqual(["x", [], "(QuantumRegister(1, 'a'), 0)"], extract_gate_info(qc, 20))
#
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 4)"], extract_gate_info(qc, 21))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 10)"], extract_gate_info(qc, 22))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 11)"], extract_gate_info(qc, 23))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 13)"], extract_gate_info(qc, 24))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 16)"], extract_gate_info(qc, 25))
# self.assertListEqual(["ccx", [], "(QuantumRegister(1, 'l^q'), 0)"], extract_gate_info(qc, 26))
#
# self.assertListEqual(["x", [], "(QuantumRegister(1, 'a'), 0)"], extract_gate_info(qc, 27))
#
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 0)"], extract_gate_info(qc, 28))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 2)"], extract_gate_info(qc, 29))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 3)"], extract_gate_info(qc, 30))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 4)"], extract_gate_info(qc, 31))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 6)"], extract_gate_info(qc, 32))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 7)"], extract_gate_info(qc, 33))
# self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 14)"], extract_gate_info(qc, 34))
# self.assertListEqual(["ccx", [], "(QuantumRegister(1, 'l^q'), 0)"], extract_gate_info(qc, 35))
def test_four(self):
encoding_map = FixedLengthQubitEncoding(2, 2)
X_train = [
[4.4, -9.53],
[18.42, 1.0]
]
y_train = [0, 1]
input = [2.043, 13.84]
X_train_in_encoded_space = [encoding_map.map(x) for x in X_train]
X_train_in_encoded_space_qubit_notation = [["{:b}".format(i).zfill(2*5) for i, _ in elem.keys()] for elem in X_train_in_encoded_space]
input_in_encoded_space = encoding_map.map(input)
input_in_encoded_space_qubit_notation = ["{:b}".format(i).zfill(2*5) for i, _ in input_in_encoded_space.keys()]
logger.info("Training samples in encoded space: {}".format(X_train_in_encoded_space_qubit_notation))
logger.info("Input sample in encoded space: {}".format(input_in_encoded_space_qubit_notation))
circuit = QmlBinaryDataStateCircuitBuilder(CCXToffoli())
qc = circuit.build_circuit('test', X_train=X_train_in_encoded_space, y_train=y_train, X_input=input_in_encoded_space)
self.assertIsNotNone(qc)
self.assertIsNotNone(qc.data)
# TODO: adjust ASAP
# self.assertEqual(28, len(qc.data))
#
# self.assertListEqual(["h"], [qc.data[0].name])
# self.assertListEqual(["h"], [qc.data[1].name])
#
# self.assertListEqual(["x", [], "(QuantumRegister(1, 'a'), 0)"], extract_gate_info(qc, 2))
# self.assertListEqual(["x", [], "(QuantumRegister(1, 'i'), 0)"], extract_gate_info(qc, 3))
#
# self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 1)"], extract_gate_info(qc, 4))
# self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 3)"], extract_gate_info(qc, 5))
# self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 4)"], extract_gate_info(qc, 6))
# self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 5)"], extract_gate_info(qc, 7))
# self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 8)"], extract_gate_info(qc, 8))
#
# self.assertListEqual(["x", [], "(QuantumRegister(1, 'a'), 0)"], extract_gate_info(qc, 9))
#
# self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 0)"], extract_gate_info(qc, 10))
# self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 1)"], extract_gate_info(qc, 11))
# self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 2)"], extract_gate_info(qc, 12))
# self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 3)"], extract_gate_info(qc, 13))
# self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 8)"], extract_gate_info(qc, 14))
#
# self.assertListEqual(["x", [], "(QuantumRegister(1, 'i'), 0)"], extract_gate_info(qc, 15))
#
# self.assertListEqual(["x", [], "(QuantumRegister(1, 'a'), 0)"], extract_gate_info(qc, 16))
#
# self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 2)"], extract_gate_info(qc, 17))
# self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 5)"], extract_gate_info(qc, 18))
# self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 8)"], extract_gate_info(qc, 19))
# self.assertListEqual(["ccx", [], "(QuantumRegister(1, 'l^q'), 0)"], extract_gate_info(qc, 20))
#
# self.assertListEqual(["x", [], "(QuantumRegister(1, 'a'), 0)"], extract_gate_info(qc, 21))
#
# self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 0)"], extract_gate_info(qc, 22))
# self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 1)"], extract_gate_info(qc, 23))
# self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 2)"], extract_gate_info(qc, 24))
# self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 3)"], extract_gate_info(qc, 25))
# self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 8)"], extract_gate_info(qc, 26))
#
# self.assertListEqual(["ccx", [], "(QuantumRegister(1, 'l^q'), 0)"], extract_gate_info(qc, 27))
cregs = [ClassicalRegister(qr.size, 'c' + qr.name) for qr in qc.qregs]
qc2 = QuantumCircuit(*qc.qregs, *cregs, name='test2')
qc2.data = qc.data
for i in range(len(qc.qregs)):
qc2.measure(qc.qregs[i], cregs[i])
execution_backend = qiskit.Aer.get_backend('qasm_simulator') # type: BackendV2
job = qiskit.execute([qc2], execution_backend, shots=8192)
counts = job.result().get_counts() # type: dict
self.assertListEqual(sorted(['0 0100111010 0 0', '0 0100001111 0 1', '1 0100100100 1 0', '1 0100001111 1 1']), sorted(counts.keys()))
def test_five(self):
X_train = np.asarray([[1.0, 1.0], [-1.0, 1.0], [-1.0, -1.0], [1.0, -1.0]])
y_train = [0, 1, 0, 1]
X_test = np.asarray([[0.2, 0.4], [0.4, -0.8]])
y_test = [0, 1]
class MyEncodingMap(EncodingMap):
def map(self, input_vector: list) -> sparse.dok_matrix:
result = sparse.dok_matrix((4, 1))
index = 0
if input_vector[0] > 0 and input_vector[1] > 0:
index = 0
if input_vector[0] < 0 and input_vector[1] > 0:
index = 1
if input_vector[0] < 0 and input_vector[1] < 0:
index = 2
if input_vector[0] > 0 and input_vector[1] < 0:
index = 3
result[index, 0] = 1.0
return result
initial_state_builder = QmlBinaryDataStateCircuitBuilder(CCXToffoli())
encoding_map = MyEncodingMap()
X_train_in_encoded_space = [encoding_map.map(s) for s in X_train]
X_test_in_encoded_space = [encoding_map.map(s) for s in X_test]
qc = initial_state_builder.build_circuit('test', X_train_in_encoded_space, y_train, X_test_in_encoded_space[0])
self.assertIsNotNone(qc)
self.assertIsNotNone(qc.data)
# self.assertEqual(len(qc.data), 28)
# self.assertListEqual(["h"], [qc.data[0].name])
# self.assertListEqual(["h"], [qc.data[1].name])
qregs = qc.qregs
cregs = [ClassicalRegister(qr.size, 'c_' + qr.name) for qr in qregs]
qc2 = QuantumCircuit(*qregs, *cregs, name='test2')
qc2.data = qc.data
for i in range(len(qregs)):
qc2.measure(qregs[i], cregs[i])
execution_backend = qiskit.Aer.get_backend('qasm_simulator') # type: BackendV2
job = qiskit.execute(qc2, execution_backend, shots=8192) # type: AerJob
counts = job.result().get_counts() # type: Dict[str, int]
self.assertListEqual(
sorted([
'00 0 00 00 0',
'00 0 00 00 1',
'00 1 01 01 0',
'00 1 00 01 1',
'00 0 10 10 0',
'00 0 00 10 1',
'00 1 11 11 0',
'00 1 00 11 1'
]),
sorted(counts.keys())
)
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
import logging
import unittest
import numpy
import qiskit
from qiskit.providers import BackendV2, JobV1
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, Normalizer
from dc_qiskit_qml.distance_based.hadamard.state import QmlGenericStateCircuitBuilder
from dc_qiskit_qml.distance_based.hadamard.state.sparsevector import MottonenStatePreparation
from dc_qiskit_qml.encoding_maps import IdentityEncodingMap
logging.basicConfig(format=logging.BASIC_FORMAT, level='INFO')
log = logging.getLogger(__name__)
class MottonenStatePreparationTest(unittest.TestCase):
def runTest(self):
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
X = numpy.asarray([x[0:2] for x, yy in zip(X, y) if yy != 2])
y = numpy.asarray([yy for x, yy in zip(X, y) if yy != 2])
preprocessing_pipeline = Pipeline([
('scaler', StandardScaler()),
('l2norm', Normalizer(norm='l2', copy=True))
])
X = preprocessing_pipeline.fit_transform(X, y)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.10, random_state=42)
encoding_map = IdentityEncodingMap()
initial_state_builder = QmlGenericStateCircuitBuilder(MottonenStatePreparation())
qc = initial_state_builder.build_circuit("test", [encoding_map.map(e) for e in X_train], y_train,
encoding_map.map(X_test[0]))
statevector_backend = qiskit.Aer.get_backend('statevector_simulator') # type: BackendV2
job = qiskit.execute(qc, statevector_backend, shots=1) # type: JobV1
simulator_state_vector = numpy.asarray(job.result().get_statevector())
input_state_vector = initial_state_builder.get_last_state_vector()
phase = set(numpy.angle(simulator_state_vector)[numpy.abs(simulator_state_vector) > 1e-3]).pop()
simulator_state_vector[numpy.abs(simulator_state_vector) < 1e-3] = 0
simulator_state_vector = numpy.exp(-1.0j * phase) * simulator_state_vector
for i, s in zip(input_state_vector.toarray(), simulator_state_vector):
log.debug("{:.4f} == {:.4f}".format(i[0], s))
self.assertAlmostEqual(i[0], s, places=3)
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018, Carsten Blank.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
import logging
import unittest
import numpy
import qiskit
from qiskit.providers import BackendV2
from scipy import sparse
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, Normalizer
from dc_qiskit_qml.distance_based.hadamard import QmlHadamardNeighborClassifier
from dc_qiskit_qml.distance_based.hadamard.state import QmlBinaryDataStateCircuitBuilder
from dc_qiskit_qml.distance_based.hadamard.state import QmlGenericStateCircuitBuilder
from dc_qiskit_qml.distance_based.hadamard.state.cnot import CCXToffoli
from dc_qiskit_qml.distance_based.hadamard.state.sparsevector import MottonenStatePreparation
from dc_qiskit_qml.distance_based.hadamard.state.sparsevector import FFQRAMStateVectorRoutine
from dc_qiskit_qml.distance_based.hadamard.state.sparsevector import QiskitNativeStatePreparation
from dc_qiskit_qml.encoding_maps import EncodingMap, NormedAmplitudeEncoding
logging.basicConfig(format=logging.BASIC_FORMAT, level='INFO')
log = logging.getLogger(__name__)
def get_data(only_two_features=True):
from sklearn.preprocessing import StandardScaler, Normalizer
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
X = [x[0:2] if only_two_features else x for x, y in zip(X, y) if y != 2]
y = [y for x, y in zip(X, y) if y != 2]
scaler, normalizer = StandardScaler(), Normalizer(norm='l2', copy=True)
X = scaler.fit_transform(X, y)
X = normalizer.fit_transform(X, y)
return X, y
def predict(qml, only_two_features=True):
# type: (QmlHadamardNeighborClassifier, bool) -> tuple
X, y = get_data(only_two_features)
X_train = [X[33], X[85]]
y_train = [y[33], y[85]]
X_test = [X[28], X[36]]
y_test = [y[28], y[36]]
log.info("Training with %d samples.", len(X_train))
qml.fit(X_train, y_train)
log.info("Predict on %d unseen samples.", len(X_test))
for i in X_test:
log.info("Predict: %s.", i)
labels = qml.predict(X_test)
log.info("Predict: %s (%s%% / %s). Expected: %s" % (labels, qml.last_predict_probability,
qml.last_predict_p_acc, y_test))
return labels, y_test
# noinspection NonAsciiCharacters
class QmlHadamardMöttönenTests(unittest.TestCase):
def runTest(self):
log.info("Testing 'QmlHadamardNeighborClassifier' with Möttönen Preparation.")
execution_backend = qiskit.Aer.get_backend('qasm_simulator') # type: BackendV2
classifier_state_factory = QmlGenericStateCircuitBuilder(MottonenStatePreparation())
qml = QmlHadamardNeighborClassifier(encoding_map=NormedAmplitudeEncoding(),
classifier_circuit_factory=classifier_state_factory,
backend=execution_backend, shots=100 * 8192)
y_predict, y_test = predict(qml)
predictions_match = [p == l for p, l in zip(y_predict, y_test)]
self.assertTrue(all(predictions_match))
self.assertEqual(len(qml.last_predict_probability), 2)
input_1_probability = qml.last_predict_probability[0]
input_2_probability = qml.last_predict_probability[1]
self.assertAlmostEqual(input_1_probability, 0.629, delta=0.02)
self.assertAlmostEqual(input_2_probability, 0.547, delta=0.02)
class QmlHadamardFFQramTests(unittest.TestCase):
def runTest(self):
log.info("Testing 'QmlHadamardNeighborClassifier' with FF Qram Preparation.")
execution_backend = qiskit.Aer.get_backend('qasm_simulator') # type: BackendV2
classifier_state_factory = QmlGenericStateCircuitBuilder(FFQRAMStateVectorRoutine())
qml = QmlHadamardNeighborClassifier(backend=execution_backend,
classifier_circuit_factory=classifier_state_factory,
encoding_map=NormedAmplitudeEncoding(),
shots=100 * 8192)
y_predict, y_test = predict(qml)
predictions_match = [p == l for p, l in zip(y_predict, y_test)]
self.assertTrue(all(predictions_match), "The predictions must be correct.")
self.assertEqual(len(qml.last_predict_probability), 2)
input_1_probability = qml.last_predict_probability[0]
input_2_probability = qml.last_predict_probability[1]
self.assertAlmostEqual(input_1_probability, 0.629, delta=0.02)
self.assertAlmostEqual(input_2_probability, 0.547, delta=0.02)
class QmlHadamardQiskitInitializerTests(unittest.TestCase):
def runTest(self):
log.info("Testing 'QmlHadamardNeighborClassifier' with FF Qram Preparation.")
execution_backend = qiskit.Aer.get_backend('qasm_simulator') # type: BackendV2
classifier_state_factory = QmlGenericStateCircuitBuilder(QiskitNativeStatePreparation())
qml = QmlHadamardNeighborClassifier(backend=execution_backend,
classifier_circuit_factory=classifier_state_factory,
encoding_map=NormedAmplitudeEncoding(),
shots=100 * 8192)
y_predict, y_test = predict(qml)
predictions_match = [p == l for p, l in zip(y_predict, y_test)]
self.assertTrue(all(predictions_match), "The predictions must be correct.")
self.assertEqual(len(qml.last_predict_probability), 2)
input_1_probability = qml.last_predict_probability[0]
input_2_probability = qml.last_predict_probability[1]
self.assertAlmostEqual(input_1_probability, 0.629, delta=0.02)
self.assertAlmostEqual(input_2_probability, 0.547, delta=0.02)
# noinspection NonAsciiCharacters
class QmlHadamardMultiClassesTests(unittest.TestCase):
def runTest(self):
log.info("Testing 'QmlHadamardNeighborClassifier' with Möttönen Preparation.")
execution_backend = qiskit.Aer.get_backend('qasm_simulator') # type: BackendV2
classifier_state_factory = QmlGenericStateCircuitBuilder(MottonenStatePreparation())
qml = QmlHadamardNeighborClassifier(encoding_map=NormedAmplitudeEncoding(),
classifier_circuit_factory=classifier_state_factory,
backend=execution_backend, shots=100 * 8192)
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler, Normalizer
from sklearn.pipeline import Pipeline
X, y = load_wine(return_X_y=True)
preprocessing_pipeline = Pipeline([
('scaler', StandardScaler()),
('pca2', PCA(n_components=2)),
('l2norm', Normalizer(norm='l2', copy=True))
])
X = preprocessing_pipeline.fit_transform(X, y)
X_train = X[[33, 88, 144]]
y_train = y[[33, 88, 144]]
X_test = X[[28, 140]]
y_test = y[[28, 140]]
qml.fit(X_train, y_train)
prediction = qml.predict(X_test)
self.assertEqual(len(prediction), len(y_test))
self.assertListEqual(prediction, list(y_test))
# noinspection NonAsciiCharacters
class QmlHadamardCNOTQubitEncodingTests(unittest.TestCase):
def runTest(self):
log.info("Testing 'QmlHadamardNeighborClassifier' with CNOT Preparation.")
execution_backend = qiskit.Aer.get_backend('qasm_simulator') # type: BackendV2
X_train = numpy.asarray([[1.0, 1.0], [-1.0, 1.0], [-1.0, -1.0], [1.0, -1.0]])
y_train = [0, 1, 0, 1]
X_test = numpy.asarray([[0.2, 0.4], [0.4, -0.8]])
y_test = [0, 1]
class MyEncodingMap(EncodingMap):
def map(self, input_vector: list) -> sparse.dok_matrix:
result = sparse.dok_matrix((4, 1))
index = 0
if input_vector[0] > 0 and input_vector[1] > 0:
index = 0
if input_vector[0] < 0 < input_vector[1]:
index = 1
if input_vector[0] < 0 and input_vector[1] < 0:
index = 2
if input_vector[0] > 0 > input_vector[1]:
index = 3
result[index, 0] = 1.0
return result
encoding_map = MyEncodingMap()
initial_state_builder = QmlBinaryDataStateCircuitBuilder(CCXToffoli())
qml = QmlHadamardNeighborClassifier(backend=execution_backend,
shots=100 * 8192,
encoding_map=encoding_map,
classifier_circuit_factory=initial_state_builder)
qml.fit(X_train, y_train)
prediction = qml.predict(X_test)
self.assertEqual(len(prediction), len(y_test))
self.assertListEqual(prediction, y_test)
class FullIris(unittest.TestCase):
def runTest(self):
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
X = numpy.asarray([x[0:2] for x, yy in zip(X, y) if yy != 2])
y = numpy.asarray([yy for x, yy in zip(X, y) if yy != 2])
preprocessing_pipeline = Pipeline([
('scaler', StandardScaler()),
('l2norm', Normalizer(norm='l2', copy=True))
])
X = preprocessing_pipeline.fit_transform(X, y)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.10, random_state=42)
initial_state_builder = QmlGenericStateCircuitBuilder(MottonenStatePreparation())
execution_backend = qiskit.Aer.get_backend('qasm_simulator') # type: BackendV2
qml = QmlHadamardNeighborClassifier(backend=execution_backend,
shots=8192,
classifier_circuit_factory=initial_state_builder,
encoding_map=NormedAmplitudeEncoding())
qml.fit(X_train, y_train)
prediction = qml.predict(X_test)
self.assertEqual(len(prediction), len(y_test))
self.assertListEqual(prediction, list(y_test))
for i in range(len(qml.last_predict_p_acc)):
self.assertAlmostEqual(qml.last_predict_p_acc[i],
QmlHadamardNeighborClassifier.p_acc_theory(X_train, y_train, X_test[i]), delta=0.05)
for i in range(len(qml.last_predict_probability)):
predicted_label = prediction[i]
self.assertAlmostEqual(qml.last_predict_probability[i],
QmlHadamardNeighborClassifier.p_label_theory(X_train, y_train, X_test[i], predicted_label),
delta=0.05)
|
https://github.com/infiniteregrets/QiskitBot
|
infiniteregrets
|
LIB_IMPORT="""
from qiskit import QuantumCircuit
from qiskit import execute, Aer
from qiskit.visualization import *"""
CIRCUIT_SCRIPT="""
circuit = build_state()
circuit.measure_all()
figure = circuit.draw('mpl')
output = figure.savefig('circuit.png')"""
PLOT_SCRIPT="""
backend = Aer.get_backend("qasm_simulator")
job = execute(circuit,backend=backend, shots =1000)
counts = job.result().get_counts()
plot_histogram(counts).savefig('plot.png', dpi=100, quality=90)"""
ASCII_CIRCUIT_SCRIPT="""
circuit = build_state()
print(circuit)
"""
|
https://github.com/infiniteregrets/QiskitBot
|
infiniteregrets
|
from math import sqrt, pi
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
import oracle_simple
import composed_gates
def get_circuit(n, oracles):
"""
Build the circuit composed by the oracle black box and the other quantum gates.
:param n: The number of qubits (not including the ancillas)
:param oracles: A list of black box (quantum) oracles; each of them selects a specific state
:returns: The proper quantum circuit
:rtype: qiskit.QuantumCircuit
"""
cr = ClassicalRegister(n)
## Testing
if n > 3:
#anc = QuantumRegister(n - 1, 'anc')
# n qubits for the real number
# n - 1 qubits for the ancillas
qr = QuantumRegister(n + n - 1)
qc = QuantumCircuit(qr, cr)
else:
# We don't need ancillas
qr = QuantumRegister(n)
qc = QuantumCircuit(qr, cr)
## /Testing
print("Number of qubits is {0}".format(len(qr)))
print(qr)
# Initial superposition
for j in range(n):
qc.h(qr[j])
# The length of the oracles list, or, in other words, how many roots of the function do we have
m = len(oracles)
# Grover's algorithm is a repetition of an oracle box and a diffusion box.
# The number of repetitions is given by the following formula.
print("n is ", n)
r = int(round((pi / 2 * sqrt((2**n) / m) - 1) / 2))
print("Repetition of ORACLE+DIFFUSION boxes required: {0}".format(r))
oracle_t1 = oracle_simple.OracleSimple(n, 5)
oracle_t2 = oracle_simple.OracleSimple(n, 0)
for j in range(r):
for i in range(len(oracles)):
oracles[i].get_circuit(qr, qc)
diffusion(n, qr, qc)
for j in range(n):
qc.measure(qr[j], cr[j])
return qc, len(qr)
def diffusion(n, qr, qc):
"""
The Grover diffusion operator.
Given the arry of qiskit QuantumRegister qr and the qiskit QuantumCircuit qc, it adds the diffusion operator to the appropriate qubits in the circuit.
"""
for j in range(n):
qc.h(qr[j])
# D matrix, flips state |000> only (instead of flipping all the others)
for j in range(n):
qc.x(qr[j])
# 0..n-2 control bits, n-1 target, n..
if n > 3:
composed_gates.n_controlled_Z_circuit(
qc, [qr[j] for j in range(n - 1)], qr[n - 1],
[qr[j] for j in range(n, n + n - 1)])
else:
composed_gates.n_controlled_Z_circuit(
qc, [qr[j] for j in range(n - 1)], qr[n - 1], None)
for j in range(n):
qc.x(qr[j])
for j in range(n):
qc.h(qr[j])
|
https://github.com/infiniteregrets/QiskitBot
|
infiniteregrets
|
import discord
from discord.ext import commands
import asyncio
import subprocess
import logging
import re
logger = logging.getLogger(__name__)
class DocInfo(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name = 'docs')
async def docs(self, ctx, *, arg):
if re.match('^`[A-Za-z]{1,20}`$', arg):
out = subprocess.run( f'echo "from qiskit import *\nhelp({arg[1:-1]})" | python3',
shell = True, text = True, capture_output = True)
if out.returncode == 0:
embed = discord.Embed(title = f'Info on {arg}',
description = f'```py{out.stdout}```')
await ctx.send(embed = embed)
else:
embed = discord.Embed(title = 'Error',
description = 'Try again with a correct class or function name and with a limit of 20 characters.')
await ctx.send(embed = embed)
def setup(bot):
bot.add_cog(DocInfo(bot))
|
https://github.com/infiniteregrets/QiskitBot
|
infiniteregrets
|
LIB_IMPORT = """
from qiskit import QuantumCircuit
from qiskit import execute, Aer
from qiskit.visualization import *"""
CIRCUIT_SCRIPT = """
circuit = build_state()
circuit.measure_all()
figure = circuit.draw('mpl')
output = figure.savefig('circuit.png')"""
PLOT_SCRIPT = """
backend = Aer.get_backend("qasm_simulator")
job = execute(circuit,backend=backend, shots =1000)
counts = job.result().get_counts()
plot_histogram(counts).savefig('plot.png', dpi=100, quality=90)"""
|
https://github.com/JanLahmann/RasQberry
|
JanLahmann
|
# https://raspberrypi.stackexchange.com/questions/85109/run-rpi-ws281x-without-sudo
# https://github.com/joosteto/ws2812-spi
# start with python3 RasQ-LED.py
import subprocess, time, math
from dotenv import dotenv_values
config = dotenv_values("/home/pi/RasQberry/rasqberry_environment.env")
n_qbit = int(config["N_QUBIT"])
LED_COUNT = int(config["LED_COUNT"])
LED_PIN = int(config["LED_PIN"])
#Import Qiskit classes
from qiskit import IBMQ, execute
from qiskit import Aer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
# set the backend
backend = Aer.get_backend('qasm_simulator')
#Set number of shots
shots = 1
def init_circuit():
# Create a Quantum Register with n qubits
global qr
qr = QuantumRegister(n_qbit)
# Create a Classical Register with n bits
global cr
cr = ClassicalRegister(n_qbit)
# Create a Quantum Circuit acting on the qr and cr register
global circuit
circuit = QuantumCircuit(qr, cr)
global counts
counts = {}
global measurement
measurement = ""
def set_up_circuit(factor):
global circuit
circuit = QuantumCircuit(qr, cr)
if factor == 0:
factor = n_qbit
# relevant qubits are the first qubits in each subgroup
relevant_qbit = 0
for i in range(0, n_qbit):
if (i % factor) == 0:
circuit.h(qr[i])
relevant_qbit = i
else:
circuit.cx(qr[relevant_qbit], qr[i])
circuit.measure(qr, cr)
def get_factors(number):
factor_list = []
# search for factors, including factor 1 and n_qbit itself
for i in range(1, math.ceil(number / 2) + 1):
if number % i == 0:
factor_list.append(i)
factor_list.append(n_qbit)
return factor_list
def circ_execute():
# execute the circuit
job = execute(circuit, backend, shots=shots)
result = job.result()
counts = result.get_counts(circuit)
global measurement
measurement = list(counts.items())[0][0]
print("measurement: ", measurement)
# alternative with statevector_simulator
# simulator = Aer.get_backend('statevector_simulator')
# result = execute(circuit, simulator).result()
# statevector = result.get_statevector(circuit)
# bin(statevector.tolist().index(1.+0.j))[2:]
def call_display_on_strip(measurement):
subprocess.call(["sudo","python3","/home/pi/RasQberry/demos/bin/RasQ-LED-display.py", measurement])
# n is the size of the entangled blocks
def run_circ(n):
init_circuit()
if n == 1:
print("build circuit without entanglement")
set_up_circuit(1)
elif n == 0 or n == n_qbit:
print("build circuit with complete entanglement")
set_up_circuit(n_qbit)
else:
print("build circuit with entangled blocks of size " + str(n))
set_up_circuit(n)
circ_execute()
call_display_on_strip(measurement)
def action():
while True:
#print(menu)
player_action = input("select circuit to execute (1/2/3/q) ")
if player_action == '1':
run_circ(1)
elif player_action == '2':
run_circ(n_qbit)
elif player_action == "3":
factors = get_factors(n_qbit)
for factor in factors:
run_circ(factor)
time.sleep(3)
elif player_action == 'q':
subprocess.call(["sudo","python3","/home/pi/RasQberry/demos/bin/RasQ-LED-display.py", "0", "-c"])
quit()
else:
print("Please type \'1\', \'2\', \'3\' or \'q\'")
def loop(duration):
print()
print("RasQ-LED creates groups of entangled Qubits and displays the measurment result using colors of the LEDs.")
print("A H(adamard) gate is applied to the first Qubit of each group; then CNOT gates to create entanglement of the whole group.")
print("The size of the groups starts with 1, then in steps up to all Qubits.")
print()
for i in range(duration):
factors = get_factors(n_qbit)
for factor in factors:
run_circ(factor)
time.sleep(3)
subprocess.call(["sudo","python3","/home/pi/RasQberry/demos/bin/RasQ-LED-display.py", "0", "-c"])
loop(5)
#action()
|
https://github.com/JanLahmann/RasQberry
|
JanLahmann
|
#!/usr/bin/env python
# coding: utf-8
# Credits: https://github.com/wmazin/Visualizing-Quantum-Computing-using-fractals
# |
# | Library imports
# └───────────────────────────────────────────────────────────────────────────────────────────────────────
# Importing standard python libraries
from threading import Thread
from pathlib import Path
from typing import Optional
from copy import deepcopy
from io import BytesIO
import traceback
import timeit
import sys
# Externally installed libraries
import matplotlib.pyplot as plt
import numpy as np
from selenium.common.exceptions import WebDriverException, NoSuchWindowException
from selenium.webdriver.common.by import By
from celluloid import Camera
from numpy import complex_, complex64, ndarray, ushort, bool_
from PIL import Image
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit
from qiskit.visualization import plot_bloch_multivector
# self-coded libraries
from fractal_webclient import WebClient
from fractal_julia_calculations import JuliaSet
from fractal_quantum_circuit import QuantumFractalCircuit
# |
# | Global settings for the script
# └───────────────────────────────────────────────────────────────────────────────────────────────────────
# Julia set calculation values
julia_iterations: int = 100
julia_escape_val: int = 2
# Image generation and animation values
GIF_ms_intervals: int = 200 # 200ms = 5 fps
number_of_frames: int = 60 # Total number of frames to generate
# Coordinate values in the Julia Set fractal image/frame
frame_resolution: int = 200 # Height and width
height: int = frame_resolution
width: int = frame_resolution
zoom: float = 1.0
x_start: float = 0
x_width: float = 1.5
x_min: float = x_start - x_width / zoom
x_max: float = x_start + x_width / zoom
y_start: float = 0
y_width: float = 1.5
y_min: float = y_start - y_width / zoom
y_max: float = y_start + y_width / zoom
# Create the basis 2D array for the fractal
x_arr = np.linspace(start=x_min, stop=x_max, num=width).reshape((1, width))
y_arr = np.linspace(start=y_min, stop=y_max, num=height).reshape((height, 1))
z_arr = np.array(x_arr + 1j * y_arr, dtype=complex64)
# Create array to keep track in which iteration the points have diverged
div_arr = np.zeros(z_arr.shape, dtype=np.uint8)
# Create Array to keep track on which points have not converged
con_arr = np.full(z_arr.shape, True, dtype=bool_)
# Dictionary to keep track of time pr. loop
timer = {"QuantumCircuit": 0.0, "Julia_calculations": 0.0, "Animation": 0.0, "Image": 0.0, "Bloch_data": 0.0}
acc_timer = timer
# |
# | Pathing, default folder and generated files, webclient
# └───────────────────────────────────────────────────────────────────────────────────────────────────────
# Set default path values
temp_image_folder = Path(Path.cwd(), "img")
browser_file_path = f"file://{temp_image_folder}"
default_image_url = f"{browser_file_path}/2cn2.png"
# Start the Chromedriver and redirect to default image before removal
driver = WebClient(default_image_url=default_image_url).get_driver() # ChromeDriver
# Remove previously generated files
if temp_image_folder.exists():
try:
for image in temp_image_folder.glob("*.*"):
Path(image).unlink()
except FileNotFoundError:
pass
else:
temp_image_folder.mkdir(parents=True, exist_ok=True)
# |
# | Defining the animation class to generate the images for the Quantum Fractal
# └───────────────────────────────────────────────────────────────────────────────────────────────────────
class QuantumFractalImages:
"""Calculate and generate Quantum Fractal Images using Julia Set formulas"""
def __init__(self):
# Define the result variables for the three Julia Set calculations
self.res_1cn: Optional[np.ndarray[np.int_, np.int_]] = None
self.res_2cn1: Optional[np.ndarray[np.int_, np.int_]] = None
self.res_2cn2: Optional[np.ndarray[np.int_, np.int_]] = None
# Save the QuantumCircuit as class variable
self.circuit: Optional[BytesIO] = None
# Save the GIF variables in class variables to keep the state for the lifetime of this class
# in contrary to qf_images which requires the variables to be defined for each iteration
self.gif_fig, self.gif_ax = plt.subplots(1, 4, figsize=(20, 5))
self.gif_cam = Camera(self.gif_fig)
def qfi_julia_calculation(self, sv_custom: complex_, sv_list: ndarray[complex_]) -> None:
"""Calculate the results for all three of the Julia-set formulas"""
timer['Julia_calculations'] = timeit.default_timer()
julia = JuliaSet(sv_custom=sv_custom, sv_list=sv_list, z=z_arr, con=con_arr, div=div_arr)
# Define the three julia-set formulas for each of their own threads
threads = [Thread(target=julia.set_1cn), Thread(target=julia.set_2cn1), Thread(target=julia.set_2cn2)]
# Start the threads and wait for threads to complete
[thread.start() for thread in threads]
[thread.join() for thread in threads]
# Define the results from the three calculations
self.res_1cn = julia.res_1cn
self.res_2cn1 = julia.res_2cn1
self.res_2cn2 = julia.res_2cn2
timer['Julia_calculations'] = timeit.default_timer() - timer['Julia_calculations']
def qfi_quantum_circuit(self, quantum_circuit: Optional[QuantumCircuit] = None) -> None:
"""Generate the Bloch Sphere image from the Quantum Circuit and convert to Bytes"""
timer['Bloch_data'] = timeit.default_timer()
bloch_data = BytesIO()
plot_bloch_multivector(quantum_circuit).savefig(bloch_data, format='png')
bloch_data.seek(0)
self.circuit = bloch_data
del bloch_data
timer['Bloch_data'] = timeit.default_timer() - timer['Bloch_data']
def qfi_animations(self) -> None:
"""Generate Animation of the Quantum Fractal Images"""
timer['Animation'] = timeit.default_timer()
# Plot Bloch sphere
self.gif_ax[0].imshow(Image.open(deepcopy(self.circuit)))
self.gif_ax[0].set_title('Bloch sphere', fontsize=20, pad=15.0)
# Plot 1st Julia Fractal
self.gif_ax[1].imshow(self.res_1cn, cmap='magma')
# Plot 2nd Julia Fractal
self.gif_ax[2].imshow(self.res_2cn1, cmap='magma')
self.gif_ax[2].set_title('3 types of Julia set fractals based on the superposition H-gate', fontsize=20, pad=15.0)
# Plot 3rd Julia Fractal
self.gif_ax[3].figure.set_size_inches(16, 5)
self.gif_ax[3].imshow(self.res_2cn2, cmap='magma')
self.gif_ax[3].figure.supxlabel('ibm.biz/quantum-fractals-blog ibm.biz/quantum-fractals', fontsize=20)
# Turn off axis values for all columns of images
for col in range(0, self.gif_ax[0].get_gridspec().ncols):
self.gif_ax[col].axis('off')
# Snap a picture of the image outcome and close the plt object
self.gif_cam.snap()
plt.close()
timer['Animation'] = timeit.default_timer() - timer['Animation']
def qfi_images(self) -> None:
"""Generate an image for each iteration of the Quantum Fractals"""
img_fig, img_ax = plt.subplots(1, 4, figsize=(20, 5))
# Secondly (b), generate the images based on the Julia set results
timer['Image'] = timeit.default_timer()
# Plot Bloch sphere
img_ax[0].imshow(Image.open(deepcopy(self.circuit)))
img_ax[0].set_title('Bloch sphere', fontsize=20, pad=15.0)
# Plot 1st Julia Fractal
img_ax[1].imshow(self.res_1cn, cmap='magma')
# Plot 2nd Julia Fractal
img_ax[2].imshow(self.res_2cn1, cmap='magma')
img_ax[2].set_title('3 types of Julia set fractals based on the superposition H-gate', fontsize=20, pad=15.0)
# Plot 3rd Julia Fractal
img_ax[3].figure.set_size_inches(16, 5)
img_ax[3].imshow(self.res_2cn2, cmap='magma')
img_ax[3].figure.supxlabel('ibm.biz/quantum-fractals-blog ibm.biz/quantum-fractals', fontsize=20)
# Turn off axis values for all columns of images
for col in range(0, img_ax[0].get_gridspec().ncols):
img_ax[col].axis('off')
# Save image locally and open image in browser and close the plt object
img_ax[3].figure.savefig(Path(temp_image_folder, "2cn2.png"))
driver.get(default_image_url)
plt.close('all')
del img_fig, img_ax
timer['Image'] = timeit.default_timer() - timer['Image']
# |
# | Running the script
# └───────────────────────────────────────────────────────────────────────────────────────────────────────
QFC = QuantumFractalCircuit(number_of_qubits=1, number_of_frames=number_of_frames)
QFI = QuantumFractalImages()
for i in range(number_of_frames):
try:
# Firstly, get the complex numbers from the complex circuit
timer['QuantumCircuit'] = timeit.default_timer()
ccc = QFC.get_quantum_circuit(frame_iteration=i)
timer['QuantumCircuit'] = timeit.default_timer() - timer['QuantumCircuit']
# Secondly, run the animation and image creation
QFI.qfi_julia_calculation(sv_custom=ccc[0], sv_list=ccc[2])
QFI.qfi_quantum_circuit(quantum_circuit=ccc[1])
QFI.qfi_animations()
QFI.qfi_images()
# Console logging output:
complex_numb = round(ccc[0].real, 2) + round(ccc[0].imag, 2) * 1j
complex_amp1 = round(ccc[2][0].real, 2) + round(ccc[2][0].imag, 2) * 1j
complex_amp2 = round(ccc[2][1].real, 2) + round(ccc[2][1].imag, 2) * 1j
print(f"Loop i = {i:>2} | One complex no: ({complex_numb:>11.2f}) | "
f"Complex amplitude one: ({complex_amp1:>11.2f}) and two: ({complex_amp2:>11.2f}) | "
f"QuantumCircuit: {round(timer['QuantumCircuit'], 4):>6.4f} | "
f"Julia_calc: {round(timer['Julia_calculations'], 4):>6.4f} | "
f"Anim: {round(timer['Animation'], 4):>6.4f} | Img: {round(timer['Image'], 4):>6.4f} | "
f"Bloch: {round(timer['Bloch_data'], 4):>6.4f} |")
acc_timer = {key: acc_timer[key] + val for key, val in timer.items()}
except (NoSuchWindowException, WebDriverException):
print("Error, Browser window closed during generation of images")
raise traceback.format_exc()
# Print the accumulated time
print("Accumulated time:", ", ".join([f"{key}: {value:.3f} seconds" for key, value in acc_timer.items()]))
# Quit the currently running driver and prepare for the animation
driver.quit()
print("\nStarting - Saving the current animation state in GIF")
anim = QFI.gif_cam.animate(blit=True, interval=GIF_ms_intervals)
anim.save(f'{temp_image_folder}/1qubit_simulator_4animations_H_{number_of_frames}.gif', writer='pillow')
gif_url = f"{browser_file_path}/1qubit_simulator_4animations_H_{number_of_frames}.gif"
print("Finished - Saving the current animation state in GIF")
# Define a fresh instance of the ChromeDriver to retrieve the image
driver = WebClient(default_image_url).get_driver() # ChromeDriver
driver.get(gif_url)
# check if the browser window is closed
while True:
try:
driver.find_element(By.TAG_NAME, 'body')
except (NoSuchWindowException, WebDriverException):
print("Error, Browser window closed, quitting the program")
driver.quit()
sys.exit()
|
https://github.com/JanLahmann/RasQberry
|
JanLahmann
|
#!/usr/bin/env python
# coding: utf-8
# Credits: https://github.com/wmazin/Visualizing-Quantum-Computing-using-fractals
#############################################################
# Importing standard python libraries
from typing import Tuple, List
from math import pi
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from numpy import complex64, ndarray
import numpy as np
class QuantumFractalCircuit:
def __init__(self, number_of_qubits:int = 1, number_of_frames: int = 60) -> None:
self.n_qubits = number_of_qubits
self.n_frames = number_of_frames
# Create the circuit for which the gates will be applied
self.quantum_circuit = QuantumCircuit(number_of_qubits)
self.quantum_circuit.h(0)
# noinspection PyUnresolvedReferences
def get_quantum_circuit(self, frame_iteration:int = 0) -> Tuple[complex64, QuantumCircuit, ndarray[complex64]]:
# Create a fresh copy of the Quantum Circuit
quantum_circuit = self.quantum_circuit.copy()
# Calculate the rotation Phi and apply it to the local Quantum Circuit
phi_rotation = frame_iteration * 2 * pi / self.n_frames
quantum_circuit.rz(phi_rotation, 0)
# Simulate the Quantum Circuit and extract the statevector
statevector_array = Statevector(quantum_circuit)
statevector_idx_n = statevector_array.data.astype(complex64)
statevector_idx_0 = statevector_array.data[0].astype(complex64)
statevector_idx_1 = statevector_array.data[1].astype(complex64)
# Check statevector values and calculate a new statevector
if statevector_idx_1.real != 0 or statevector_idx_1.imag != 0:
statevector_new = statevector_idx_0 / statevector_idx_1
statevector_new = round(statevector_new.real, 2) + round(statevector_new.imag, 2) * 1j
else:
statevector_new = 0
return statevector_new.astype(complex64), quantum_circuit, statevector_idx_n
|
https://github.com/JanLahmann/RasQberry
|
JanLahmann
|
import numpy as np
import networkx as nx
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble
from qiskit.quantum_info import Statevector
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.visualization import plot_histogram
from qiskit.providers.aer.extensions.snapshot_statevector import *
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
import matplotlib.pyplot as plt
LAMBDA = 10
SEED = 10
SHOTS = 10000
# returns the bit index for an alpha and j
def bit(i_city, l_time, num_cities):
return i_city * num_cities + l_time
# e^(cZZ)
def append_zz_term(qc, q_i, q_j, gamma, constant_term):
qc.cx(q_i, q_j)
qc.rz(2*gamma*constant_term,q_j)
qc.cx(q_i, q_j)
# e^(cZ)
def append_z_term(qc, q_i, gamma, constant_term):
qc.rz(2*gamma*constant_term, q_i)
# e^(cX)
def append_x_term(qc,qi,beta):
qc.rx(-2*beta, qi)
def get_not_edge_in(G):
N = G.number_of_nodes()
not_edge = []
for i in range(N):
for j in range(N):
if i != j:
buffer_tupla = (i,j)
in_edges = False
for edge_i, edge_j in G.edges():
if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)):
in_edges = True
if in_edges == False:
not_edge.append((i, j))
return not_edge
def get_classical_simplified_z_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# z term #
z_classic_term = [0] * N**2
# first term
for l in range(N):
for i in range(N):
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += -1 * _lambda
# second term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_jl
z_jl_index = bit(j, l, N)
z_classic_term[z_jl_index] += _lambda / 2
# third term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_ij
z_ij_index = bit(i, j, N)
z_classic_term[z_ij_index] += _lambda / 2
# fourth term
not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 4
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
z_classic_term[z_jlplus_index] += _lambda / 4
# fifthy term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
z_classic_term[z_il_index] += weight_ij / 4
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
z_classic_term[z_il_index] += weight_ji / 4
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ji / 4
return z_classic_term
def tsp_obj_2(x, G,_lambda):
# obtenemos el valor evaluado en f(x_1, x_2,... x_n)
not_edge = get_not_edge_in(G)
N = G.number_of_nodes()
tsp_cost=0
#Distancia
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# x_il
x_il_index = bit(edge_i, l, N)
# x_jlplus
l_plus = (l+1) % N
x_jlplus_index = bit(edge_j, l_plus, N)
tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij
# add order term because G.edges() do not include order tuples #
# x_i'l
x_il_index = bit(edge_j, l, N)
# x_j'lplus
x_jlplus_index = bit(edge_i, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji
#Constraint 1
for l in range(N):
penal1 = 1
for i in range(N):
x_il_index = bit(i, l, N)
penal1 -= int(x[x_il_index])
tsp_cost += _lambda * penal1**2
#Contstraint 2
for i in range(N):
penal2 = 1
for l in range(N):
x_il_index = bit(i, l, N)
penal2 -= int(x[x_il_index])
tsp_cost += _lambda*penal2**2
#Constraint 3
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# x_il
x_il_index = bit(i, l, N)
# x_j(l+1)
l_plus = (l+1) % N
x_jlplus_index = bit(j, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda
return tsp_cost
def get_classical_simplified_zz_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# zz term #
zz_classic_term = [[0] * N**2 for i in range(N**2) ]
# first term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
# z_jl
z_jl_index = bit(j, l, N)
zz_classic_term[z_il_index][z_jl_index] += _lambda / 2
# second term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
# z_ij
z_ij_index = bit(i, j, N)
zz_classic_term[z_il_index][z_ij_index] += _lambda / 2
# third term
not_edge = get_not_edge_in(G)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4
# fourth term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4
return zz_classic_term
def get_classical_simplified_hamiltonian(G, _lambda):
# z term #
z_classic_term = get_classical_simplified_z_term(G, _lambda)
# zz term #
zz_classic_term = get_classical_simplified_zz_term(G, _lambda)
return z_classic_term, zz_classic_term
def get_cost_circuit(G, gamma, _lambda):
N = G.number_of_nodes()
N_square = N**2
qc = QuantumCircuit(N_square,N_square)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda)
# z term
for i in range(N_square):
if z_classic_term[i] != 0:
append_z_term(qc, i, gamma, z_classic_term[i])
# zz term
for i in range(N_square):
for j in range(N_square):
if zz_classic_term[i][j] != 0:
append_zz_term(qc, i, j, gamma, zz_classic_term[i][j])
return qc
def get_mixer_operator(G,beta):
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
for n in range(N**2):
append_x_term(qc, n, beta)
return qc
def get_QAOA_circuit(G, beta, gamma, _lambda):
assert(len(beta)==len(gamma))
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
# init min mix state
qc.h(range(N**2))
p = len(beta)
for i in range(p):
qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda))
qc = qc.compose(get_mixer_operator(G, beta[i]))
qc.barrier(range(N**2))
qc.snapshot_statevector("final_state")
qc.measure(range(N**2),range(N**2))
return qc
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
# Sample expectation value
def compute_tsp_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj_2(meas, G, LAMBDA)
energy += obj_for_meas*meas_count
total_counts += meas_count
mean = energy/total_counts
return mean
def get_black_box_objective_2(G,p):
backend = Aer.get_backend('qasm_simulator')
sim = Aer.get_backend('aer_simulator')
# function f costo
def f(theta):
beta = theta[:p]
gamma = theta[p:]
# Anzats
qc = get_QAOA_circuit(G, beta, gamma, LAMBDA)
result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result()
final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0]
state_vector = Statevector(final_state_vector)
probabilities = state_vector.probabilities()
probabilities_states = invert_counts(state_vector.probabilities_dict())
expected_value = 0
for state,probability in probabilities_states.items():
cost = tsp_obj_2(state, G, LAMBDA)
expected_value += cost*probability
counts = result.get_counts()
mean = compute_tsp_energy_2(invert_counts(counts),G)
return mean
return f
def crear_grafo(cantidad_ciudades):
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
return G, mejor_costo, mejor_camino
def run_QAOA(p,ciudades, grafo):
if grafo == None:
G, mejor_costo, mejor_camino = crear_grafo(ciudades)
print("Mejor Costo")
print(mejor_costo)
print("Mejor Camino")
print(mejor_camino)
print("Bordes del grafo")
print(G.edges())
print("Nodos")
print(G.nodes())
print("Pesos")
labels = nx.get_edge_attributes(G,'weight')
print(labels)
else:
G = grafo
intial_random = []
# beta, mixer Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,np.pi))
# gamma, cost Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,2*np.pi))
init_point = np.array(intial_random)
obj = get_black_box_objective_2(G,p)
res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
print(res_sample)
if __name__ == '__main__':
# Run QAOA parametros: profundidad p, numero d ciudades,
run_QAOA(5, 3, None)
|
https://github.com/bartubisgin/QSVTinQiskit-2021-Europe-Hackathon-Winning-Project-
|
bartubisgin
|
import warnings; warnings.simplefilter('ignore')
# Importing the necessary libraries
import numpy as np
from numpy import pi
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries
from qiskit import *
from qiskit.quantum_info import Statevector
from qiskit.tools.jupyter import *
from qiskit.visualization import *
#we have 2 system qubits
system_qubits = 2
#following the argument above we need 2 additional qubits
nqubits = system_qubits + 2
q = QuantumRegister(nqubits, 'q')
circuit = QuantumCircuit(q)
x = np.linspace(-1, 1)
test = np.polynomial.Chebyshev((0, 0, 0, 1)) # The 3rd Chebyshev polynomial!
y = test(x)
plt.plot(x, y)
# Define projectors.
# Note that p_left is actually p_right from above because the order
# of operations are reversed when equations are turned into circuits
# due to how time-flow is defined in circuit structures
# In the Qiskit implementation qubit indexes start from 0
# and the most significant qubit is the highest index
# keeping this in mind e.g for 4 nqubits = {q0,q1,q2,q3}
# q0 and q1 are the system qubits
# q2 is the signal qubit
# q3 is the ancillary rotation qubit
# nqubits-1 = 4-1 = 3 below, then corresponds to q3
def p_left(q, phi): #right projector
qc = QuantumCircuit(q)
n = q
ctrl_range = list(range(0,n-1))
for qubit in range(n-1): # Implement a simple multi 0-controlled
qc.x(qubit)
qc.mcx(ctrl_range , n-1) # 0-Controlled on all but the last qubits, acts on the last qubit
for qubit in range(n-1):
qc.x(qubit)
#qc.barrier(0, 1, 2, 3)
qc.rz(phi, n-1) # RZ(phi) on the last qubit
#qc.barrier(0, 1, 2, 3)
for qubit in range(n-1): # Reverse the effect of the first multi-control
qc.x(qubit)
qc.mcx(ctrl_range ,n-1)
for qubit in range(n-1):
qc.x(qubit)
p_left_gate = qc.to_gate() # Compiles all this into a gate
p_left_gate.name = "P$_l$(Φ)"
return p_left_gate
def p_right(phi): # Left projector acts just on the signal and the ancillary qubit
qc = QuantumCircuit(2)
qc.cx(0, 1)
qc.rz(phi, 1)
qc.cx(0 ,1)
p_right_gate = qc.to_gate()
p_right_gate.name = "P$_r$(Φ)"
return p_right_gate
#Define Oracle and the reverse-gate for
#constructing the dagger later
def U(q):
qc = QuantumCircuit(q)
n = q + 1
for qubit in range(n-2):
qc.h(qubit)
qc.mcx(list(range(0,n-2)), n-2)
U_gate = qc.to_gate()
U_gate.name = "U"
return U_gate
def reverse_gate(gate):
gate_rev = gate.reverse_ops()
gate_rev.name = gate.name + "$^†$"
return gate_rev
#we have 2 system qubits
system_qubits = 2
#following the argument above we need 2 additional qubits
nqubits = system_qubits + 2
q = QuantumRegister(nqubits, 'q')
circuit = QuantumCircuit(q)
d = 3
u = U(nqubits-1)
u_dag = reverse_gate(u) #construct U_dagger
p_right_range = [nqubits-2, nqubits-1] # build the ranges of qubits for gates to act upon
u_range = list(range(0, nqubits-1))
p_left_range = list(range(0, nqubits))
circuit.append(p_left(nqubits, (1-d)*pi), p_left_range) # in general, starting from this line,
circuit.append(u, u_range) # the circuit would iterate over the phases,
# but the phases for pure Cheby are just trivial pi/2
# so we chose to directly putting pi's in here for simplification
for i in range((d-1)//2): # we put pi instead of pi/2 because of how RZ is defined in Qiskit
circuit.append(p_right(pi), p_right_range)
circuit.append(u_dag, u_range)
circuit.append(p_left(nqubits, pi), p_left_range)
circuit.append(u, u_range)
circuit.measure_all()
circuit.draw('mpl')
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_circuit = transpile(circuit, qasm_sim)
qobj = assemble(transpiled_circuit)
results = qasm_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
# We have 2 system qubits
system_qubits = 2
# Following the argument above we need 2 additional qubits
nqubits = system_qubits + 2
q = QuantumRegister(nqubits, 'q')
circuit = QuantumCircuit(q)
############################## d in terms of n!
d = (2*system_qubits) - 1
if system_qubits > 6 and system_qubits < 10:
for i in range(1, system_qubits - 6 + 1):
d += 2 * i
###############################
u = U(nqubits-1)
u_dag = reverse_gate(u)
p_right_range = [nqubits-2, nqubits-1]
u_range = list(range(0, nqubits-1))
p_left_range = list(range(0, nqubits))
circuit.append(p_left(nqubits, (1-d)*pi), p_left_range)
circuit.append(U(nqubits-1), u_range)
for i in range((d-1)//2):
circuit.append(p_right(pi), p_right_range) #debug this, doesnt work just as a 2 qubit gate
circuit.append(u_dag, u_range)
circuit.append(p_left(nqubits,pi), p_left_range)
circuit.append(u, u_range)
circuit.measure_all()
circuit.draw('mpl')
def qsvt_search(target): # target = marked element, is a bit-string!
systemqubits = len(target)
nqubits = systemqubits + 2
q = QuantumRegister(nqubits, 'q')
circuit = QuantumCircuit(q)
d = (2*systemqubits) - 1
if systemqubits > 6 and systemqubits < 10:
for i in range(1, systemqubits - 6 + 1):
d += 2 * i
u = U(nqubits-1)
u_dag = reverse_gate(u)
p_right_range = [nqubits-2, nqubits-1]
u_range = list(range(0, nqubits-1))
p_left_range = list(range(0, nqubits))
circuit.append(p_left(nqubits,(1-d)*pi), p_left_range)
circuit.append(U(nqubits-1), u_range)
for i in range((d-1)//2):
circuit.append(p_right(pi), p_right_range) #debug this, doesnt work just as a 2 qubit gate
circuit.append(u_dag, u_range)
circuit.append(p_left(nqubits,pi), p_left_range)
circuit.append(u, u_range)
for i in range(len(target)): # The operation for acquiring arbitrary marked element
bts = target [::-1] # bitstring is reversed to be compatible with the reverse qubit order in Qiskit
if bts[i] == '0':
circuit.x(i)
circuit.measure_all()
return circuit
circuit_test = qsvt_search('1101')
circuit_test.draw('mpl')
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_circuit = transpile(circuit_test, qasm_sim)
qobj = assemble(transpiled_circuit)
results = qasm_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
qc = qsvt_search('001')
qc.draw('mpl')
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_circuit = transpile(qc, qasm_sim)
qobj = assemble(transpiled_circuit)
results = qasm_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
# We have 4 system qubits
system_qubits = 4
nqubits = system_qubits + 2
q = QuantumRegister(nqubits, 'q')
circuit = QuantumCircuit(q)
d = 3 # set d = something you chose to test different values!
u = U(nqubits-1)
u_dag = reverse_gate(u)
p_right_range = [nqubits-2, nqubits-1]
u_range = list(range(0, nqubits-1))
p_left_range = list(range(0, nqubits))
circuit.append(p_left(nqubits,(1-d)*pi), p_left_range)
circuit.append(U(nqubits-1), u_range)
for i in range((d-1)//2):
circuit.append(p_right(pi), p_right_range) #debug this, doesnt work just as a 2 qubit gate
circuit.append(u_dag, u_range)
circuit.append(p_left(nqubits,pi), p_left_range)
circuit.append(u, u_range)
circuit.measure_all()
circuit.draw('mpl')
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_circuit = transpile(circuit, qasm_sim)
qobj = assemble(transpiled_circuit)
results = qasm_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
qc = qsvt_search('001110')
qc.draw('mpl')
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_circuit = transpile(qc, qasm_sim)
qobj = assemble(transpiled_circuit)
results = qasm_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
qc = qsvt_search('001110110')
qc.draw('mpl')
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_circuit = transpile(qc, qasm_sim)
qobj = assemble(transpiled_circuit)
results = qasm_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
|
https://github.com/bartubisgin/QSVTinQiskit-2021-Europe-Hackathon-Winning-Project-
|
bartubisgin
|
using GenericLinearAlgebra
using LinearAlgebra
using SpecialFunctions
using Dates
using PolynomialRoots
using Printf
using FFTW
using PyPlot
using MAT
function GSLW(P, p_P, stop_criteria, R_init, R_max, if_polish = false)
#------------------------------------------------------------------------------------------------------------
# Input:
# P: Chebyshev coefficients of polynomial P, only need to provide non-zero coefficient.
# P should satisfy parity constraint and |P|^2 \le 1
# p_P: parity of P, 0 -- even, 1 -- odd
# stop_eps: algorithm will stop if it find factors that approximate polynomials with error less than
# stop_eps on Chebyshev points
# R_init: number of bits used at the beginning
# R_max: number of bits available
# if_polish: whether polish the roots, it cost more time but may improve performance
#
# Output:
# Phase factor Phi such that real part of (0,0)-component of U_\Phi(x) approximates P(x),
# where U_\Phi(x) = e^{\I \phi_0 \sigma_z} \prod_{j=1}^{\qspdeg} \left[ W(x) e^{\I \phi_j \sigma_z} \right]
#
# Besides, the algorithm will return the L^∞ error of such approximation on Chebyshev points
#
#------------------------------------------------------------------------------------------------------------
#
# Reference:
# A. Gily ́en, Y. Su, G. H. Low, and N. Wiebe.
# Quantum singular value transformation and beyond: exponentialimprovements for quantum matrix arithmetics.
#
# Author: X.Meng, Y. Dong
# Version 1.0 .... 02/2020
#
#------------------------------------------------------------------------------------------------------------
# Step 1: Find all the roots of 1-P^2
R = R_init
while(true)
if(R>=R_max)
return Inf,[]
end
setprecision(BigFloat, R)
P = big.(P)
degree = length(P)
if(p_P==0)
coef_PQ = zeros(BigFloat,degree*2)
for j=1:degree
for k=1:degree
coef_PQ[j+k-1] -= P[j]*P[k]
end
end
coef_PQ[1] += 1
coef_PQ1 = zeros(BigFloat,degree)
for j=1:degree
coef_PQ1[j] -= P[j]
end
coef_PQ1[1] += 1
coef_PQ2 = zeros(BigFloat,degree)
for j=1:degree
coef_PQ2[j] += P[j]
end
coef_PQ2[1] += 1
Proot1 = roots(coef_PQ1, polish = if_polish, epsilon = big.(0.0))
Proot2 = roots(coef_PQ2, polish = if_polish, epsilon = big.(0.0))
Proot = [Proot1;Proot2]
else
coef_PQ = zeros(BigFloat,degree*2)
for j=1:degree
for k=1:degree
coef_PQ[j+k] -= P[j]*P[k]
end
end
coef_PQ[1] += 1
Proot = roots(coef_PQ, polish = if_polish, epsilon = big.(0.0))
end
# Step 2: Find root of 1-P^2, construct full P and Q by FFT
# recover full root list
all_root = zeros(Complex{BigFloat},length(Proot)*2)
for i=1:length(Proot)
tmpnorm = norm(Proot[i])
tmpangle = angle(Proot[i])
all_root[2*i-1] = sqrt(tmpnorm)*exp(1im*tmpangle/2)
all_root[2*i] = -sqrt(tmpnorm)*exp(1im*tmpangle/2)
end
# Construct W such that W(x)W(x)^*=1-P^2(x)
eps = 1e-16
S_0 = 0
S_1 = 0
S_2 = 0
S_3 = 0
S_4 = 0
S1_list = zeros(Complex{BigFloat},length(all_root))
S2_list = zeros(Complex{BigFloat},length(all_root))
S3_list = zeros(Complex{BigFloat},length(all_root))
S4_list = zeros(Complex{BigFloat},length(all_root))
for i=1:length(all_root)
if(abs(all_root[i])<eps)
S_0 += 1
continue
end
if(abs(imag(all_root[i]))<eps&&real(all_root[i])>0)
if(real(all_root[i])<1-eps)
S_1 += 1
S1_list[S_1] = real(all_root[i])
else
S_2 += 1
S2_list[S_2] = findmax([real(all_root[i]),1])[1]
end
continue
end
if(abs(real(all_root[i]))<eps&&imag(all_root[i])>0)
S_3 += 1
S3_list[S_3] = all_root[i]
continue
end
if(imag(all_root[i])>0&&real(all_root[i])>0)
S_4 += 1
S4_list[S_4] = all_root[i]
end
end
K = abs(P[end])
function get_w(x,use_real = true) # W(x)
x = big.(x)
Wx = K*x^(S_0/2)
eps3 = 1e-24
if(x==1) # if x==\pm 1, silghtly move x such that make \sqrt{1-x^2}>0
x -= eps3
elseif(x==-1)
x += eps3
end
for i=1:S_1
Wx *= sqrt(x^2-S1_list[i]^2)
end
for i=1:S_2
Wx *= sqrt(S2_list[i]^2-big.(1))*x+im*S2_list[i]*sqrt(big.(1)-x^2)
end
for i=1:S_3
Wx *= sqrt(abs(S3_list[i])^2+big.(1))*x+im*abs(S3_list[i])*sqrt(big.(1)-x^2)
end
for i=1:S_4
tmpre = real(S4_list[i])
tmpim = imag(S4_list[i])
tmpc = tmpre^2+tmpim^2+sqrt(2*(tmpre^2+1)*tmpim^2+(tmpre^2-1)^2+tmpim^4)
Wx *= tmpc*x^2-(tmpre^2+tmpim^2)+im*sqrt(tmpc^2-1)*x*sqrt(big.(1)-x^2)
end
if(use_real)
return real(Wx)
else
return imag(Wx)/sqrt(big.(1)-x^2)
end
end
function get_p(x) # P(x)
P_t = big.(0)
for j=1:length(P)
if(p_P==1)
P_t += P[j]*x^big.(2*j-1)
else
P_t += P[j]*x^big.(2*j-2)
end
end
return P_t
end
# Represent full P and Q under Chevyshev basis
get_wr(x) = get_w(x,true)
get_wi(x) = get_w(x,false)
DEG = 2^ceil(Int,log2(degree)+1)
coef_r = ChebyExpand(get_wr, DEG)
coef_i = ChebyExpand(get_wi, DEG)
coef_p = ChebyExpand(get_p, DEG)
if(p_P==0)
P_new = 1im.*coef_r[1:2*degree-1]+coef_p[1:2*degree-1]
Q_new = coef_i[1:2*degree-2].*1im
else
P_new = 1im.*coef_r[1:2*degree]+coef_p[1:2*degree]
Q_new = coef_i[1:2*degree-1].*1im
end
# Step 3: Get phase factors and check convergence
phi = get_factor(P_new,Q_new)
max_err = 0
t = cos.(collect(1:2:(2*degree-1))*big.(pi)/big.(4)/big.(degree))
for i=1:length(t)
targ, ret = QSPGetUnitary(phi, t[i])
P_t = big.(0)
for j=1:degree
if(p_P==1)
P_t += P[j]*t[i]^big.(2*j-1)
else
P_t += P[j]*t[i]^big.(2*j-2)
end
end
t_err = norm(real(ret[1,1])-P_t)
if(t_err>max_err)
max_err = t_err
end
end
@printf("For degree N = %d, precision R = %d, the estimated inf norm of err is %5.4e\n",length(phi)-1,R,max_err)
if(max_err<stop_criteria)
return max_err,phi
else
@printf("Error is too big, increase R.\n")
end
R = R*2
end
end
function get_factor(P,Q)
# From polynomials P, Q generate phase factors phi such that
# U_\Phi(x) = [P & i\sqrt{1-x^2}Q \\ i\sqrt{1-x^2}Q^* & P]
# phase factors are generated via a reduction procedure under Chebyshev basis
phi = zeros(BigFloat,length(P))
lenP = length(P)
for i=1:lenP-1
P, Q, phit = ReducePQ(P, Q)
phi[end+1-i] = real(phit)
end
phi[1] = angle(P[1])
return phi
end
function ReducePQ(P, Q)
# A single reduction step
P = big.(P)
Q = big.(Q)
colP = length(P)
colQ = length(Q)
degQ = colQ-1
tmp1 = zeros(Complex{BigFloat},colP+1)
tmp2 = zeros(Complex{BigFloat},colP+1)
tmp1[2:end] = big.(0.5)*P
tmp2[1:end-2] = big.(0.5)*P[2:end]
Px = tmp1 + tmp2
Px[2] = Px[2] + big.(0.5)*P[1]
if(degQ>0)
tmp1 = zeros(Complex{BigFloat},colQ+2)
tmp2 = zeros(Complex{BigFloat},colQ+2)
tmp3 = zeros(Complex{BigFloat},colQ+2)
tmp1[1:end-2] = big.(0.5)*Q
tmp2[3:end] = -big.(1)/big.(4)*Q
tmp3[1:end-4] = -big.(1)/big.(4)*Q[3:end]
Q1_x2 = tmp1 + tmp2 + tmp3
Q1_x2[2] = Q1_x2[2] - 1/big.(4)*Q[2]
Q1_x2[3] = Q1_x2[3] - 1/big.(4)*Q[1]
else
Q1_x2 = zeros(Complex{BigFloat},3)
Q1_x2[1] = big.(0.5)*Q[1]
Q1_x2[end] = -big.(0.5)*Q[1]
end
tmp1 = zeros(Complex{BigFloat},colQ+1)
tmp2 = zeros(Complex{BigFloat},colQ+1)
tmp1[2:end] = big.(0.5)*Q
tmp2[1:end-2] = big.(0.5)*Q[2:end]
Qx = tmp1 + tmp2
Qx[2] = Qx[2] + big.(0.5)*Q[1];
if(degQ>0)
ratio = P[end]/Q[end]*big.(2)
else
ratio = P[end]/Q[end]
end
phi = big.(0.5)*angle(ratio)
rexp = exp(-1im*phi)
Ptilde = rexp * (Px + ratio*Q1_x2)
Qtilde = rexp * (ratio*Qx - P)
Ptilde = Ptilde[1:degQ+1]
Qtilde = Qtilde[1:degQ]
return Ptilde,Qtilde,phi
end
function QSPGetUnitary(phase, x)
# Given phase factors Phi and x, yield U_\Phi(x)
phase = big.(phase)
Wx = zeros(Complex{BigFloat},2,2)
Wx[1,1] = x
Wx[2,2] = x
Wx[1,2] = sqrt(1-x^2)*1im
Wx[2,1] = sqrt(1-x^2)*1im
expphi = exp.(1im*phase)
ret = zeros(Complex{BigFloat},2,2)
ret[1,1] = expphi[1]
ret[2,2] = conj(expphi[1])
for k = 2:length(expphi)
temp = zeros(Complex{BigFloat},2,2)
temp[1,1] = expphi[k]
temp[2,2] = conj(expphi[k])
ret = ret * Wx * temp
end
targ = real(ret[1,1])
return targ,ret
end
function ChebyExpand(func, maxorder)
# Evaluate Chebyshev coefficients of a polynomial of degree at most maxorder
M = maxorder
theta = zeros(BigFloat,2*M)
for i=1:2*M
theta[i] = (i-1)*big.(pi)/M
end
f = func.(-cos.(theta))
c = real.(BigFloatFFT(f))
c = copy(c[1:M+1])
c[2:end-1] = c[2:end-1]*2
c[2:2:end] = -copy(c[2:2:end])
c = c./(big.(2)*big.(M))
return c
end
function Chebytonormal(coef)
#Convert Chebyshev basis to normal basis
coef = big.(coef)
coef2 = zeros(BigFloat,length(coef))
A = zeros(BigFloat,length(coef),length(coef))
b = zeros(BigFloat,length(coef))
t = cos.(collect(1:2:(2*length(coef)-1))*big.(pi)/big.(4)/big.(length(coef)))
t2 = collect(1:2:(2*length(coef)-1))*big.(pi)/big.(4)/big.(length(coef))
for i=1:length(coef)
for j=1:length(coef)
A[i,j] = t[i]^(j-1)
b[i] += coef[j]*cos((j-1)*t2[i])
end
end
coef2 = A\b
#@printf("Error is %5.4e\n",norm(A*coef2-b))
return coef2
end
function BigFloatFFT(x)
# Perform FFT on vector x
# This function only works for length(x) = 2^k
N = length(x);
xp = x[1:2:end];
xpp = x[2:2:end];
if(N>=8)
Xp = BigFloatFFT(xp);
Xpp = BigFloatFFT(xpp);
X = zeros(Complex{BigFloat},N,1);
Wn = exp.(big.(-2)im*big.(pi)*(big.(0:N/2-1))/big.(N));
tmp = Wn .* Xpp;
X = [(Xp + tmp);(Xp -tmp)];
elseif(N==2)
X = big.([1 1;1 -1])*x;
elseif(N==4)
X = big.([1 0 1 0; 0 1 0 -1im; 1 0 -1 0;0 1 0 1im]*[1 0 1 0;1 0 -1 0;0 1 0 1;0 1 0 -1])*x;
end
return X
end
# Test case 1: Hamiltonian simulation
#
# Here we want to approxiamte e^{-i\tau x} by Jacobi-Anger expansion:
#
# e^{-i\tau x} = J_0(\tau)+2\sum_{k even} (-1)^{k/2}J_{k}(\tau)T_k(x)+2i\sum_{k odd} (-1)^{(k-1)/2}J_{k}(\tau) T_k(x)
#
# We truncate the series up to N = 1.4\tau+log(10^{14}), which gives an polynomial approximation of e^{-i\tau x} with
# accuracy 10^{-14}. Besides, we deal with real and imaginary part of the truncated series seperatly and divide them
# by a constant factor 2 to enhance stability.
#
# parameters
# stop_eps: desired accuracy
# tau: the duration \tau in Hamiltonian simulation
# R_init: number of bits used at the beginning
# R_max: number of bits available
stop_eps = 1e-12
tau = 100
R_init = 1024
R_max = 1025
#------------------------------------------------------------------
phi1 = []
phi2 = []
for p_P=0:1
N = ceil.(Int,tau*1.4+log(1e14))
if(p_P==0)
setprecision(BigFloat,4096)
if(mod(N,2)==1)
N -= 1
end
coef = zeros(BigFloat,N+1)
for i=1:(round(Int,N/2)+1)
coef[2*i-1] = (-1)^(i-1)*besselj(big.(2.0*(i-1)),tau)
end
coef[1] = coef[1]/2
P = Chebytonormal(coef)
P = P[1:2:end]
else
setprecision(BigFloat,4096)
if(mod(N,2)==0)
N += 1
end
coef = zeros(BigFloat,N+1)
for i=1:round(Int,(N+1)/2)
coef[2*i] = (-1)^(i-1)*besselj(big.(2*i-1),tau)
end
P = Chebytonormal(coef)[2:2:end]
end
start_time = time()
err,phi = GSLW(P,p_P,stop_eps,R_init,R_max)
elpased_time = time()-start_time
@printf("Elapsed time is %4.2e s\n", elpased_time)
end
# Test case 2: Eigenstate filter
#
# Here we want to generate factors for the eigenstate filter function:
#
# f_n(x,\delta)=\frac{T_n(-1+2\frac{x^2-\delta^2}{1-\delta^2})}{T_n(-1+2\frac{-\delta^2}{1-\delta^2})}.
#
# We divide f_n by a constant factor \sqrt{2} to enhance stability.
#
# Reference: Lin Lin and Yu Tong
# Solving quantum linear system problem with near-optimal complexity
#
# parameters
# stop_eps: desired accuracy
# n, \delta: parameters of f_n
# R_init: number of bits used at the beginning
# R_max: number of bits available
#
stop_eps = 1e-12
n = 100
delta = 0.03
R_init = 1024
R_max = 1025
#------------------------------------------------------------------
function f_n(x,n,delta)
val = copy(x)
delta = big.(delta)
fact = chebyshev(-big.(1)-big.(2)*delta^2/(big.(1)-delta^2),n)
if(length(x)==1)
return chebyshev(-big.(1)+big.(2)*(x^2-delta^2)/(big.(1)-delta^2),n)/fact
else
for i=1:length(x)
val[i] = chebyshev(-1+2*(x[i]^2-delta^2)/(1-delta^2),n)/fact
end
return val
end
end
function chebyshev(x,n) # T_n(x)
if(abs(x)<=1)
return cos(big.(n)*acos(x))
elseif(x>1)
return cosh(big.(n)*acosh(x))
else
return big.((-1)^n)*cosh(big.(n)*acosh(-x))
end
end
# Obtain expansion of f_n under Chebyshev basis via FFT
setprecision(BigFloat,1024)
M = 2*n
theta = range(0, stop=2*pi, length=2*M+1)
theta = theta[1:2*M]
f = f_n(-cos.(theta),n,delta)
c = real(fft(f))
c = c[1:M+1]
c[2:end-1] = c[2:end-1]*2
c[2:2:end] = - c[2:2:end]
c = c / (2*M)
setprecision(BigFloat,4096)
P = Chebytonormal(c)[1:2:end]/sqrt(big.(2.0))
p_P = 0
start_time = time()
err,phi = GSLW(P,p_P,stop_eps,R_init,R_max)
elpased_time = time()-start_time
@printf("Elapsed time is %4.2e s\n", elpased_time)
# Test case 3: Matrix inversion
#
# We would like to approximate 1/x over [1/kappa,1] by a polynomial, such polynomial is generated
# by Remez algorithm and the approximation error is bounded by 10^{-6}
#
# parameters
# stop_eps: desired accuracy
# kappa: parameters of polynomial approximation
# R_init: number of bits used at the beginning
# R_max: number of bits available
#
stop_eps = 1e-12
kappa = 20
R_init = 2048
R_max = 2049
#------------------------------------------------------------------
# even approximation
# enter your path here
matpath2 = "Data\\inversex\\"
vars = matread(matpath2 * "coef_xeven_" * string(kappa)*"_6"* ".mat")
coef = vars["coef"]
setprecision(BigFloat,4096)
coef2 = zeros(2*length(coef)-1)
coef2[1:2:end] = coef
P = Chebytonormal(coef2)[1:2:end]
p_P = 0
start_time = time()
err,phi1 = GSLW(P,p_P,stop_eps,R_init,R_max)
elpased_time = time()-start_time
@printf("Elapsed time is %4.2e s\n", elpased_time)
# odd approximation
vars = matread(matpath2 * "coef_xodd_" * string(kappa)*"_6"* ".mat")
coef = vars["coef"]
setprecision(BigFloat,4096)
coef2 = zeros(2*length(coef))
coef2[2:2:end] = coef
P = Chebytonormal(coef2)[2:2:end]
start_time = time()
p_P = 1
err,phi = GSLW(P,p_P,stop_eps,R_init,R_max)
elpased_time = time()-start_time
@printf("Elapsed time is %4.2e s\n", elpased_time)
## Test case whatever: QSVT
stop_eps = 1e-12
tau = 100
R_init = 65536
R_max = 65537
#------------------------------------------------------------------
phi1 = []
phi2 = []
coeff = [0, 1.15635132, 0, 0, 0, 0.225911198, 0, 0, 0, 0.11899033, 0, 0, 0, 0.0760566958, 0, 0, 0, 0.0525742336, 0, 0, 0, 0.0379644735, 0, 0, 0, 0.0283926438, 0, 0, 0, 0.0221076246, 0]
# coeff = [1.15635132, 0.225911198, 0.11899033, 0.0760566958, 0.0525742336, 0.0379644735, 0.0283926438, 0.0221076246]
setprecision(BigFloat,4096)
start_time = time()
p_P = 1
c = Chebytonormal(coeff)[2:2:end]
err, phi = GSLW(c, p_P, stop_eps, R_init, R_max)
elapsed_time = time() - start_time
# for p_P=0:1
# N = ceil.(Int,tau*1.4+log(1e14))
# if(p_P==0)
# setprecision(BigFloat,4096)
# if(mod(N,2)==1)
# N -= 1
# end
# coef = zeros(BigFloat,N+1)
# for i=1:(round(Int,N/2)+1)
# coef[2*i-1] = (-1)^(i-1)*besselj(big.(2.0*(i-1)),tau)
# end
# coef[1] = coef[1]/2
# P = Chebytonormal(coef)
# P = P[1:2:end]
# else
# setprecision(BigFloat,4096)
# if(mod(N,2)==0)
# N += 1
# end
# coef = zeros(BigFloat,N+1)
# for i=1:round(Int,(N+1)/2)
# coef[2*i] = (-1)^(i-1)*besselj(big.(2*i-1),tau)
# end
# P = Chebytonormal(coef)[2:2:end]
# end
# start_time = time()
# err,phi = GSLW(P,p_P,stop_eps,R_init,R_max)
# elpased_time = time()-start_time
# @printf("Elapsed time is %4.2e s\n", elpased_time)
# end
|
https://github.com/bartubisgin/QSVTinQiskit-2021-Europe-Hackathon-Winning-Project-
|
bartubisgin
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/qBraid/qiskit-fall-fest-algiers
|
qBraid
|
! qbraid jobs enable qbraid_sdk
!pip install qiskit
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from numpy.random import randint
import numpy as np
import math
qc=QuantumCircuit(2,1)
qc.h(0) #Apply Hadamard Gate to the first qubit
qc.cx(0,1) #Apply Control Unit Operation on the second qubit, in this case the control NOT gate (for the sake of simplicity
qc.h(0) #Apply the Hadamard Gate again before output on the first qubit
qc.measure(0,0) #Mesaure the output value of the first Qubit
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(qc, shots=1, memory=True)
result = aer_sim.run(qobj).result()
measured_bit = int(result.get_memory()[0])
measured_bit
print(qc) #we draw the circuit
print(measured_bit)
def hadamard_test_real(): ##We copy the code above to create the circuit, the output is only the measured real value
qc=QuantumCircuit(2,1)
qc.h(0)
qc.cx(0,1)
qc.h(0)
qc.measure(0,0)
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(qc, shots=1, memory=True)
result = aer_sim.run(qobj).result()
measured_bit = int(result.get_memory()[0])
return measured_bit
print(hadamard_test_real())
def hadamard_test_imag(): ##We copy the code above to create the circuit, the output is only the measured Imaginary value
qc=QuantumCircuit(2,1)
qc.h(0)
qc.p(-math.pi/2,0)
qc.cx(0,1)
qc.h(0)
qc.measure(0,0)
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(qc, shots=1, memory=True)
result = aer_sim.run(qobj).result()
measured_bit = int(result.get_memory()[0])
return measured_bit
print(hadamard_test_imag())
def roll_the_dice_twice():
k=0
a=0
b=0
while(k<6):
k=k+1
a=hadamard_test_real()+a
b=hadamard_test_imag()+b
return a,b
a,b=roll_the_dice_twice()
print("Your Dice Rolled a: ",a," And Your Friend Rolled a: ",b)
if (a<b):
print("You WIN!")
else:
if(a==b):
print("It's a TIE!")
else:
print("Your friend WINS!")
from qbraid import get_devices
get_devices()
IBMQ.save_account('YOUR_IBMQ_KEY')
from qbraid import device_wrapper, job_wrapper, get_jobs
from qbraid.api import ibmq_least_busy_qpu, verify_config
from qiskit import QuantumCircuit
import numpy as np
qiskit_circuit = QuantumCircuit(1, 1)
qiskit_circuit.h(0)
qiskit_circuit.ry(np.pi / 4, 0)
qiskit_circuit.rz(np.pi / 2, 0)
qiskit_circuit.measure(0, 0)
qiskit_circuit.draw()
shots=200
google_id = "google_cirq_dm_sim"
qbraid_google_device = device_wrapper(google_id)
aws_id = "aws_dm_sim"
qbraid_aws_device = device_wrapper(aws_id) # Credential handled by qBraid Quantum Jobs
qbraid_google_job = qbraid_google_device.run(qiskit_circuit, shots=shots)
qbraid_aws_job = qbraid_aws_device.run(qiskit_circuit, shots=shots)
get_jobs()
jobs = [qbraid_google_job, qbraid_aws_job]
google_result, aws_result = [job.result() for job in jobs]
print(f"{qbraid_google_device.name} counts: {google_result.measurement_counts()}")
print(f"{qbraid_aws_device.name} counts: {aws_result.measurement_counts()}")
google_result.plot_counts()
aws_result.plot_counts()
|
https://github.com/qBraid/qiskit-fall-fest-algiers
|
qBraid
|
!qbraid
!qbraid --version
!qbraid jobs enable qbraid_sdk
import qbraid
qbraid.__version__
IBMQ.save_account('YOUR_IBM_KEY')
from qbraid import get_devices
get_devices()
get_devices(
filters={
"type": "Simulator",
"name": {"$regex": "State"},
"vendor": {"$in": ["AWS", "IBM"]},
}
)
get_devices(
filters={
"paradigm": "gate-based",
"type": "QPU",
"numberQubits": {"$gte": 5},
"status": "ONLINE",
}
)
get_devices(filters={"runPackage": "qiskit", "requiresCred": "false"})
from qbraid import device_wrapper, job_wrapper, get_jobs
from qbraid.api import ibmq_least_busy_qpu, verify_config
qbraid_device = device_wrapper("ibm_aer_qasm_sim")
qbraid_device.info
verify_config("IBM")
least_busy = ibmq_least_busy_qpu() # requires credential
least_busy
ibmq_id = "ibm_q_qasm_sim"
qbraid_ibmq_device = device_wrapper(ibmq_id)
qbraid_ibmq_device.vendor_dlo
from qiskit import QuantumCircuit
import numpy as np
qiskit_circuit = QuantumCircuit(1, 1)
qiskit_circuit.h(0)
qiskit_circuit.ry(np.pi / 4, 0)
qiskit_circuit.rz(np.pi / 2, 0)
qiskit_circuit.measure(0, 0)
qiskit_circuit.draw()
shots = 2
# qbraid_ibmq_job = qbraid_ibmq_device.run(qiskit_circuit, shots=shots)
# qbraid_ibmq_job.status()
google_id = "google_cirq_dm_sim"
qbraid_google_device = device_wrapper(google_id)
aws_id = "aws_dm_sim"
qbraid_aws_device = device_wrapper(aws_id) # Credential handled by qBraid Quantum Jobs
qbraid_google_job = qbraid_google_device.run(qiskit_circuit, shots=shots)
qbraid_aws_job = qbraid_aws_device.run(qiskit_circuit, shots=shots)
get_jobs()
# qbraid_ibmq_job.wait_for_final_state()
jobs = [qbraid_google_job, qbraid_aws_job]
google_result, aws_result = [job.result() for job in jobs]
print(f"{qbraid_google_device.name} counts: {google_result.measurement_counts()}")
print(f"{qbraid_aws_device.name} counts: {aws_result.measurement_counts()}")
# print(f"{qbraid_ibmq_device.name} counts: {ibmq_result.measurement_counts()}")
google_result.plot_counts()
aws_result.plot_counts()
ibmq_result.plot_counts()
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
from qiskit.visualization import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# Qiskitバージョンの確認
qiskit.__qiskit_version__
q = QuantumCircuit(1) # 1量子ビット回路を用意
q.x(0) # Xゲートを0番目の量子ビットに操作します。
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(1) # 1量子ビット回路を用意
q.h(0) # Hゲートを0番目の量子ビットに操作します。
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(1) # 1量子ビット回路を用意
# Hゲートを0番目の量子ビットに操作します。
q.h(0)
# 次にZゲートを0番目の量子ビットに操作します。
q.z(0)
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(1) # 1量子ビット回路を用意
q.h(0) # Hゲートを0番目の量子ビットに操作します。
q.s(0) # 次にSゲートを0番目の量子ビットに操作します。
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(1) # 1量子ビット回路を用意
q.h(0) # Hゲートを0番目の量子ビットに操作します。
q.t(0) # 次にTゲートを0番目の量子ビットに操作します。
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(1) # 1量子ビット回路を用意
q.h(0) # Hゲートを0番目の量子ビットに操作します。
q.u1(np.pi/8,0) # 次にU1ゲートを0番目の量子ビットに操作します。
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(2) # 2量子ビット回路を用意
q.h(0) # Hゲートを0番目の量子ビットに操作します。
q.h(1) # Hゲートを1番目の量子ビットに操作します。
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(2) # 2量子ビット回路を用意
# q0=|1>, q1=|+>の場合:
q.x(0)
q.h(1)
# CU1ゲートの制御ビットをq0、目標ビットをq1、角度をpi/2にセットします。
q.cu1(np.pi/2,0,1)
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
from qiskit.visualization import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
q = QuantumCircuit(1) # 1量子ビット回路を用意
q.x(0) # Xゲートを0番目の量子ビットに操作します。
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(1) # 1量子ビット回路を用意
q.h(0) # Hゲートを0番目の量子ビットに操作します。
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(1) # 1量子ビット回路を用意
# Xゲートを0番目の量子ビットに操作します。
q.x(0)
# 次にHゲートを0番目の量子ビットに操作します。
q.h(0)
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(2) # 2量子ビット回路を用意
q.h(0) # Hゲートを0番目の量子ビットに操作します。
q.h(1) # Hゲートを1番目の量子ビットに操作します。
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(2) # 2量子ビット回路を用意
# q0=1, q1=0の場合:q0を1にします。
q.x(0)
# CXゲートの制御ビットをq0、目標ビットをq1にセットします。
q.cx(0,1)
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(2) # 2量子ビット回路を用意
# q0とq1をそれぞれ|+⟩にします
q.h(0)
q.h(1)
# CXゲートの制御ビットをq0、目標ビットをq1にセットします。
q.cx(0,1)
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(2) # 2量子ビット回路を用意
# q0を|+⟩、q1を|−⟩にします
q.h(0)
q.x(1)
q.h(1)
# CXゲートの制御ビットをq0、目標ビットをq1にセットします。
q.cx(0,1)
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(4) # 4量子ビット回路を用意
# q0、q1、q2をそれぞれ|1⟩にします
q.x(0)
q.x(1)
q.x(2)
# cxゲートを3つ追加します。制御/目標のペアは、q0/q3、q1/q3、q2/q3です。
q.cx(0,3)
q.cx(1,3)
q.cx(2,3)
q.draw(output='mpl')
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
# ブロッホ球の表示
plot_bloch_multivector(result)
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# 必要なライブラリのインポート
from qiskit import IBMQ, BasicAer, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, execute
import numpy as np
# 描画ツールのインポート
from qiskit.visualization import plot_histogram
#qiskitのversion確認
import qiskit
qiskit.__qiskit_version__
#入力用量子ビットの数を設定
n = 3
const_f = QuantumCircuit(n+1,n) #量子回路を準備(アンシラ用にn+1個の量子レジスタを準備)
input = np.random.randint(2) #乱数生成にランダム関数をつかいます
if input == 1:
const_f.x(n)
for i in range(n):
const_f.measure(i, i)
const_f.draw()
const_f = QuantumCircuit(n+1,n)
input = np.random.randint(2) #乱数生成にランダム関数をつかいます
if input == 1:
const_f.id(n)
for i in range(n):
const_f.measure(i, i)
const_f.draw()
#上記の図のとおり4量子ビット回路を用意してください。
#各入力用量子ビットを制御に、出力用量子ビットを標的としたCNOT回路を作成してください。
q = QuantumCircuit(4) # 4量子ビット回路を用意
q.cx(0,3)
q.cx(1,3)
q.cx(2,3)
q.draw(output="mpl") # 回路を描画
# 上記回路にあるように入力|𝑞2𝑞1𝑞0⟩=|010⟩をつくって|𝑞3⟩の状態を確認してください。
q = QuantumCircuit(4) # 4量子ビット回路を用意
q.x(1) # Xゲートを1番目の量子ビットに操作します。
q.cx(0,3)
q.cx(1,3)
q.cx(2,3)
q.barrier() # 回路をみやすくするためにバリアを配置
q.x(1) # 最後にXゲートで1番目の量子ビットを挟みます。
q.draw(output="mpl") # 回路を描画
balanced_f = QuantumCircuit(n+1,n)
b_str = "101"
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_f.x(qubit)
balanced_f.draw()
balanced_f.barrier() #回路をみやすくするためにバリアを配置
for qubit in range(n): #入力用量子ビットにCNOTゲートを適用
balanced_f.cx(qubit, n)
balanced_f.barrier() #回路をみやすくするためにバリアを配置
balanced_f.draw()
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_f.x(qubit)
balanced_f.draw()
#ドイチ・ジョザアルゴリズムに均等な関数を実装した回路を"balanced_dj"と名付ける
balanced_dj = QuantumCircuit(n+1, n)
#Step 1: 各量子ビットはもともと|0>に初期化されているため、最後のアンシラだけ|1>に
balanced_dj.x(n) #Xゲートを最後のアンシラに適用
#Step 2: 全体にアダマールをかけて入力用量子ビットはすべて|+⟩ に、そして補助の量子ビットは|−⟩に
for qubit in range(n): #全量子ビットにアダマールを適用
balanced_dj.h(qubit)
#Step 3: オラクルUf |𝑥⟩|𝑦⟩↦|𝑥⟩|𝑓(𝑥)⊕𝑦⟩を適用
# 次ステップでUfを構築します
#Step 4: 最後の補助量子ビットにアダマールを適用して回路を描画
balanced_dj.h(n)
balanced_dj.draw()
balanced_dj += balanced_f #均等な関数の追加
balanced_dj.draw()
for qubit in range(n):
balanced_dj.h(qubit)
balanced_dj.barrier()
for i in range(n):
balanced_dj.measure(i, i)
balanced_dj.draw()
# 回路をシミュレーターに投げて結果を出力します
simulator = Aer.get_backend('qasm_simulator')
result = execute(balanced_dj, backend=simulator, shots=1).result()
# 結果をヒストグラムでプロットします
plot_histogram(result.get_counts(balanced_dj))
#IBM Q accountをロードししプロバイダを指定
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
#一番空いているバックエンドを自動的に選択して実行
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
#上記で特定したバックエンドを指定してジョブを実行します。
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(balanced_dj, backend=backend, shots=shots, optimization_level=3)
#プログラムの実行ステータスをモニターします。
job_monitor(job, interval = 2)
#計算結果(results)を取得し、答え(answer)をプロットします。
results = job.result()
answer = results.get_counts()
# 結果をヒストグラムでプロットします
plot_histogram(answer)
#必要に応じてQiskitのライブラリ等のインポート
# from qiskit import *
# %matplotlib inline
# from qiskit.tools.visualization import plot_histogram
#適当なバイナリ文字列を設定
s = '0110001'
#qcという名の量子回路を準備
qc = QuantumCircuit(6+1,6)
qc.x(6)
qc.h(6)
qc.h(range(6))
qc.draw()
# Step 1
s = '0110001'
#$n+1$ 量子ビットと結果を格納する $n$個の古典レジスタを用意する。$n$は秘密の文字列の長さと同じ。
n = len(s)
qc = QuantumCircuit(n+1,n)
# Step 2
qc.x(n) #最後の量子ビットを|1⟩にする
qc.barrier() #回路をみやすくするためにバリアを配置
# Step 3
qc.h(range(n+1)) #全体にHゲートを適用
qc.barrier() #回路をみやすくするためにバリアを配置
# Step 4
for ii, yesno in enumerate(reversed(s)):
if yesno == '1':
qc.cx(ii, n)
qc.barrier() #回路をみやすくするためにバリアを配置
# Step 5
qc.h(range(n+1)) #全量子ビットに再びHを適用
qc.barrier() #回路をみやすくするためにバリアを配置
qc.measure(range(n), range(n)) # 0 から n-1までの入力n量子ビットを測定し古典レジスタに結果を格納
%matplotlib inline
#回路図を描画
qc.draw(output='mpl')
# 回路をシミュレーターに投げて結果を出力します
simulator = Aer.get_backend('qasm_simulator')
# shots=1で実施
result = execute(qc, backend=simulator, shots=1).result()
# 結果をヒストグラムでプロットします
from qiskit.visualization import plot_histogram
plot_histogram(result.get_counts(qc))
# 必要似応じてIBM Q accountをロードししプロバイダを指定
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q')
#一番空いているバックエンドを自動的に選択して実行
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
#上記で特定したバックエンドを指定してジョブを実行します。
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(qc, backend=backend, shots=shots, optimization_level=3)
#プログラムの実行ステータスをモニターします。
job_monitor(job, interval = 2)
#計算結果(results)を取得し、答え(answer)をプロットします。
results = job.result()
answer = results.get_counts()
# 結果をヒストグラムでプロットします
plot_histogram(answer)
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
from qiskit.visualization import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# Qiskitバージョンの確認
qiskit.__qiskit_version__
q = QuantumCircuit(1) # 1量子ビット回路を用意
q.x(0) # Xゲートを0番目の量子ビットに操作します。
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(1) # 1量子ビット回路を用意
q.h(0) # Hゲートを0番目の量子ビットに操作します。
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(1) # 1量子ビット回路を用意
# Hゲートを0番目の量子ビットに操作します。
q.h(0)
# 次にZゲートを0番目の量子ビットに操作します。
q.z(0)
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(1) # 1量子ビット回路を用意
q.h(0) # Hゲートを0番目の量子ビットに操作します。
q.s(0) # 次にSゲートを0番目の量子ビットに操作します。
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(1) # 1量子ビット回路を用意
q.h(0) # Hゲートを0番目の量子ビットに操作します。
q.t(0) # 次にTゲートを0番目の量子ビットに操作します。
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(1) # 1量子ビット回路を用意
q.h(0) # Hゲートを0番目の量子ビットに操作します。
q.u1(np.pi/8,0) # 次にU1ゲートを0番目の量子ビットに操作します。
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(2) # 2量子ビット回路を用意
q.h(0) # Hゲートを0番目の量子ビットに操作します。
q.h(1) # Hゲートを1番目の量子ビットに操作します。
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(2) # 2量子ビット回路を用意
# q0=|1>, q1=|+>の場合:
q.x(0)
q.h(1)
# CU1ゲートの制御ビットをq0、目標ビットをq1、角度をpi/2にセットします。
q.cu1(np.pi/2,0,1)
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
import numpy as np
from scipy.fftpack import fft
import matplotlib.pyplot as plt
%matplotlib inline
# parameters
N = 2**20 # data number
dt = 0.0001 # data step [s]
f1, f2 = 5, 0 # frequency[Hz]
A1, A2 = 5, 0 # Amplitude
p1, p2 = 0, 0 # phase
t = np.arange(0, N*dt, dt) # time
freq = np.linspace(0, 1.0/dt, N) # frequency step
x = A1*np.sin(2*np.pi*f1*t + p1) + A2*np.sin(2*np.pi*f2*t + p2)
y = fft(x)/(N/2) # 離散フーリエ変換&規格化
plt.figure(2)
plt.subplot(211)
plt.plot(t, x)
plt.xlim(0, 1)
plt.xlabel("time")
plt.ylabel("amplitude")
plt.subplot(212)
plt.plot(freq, np.abs(y))
plt.xlim(0, 10)
#plt.ylim(0, 5)
plt.xlabel("frequency")
plt.ylabel("amplitude")
plt.tight_layout()
plt.savefig("01")
plt.show()
import numpy as np
from numpy import pi
# importing Qiskit
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import plot_histogram, plot_bloch_multivector
%config InlineBackend.figure_format = 'svg' # Makes the images look nice
qc = QuantumCircuit(3)
qc.h(2)
qc.cu1(pi/2, 1, 2) # CROT from qubit 1 to qubit 2
qc.cu1(pi/4, 0, 2) # CROT from qubit 2 to qubit 0
qc.h(1)
qc.cu1(pi/2, 0, 1) # CROT from qubit 0 to qubit 1
qc.h(0)
qc.swap(0,2)
qc.draw('mpl')
import numpy as np
from numpy import pi
# importing Qiskit
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import plot_histogram, plot_bloch_multivector
%config InlineBackend.figure_format = 'svg' # Makes the images look nice
def qft_rotations(circuit, n):
"""Performs qft on the first n qubits in circuit (without swaps)"""
if n == 0:
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cu1(pi/2**(n-qubit), qubit, n)
# At the end of our function, we call the same function again on
# the next qubits (we reduced n by one earlier in the function)
qft_rotations(circuit, n)
# Let's see how it looks:
qc = QuantumCircuit(4)
qft_rotations(qc,4)
qc.draw('mpl')
def swap_registers(circuit, n):
for qubit in range(n//2):
circuit.swap(qubit, n-qubit-1)
return circuit
# Let's see how it looks:
qc = QuantumCircuit(4)
swap_registers(qc,4)
qc.draw('mpl')
def qft(circuit, n):
"""QFT on the first n qubits in circuit"""
qft_rotations(circuit, n)
swap_registers(circuit, n)
return circuit
# Let's see how it looks:
qc = QuantumCircuit(4)
qft(qc,4)
qc.draw('mpl')
bin(5)
# Create the circuit
qc = QuantumCircuit(3)
# Encode the state 5
qc.x(0)
qc.x(2)
%config InlineBackend.figure_format = 'svg' # Makes the images fit
qc.draw('mpl')
backend = Aer.get_backend("statevector_simulator")
statevector = execute(qc, backend=backend).result().get_statevector()
plot_bloch_multivector(statevector)
qft(qc,3)
qc.draw('mpl')
statevector = execute(qc, backend=backend).result().get_statevector()
plot_bloch_multivector(statevector)
def inverse_qft(circuit, n):
"""Does the inverse QFT on the first n qubits in circuit"""
# First we create a QFT circuit of the correct size:
qft_circ = qft(QuantumCircuit(n), n)
# Then we take the inverse of this circuit
invqft_circ = qft_circ.inverse()
# And add it to the first n qubits in our existing circuit
circuit.append(invqft_circ, circuit.qubits[:n])
return circuit.decompose() # .decompose() allows us to see the individual gates
nqubits = 3
number = 5
qc = QuantumCircuit(nqubits)
for qubit in range(nqubits):
qc.h(qubit)
qc.u1(number*pi/4,0)
qc.u1(number*pi/2,1)
qc.u1(number*pi,2)
qc.draw('mpl')
backend = Aer.get_backend("statevector_simulator")
statevector = execute(qc, backend=backend).result().get_statevector()
plot_bloch_multivector(statevector)
qc = inverse_qft(qc,nqubits)
qc.measure_all()
qc.draw('mpl')
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to nqubits
# IBMQ.save_account('Your_Token')
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= nqubits
and not x.configuration().simulator
and x.status().operational==True))
print("least busy backend: ", backend)
shots = 2048
job = execute(qc, backend=backend, shots=shots, optimization_level=3)
job_monitor(job)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
qiskit.__qiskit_version__
grover11=QuantumCircuit(2,2)
grover11.draw(output='mpl')
# 問題-1 上の回路図を作ってください。
# 正解
grover11.h([0,1]) # ← これが(一番記述が短い正解)
grover11.draw(output='mpl')
# 問題-2 上の回路図(問題-1に赤枠部分を追加したもの)を作ってください。
grover11.h(1) # 正解
grover11.cx(0,1) # 正解
grover11.h(1) # 正解
grover11.draw(output='mpl')
#問題-3 上の回路図(問題-2に赤枠部分を追加したもの)を作ってください。
grover11.i(0) # 回路の見栄えを整えるために、恒等ゲートを差し込む。無くても動くが、表示の見栄えが崩れるのを防止するために、残しておく。
grover11.h([0,1]) # ← 正解
grover11.x([0,1]) # ← 正解
grover11.h(1) # ← 正解
grover11.cx(0,1) # ← 正解
grover11.h(1) # ← 正解
grover11.i(0) # ← 正解
grover11.x([0,1]) # ← 正解
grover11.h([0,1]) # ← 正解
grover11.draw(output='mpl')
grover11.measure(0,0)
grover11.measure(1,1)
grover11.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator') # 実行環境の定義
job = execute(grover11, backend) # 処理の実行
result = job.result() # 実行結果
counts = result.get_counts(grover11) # 実行結果の詳細を取り出し
print(counts)
from qiskit.visualization import *
plot_histogram(counts) # ヒストグラムで表示
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 1量子ビット回路を用意
q = QuantumCircuit(1)
# 回路を描画
q.draw(output="mpl")
# 量子ゲートで回路を作成
q.x(0) # Xゲートを0番目の量子ビットに操作します。
# 回路を描画
q.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute( q, vector_sim )
result = job.result().get_statevector(q, decimals=3)
print(result)
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 1量子ビット回路を定義
q1 = QuantumCircuit(1)
## 回路を描画
q1.draw(output="mpl")
# 量子ゲートで回路を作成
q1.x(0)
q1.x(0)
## 回路を描画
q1.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q1, vector_sim )
result = job.result().get_statevector(q1, decimals=3)
print(result)
# 1量子ビット回路を定義
q2 = QuantumCircuit(1)
# 量子ゲートで回路を作成
q2.h(0)
# 回路を描画
q2.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q2, vector_sim )
result = job.result().get_statevector(q2, decimals=3)
print(result)
# 1量子ビット回路を定義
q3 = QuantumCircuit(1)
# 量子ゲートで回路を作成
q3.h(0)
q3.h(0)
# 回路を描画
q3.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q3, vector_sim )
result = job.result().get_statevector(q3, decimals=3)
print(result)
# 1量子ビット回路を定義
q4 = QuantumCircuit(1)
# 量子ゲートで回路を作成
q4.x(0)
q4.h(0)
# 回路を描画
q4.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q4, vector_sim )
result = job.result().get_statevector(q4, decimals=3)
print(result)
# 1量子ビット回路を定義
q5 = QuantumCircuit(1)
# 量子ゲートで回路を作成
q5.h(0)
q5.z(0)
# 回路を描画
q5.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q5, vector_sim )
result = job.result().get_statevector(q5, decimals=3)
print(result)
# 1量子ビット回路を定義
q6 = QuantumCircuit(1)
# 量子ゲートで回路を作成
q6.x(0)
q6.h(0)
q6.z(0)
# 回路を描画
q6.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q6, vector_sim )
result = job.result().get_statevector(q6, decimals=3)
print(result)
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 2量子ビット回路を用意
q = QuantumCircuit(2,2) # 2量子ビット回路と2ビットの古典レジスターを用意します。
# 回路を描画
q.draw(output="mpl")
# 量子ゲートで回路を作成
q.h(0) # Hゲートを量子ビットq0に実行します。
q.h(1) # Hゲートを量子ビットq1に実行します。
# q.h([0,1]) # またはこのように書くこともできます。
# 回路を描画
q.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q, vector_sim )
result = job.result().get_statevector(q, decimals=3)
print(result)
# 回路を測定
q.measure(0,0)
q.measure(1,1)
# 回路を描画
q.draw(output='mpl')
# QASMシミュレーターで実験
simulator = Aer.get_backend('qasm_simulator')
job = execute(q, backend=simulator, shots=1024)
result = job.result()
# 測定された回数を表示
counts = result.get_counts(q)
print(counts)
## ヒストグラムで測定された確率をプロット
from qiskit.visualization import *
plot_histogram( counts )
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 2量子ビット回路を用意
q1 = QuantumCircuit(2,2) # 2量子ビット回路と2ビットの古典レジスターを用意します。
# 回路を描画
q1.draw(output="mpl")
# 量子ゲートで回路を作成
q1.x(0) # Xゲートを量子ビットq0に操作します。
q1.x(1) # Xゲートを量子ビットq1に操作します。
# 回路を描画
q1.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q1, vector_sim )
result = job.result().get_statevector(q1, decimals=3)
print(result)
# 回路を測定
q1.measure(0,0)
q1.measure(1,1)
# 回路を描画
q1.draw(output='mpl')
# QASMシミュレーターで実験
simulator = Aer.get_backend('qasm_simulator')
job = execute(q1, backend=simulator, shots=1024)
result = job.result()
# 測定された回数を表示
counts = result.get_counts(q1)
print(counts)
# ヒストグラムで測定された確率をプロット
from qiskit.visualization import *
plot_histogram( counts )
# 2量子ビット回路を用意
q2 = QuantumCircuit(2,2) # 2量子ビット回路と2ビットの古典レジスターを用意します。
# 量子ゲートで回路を作成
q2.x(0) # Xゲートを量子ビットq0に操作します。
q2.h(0) # Hゲートを量子ビットq0に操作します。
q2.x(1) # Xゲートを量子ビットq1に操作します。
q2.h(1) # Hゲートを量子ビットq1に操作します。
# 回路を描画
q2.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q2, vector_sim )
result = job.result().get_statevector(q2, decimals=3)
print(result)
# 回路を測定
q2.measure(0,0)
q2.measure(1,1)
# 回路を描画
q2.draw(output='mpl')
# QASMシミュレーターで実験
simulator = Aer.get_backend('qasm_simulator')
job = execute(q2, backend=simulator, shots=1024)
result = job.result()
## 測定された回数を表示
counts = result.get_counts(q2)
print(counts)
## ヒストグラムで測定された確率をプロット
from qiskit.visualization import *
plot_histogram( counts )
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 2量子ビット回路を用意
q = QuantumCircuit(2,2) # 2量子ビット回路と2ビットの古典レジスターを用意します。
# 回路を描画
q.draw(output="mpl")
# q0, q1が0の場合
q.cx(0,1) # CNOTゲートの制御ゲートをq0、目標ゲートをq1にセットします。
# 回路を描画
q.draw(output="mpl")
## First, simulate the circuit
## 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q, vector_sim )
result = job.result().get_statevector(q, decimals=3)
print(result)
# 2量子ビット回路を用意
q1 = QuantumCircuit(2,2) # 2量子ビット回路と2ビットの古典レジスターを用意します。
# 回路を描画
q1.draw(output="mpl")
# q0=1, q1=0の場合
q1.x(0) # q0を1にします。
q1.cx(0,1) # CNOTゲートの制御ゲートをq0、目標ゲートをq1にセットします。
# 回路を描画
q1.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q1, vector_sim )
result = job.result().get_statevector(q1, decimals=3)
print(result)
# 回路を測定
q1.measure(0,0)
q1.measure(1,1)
# 回路を描画
q1.draw(output="mpl")
# QASMシミュレーターで実験
simulator = Aer.get_backend('qasm_simulator')
job = execute(q1, backend=simulator, shots=1024)
result = job.result()
# 測定された回数を表示
counts = result.get_counts(q1)
print(counts)
# ヒストグラムで測定された確率をプロット
from qiskit.visualization import *
plot_histogram( counts )
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 2量子ビット回路を用意
q1 = QuantumCircuit(2)
# 回路を描画
q1.draw(output="mpl")
# q0=0, q1=1の場合
q1.x(1) # q1を1にします。
q1.cx(0,1) # CNOTゲートの制御ゲートをq0、目標ゲートをq1にセットします。
# 回路を描画
q1.draw(output="mpl")
## First, simulate the circuit
## 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q1, vector_sim )
result = job.result().get_statevector(q1, decimals=3)
print(result)
# 2量子ビット回路を用意
q2 = QuantumCircuit(2)
# q0=1, q1=1の場合
q2.x(0) # q0を1にします。
q2.x(1) # q1を1にします。
q2.cx(0,1) # CNOTゲートの制御ゲートをq0、目標ゲートをq1にセットします。
# 回路を描画
q2.draw(output="mpl")
## First, simulate the circuit
## 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q2, vector_sim )
result = job.result().get_statevector(q2, decimals=3)
print(result)
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 2量子ビット回路を用意
qe = QuantumCircuit(2) # 今回は量子ビットのみ用意します。
# 回路を描画
qe.draw(output="mpl")
#qe # ← 修正して回路を完成させてください。片方の量子ビットに重ね合わせを掛けます。
qe.draw(output='mpl')
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(qe, vector_sim )
counts = job.result().get_counts(qe) # 実行結果の詳細を取り出し
print(counts)
# ヒストグラムで測定された確率をプロット
from qiskit.visualization import *
plot_histogram( counts )
# qe # ← cxゲートを使って回路を完成させてください。順番に注意してください。
qe.draw(output='mpl')
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(qe, vector_sim )
# result = job.result().get_statevector(qe, decimals=3)
# print(result)
counts = job.result().get_counts(qe) # 実行結果の詳細を取り出し
print(counts)
# ヒストグラムで測定された確率をプロット
from qiskit.visualization import *
plot_histogram( counts )
# 2量子ビット回路を用意
qe2 = QuantumCircuit(2,2) # 量子ビットと古典レジスターを用意します
# 量子回路を設計
qe2.h(0)
qe2.cx(0,1)
# 回路を測定
qe2.measure(0,0)
qe2.measure(1,1)
# 回路を描画
qe2.draw(output="mpl")
# QASMシミュレーターで実験
simulator = Aer.get_backend('qasm_simulator')
job = execute(qe2, backend=simulator, shots=1024)
result = job.result()
# 測定された回数を表示
counts = result.get_counts(qe2)
print(counts)
# ヒストグラムで測定された確率をプロット
from qiskit.visualization import *
plot_histogram( counts )
from qiskit import IBMQ
IBMQ.save_account('MY_API_TOKEN')
# IBM Q アカウントをロードします。
provider = IBMQ.load_account()
from qiskit.providers.ibmq import least_busy
# 実行可能な量子コンピューターをリストします
large_enough_devices = IBMQ.get_provider().backends(filters=lambda x: x.configuration().n_qubits > 3 and not x.configuration().simulator)
print(large_enough_devices)
real_backend = least_busy(large_enough_devices) # その中から、最も空いている量子コンピューターを選出
print("The best backend is " + real_backend.name())
print('run on real device!')
real_result = execute(qe2,real_backend).result() # 計算を実行します
print(real_result.get_counts(qe2)) # 結果を表示
plot_histogram(real_result.get_counts(qe2)) # ヒストグラムを表示
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 2量子ビット回路を用意
qe = QuantumCircuit(2) # 今回は量子ビットのみ用意します。
# 回路を描画
qe.draw(output="mpl")
# 正解
qe.h(0) # ← 修正して回路を完成させてください。片方の量子ビットに重ね合わせを掛けます。
qe.draw(output='mpl')
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(qe, vector_sim )
counts = job.result().get_counts(qe) # 実行結果の詳細を取り出し
print(counts)
# ヒストグラムで測定された確率をプロット
from qiskit.visualization import *
plot_histogram( counts )
#正解
qe.cx(0,1) # ← cxゲートを使って回路を完成させてください。順番に注意してください。
qe.draw(output='mpl')
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(qe, vector_sim )
# result = job.result().get_statevector(qe, decimals=3)
# print(result)
counts = job.result().get_counts(qe) # 実行結果の詳細を取り出し
print(counts)
# ヒストグラムで測定された確率をプロット
from qiskit.visualization import *
plot_histogram( counts )
# 2量子ビット回路を用意
qe2 = QuantumCircuit(2,2) # 量子ビットと古典レジスターを用意します
# 量子回路を設計
qe2.h(0)
qe2.cx(0,1)
# 回路を測定
qe2.measure(0,0)
qe2.measure(1,1)
# 回路を描画
qe2.draw(output="mpl")
# QASMシミュレーターで実験
simulator = Aer.get_backend('qasm_simulator')
job = execute(qe2, backend=simulator, shots=1024)
result = job.result()
# 測定された回数を表示
counts = result.get_counts(qe2)
print(counts)
# ヒストグラムで測定された確率をプロット
from qiskit.visualization import *
plot_histogram( counts )
from qiskit import IBMQ
#IBMQ.save_account('MY_API_TOKEN')
# IBM Q アカウントをロードします。
provider = IBMQ.load_account()
from qiskit.providers.ibmq import least_busy
# 実行可能な量子コンピューターをリストします
large_enough_devices = IBMQ.get_provider().backends(filters=lambda x: x.configuration().n_qubits > 3 and not x.configuration().simulator)
print(large_enough_devices)
real_backend = least_busy(large_enough_devices) # その中から、最も空いている量子コンピューターを選出
print("The best backend is " + real_backend.name())
print('run on real device!')
real_result = execute(qe2,real_backend).result() # 計算を実行します
print(real_result.get_counts(qe2)) # 結果を表示
plot_histogram(real_result.get_counts(qe2)) # ヒストグラムを表示
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
qiskit.__qiskit_version__
grover11=QuantumCircuit(2,2)
grover11.draw(output='mpl')
# 問題-1 上の回路図を作ってください。
grover11.draw(output='mpl')
# 問題-2 上の回路図(問題-1に赤枠部分を追加したもの)を作ってください。
grover11.draw(output='mpl')
#問題-3 上の回路図(問題-2に赤枠部分を追加したもの)を作ってください。
grover11.i(0) # 回路の見栄えを整えるために、恒等ゲートを差し込む。無くても動くが、表示の見栄えが崩れるのを防止するために、残しておく。
grover11.draw(output='mpl')
grover11.measure(0,0)
grover11.measure(1,1)
grover11.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator') # 実行環境の定義
job = execute(grover11, backend) # 処理の実行
result = job.result() # 実行結果
counts = result.get_counts(grover11) # 実行結果の詳細を取り出し
print(counts)
from qiskit.visualization import *
plot_histogram(counts) # ヒストグラムで表示
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
qiskit.__qiskit_version__
grover11=QuantumCircuit(2,2)
grover11.draw(output='mpl')
# 問題-1 上の回路図を作ってください。
# 正解
grover11.h([0,1]) # ← これが(一番記述が短い正解)
grover11.draw(output='mpl')
# 問題-2 上の回路図(問題-1に赤枠部分を追加したもの)を作ってください。
grover11.h(1) # 正解
grover11.cx(0,1) # 正解
grover11.h(1) # 正解
grover11.draw(output='mpl')
#問題-3 上の回路図(問題-2に赤枠部分を追加したもの)を作ってください。
grover11.i(0) # 回路の見栄えを整えるために、恒等ゲートを差し込む。無くても動くが、表示の見栄えが崩れるのを防止するために、残しておく。
grover11.h([0,1]) # ← 正解
grover11.x([0,1]) # ← 正解
grover11.h(1) # ← 正解
grover11.cx(0,1) # ← 正解
grover11.h(1) # ← 正解
grover11.i(0) # ← 正解
grover11.x([0,1]) # ← 正解
grover11.h([0,1]) # ← 正解
grover11.draw(output='mpl')
grover11.measure(0,0)
grover11.measure(1,1)
grover11.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator') # 実行環境の定義
job = execute(grover11, backend) # 処理の実行
result = job.result() # 実行結果
counts = result.get_counts(grover11) # 実行結果の詳細を取り出し
print(counts)
from qiskit.visualization import *
plot_histogram(counts) # ヒストグラムで表示
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 1量子ビット回路を定義
q1 = QuantumCircuit(1)
## 回路を描画
q1.draw(output="mpl")
# 量子ゲートで回路を作成
q1.x(0)
q1.x(0)
## 回路を描画
q1.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q1, vector_sim )
result = job.result().get_statevector(q1, decimals=3)
print(result)
# 1量子ビット回路を定義
q2 = QuantumCircuit(1)
# 量子ゲートで回路を作成
q2.h(0)
# 回路を描画
q2.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q2, vector_sim )
result = job.result().get_statevector(q2, decimals=3)
print(result)
# 1量子ビット回路を定義
q3 = QuantumCircuit(1)
# 量子ゲートで回路を作成
q3.h(0)
q3.h(0)
# 回路を描画
q3.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q3, vector_sim )
result = job.result().get_statevector(q3, decimals=3)
print(result)
# 1量子ビット回路を定義
q4 = QuantumCircuit(1)
# 量子ゲートで回路を作成
q4.x(0)
q4.h(0)
# 回路を描画
q4.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q4, vector_sim )
result = job.result().get_statevector(q4, decimals=3)
print(result)
# 1量子ビット回路を定義
q5 = QuantumCircuit(1)
# 量子ゲートで回路を作成
q5.h(0)
q5.z(0)
# 回路を描画
q5.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q5, vector_sim )
result = job.result().get_statevector(q5, decimals=3)
print(result)
# 1量子ビット回路を定義
q6 = QuantumCircuit(1)
# 量子ゲートで回路を作成
q6.x(0)
q6.h(0)
q6.z(0)
# 回路を描画
q6.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q6, vector_sim )
result = job.result().get_statevector(q6, decimals=3)
print(result)
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
qiskit.__qiskit_version__
grover11=QuantumCircuit(2,2)
grover11.draw(output='mpl')
# 問題-1 上の回路図を作ってください。
grover11.draw(output='mpl')
# 問題-2 上の回路図(問題-1に赤枠部分を追加したもの)を作ってください。
grover11.draw(output='mpl')
#問題-3 上の回路図(問題-2に赤枠部分を追加したもの)を作ってください。
grover11.i(0) # 回路の見栄えを整えるために、恒等ゲートを差し込む。無くても動くが、表示の見栄えが崩れるのを防止するために、残しておく。
grover11.draw(output='mpl')
grover11.measure(0,0)
grover11.measure(1,1)
grover11.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator') # 実行環境の定義
job = execute(grover11, backend) # 処理の実行
result = job.result() # 実行結果
counts = result.get_counts(grover11) # 実行結果の詳細を取り出し
print(counts)
from qiskit.visualization import *
plot_histogram(counts) # ヒストグラムで表示
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
import math
import numpy as np
import matplotlib.pyplot as plt
#from fractions import Fraction
from quantum_computer_math_guide_trigonometric_intro_exercise_answer import *
ans1 = # こちらに値を書いてください
print(check_answer_exercise(ans1,"ans1"))
ans2 = # こちらに値を書いてください。
print(check_answer_exercise(ans2,"ans2"))
ans3 = # こちらに値を書いてください。
print(check_answer_exercise(ans3,"ans3"))
ans4 = # こちらに値を書いてください。
print(check_answer_exercise(ans4,"ans4"))
ans5 = # こちらに値を書いてください。
print(check_answer_exercise(ans5,"ans5"))
ans6 = # こちらに値を書いてください。
print(check_answer_exercise(ans6,"ans6"))
ans7 = # こちらに値を書いてください。
print(check_answer_exercise(ans7,"ans7"))
ans8 = # こちらに値を書いてください。
print(check_answer_exercise(ans8,"ans8"))
ans9 = # こちらに値を書いてください。
print(check_answer_exercise(ans9,"ans9"))
ans10 = # こちらに値を書いてください。
print(check_answer_exercise(ans10,"ans10"))
ans11 = # こちらに値を書いてください。
print(check_answer_exercise(ans11,"ans11"))
ans12 = # こちらに度数法での値を書いてください(「°」は省略してください。)
print(check_answer_exercise(ans12,"ans12"))
ans13 = # こちらに度数法での値を書いてください(「°」は省略してください。)
print(check_answer_exercise(ans13,"ans13"))
ans14 = # こちらに度数法での値を書いてください(「°」は省略してください。)
print(check_answer_exercise(ans14,"ans14"))
ans15 = # こちらに値を書いてください
print(check_answer_exercise(ans15,"ans15"))
ans16 = # こちらに値を書いてください
print(check_answer_exercise(ans16,"ans16"))
ans1_deg = math.sin(math.radians(ここに度数を入力)) # こちらに度数法の計算式を書いてください。
ans1_rad = math.sin(np.pi*(ここに弧度数を入力)) # こちらに弧度法の計算式を書いてください。
print("ans1 =", round(ans1,3)," : ans1_deg = ", round(ans1_deg,3)," : ans1_rad = ", round(ans1_rad,3))
ans2_deg = # こちらに度数法の計算式を書いてください。
ans2_rad = # こちらに弧度法の計算式を書いてください。
print("ans2 =", round(ans2,3)," : ans2_deg = ", round(ans2_deg,3)," : ans2_rad = ", round(ans2_rad,3))
ans3_deg = # こちらに度数法の計算式を書いてください。
ans3_rad = # こちらに弧度法の計算式を書いてください。
print("ans3 =", round(ans3,3)," : ans3_deg = ", round(ans3_deg,3)," : ans3_rad = ", round(ans3_rad,3))
ans4_deg = # こちらに度数法の計算式を書いてください。
ans4_rad = # こちらに弧度法の計算式を書いてください。
print("ans4 =", round(ans4,3)," : ans4_deg = ", round(ans4_deg,3)," : ans4_rad = ", round(ans4_rad,3))
ans5_deg = # こちらに度数法の計算式を書いてください。
ans5_rad = # こちらに弧度法の計算式を書いてください。
print("ans5 =", round(ans5,3)," : ans5_deg = ", round(ans5_deg,3)," : ans5_rad = ", round(ans5_rad,3))
ans6_deg = # こちらに度数法の計算式を書いてください。
ans6_rad = # こちらに弧度法の計算式を書いてください。
print("ans6 =", round(ans6,3)," : ans6_deg = ", round(ans6_deg,3)," : ans6_rad = ", round(ans6_rad,3))
ans7_deg = # こちらに度数法の計算式を書いてください。
ans7_rad = # こちらに弧度法の計算式を書いてください。
print("ans7 =", round(ans7,3)," : ans7_deg = ", round(ans7_deg,3)," : ans7_rad = ", round(ans7_rad,3))
ans8_deg = # こちらに度数法の計算式を書いてください。
ans8_rad = # こちらに弧度法の計算式を書いてください。
print("ans8 =", round(ans8,3)," : ans8_deg = ", round(ans8_deg,3)," : ans8_rad = ", round(ans8_rad,3))
ans9_deg = # こちらに度数法の計算式を書いてください。
ans9_rad = # こちらに弧度法の計算式を書いてください。
print("ans9 =", round(ans9,3)," : ans9_deg = ", round(ans9_deg,3)," : ans9_rad = ", round(ans9_rad,3))
ans10_deg = # こちらに度数法の計算式を書いてください。
ans10_rad = # こちらに弧度法の計算式を書いてください。
print("ans10 =", round(ans10,3)," : ans10_deg = ", round(ans10_deg,3)," : ans10_rad = ", round(ans10_rad,3))
ans11_deg = # こちらに度数法の計算式を書いてください。
ans11_rad = # こちらに弧度法の計算式を書いてください。
print("ans11 =", round(ans11,3)," : ans11_deg = ", round(ans11_deg,3)," : ans11_rad = ", round(ans11_rad,3))
ans12_deg = # こちらに度数法の計算式を書いてください。
print("ans12 =", round(ans12,3)," : ans12_deg = ", round(ans12_deg,3))
ans13_deg = # こちらに度数法の計算式を書いてください。
print("ans13 =", round(ans13,3)," : ans13_deg = ", round(ans13_deg,3))
ans14_deg = # こちらに度数法の計算式を書いてください。
print("ans14 =", round(ans14,3)," : ans14_deg = ", round(ans14_deg,3))
ans15_deg = # こちらに度数法の計算式を書いてください。
ans15_rad = # こちらに弧度法の計算式を書いてください。
print("ans15 =", round(ans15,3)," : ans15_deg = ", round(ans15_deg,3)," : ans15_rad = ", round(ans15_rad,3))
ans16_deg = # こちらに度数法の計算式を書いてください。
ans16_rad = # こちらに弧度法の計算式を書いてください。
print("ans16 =", round(ans16,3)," : ans16_deg = ", round(ans16_deg,3)," : ans16_rad = ", round(ans16_rad,3))
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi)
plt.plot(x, np.sin(x), color='b', label='sin') # color = 'r': red, 'g': green
plt.xlim(-np.pi, np.pi)
plt.ylim(-1.5, 1.5)
plt.axhline(0, ls='-', c='b', lw=0.5)
plt.axvline(0, ls='-', c='b', lw=0.5)
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Graphs')
plt.show()
class GraphClass:
# x_start:x軸の最小値
# x_end:x軸の最大値
# x_start、x_endは表示する関数のデフォルトの定義域
# y_start:y軸の最小値
# y_end:y軸の最大値
def __init__(self, x_start, x_end, y_start , y_end):
self.x_start = x_start
self.x_end = x_end
self.y_start = y_start
self.y_end = y_end
self.x = np.linspace(x_start,x_end)
self.plt = plt
# オーバーライドする。自分が表示したいグラフを定義する
def setGraph(self):
pass
# グラフを表示する
def displayGraph(self):
self.setGraph()
self.__setBasicConfig()
self.plt.show()
# sinグラフを表示する
def displaySin(self):
self.plt.plot(self.x, np.sin(self.x), color='b', label='sin')
self.__setBasicConfig()
self.plt.show()
# cosグラフを表示する
def displayCos(self):
self.plt.plot(self.x, np.cos(self.x), color='r', label='cos')
self.__setBasicConfig()
self.plt.show()
# tanグラフを表示する
def displayTan(self):
self.plt.plot(self.x, np.tan(self.x), color='y', label='tan')
self.__setBasicConfig()
self.plt.show()
# 基本的な設定
def __setBasicConfig(self):
self.plt.xlim(self.x_start, self.x_end)
self.plt.ylim(self.y_start, self.y_end)
self.plt.gca().set_aspect('equal', adjustable='box')
self.plt.axhline(0, ls='-', c='b', lw=0.5)
self.plt.axvline(0, ls='-', c='b', lw=0.5)
self.plt.xticks(rotation=45)
self.plt.legend()
self.plt.xlabel('x')
self.plt.ylabel('y')
self.plt.title('Graphs')
# 自分のクラスを定義する 以下はサンプル
class MyGraphClass(GraphClass):
def __init__(self, x_start, x_end, y_start , y_end):
super().__init__(x_start, x_end, y_start , y_end)
# オーバーライドする
def setGraph(self):
#sin
self.plt.plot(self.x, 2*np.sin(self.x), color='b', label='sin')
#cos
self.plt.plot(self.x, np.cos(self.x), color='g', label='cos')
#単位円 デフォルトとは異なる定義域にする。
r=1
x = np.linspace(-r, r)
self.plt.plot(x, np.sqrt(r ** 2 - x ** 2), color='r', label='x^2+y^2')
self.plt.plot(x, -np.sqrt(r ** 2 - x ** 2), color='r', label='x^2+y^2')
# 点を入れる
self.plt.plot(np.cos(math.radians(30)), np.sin(math.radians(30)), marker='X', markersize=20)
#tan
#self.plt.plot(self.x, np.tan(self.x), color='y', label='tan')
#exp
#self.plt.plot(self.x, np.exp(self.x), color='m', label='exp')
myGraphClass = MyGraphClass(-1,1,-1,1)
myGraphClass.displayGraph()
#myGraphClass.displaySin()
#myGraphClass.displayCos()
#myGraphClass.displayTan()
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
import math
import numpy as np
import matplotlib.pyplot as plt
#from fractions import Fraction
from quantum_computer_math_guide_trigonometric_intro_exercise_answer import *
ans1 = 1/2 # こちらに値を書いてください
print(check_answer_exercise(ans1,"ans1"))
ans2 = 0# こちらに値を書いてください。
print(check_answer_exercise(ans2,"ans2"))
ans3 = 1# こちらに値を書いてください。
print(check_answer_exercise(ans3,"ans3"))
ans4 = 1/2 # こちらに値を書いてください。
print(check_answer_exercise(ans4,"ans4"))
ans5 = 0 # こちらに値を書いてください。
print(check_answer_exercise(ans5,"ans5"))
ans6 = -1/2 # こちらに値を書いてください。
print(check_answer_exercise(ans6,"ans6"))
ans7 = -1 # こちらに値を書いてください。
print(check_answer_exercise(ans7,"ans7"))
ans8 = -1# こちらに値を書いてください。
print(check_answer_exercise(ans8,"ans8"))
ans9 = -1/2# こちらに値を書いてください。
print(check_answer_exercise(ans9,"ans9"))
ans10 = 0 # こちらに値を書いてください。
print(check_answer_exercise(ans10,"ans10"))
ans11 = 1 # こちらに値を書いてください。
print(check_answer_exercise(ans11,"ans11"))
ans12 = 45 # こちらに値を書いてください(「°」は省略してください。)
print(check_answer_exercise(ans12,"ans12"))
ans13 = 60 # こちらに値を書いてください(「°」は省略してください。)
print(check_answer_exercise(ans13,"ans13"))
ans14 = 45 # こちらに値を書いてください(「°」は省略してください。)
print(check_answer_exercise(ans14,"ans14"))
ans15 = 1 # こちらに値を書いてください
print(check_answer_exercise(ans15,"ans15"))
ans16 = 1 # こちらに値を書いてください
print(check_answer_exercise(ans16,"ans16"))
ans1_deg = math.sin(math.radians(30)) # こちらに度数法の計算式を書いてください。
ans1_rad = math.sin(np.pi*(1/6)) # こちらに弧度法の計算式を書いてください。
print("ans1 =", round(ans1,3)," : ans1_deg = ", round(ans1_deg,3)," : ans1_rad = ", round(ans1_rad,3))
ans2_deg = math.cos(math.radians(90)) # 度数法
ans2_rad = math.cos(np.pi*(1/2)) # 弧度法
print("ans2 =", round(ans2,3)," : ans2_deg = ", round(ans2_deg,3)," : ans2_rad = ", round(ans2_rad,3))
ans3_deg = math.tan(math.radians(45)) # 度数法
ans3_rad = math.tan(np.pi*(1/4)) # 弧度法
print("ans3 =", round(ans3,3)," : ans3_deg = ", round(ans3_deg,3)," : ans3_rad = ", round(ans3_rad,3))
ans4_deg = math.cos(math.radians(60)) # 度数法
ans4_rad = math.cos(np.pi*(1/3)) # 弧度法
print("ans4 =", round(ans4,3)," : ans4_deg = ", round(ans4_deg,3)," : ans4_rad = ", round(ans4_rad,3))
ans5_deg = math.sin(math.radians(0)) # 度数法
ans5_rad = math.sin(np.pi*(0)) # 弧度法
print("ans5 =", round(ans5,3)," : ans5_deg = ", round(ans5_deg,3)," : ans5_rad = ", round(ans5_rad,3))
ans6_deg = math.cos(math.radians(120)) # 度数法
ans6_rad = math.cos(np.pi*(2/3)) # 弧度法
print("ans6 =", round(ans6,3)," : ans6_deg = ", round(ans6_deg,3)," : ans6_rad = ", round(ans6_rad,3))
ans7_deg = math.tan(math.radians(135)) # 度数法
ans7_rad = math.tan(np.pi*(3/4)) # 弧度法
print("ans7 =", round(ans7,3)," : ans7_deg = ", round(ans7_deg,3)," : ans7_rad = ", round(ans7_rad,3))
ans8_deg = math.cos(math.radians(180)) # 度数法
ans8_rad = math.cos(np.pi*(1)) # 弧度法
print("ans8 =", round(ans8,3)," : ans8_deg = ", round(ans8_deg,3)," : ans8_rad = ", round(ans8_rad,3))
ans9_deg = math.sin(math.radians(-30)) # 度数法
ans9_rad = math.sin(np.pi*(-1/6)) # 弧度法
print("ans9 =", round(ans9,3)," : ans9_deg = ", round(ans9_deg,3)," : ans9_rad = ", round(ans9_rad,3))
ans10_deg = math.cos(math.radians(-90)) # 度数法
ans10_rad = math.cos(np.pi*(-1/2)) # 弧度法
print("ans10 =", round(ans10,3)," : ans10_deg = ", round(ans10_deg,3)," : ans10_rad = ", round(ans10_rad,3))
ans11_deg = math.sin(math.radians(450)) # 度数法
ans11_rad = math.sin(np.pi*(5/2)) # 弧度法
print("ans11 =", round(ans11,3)," : ans11_deg = ", round(ans11_deg,3)," : ans11_rad = ", round(ans11_rad,3))
ans12_deg = math.degrees(math.asin(1/math.sqrt(2))) # 度数法
print("ans12 =", round(ans12,3)," : ans12_deg = ", round(ans12_deg,3))
ans13_deg = math.degrees(math.acos(1/2)) # 度数法
print("ans13 =", round(ans13,3)," : ans13_deg = ", round(ans13_deg,3))
ans14_deg = math.degrees(math.atan(1)) # 度数法
print("ans14 =", round(ans14,3)," : ans14_deg = ", round(ans14_deg,3))
ans15_deg = math.sin(math.radians(30))**2 + math.cos(math.radians(30))**2 # 度数法
ans15_rad = (math.sin(np.pi*(1/2)))**2+(math.cos(np.pi*(1/2)))**2 # 弧度法
print("ans15 =", round(ans15,3)," : ans15_deg = ", round(ans15_deg,3)," : ans15_rad = ", round(ans15_rad,3))
ans16_deg = math.sin(math.radians(-45))**2 + math.cos(math.radians(-45))**2 # 度数法
ans16_rad = (math.sin(np.pi*(-1/4)))**2+(math.cos(np.pi*(-1/4)))**2 # 弧度法
print("ans16 =", round(ans16,3)," : ans16_deg = ", round(ans16_deg,3)," : ans16_rad = ", round(ans16_rad,3))
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi)
plt.plot(x, np.sin(x), color='b', label='sin') # color = 'r': red, 'g': green
plt.xlim(-np.pi, np.pi)
plt.ylim(-1.5, 1.5)
plt.axhline(0, ls='-', c='b', lw=0.5)
plt.axvline(0, ls='-', c='b', lw=0.5)
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Graphs')
plt.show()
x = np.linspace(-np.pi, np.pi)
plt.plot(x, np.cos(x), color='r', label='cos')
plt.xlim(-np.pi, np.pi)
plt.ylim(-1.5, 1.5)
plt.axhline(0, ls='-', c='b', lw=0.5)
plt.axvline(0, ls='-', c='b', lw=0.5)
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Graphs')
plt.show()
x = np.linspace(-np.pi, np.pi)
plt.plot(x, np.sin(x), color='b', label='sin')
plt.plot(x, np.cos(x), color='r', label='cos')
plt.xlim(-np.pi, np.pi)
plt.ylim(-1.5, 1.5)
plt.axhline(0, ls='-', c='b', lw=0.5)
plt.axvline(0, ls='-', c='b', lw=0.5)
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Graphs')
plt.show()
x = np.linspace(-2*np.pi, 2*np.pi)
plt.plot(x, np.tan(x), color='r', label='tan')
plt.xlim(-2*np.pi, 2*np.pi)
plt.ylim(-1.5, 1.5)
plt.axhline(0, ls='-', c='b', lw=0.5)
plt.axvline(0, ls='-', c='b', lw=0.5)
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Graphs')
plt.show()
class GraphClass:
# x_start:x軸の最小値
# x_end:x軸の最大値
# x_start、x_endは表示する関数のデフォルトの定義域
# y_start:y軸の最小値
# y_end:y軸の最大値
def __init__(self, x_start, x_end, y_start , y_end):
self.x_start = x_start
self.x_end = x_end
self.y_start = y_start
self.y_end = y_end
self.x = np.linspace(x_start,x_end)
self.plt = plt
# オーバーライドする。自分が表示したいグラフを定義する
def setGraph(self):
pass
# グラフを表示する
def displayGraph(self):
self.setGraph()
self.__setBasicConfig()
self.plt.show()
# sinグラフを表示する
def displaySin(self):
self.plt.plot(self.x, np.sin(self.x), color='b', label='sin')
self.__setBasicConfig()
self.plt.show()
# cosグラフを表示する
def displayCos(self):
self.plt.plot(self.x, np.cos(self.x), color='r', label='cos')
self.__setBasicConfig()
self.plt.show()
# tanグラフを表示する
def displayTan(self):
self.plt.plot(self.x, np.tan(self.x), color='y', label='tan')
self.__setBasicConfig()
self.plt.show()
# 基本的な設定
def __setBasicConfig(self):
self.plt.xlim(self.x_start, self.x_end)
self.plt.ylim(self.y_start, self.y_end)
self.plt.gca().set_aspect('equal', adjustable='box')
self.plt.axhline(0, ls='-', c='b', lw=0.5)
self.plt.axvline(0, ls='-', c='b', lw=0.5)
self.plt.xticks(rotation=45)
self.plt.legend()
self.plt.xlabel('x')
self.plt.ylabel('y')
self.plt.title('Graphs')
# 自分のクラスを定義する 以下はサンプル
class MyGraphClass(GraphClass):
def __init__(self, x_start, x_end, y_start , y_end):
super().__init__(x_start, x_end, y_start , y_end)
# オーバーライドする
def setGraph(self):
#sin
self.plt.plot(self.x, 2*np.sin(self.x), color='b', label='sin')
#cos
self.plt.plot(self.x, np.cos(self.x), color='g', label='cos')
#単位円 デフォルトとは異なる定義域にする。
r=1
x = np.linspace(-r, r)
self.plt.plot(x, np.sqrt(r ** 2 - x ** 2), color='r', label='x^2+y^2')
self.plt.plot(x, -np.sqrt(r ** 2 - x ** 2), color='r', label='x^2+y^2')
# 点を入れる
self.plt.plot(np.cos(math.radians(30)), np.sin(math.radians(30)), marker='X', markersize=20)
#tan
#self.plt.plot(self.x, np.tan(self.x), color='y', label='tan')
#exp
#self.plt.plot(self.x, np.exp(self.x), color='m', label='exp')
myGraphClass = MyGraphClass(-1,1,-1,1)
myGraphClass.displayGraph()
#myGraphClass.displaySin()
#myGraphClass.displayCos()
#myGraphClass.displayTan()
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# 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
b = '110'
n = len(b) #=> 3
simon_circuit = QuantumCircuit(n*2, n) #=> QuantumCircuit(6, 3)
# 最初の3量子ビットにアダマール変換する
simon_circuit.h(range(n))
# Apply barrier for visual separation
simon_circuit.barrier()
# ビット列b に従って動く f (x) のオラクルを回路に追加する
simon_circuit += simon_oracle(b)
# Apply barrier for visual separation
simon_circuit.barrier()
# 最初の3量子ビットにアダマール変換する
simon_circuit.h(range(n))
# 測定する
simon_circuit.measure(range(n), range(n))
simon_circuit.draw()
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(simon_circuit, backend=backend, shots=shots).result()
counts = results.get_counts()
plot_histogram(counts)
# 結果に対して、ドット積を計算する。
def bdotz(b, z):
accum = 0
for i in range(len(b)):
accum += int(b[i]) * int(z[i])
return (accum % 2)
for z in counts:
print( '{}.{} = {} (mod 2)'.format(b, z, bdotz(b,z)) )
b = '11'
n = len(b)
simon_circuit_2 = QuantumCircuit(n*2, n)
# 最初の2量子ビットにアダマール変換する
simon_circuit_2.h(range(n))
# ビット列b に従って動く f (x) のオラクルを回路に追加する
simon_circuit_2 += simon_oracle(b)
# 最初の2量子ビットにアダマール変換する
simon_circuit_2.h(range(n))
# 測定する
simon_circuit_2.measure(range(n), range(n))
simon_circuit_2.draw()
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits
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)
# 結果に対して、ドット積を計算する。
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))
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 1量子ビット回路を用意
q = QuantumCircuit(1,1)
# 回路を描画
q.draw(output="mpl")
# 量子ゲートで回路を作成
q.h(0) # Hゲートを0番目の量子ビットに操作します。
# 回路を描画
q.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q, vector_sim )
result = job.result().get_statevector(q, decimals=3)
print(result)
# ブロッホ球での表示
from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(result)
# 数値計算モジュールを導入
import numpy as np
q = QuantumCircuit(1,1) # 1量子ビット回路を用意
q.rx(np.pi/2,0) # x軸を中心にπ/2回転
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q, vector_sim )
result = job.result().get_statevector(q, decimals=3)
print(result)
# ブロッホ球での表示
plot_bloch_multivector(result)
# 2量子ビット回路を用意
q = QuantumCircuit(2,2)
# 回路を描画
q.draw(output="mpl")
# 量子ゲートで回路を作成
q.h(0) # Hゲートを0番目の量子ビットに操作します。
q.h(1) # Hゲートを1番目の量子ビットに操作します。
# 回路を描画
q.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q, vector_sim )
result = job.result().get_statevector(q, decimals=3)
print(result)
q = QuantumCircuit(2,2) # 2量子ビット回路を用意
q.h(0) # Hゲートを0番目の量子ビットに操作します。
q.h(1) # Hゲートを1番目の量子ビットに操作します。
# 回路を測定
q.measure(0,0)
q.measure(1,1)
# 回路を描画
q.draw(output='mpl')
# QASMシミュレーターで実験
simulator = Aer.get_backend('qasm_simulator')
job = execute(q, backend=simulator, shots=1024)
result = job.result()
# 測定された回数を表示
counts = result.get_counts(q)
print(counts)
## ヒストグラムで測定された確率をプロット
from qiskit.visualization import *
plot_histogram( counts )
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 数値計算モジュールを導入
import numpy as np
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
q = QuantumCircuit(1,1) # 1量子ビット回路を用意
q.ry(np.pi/3,0) # y軸を中心にπ/3回転
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q, vector_sim )
result = job.result().get_statevector(q, decimals=3)
print(result)
# ブロッホ球での表示
from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(result)
q = QuantumCircuit(2,2) # 2量子ビット回路を用意
q.h(0) # Hゲートを0番目の量子ビットに操作します。
q.cx(0,1) # CNOTゲートを0番目を制御ビット、1番目を目標ビットとして操作します。
# 回路を測定
q.measure(0,0)
q.measure(1,1)
q.draw(output="mpl") # 回路を描画
# QASMシミュレーターで実験
simulator = Aer.get_backend('qasm_simulator')
job = execute(q, backend=simulator, shots=1024)
result = job.result()
# 測定された回数を表示
counts = result.get_counts(q)
print(counts)
## ヒストグラムで測定された確率をプロット
from qiskit.visualization import *
plot_histogram( counts )
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# 数値計算モジュールを導入
import numpy as np
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 3量子ビット回路を用意
qr = QuantumRegister(3)
a_0 = ClassicalRegister(1)
a_1 = ClassicalRegister(1)
b_0 = ClassicalRegister(1)
qc = QuantumCircuit(qr,a_0,a_1,b_0)
# 回路を描画
qc.draw(output="mpl")
# Aliceのもつ未知の量子状態ψを今回はRxで作ります
qc.rx(np.pi/3,0)
qc.barrier() #回路を見やすくするために入れます
# 回路を描画
qc.draw(output="mpl")
# EveがEPRペアを作ってq1をAliceにq2をBobに渡します
qc.h(1)
qc.cx(1, 2)
qc.barrier() #回路を見やすくするために入れます
# 回路を描画
qc.draw(output="mpl")
# AliceがCNOTとHでψと自分のEPRペアをエンタングルさせ測定します。
qc.cx(0, 1)
qc.h(0)
qc.barrier()
qc.measure(0, a_0)
qc.measure(1, a_1)
# 回路を描画
qc.draw(output="mpl")
#Aliceが測定結果をBobに送り、Bobが結果に合わせて操作します
qc.z(2).c_if(a_0, 1)
qc.x(2).c_if(a_1, 1)
qc.draw(output="mpl")
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# 数値計算モジュールを導入
import numpy as np
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 3量子ビット回路を用意
qr = QuantumRegister(3)
a_0 = ClassicalRegister(1)
a_1 = ClassicalRegister(1)
b_0 = ClassicalRegister(1)
qc = QuantumCircuit(qr,a_0,a_1,b_0)
# Aliceのもつ未知の量子状態ψをRyで作ります。角度はπ/5にしました。
qc.ry(np.pi/5,0)
qc.barrier() #回路を見やすくするために入れます
# EveがEPRペアを作ってq1をAliceにq2をBobに渡します
qc.h(1)
qc.cx(1, 2)
qc.barrier()
# AliceがCNOTとHでψと自分のEPRペアをエンタングルさせ測定します。
qc.cx(0, 1)
qc.h(0)
qc.barrier()
qc.measure(0, a_0)
qc.measure(1, a_1)
#Aliceが測定結果をBobに送り、Bobが結果に合わせて操作します
qc.z(2).c_if(a_0, 1)
qc.x(2).c_if(a_1, 1)
# 回路を描画
qc.draw(output="mpl")
# 3量子ビット回路を用意
qr = QuantumRegister(3)
a_0 = ClassicalRegister(1)
a_1 = ClassicalRegister(1)
b_0 = ClassicalRegister(1)
qc = QuantumCircuit(qr,a_0,a_1,b_0)
# Aliceのもつ未知の量子状態ψをRyで作ります。角度はπ/5にしました。
qc.ry(np.pi/5,0)
qc.barrier() #回路を見やすくするために入れます
# EveがEPRペアを作ってq1をAliceにq2をBobに渡します
qc.h(1)
qc.cx(1, 2)
qc.barrier()
# AliceがCNOTとHでψと自分のEPRペアをエンタングルさせ測定します。
qc.cx(0, 1)
qc.h(0)
qc.barrier()
qc.measure(0, a_0)
qc.measure(1, a_1)
#Aliceが測定結果をBobに送り、Bobが結果に合わせて操作します
qc.z(2).c_if(a_0, 1)
qc.x(2).c_if(a_1, 1)
# 未知の量子状態ψの逆ゲートをかけて0が測定できるか確かめます
qc.ry(-np.pi/5, 2)
qc.measure(2, b_0)
qc.draw(output="mpl")
# qasm_simulatorで実行して確認します
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(qc, backend).result().get_counts()
print(counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
# 3量子ビット、1古典ビットの回路を用意
qc = QuantumCircuit(3,1)
# Aliceのもつ未知の量子状態ψをRyで作ります。角度はπ/5にしました。
qc.ry(np.pi/5,0)
qc.barrier() #回路を見やすくするために入れます
# EveがEPRペアを作ってq1をAliceにq2をBobに渡します
qc.h(1)
qc.cx(1, 2)
qc.barrier()
# AliceがCNOTとHでψと自分のEPRペアをエンタングルさせます。
qc.cx(0, 1)
qc.h(0)
qc.barrier()
# Aliceの状態に合わせてBobが操作します(ここを変えています!)
qc.cz(0,2)
qc.cx(1,2)
# 未知の量子状態ψの逆ゲートをかけて0が測定できるか確かめます
qc.ry(-np.pi/5, 2)
qc.measure(2, 0)
qc.draw(output="mpl")
# 先にシミュレーターでコードが合っているか確認します
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(qc, backend).result().get_counts()
print(counts)
plot_histogram(counts)
# 初めて実デバイスで実行する人はこちらを実行
from qiskit import IBMQ
IBMQ.save_account('MY_API_TOKEN') # ご自分のトークンを入れてください
# アカウント情報をロードして、使える量子デバイスを確認します
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
# 最もすいているバックエンドを選びます
from qiskit.providers.ibmq import least_busy
large_enough_devices = IBMQ.get_provider().backends(filters=lambda x: x.configuration().n_qubits > 3 and not x.configuration().simulator)
print(large_enough_devices)
real_backend = least_busy(large_enough_devices)
print("ベストなバックエンドは " + real_backend.name())
# 上記のバックエンドで実行します
job = execute(qc,real_backend)
# ジョブの実行状態を確認します
from qiskit.tools.monitor import job_monitor
job_monitor(job)
# 結果を確認します
real_result= job.result()
print(real_result.get_counts(qc))
plot_histogram(real_result.get_counts(qc))
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 2量子ビット回路を用意してください
# 回路を描画して確認します
qc.draw(output="mpl")
# EPRペアを作ってください(AliceとBobに1個ずつ渡すものです)
# 回路を描画して確認します
qc.draw(output="mpl")
# Aliceが送りたいメッセージ(2古典ビット)をセットしてください
msg = "xx" # 送りたいメッセージの入力
# メッセージの値によって、Aliceが適用するゲートを作ってください
if msg == "00":
pass
# elif msg == "10": #10の場合
#ゲート適用
# 以降同じようにmsgに合わせてゲートを適用してください
#
#
#
#
# 回路を描画して確認します
qc.draw(output="mpl")
# BobがAliceからEPRビットをもらった後に、復元するためのゲートを適用してください
# 回路を描画します
qc.draw(output="mpl")
# 測定してください(Bobが行います)
# 回路を描画します
qc.draw(output="mpl")
# qasm_simulator で実行して、AliceからBobに2ビットが転送されたか確認してください
backend = Aer.get_backend('qasm_simulator')
job_sim = execute(qc,backend)
sim_result = job_sim.result()
print(sim_result.get_counts(qc))
from qiskit.visualization import plot_histogram
plot_histogram(sim_result.get_counts(qc))
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 2量子ビット回路を用意してください
qc=QuantumCircuit(2,2)
# 回路を描画します
qc.draw(output="mpl")
# EveがEPRペアを作ってAliceとBobに渡します
qc.h(0)
qc.cx(0,1)
qc.barrier()
# 回路を描画します
qc.draw(output="mpl")
# Aliceが送りたい2古典ビットをセットします
msg = "11" # 送りたいメッセージの入力
if msg == "00":
pass
elif msg == "10": #10の場合
qc.x(0)
elif msg == "01": #01の場合
qc.z(0)
elif msg == "11": #01の場合
qc.z(0)
qc.x(0)
# 回路を描画します
qc.draw(output="mpl")
# BobはAliceからEPRビットをもらい、復元のためのゲートを適用します
qc.cx(0,1)
qc.h(0)
qc.barrier()
# 回路を描画します
qc.draw(output="mpl")
# Bobが測定します
qc.measure(0,0)
qc.measure(1,1)
# 回路を描画します
qc.draw(output="mpl")
# qasm_simulator で実行して、AliceからBobに2ビットが転送されたか確認します。
backend = Aer.get_backend('qasm_simulator')
job_sim = execute(qc,backend)
sim_result = job_sim.result()
print(sim_result.get_counts(qc))
from qiskit.visualization import plot_histogram
plot_histogram(sim_result.get_counts(qc))
# 初めて実デバイスで実行する人はこちらを実行
from qiskit import IBMQ
IBMQ.save_account('MY_API_TOKEN') # ご自分のトークンを入れてください
# アカウント情報をロードして、使える量子デバイスを確認します
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
# 最もすいているバックエンドを選びます
from qiskit.providers.ibmq import least_busy
large_enough_devices = IBMQ.get_provider().backends(filters=lambda x: x.configuration().n_qubits > 3 and not x.configuration().simulator)
print(large_enough_devices)
real_backend = least_busy(large_enough_devices)
print("ベストなバックエンドは " + real_backend.name())
# 上記のバックエンドで実行します
job = execute(qc,real_backend)
# ジョブの実行状態を確認します
from qiskit.tools.monitor import job_monitor
job_monitor(job)
# 結果を確認します
real_result= job.result()
print(real_result.get_counts(qc))
plot_histogram(real_result.get_counts(qc))
|
https://github.com/henrik-dreyer/MPS-in-Qiskit
|
henrik-dreyer
|
import prepare_MPS as mps
import numpy as np
from qiskit import BasicAer, execute
#Create Random MPS with size 4, bond dimension 4 and physical dimension 2 (qubits)
N=4
d=2
chi=4
phi_final=np.random.rand(chi)
phi_initial=np.random.rand(chi)
A=mps.create_random_tensors(N,chi,d)
#Create the circuit. The 'reg' register corresponds to the 'MPS' register in the picture above
qc, reg = mps.MPS_to_circuit(A, phi_initial, phi_final)
#Run the circuit on the statevector simulator
backend = BasicAer.get_backend("statevector_simulator")
job = execute(qc, backend)
result = job.result()
psi_out=result.get_statevector()
#Contract out the ancilla with the known state
psi_out=psi_out.reshape(d**N,chi)
exp=psi_out.dot(phi_final)
#Prepare the MPS classically
thr,_=mps.create_statevector(A,phi_initial,phi_final,qiskit_ordering=True)
#Compare the resulting vectors (fixing phase and normalization)
exp=mps.normalize(mps.extract_phase(exp))
thr=mps.normalize(mps.extract_phase(thr))
print("The MPS is \n {}".format(thr))
print("The statevector produced by the circuit is \n {}".format(exp))
from qiskit import ClassicalRegister
N=5
chi=2
#The following is the standard representation of a GHZ state in terms of MPS
phi_initial=np.array([1,1])
phi_final=np.array([1,1])
T=np.zeros((d,chi,chi))
T[0,0,0]=1
T[1,1,1]=1
A=[]
for _ in range(N):
A.append(T)
#Create the circuit, store the relevant wavefunction is register 'reg' and measure
qc, reg = mps.MPS_to_circuit(A, phi_initial, phi_final)
creg=ClassicalRegister(N)
qc.add_register(creg)
qc.measure(reg,creg)
#Run on a simulator
backend = BasicAer.get_backend("qasm_simulator")
job = execute(qc, backend)
result = job.result()
counts = result.get_counts(qc)
print("\nTotal counts are:",counts)
|
https://github.com/henrik-dreyer/MPS-in-Qiskit
|
henrik-dreyer
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 5 17:51:05 2019
@author: henrikdreyer
Indexing convention for all tensors
2-A-3
|
1
1
|
2-A-3
"""
from ncon import ncon
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info.operators import Operator
def normalize(x):
"""
INPUT:
x(vector):input state
OUPUT
y(vector): x normalized
"""
y=x/np.linalg.norm(x)
return y
def extract_phase(x):
"""
INPUT:
x(vector): input state
OUPUT
y(vector): same state but the first coefficient is real positive
"""
y=x*np.exp(-1j*np.angle(x[0]))
return y
def complement(V):
"""
INPUT:
V(array): rectangular a x b matrix with a > b
OUTPUT
W(array): columns = orthonormal basis for complement of V
"""
W=embed_isometry(V)
W=W[:,V.shape[1]:]
return W
def find_orth(O):
"""
Given a non-complete orthonormal basis of a vector space O, find
another vector that is orthogonal to all others
"""
rand_vec=np.random.rand(O.shape[0],1)
A=np.hstack((O,rand_vec))
b=np.zeros(O.shape[1]+1)
b[-1]=1
x=np.linalg.lstsq(A.T,b,rcond=None)[0]
return x/np.linalg.norm(x)
def embed_isometry(V,defect=0):
"""
V (array): rectangular a x b matrix with a > b with orthogonal columns
defect (int): if V should not be filled up to a square matrix, set defect
s.t. the output matrix is a x (a-defect)
Complete an isometry V with dimension a x b to a unitary
with dimension a x a, i.e.
add a-b normalized columns to V that are orthogonal to the first a columns
"""
a=V.shape[0]
b=V.shape[1]
for i in range(a-b-defect):
x=np.expand_dims(find_orth(V),axis=1)
V=np.hstack((V,x.conj()))
return V
def test_isometry(V):
"""
check if
---V------ ----
| | |
| | = |
| | |
--V.conj-- ----
is true
"""
VdaggerV=ncon([V,V.conj()],([1,2,-1],[1,2,-2]))
return np.allclose(VdaggerV,np.eye(V.shape[2]))
def create_random_tensors(N,chi,d=2):
"""
N (int): number of sites
d (int): physical dimension. Default = qubits
chi (int): bond dimension
Creates a list of N random complex tensors with bond dimension chi and
physical dimension d each
"""
A=[]
for _ in range(N):
A.append(np.random.rand(d,chi,chi)+1j*np.random.rand(d,chi,chi))
return A
def convert_to_isometry(A,phi_initial,phi_final):
"""
Input:
A (list): list of tensors of shape (d, chi, chi)
phi_initial (vector): (chi,1)
phi_final (vector): (chi,1)
Takes as input an MPS of the form
PSI = phi_final - A_N - A_{N-1} - ... - A_1 - phi_initial
| | |
and creates a list of isometries V_1, ... V_N and new vectors
phi_initial_out and phi_final_out,s.t.
PSI = phi_final' - V_N - V_{N-1} - ... - V_1 - phi_final_out
| | |
the Vs are isometries in the sense that
---V------ ----
| | |
| | = |
| | |
--V.conj-- ----
Return:
isometries (list): list of isometric tensors that generates the same state
phi_initial (vector): bew right boundary
phi_final (vector): bew left boundary
Ms (list): list of intermediary Schmidt matrices
"""
N=len(A)
chi=A[0].shape[1]
d=A[0].shape[0]
#Construct isometries from N to 1
A=A[::-1]
"""
SVD:
phi_final - A_N - 2 = U_N - M_N - 2
| |
1 1
then append phi_final to disentangle
2-U_N-3 = 2-phi_final U_N - 3
| |
1 1
"""
left_hand_side=ncon([phi_final,A[0]],([1],[-1,1,-2]))
U,S,VH=np.linalg.svd(left_hand_side,full_matrices=True)
S=np.append(S,np.zeros(max(0,chi-S.shape[0])))
M=np.dot(np.diag(S),VH)
Ms=[M]
U=ncon([U,phi_final],([-1,-3],[-2]))
U=U.reshape(chi*d,d)
U=embed_isometry(U,defect=chi*(d-1))
#First unitary can have dimension d<chi, so add orthogonal vectors
isometries=[U]
"""
from N to 1, SVD successively:
2 - M_k - V_{k-1} - 3 = 2- U_{k-1} - M_{k-1} - 3
| |
1 1
"""
for k in range(1,N):
left_hand_side=ncon([M,A[k]],([-2,1],[-1,1,-3]))
left_hand_side=left_hand_side.reshape(chi*d,chi)
U,S,VH=np.linalg.svd(left_hand_side,full_matrices=False)
M=np.dot(np.diag(S),VH)
Ms.append(M)
isometries.append(U)
phi_initial_out=np.dot(M,phi_initial)
phi_final_out=phi_final
isometries=isometries[::-1]
Ms=Ms[::-1]
return isometries, phi_initial_out, phi_final_out, Ms
def create_statevector(A,phi_initial,phi_final,qiskit_ordering=False):
"""
INPUT:
A (list): list of N MPS tensors of size (d,chi,chi)
phi_initial (vector): right boundary condition of size (chi,1)
phi_final (vector): left boundary condition of size (chi,1)
RETURNS:
Psi(vector): the vector
phi_final - A_N - A_{N-1} - ... - A_1 - phi_initial
| | |
N N-1 1 [N.B.: Reversed Qiskit Ordering]
B L O C K E D
schmidt_matrix (array, optional): the matrix
2 - A_N - A_{N-1} - ... - A_1 - phi_initial
| | |
1
This is useful to check, for the unitary MPS, if after the
application of A_N, the state is a product state between ancilla
and physical space (the schmidt_matrix has rank 1 in this case).
This must be the case, in order to implement successfully on the
quantum computer.
"""
N=len(A)
chi=A[0].shape[1]
d=A[0].shape[0]
Psi=ncon([phi_initial, A[0]], ([1],[-1,-2,1]))
for i in range(1,N):
Psi=ncon([Psi,A[i]],([-1,1],[-2,-3,1]))
Psi=Psi.reshape((d**(i+1),chi))
if qiskit_ordering:
Psi=Psi.reshape(np.append(d*np.ones(N,dtype=int),chi))
Psi=ncon([Psi],-np.append(list(range(N,0,-1)),N+1))
Psi=Psi.reshape(d**N,chi)
schmidt_matrix=Psi
Psi=np.dot(Psi,phi_final)
return Psi, schmidt_matrix
def isunitary(U):
"""
INPUT:
U (array)
OUPUT:
flag (bool)
"""
if np.allclose(np.eye(len(U)), U.dot(U.T.conj())):
return True
else:
return False
def isometry_to_unitary(V):
"""
INPUT:
V(tensor): tensor with indices
2-V-3
|
1
that is isometric in the sense that
---V------ ----
| | |
| | = |
| | |
--V.conj-- ----
OUTPUT:
U(matrix): unitary matrix that fulfills
|0>
|
-U- = -V-
| |
with leg ordering
3
|
2-U-4
|
1
"""
chi=V.shape[1]
d=V.shape[0]
Vp=V.reshape(chi*d,chi)
W=complement(Vp)
U=np.zeros((chi*d,d,chi),dtype=np.complex128)
U[:,0,:]=Vp
U[:,1,:]=W
U=U.reshape(chi*d,chi*d)
return U
def MPS_to_circuit(A, phi_initial, phi_final):
"""
INPUT:
A (list): list of N MPS tensors of size (d,chi,chi)
phi_initial (vector): right boundary condition of size (chi,1)
phi_final (vector): left boundary condition of size (chi,1)
keep_ancilla (bool, optional): the MPS is generated via an ancilla
that disentangles at the end of the
procedure. By default, the ancilla is
measured out and thrown away at the end.
Set to True to keep the ancilla
(in the first ceil(log(chi)) qubits)
OUTPUT:
qc(QuantumCircuit): the circuit that produces the MPS
q0...qn phi_final - A_{N-1} - A_{N-2} - ... - A_0 - phi_initial
| | |
q_{n+N} q_{n+N-1} q_{n+1}
where n = ceil(log2(chi)) is the number of ancilla qubits
reg(QuantumRegister): the register in which the MPS wavefunction sits
(to distinguish from the ancilla)
N.B. By construction, after applying qc the system will be in a product
state between the first ceil(log2(chi)) qubits and the rest.
Those first qubits form the ancilla register and the remaining qubits
are in the QuantumRegister 'reg'.
The ancilla is guaranteed to be in phi_final.
"""
N=len(A)
chi=A[0].shape[1]
d=A[0].shape[0]
#Normalize boundary conditions
phi_final=phi_final/np.linalg.norm(phi_final)
phi_initial=phi_initial/np.linalg.norm(phi_initial)
#Convert MPS to isometric form
Vs,phi_initial_U,phi_final_U,Ms=convert_to_isometry(A,phi_initial,phi_final)
#Construct circuit
n_ancilla_qubits=int(np.log2(chi))
ancilla = QuantumRegister(n_ancilla_qubits)
reg = QuantumRegister(N)
qc=QuantumCircuit(ancilla,reg)
phi_initial_U=phi_initial_U/np.linalg.norm(phi_initial_U)
qc.initialize(phi_initial_U,range(n_ancilla_qubits))
for i in range(N):
qubits=list(range(n_ancilla_qubits))
qubits.append(i+n_ancilla_qubits)
qc.unitary(Operator(isometry_to_unitary(Vs[i].reshape(d,chi,chi))), qubits)
return qc, reg
|
https://github.com/quantastica/qiskit-forest
|
quantastica
|
import unittest
import warnings
from quantastica.qiskit_forest import ForestBackend
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute, Aer
from qiskit.compiler import transpile, assemble
from numpy import pi
class TestForestBackend(unittest.TestCase):
def setUp(self):
"""
Ignore following warning since it seems
that there is nothing that we can do about it
ResourceWarning: unclosed <socket.socket fd=9, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=6, laddr=('127.0.0.1', 50494), raddr=('127.0.0.1', 5000)>
"""
warnings.filterwarnings(action="ignore",
category=ResourceWarning)
def tearDown(self):
"""
Restore warnings back
"""
warnings.filterwarnings(action="always",
category=ResourceWarning)
def test_bell_counts_with_seed(self):
shots = 1024
qc=TestForestBackend.get_bell_qc()
stats1 = TestForestBackend.execute_and_get_stats(
ForestBackend.ForestBackend(),
qc,
shots,
seed = 1
)
stats2 = TestForestBackend.execute_and_get_stats(
ForestBackend.ForestBackend(),
qc,
shots,
seed = 1
)
stats3 = TestForestBackend.execute_and_get_stats(
ForestBackend.ForestBackend(),
qc,
shots,
seed = 2
)
self.assertTrue( stats1['statevector'] is None)
self.assertEqual( len(stats1['counts']), 2)
self.assertEqual( stats1['totalcounts'], shots)
self.assertEqual(stats1['counts'],stats2['counts'])
self.assertNotEqual(stats1['counts'],stats3['counts'])
def test_bell_counts(self):
shots = 256
qc=TestForestBackend.get_bell_qc()
stats = TestForestBackend.execute_and_get_stats(
ForestBackend.ForestBackend(),
qc,
shots
)
self.assertTrue( stats['statevector'] is None)
self.assertEqual( len(stats['counts']), 2)
self.assertEqual( stats['totalcounts'], shots)
def test_bell_state_vector(self):
"""
This is test for statevector which means that
even with shots > 1 it should execute only one shot
"""
shots = 256
qc = TestForestBackend.get_bell_qc()
stats = TestForestBackend.execute_and_get_stats(
ForestBackend.ForestBackend(lattice_name="statevector_simulator"),
qc,
shots
)
self.assertEqual( len(stats['statevector']), 4)
self.assertEqual( len(stats['counts']), 1)
self.assertEqual( stats['totalcounts'], 1)
def test_teleport_state_vector(self):
"""
This is test for statevector which means that
even with shots > 1 it should execute only one shot
"""
shots = 256
qc = TestForestBackend.get_teleport_qc()
"""
Let's first run the aer simulation to get statevector
and counts so we can compare those results against forest's
"""
stats_aer = TestForestBackend.execute_and_get_stats(
Aer.get_backend('statevector_simulator'),
qc,
shots
)
"""
Now execute forest backend
"""
stats = TestForestBackend.execute_and_get_stats(
ForestBackend.ForestBackend(lattice_name="statevector_simulator"),
qc,
shots
)
self.assertEqual(len(stats['counts']), len(stats_aer['counts']))
self.assertEqual(len(stats['statevector']), len(stats_aer['statevector']))
self.assertEqual(stats['totalcounts'], stats_aer['totalcounts'])
"""
Let's verify that tests are working as expected
by running fail case
"""
stats = TestForestBackend.execute_and_get_stats(
ForestBackend.ForestBackend(),
qc,
shots
)
self.assertNotEqual(len(stats['counts']), len(stats_aer['counts']))
self.assertTrue(stats['statevector'] is None)
self.assertNotEqual(stats['totalcounts'], stats_aer['totalcounts'])
def test_multiple_jobs(self):
qc = self.get_bell_qc()
backend = ForestBackend.ForestBackend()
jobs = []
for i in range(1, 50):
jobs.append(execute(qc, backend=backend, shots=1))
for job in jobs:
result = job.result()
counts = result.get_counts(qc)
self.assertEqual(len(counts), 1)
def test_multiple_experiments(self):
backend = ForestBackend.ForestBackend()
qc_list = [ self.get_bell_qc(), self.get_teleport_qc() ]
transpiled = transpile(qc_list, backend = backend)
qobjs = assemble(transpiled, backend=backend, shots=4096)
job_info = backend.run(qobjs)
bell_counts = job_info.result().get_counts("Bell")
tel_counts = job_info.result().get_counts("Teleport")
self.assertEqual(len(bell_counts),2)
self.assertEqual(len(tel_counts),4)
@staticmethod
def execute_and_get_stats(backend, qc, shots, seed = None):
job = execute(qc, backend=backend, shots=shots, seed_simulator = seed)
job_result = job.result()
counts = job_result.get_counts(qc)
total_counts = 0
for c in counts:
total_counts += counts[c]
try:
state_vector = job_result.get_statevector(qc)
except:
state_vector = None
ret = dict()
ret['counts'] = counts
ret['statevector'] = state_vector
ret['totalcounts'] = total_counts
return ret
@staticmethod
def get_bell_qc():
qc = QuantumCircuit(name="Bell")
q = QuantumRegister(2, 'q')
c = ClassicalRegister(2, 'c')
qc.add_register(q)
qc.add_register(c)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.measure(q[0], c[0])
qc.measure(q[1], c[1])
return qc
@staticmethod
def get_teleport_qc():
qc = QuantumCircuit(name="Teleport")
q = QuantumRegister(3, 'q')
c0 = ClassicalRegister(1, 'c0')
c1 = ClassicalRegister(1, 'c1')
qc.add_register(q)
qc.add_register(c0)
qc.add_register(c1)
qc.rx(pi / 4, q[0])
qc.h(q[1])
qc.cx(q[1], q[2])
qc.cx(q[0], q[1])
qc.h(q[0])
qc.measure(q[1], c1[0])
qc.x(q[2]).c_if(c1, 1)
qc.measure(q[0], c0[0])
qc.z(q[2]).c_if(c0, 1)
return qc
if __name__ == '__main__':
unittest.main()
|
https://github.com/quantastica/qiskit-forest
|
quantastica
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the QAOA algorithm."""
import unittest
from functools import partial
from test.python.algorithms import QiskitAlgorithmsTestCase
import numpy as np
import rustworkx as rx
from ddt import ddt, idata, unpack
from scipy.optimize import minimize as scipy_minimize
from qiskit import QuantumCircuit
from qiskit_algorithms.minimum_eigensolvers import QAOA
from qiskit_algorithms.optimizers import COBYLA, NELDER_MEAD
from qiskit.circuit import Parameter
from qiskit.primitives import Sampler
from qiskit.quantum_info import Pauli, SparsePauliOp
from qiskit.result import QuasiDistribution
from qiskit.utils import algorithm_globals
W1 = np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]])
P1 = 1
M1 = SparsePauliOp.from_list(
[
("IIIX", 1),
("IIXI", 1),
("IXII", 1),
("XIII", 1),
]
)
S1 = {"0101", "1010"}
W2 = np.array(
[
[0.0, 8.0, -9.0, 0.0],
[8.0, 0.0, 7.0, 9.0],
[-9.0, 7.0, 0.0, -8.0],
[0.0, 9.0, -8.0, 0.0],
]
)
P2 = 1
M2 = None
S2 = {"1011", "0100"}
CUSTOM_SUPERPOSITION = [1 / np.sqrt(15)] * 15 + [0]
@ddt
class TestQAOA(QiskitAlgorithmsTestCase):
"""Test QAOA with MaxCut."""
def setUp(self):
super().setUp()
self.seed = 10598
algorithm_globals.random_seed = self.seed
self.sampler = Sampler()
@idata(
[
[W1, P1, M1, S1],
[W2, P2, M2, S2],
]
)
@unpack
def test_qaoa(self, w, reps, mixer, solutions):
"""QAOA test"""
self.log.debug("Testing %s-step QAOA with MaxCut on graph\n%s", reps, w)
qubit_op, _ = self._get_operator(w)
qaoa = QAOA(self.sampler, COBYLA(), reps=reps, mixer=mixer)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
self.assertIn(graph_solution, solutions)
@idata(
[
[W1, P1, S1],
[W2, P2, S2],
]
)
@unpack
def test_qaoa_qc_mixer(self, w, prob, solutions):
"""QAOA test with a mixer as a parameterized circuit"""
self.log.debug(
"Testing %s-step QAOA with MaxCut on graph with a mixer as a parameterized circuit\n%s",
prob,
w,
)
optimizer = COBYLA()
qubit_op, _ = self._get_operator(w)
num_qubits = qubit_op.num_qubits
mixer = QuantumCircuit(num_qubits)
theta = Parameter("θ")
mixer.rx(theta, range(num_qubits))
qaoa = QAOA(self.sampler, optimizer, reps=prob, mixer=mixer)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
self.assertIn(graph_solution, solutions)
def test_qaoa_qc_mixer_many_parameters(self):
"""QAOA test with a mixer as a parameterized circuit with the num of parameters > 1."""
optimizer = COBYLA()
qubit_op, _ = self._get_operator(W1)
num_qubits = qubit_op.num_qubits
mixer = QuantumCircuit(num_qubits)
for i in range(num_qubits):
theta = Parameter("θ" + str(i))
mixer.rx(theta, range(num_qubits))
qaoa = QAOA(self.sampler, optimizer, reps=2, mixer=mixer)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
self.log.debug(x)
graph_solution = self._get_graph_solution(x)
self.assertIn(graph_solution, S1)
def test_qaoa_qc_mixer_no_parameters(self):
"""QAOA test with a mixer as a parameterized circuit with zero parameters."""
qubit_op, _ = self._get_operator(W1)
num_qubits = qubit_op.num_qubits
mixer = QuantumCircuit(num_qubits)
# just arbitrary circuit
mixer.rx(np.pi / 2, range(num_qubits))
qaoa = QAOA(self.sampler, COBYLA(), reps=1, mixer=mixer)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
# we just assert that we get a result, it is not meaningful.
self.assertIsNotNone(result.eigenstate)
def test_change_operator_size(self):
"""QAOA change operator size test"""
qubit_op, _ = self._get_operator(
np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]])
)
qaoa = QAOA(self.sampler, COBYLA(), reps=1)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
with self.subTest(msg="QAOA 4x4"):
self.assertIn(graph_solution, {"0101", "1010"})
qubit_op, _ = self._get_operator(
np.array(
[
[0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0],
]
)
)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
with self.subTest(msg="QAOA 6x6"):
self.assertIn(graph_solution, {"010101", "101010"})
@idata([[W2, S2, None], [W2, S2, [0.0, 0.0]], [W2, S2, [1.0, 0.8]]])
@unpack
def test_qaoa_initial_point(self, w, solutions, init_pt):
"""Check first parameter value used is initial point as expected"""
qubit_op, _ = self._get_operator(w)
first_pt = []
def cb_callback(eval_count, parameters, mean, metadata):
nonlocal first_pt
if eval_count == 1:
first_pt = list(parameters)
qaoa = QAOA(
self.sampler,
COBYLA(),
initial_point=init_pt,
callback=cb_callback,
)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
with self.subTest("Initial Point"):
# If None the preferred random initial point of QAOA variational form
if init_pt is None:
self.assertLess(result.eigenvalue, -0.97)
else:
self.assertListEqual(init_pt, first_pt)
with self.subTest("Solution"):
self.assertIn(graph_solution, solutions)
def test_qaoa_random_initial_point(self):
"""QAOA random initial point"""
w = rx.adjacency_matrix(
rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed)
)
qubit_op, _ = self._get_operator(w)
qaoa = QAOA(self.sampler, NELDER_MEAD(disp=True), reps=2)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
self.assertLess(result.eigenvalue, -0.97)
def test_optimizer_scipy_callable(self):
"""Test passing a SciPy optimizer directly as callable."""
w = rx.adjacency_matrix(
rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed)
)
qubit_op, _ = self._get_operator(w)
qaoa = QAOA(
self.sampler,
partial(scipy_minimize, method="Nelder-Mead", options={"maxiter": 2}),
)
result = qaoa.compute_minimum_eigenvalue(qubit_op)
self.assertEqual(result.cost_function_evals, 5)
def _get_operator(self, weight_matrix):
"""Generate Hamiltonian for the max-cut problem of a graph.
Args:
weight_matrix (numpy.ndarray) : adjacency matrix.
Returns:
PauliSumOp: operator for the Hamiltonian
float: a constant shift for the obj function.
"""
num_nodes = weight_matrix.shape[0]
pauli_list = []
shift = 0
for i in range(num_nodes):
for j in range(i):
if weight_matrix[i, j] != 0:
x_p = np.zeros(num_nodes, dtype=bool)
z_p = np.zeros(num_nodes, dtype=bool)
z_p[i] = True
z_p[j] = True
pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))])
shift -= 0.5 * weight_matrix[i, j]
lst = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list]
return SparsePauliOp.from_list(lst), shift
def _get_graph_solution(self, x: np.ndarray) -> str:
"""Get graph solution from binary string.
Args:
x : binary string as numpy array.
Returns:
a graph solution as string.
"""
return "".join([str(int(i)) for i in 1 - x])
def _sample_most_likely(self, state_vector: QuasiDistribution) -> np.ndarray:
"""Compute the most likely binary string from state vector.
Args:
state_vector: Quasi-distribution.
Returns:
Binary string as numpy.ndarray of ints.
"""
values = list(state_vector.values())
n = int(np.log2(len(values)))
k = np.argmax(np.abs(values))
x = np.zeros(n)
for i in range(n):
x[i] = k % 2
k >>= 1
return x
if __name__ == "__main__":
unittest.main()
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumRegister, ClassicalRegister, BasicAer
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
from qiskit.aqua.components.uncertainty_models import NormalDistribution,UniformDistribution,LogNormalDistribution
IBMQ.enable_account('Enter API key') #Key can be obtained from IBM Quantum
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
q = QuantumRegister(5,'q')
c = ClassicalRegister(5,'c')
print("\n Normal Distribution")
print("-----------------")
circuit = QuantumCircuit(q,c)
normal = NormalDistribution(num_target_qubits = 5, mu=0, sigma=1, low=- 1, high=1)
normal.build(circuit,q)
circuit.measure(q,c)
circuit.draw(output='mpl',filename='normal.png')
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
sortedcounts = []
sortedkeys = sorted(counts)
for i in sortedkeys:
for j in counts:
if(i == j):
sortedcounts.append(counts.get(j))
plt.suptitle('Normal Distribution')
plt.plot(sortedcounts)
plt.show()
print("\n Uniform Distribution")
print("-----------------")
circuit = QuantumCircuit(q,c)
uniform = UniformDistribution(num_target_qubits = 5,low=- 0, high=1)
uniform.build(circuit,q)
circuit.measure(q,c)
circuit.draw(output='mpl',filename='uniform.png')
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
sortedcounts = []
sortedkeys = sorted(counts)
for i in sortedkeys:
for j in counts:
if(i == j):
sortedcounts.append(counts.get(j))
plt.suptitle('Uniform Distribution')
plt.plot(sortedcounts)
plt.show()
print("\n Log-Normal Distribution")
print("-----------------")
circuit = QuantumCircuit(q,c)
lognorm = LogNormalDistribution(num_target_qubits = 5, mu=0, sigma=1, low= 0, high=1)
lognorm.build(circuit,q)
circuit.measure(q,c)
circuit.draw(output='mpl',filename='log.png')
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
sortedcounts = []
sortedkeys = sorted(counts)
for i in sortedkeys:
for j in counts:
if(i == j):
sortedcounts.append(counts.get(j))
plt.suptitle('Log-Normal Distribution')
plt.plot(sortedcounts)
plt.show()
input()
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
print('\nGrovers Algorithm')
print('------------------\n')
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute,IBMQ
import math
IBMQ.enable_account('Enter API token')
provider = IBMQ.get_provider(hub='ibm-q')
pi = math.pi
q = QuantumRegister(4,'q')
c = ClassicalRegister(4,'c')
qc = QuantumCircuit(q,c)
print('\nInitialising Circuit...\n')
### Initialisation ###
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.h(q[3])
print('\nPreparing Oracle circuit....\n')
### 0000 Oracle ###
qc.x(q[0])
qc.x(q[1])
qc.x(q[2])
qc.x(q[3])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[0])
qc.x(q[1])
qc.x(q[2])
qc.x(q[3])
'''
### 0001 Oracle ###
qc.x(q[1])
qc.x(q[2])
qc.x(q[3])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[1])
qc.x(q[2])
qc.x(q[3])
'''
'''
### 0010 Oracle ###
qc.x(q[0])
qc.x(q[2])
qc.x(q[3])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[0])
qc.x(q[2])
qc.x(q[3])
'''
'''
### 0011 Oracle ###
qc.x(q[2])
qc.x(q[3])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[2])
qc.x(q[3])
'''
'''
### 0100 Oracle ###
qc.x(q[0])
qc.x(q[1])
qc.x(q[3])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[0])
qc.x(q[1])
qc.x(q[3])
'''
'''
### 0101 Oracle ###
qc.x(q[1])
qc.x(q[3])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[1])
qc.x(q[3])
'''
'''
### 0110 Oracle ###
qc.x(q[0])
qc.x(q[3])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[0])
qc.x(q[3])
'''
'''
### 0111 Oracle ###
qc.x(q[3])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[3])
'''
'''
### 1000 Oracle ###
qc.x(q[0])
qc.x(q[1])
qc.x(q[2])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[0])
qc.x(q[1])
qc.x(q[2])
'''
'''
### 1001 Oracle ###
qc.x(q[1])
qc.x(q[2])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[1])
qc.x(q[2])
'''
'''
### 1010 Oracle ###
qc.x(q[0])
qc.x(q[2])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[0])
qc.x(q[2])
'''
'''
### 1011 Oracle ###
qc.x(q[3])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[3])
'''
'''
### 1100 Oracle ###
qc.x(q[0])
qc.x(q[1])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[0])
qc.x(q[1])
'''
'''
### 1101 Oracle ###
qc.x(q[1])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[1])
'''
'''
### 1110 Oracle ###
qc.x(q[0])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[0])
'''
'''
###1111 Oracle###
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
'''
print('\nPreparing Amplification circuit....\n')
#### Amplification ####
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.h(q[3])
qc.x(q[0])
qc.x(q[1])
qc.x(q[2])
qc.x(q[3])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[0])
qc.x(q[1])
qc.x(q[2])
qc.x(q[3])
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.h(q[3])
### Measurment ###
qc.barrier(q)
qc.measure(q[0], c[0])
qc.measure(q[1], c[1])
qc.measure(q[2], c[2])
qc.measure(q[3], c[3])
backend = provider.get_backend('ibmq_qasm_simulator')
print('\nExecuting job....\n')
job = execute(qc, backend, shots=100)
result = job.result()
counts = result.get_counts(qc)
print('RESULT: ',counts,'\n')
print('Press any key to close')
input()
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import IBMQ
from qiskit.aqua.algorithms import Grover
from qiskit.aqua.components.oracles import LogicalExpressionOracle
from qiskit.visualization import plot_histogram
IBMQ.enable_account('ENTER API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
expression = '(a & b)& ~(c)'
oracle = LogicalExpressionOracle(expression)
grover = Grover(oracle)
result = grover.run(backend, shots=1024)
counts = result['measurement']
print(counts)
print('Press any key to close')
input()
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumCircuit, Aer, execute
from math import pi, sin
from qiskit.compiler import transpile, assemble
from grover_operator import GroverOperator
def qft(n): # returns circuit for inverse quantum fourier transformation for given n
circuit = QuantumCircuit(n)
def swap_registers(circuit, n):
for qubit in range(n // 2):
circuit.swap(qubit, n - qubit - 1)
return circuit
def qft_rotations(circuit, n):
if n == 0:
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cp(pi / 2 ** (n - qubit), qubit, n)
qft_rotations(circuit, n)
qft_rotations(circuit, n)
swap_registers(circuit, n)
return circuit
class PhaseEstimation:
def get_control_gft(self, label="QFT †"):
qft_dagger = self.qft_circuit.to_gate().inverse()
qft_dagger.label = label
return qft_dagger
def get_main_circuit(self):
qc = QuantumCircuit(self.c_bits + self.s_bits, self.c_bits) # Circuit with n+t qubits and t classical bits
# Initialize all qubits to |+>
qc.h(range(self.c_bits + self.n_bits))
qc.h(self.c_bits + self.s_bits - 1)
qc.z(self.c_bits + self.s_bits - 1)
# Begin controlled Grover iterations
iterations = 1
for qubit in range(self.c_bits):
for i in range(iterations):
qc.append(self.c_grover, [qubit] + [*range(self.c_bits, self.s_bits + self.c_bits)])
iterations *= 2
# Do inverse QFT on counting qubits
qc.append(self.c_qft, range(self.c_bits))
# Measure counting qubits
qc.measure(range(self.c_bits), range(self.c_bits))
return qc
def simulate(self):
aer_sim = Aer.get_backend('aer_simulator')
transpiled_qc = transpile(self.main_circuit, aer_sim)
qobj = assemble(transpiled_qc)
job = aer_sim.run(qobj)
hist = job.result().get_counts()
# plot_histogram(hist)
measured_int = int(max(hist, key=hist.get), 2)
theta = (measured_int / (2 ** self.c_bits)) * pi * 2
N = 2 ** self.n_bits
M = N * (sin(theta / 2) ** 2)
# print(N - M, round(N - M))
return round(N - M)
def __init__(self, grover: GroverOperator, c_bits=5):
self.c_grover = grover.get_control_circuit()
self.c_bits = c_bits
self.n_bits = grover.n_bits
self.s_bits = grover.total_bits
self.qft_circuit = qft(c_bits)
self.c_qft = self.get_control_gft()
self.main_circuit = self.get_main_circuit()
self.M = self.simulate()
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import QFT
import numpy as np
pi = np.pi
IBMQ.enable_account(‘ENTER API KEY HERE’)
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
q = QuantumRegister(5,'q')
c = ClassicalRegister(5,'c')
circuit = QuantumCircuit(q,c)
circuit.x(q[4])
circuit.x(q[2])
circuit.x(q[0])
circuit += QFT(num_qubits=5, approximation_degree=0, do_swaps=True, inverse=False, insert_barriers=False, name='qft')
circuit.measure(q,c)
circuit.draw(output='mpl', filename='qft1.png')
print(circuit)
job = execute(circuit, backend, shots=1000)
job_monitor(job)
counts = job.result().get_counts()
print("\n QFT Output")
print("-------------")
print(counts)
input()
q = QuantumRegister(5,'q')
c = ClassicalRegister(5,'c')
circuit = QuantumCircuit(q,c)
circuit.x(q[4])
circuit.x(q[2])
circuit.x(q[0])
circuit += QFT(num_qubits=5, approximation_degree=0, do_swaps=True, inverse=False, insert_barriers=True, name='qft')
circuit += QFT(num_qubits=5, approximation_degree=0, do_swaps=True, inverse=True, insert_barriers=True, name='qft')
circuit.measure(q,c)
circuit.draw(output='mpl',filename='qft2.png')
print(circuit)
job = execute(circuit, backend, shots=1000)
job_monitor(job)
counts = job.result().get_counts()
print("\n QFT with inverse QFT Output")
print("------------------------------")
print(counts)
input()
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
import numpy
import matplotlib.pyplot as plt
pi = numpy.pi
IBMQ.enable_account('ENTER API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_armonk')
q = QuantumRegister(1,'q')
c = ClassicalRegister(1,'c')
phi = 0
a = []
b = []
xticks = []
qc_list = []
while phi <= 2*pi:
xticks.append(phi)
circuit = QuantumCircuit(q,c)
circuit.rx(phi,q[0]) #RX gate where Phi is the rotation angle
circuit.measure(q,c) # Qubit Measurement
qc_list.append(circuit)
phi += pi/8
job = execute(qc_list, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
highest_count1 = 0
highest_count1_1 = 0
highest_count1_0 = 0
index1 = 0
highest_count0 = 0
highest_count0_1 = 0
highest_count0_0 = 0
index0 = 0
for count in counts:
a.append(count['0'])
b.append(count['1'])
if count['1'] > highest_count1:
highest_count1 = count['1']
index1 = counts.index(count)
highest_count1_1 = count['1']
highest_count1_0 = count['0']
if count['0'] > highest_count0:
highest_count0 = count['0']
index0 = counts.index(count)
highest_count0_1 = count['1']
highest_count0_0 = count['0']
print("\nOptimal rotation angle for '1' is: ", xticks[index1], ", Counts: 0:", highest_count1_0, "1:", highest_count1_1)
print("Optimal rotation angle for '0' is: ", xticks[index0], ", Counts: 0:", highest_count0_0, "1:", highest_count0_1)
plt.suptitle('Rabi Oscillations on IBMQ Armonk')
plt.plot(xticks,a)
plt.plot(xticks,b)
plt.legend(["Measurements for '0' ", "Measurements for '1'"])
plt.show()
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import IBMQ
from qiskit.utils import QuantumInstance
from qiskit.algorithms import Shor
IBMQ.enable_account('ENTER API KEY HERE') # Enter your API token here
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator') # Specifies the quantum device
print('\n Shors Algorithm')
print('--------------------')
print('\nExecuting...\n')
factors = Shor(QuantumInstance(backend, shots=100, skip_qobj_validation=False))
result_dict = factors.factor(N=21, a=2)
result = result_dict.factors
print(result)
print('\nPress any key to close')
input()
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
print('\n Superdense Coding')
print('--------------------------\n')
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
IBMQ.enable_account('ENTER API TOKEN')
provider = IBMQ.get_provider(hub='ibm-q')
q = QuantumRegister(2,'q')
c = ClassicalRegister(2,'c')
backend = provider.get_backend('ibmq_qasm_simulator')
print('Provider: ',backend)
#################### 00 ###########################
circuit = QuantumCircuit(q,c)
circuit.h(q[0]) # Hadamard gate applied to q0
circuit.cx(q[0],q[1]) # CNOT gate applied
circuit.cx(q[0],q[1])
circuit.h(q[0])
circuit.measure(q,c) # Qubits measured
job = execute(circuit, backend, shots=10)
print('Executing Job...\n')
job_monitor(job)
counts = job.result().get_counts()
print('RESULT: ',counts,'\n')
#################### 10 ###########################
circuit = QuantumCircuit(q,c)
circuit.h(q[0])
circuit.cx(q[0],q[1])
circuit.x(q[0]) # X-gate applied
circuit.cx(q[0],q[1])
circuit.h(q[0])
circuit.measure(q,c)
job = execute(circuit, backend, shots=10)
print('Executing Job...\n')
job_monitor(job)
counts = job.result().get_counts()
print('RESULT: ',counts,'\n')
#################### 01 ###########################
circuit = QuantumCircuit(q,c)
circuit.h(q[0])
circuit.cx(q[0],q[1])
circuit.z(q[0]) # Z-gate applied to q0
circuit.cx(q[0],q[1])
circuit.h(q[0])
circuit.measure(q,c)
job = execute(circuit, backend, shots=10)
print('Executing Job...\n')
job_monitor(job)
counts = job.result().get_counts()
print('RESULT: ',counts,'\n')
#################### 11 ###########################
circuit = QuantumCircuit(q,c)
circuit.h(q[0])
circuit.cx(q[0],q[1])
circuit.z(q[0]) # Z-gate applied
circuit.x(q[0]) # X-gate applied
circuit.cx(q[0],q[1])
circuit.h(q[0])
circuit.measure(q,c)
job = execute(circuit, backend, shots=10)
print('Executing Job...\n')
job_monitor(job)
counts = job.result().get_counts()
print('RESULT: ',counts,'\n')
print('Press any key to close')
input()
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import IBMQ
from qiskit.aqua.algorithms import Grover
from qiskit.aqua.components.oracles import TruthTableOracle
IBMQ.enable_account('ENTER API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
expression = '11000001'
oracle = TruthTableOracle(expression)
print(oracle)
grover = Grover(oracle)
result = grover.run(backend, shots=1024)
counts = result['measurement']
print('\nTruth tables with Grovers Search')
print('--------------------------------\n')
print('Bit string is ', expression)
print('\nResults ',counts)
print('\nPress any key to close')
input()
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
import math
from qiskit import *
from utils import bcolors, executeQFT, evolveQFTStateSum, inverseQFT
pie = math.pi
def sum(a, b, qc):
n = len(a)-1
# Compute the Fourier transform of register a
for i in range(n+1):
executeQFT(qc, a, n-i, pie)
# Add the two numbers by evolving the Fourier transform F(ψ(reg_a))>
# to |F(ψ(reg_a+reg_b))>
for i in range(n+1):
evolveQFTStateSum(qc, a, b, n-i, pie)
# Compute the inverse Fourier transform of register a
for i in range(n+1):
inverseQFT(qc, a, i, pie)
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
IBMQ.enable_account('ENTER API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
q = QuantumRegister(2,'q')
c = ClassicalRegister(2,'c')
def firstBellState():
circuit = QuantumCircuit(q,c)
circuit.h(q[0]) # Hadamard gate
circuit.cx(q[0],q[1]) # CNOT gate
circuit.measure(q,c) # Qubit Measurment
print(circuit)
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
def secondBellState():
circuit = QuantumCircuit(q,c)
circuit.x(q[0]) # Pauli-X gate
circuit.h(q[0]) # Hadamard gate
circuit.cx(q[0],q[1]) # CNOT gate
circuit.measure(q,c) # Qubit Measurment
print(circuit)
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
def thirdBellState():
circuit = QuantumCircuit(q,c)
circuit.x(q[1]) # Pauli-X gate
circuit.h(q[0]) # Hadamard gate
circuit.cx(q[0],q[1]) # CNOT gate
circuit.measure(q,c) # Qubit Measurment
print(circuit)
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
def fourthBellState():
circuit = QuantumCircuit(q,c)
circuit.x(q[1]) # Pauli-X gate
circuit.h(q[0]) # Hadamard gate
circuit.z(q[0]) # Pauli-Z gate
circuit.z(q[1]) # Pauli-Z gate
circuit.cx(q[0],q[1]) # CNOT gate
circuit.measure(q,c) # Qubit Measurment
print(circuit)
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
print("Creating first Bell State:\n")
firstBellState()
print("\nCreating second Bell State:\n")
secondBellState()
print("\nCreating third Bell State:\n")
thirdBellState()
print("\nCreating fourth Bell State:\n")
fourthBellState()
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute,IBMQ
IBMQ.enable_account('Enter API token here')
provider = IBMQ.get_provider(hub='ibm-q')
q = QuantumRegister(2,'q')
c = ClassicalRegister(2,'c')
circuit = QuantumCircuit(q,c)
circuit.x(q[0]) # Pauli x gate applied to first qubit
circuit.cx(q[0],q[1]) # CNOT applied to both qubits
circuit.measure(q,c) # Qubits states are measured
backend = provider.get_backend('ibmq_qasm_simulator') # Specifying qasm simulator as the target device
print('Provider: ',backend)
print('')
job = execute(circuit, backend, shots=1)
print('Executing Job...')
print('')
result = job.result()
counts = result.get_counts(circuit)
print('RESULT: ',counts)
print('')
print('Press any key to close')
input()
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
IBMQ.enable_account('Enter API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
q = QuantumRegister(2,'q')
c = ClassicalRegister(2,'c')
circuit = QuantumCircuit(q,c)
circuit.x(q[0])
circuit.ch(q[0], q[1]);
circuit.measure(q,c)
print(circuit)
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import Diagonal
import numpy as np
pi = np.pi
IBMQ.enable_account('ENTER API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
diagonals = [-1,-1,-1,-1]
q = QuantumRegister(2,'q')
c = ClassicalRegister(2,'c')
circuit = QuantumCircuit(q,c)
circuit.h(q[0])
circuit.h(q[1])
circuit += Diagonal(diagonals)
circuit.h(q[0])
circuit.h(q[1])
circuit.measure(q,c) # Qubit Measurment
print(circuit)
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, IBMQ
IBMQ.enable_account('Insert account token here') # Get this from your IBM Q account
provider = IBMQ.get_provider(hub='ibm-q')
q = QuantumRegister(1,'q') # Initialise quantum register
c = ClassicalRegister(1,'c') # Initialise classical register
circuit = QuantumCircuit(q,c) # Initialise circuit
circuit.h(q[0]) # Put Qubit 0 in to superposition using hadamard gate
circuit.measure(q,c) # Measure qubit
backend = provider.get_backend('ibmq_qasm_simulator') # Set device to IBMs quantum simulator
job = execute(circuit, backend, shots=1024) # Execute job and run program 1024 times
result = job.result() # Get result
counts = result.get_counts(circuit) # Count the number of measurements for each state
print('RESULT: ',counts) # Print result
print('Press any key to close')
input()
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Multiple-Control, Multiple-Target Gate."""
from __future__ import annotations
from collections.abc import Callable
from qiskit import circuit
from qiskit.circuit import ControlledGate, Gate, Qubit, QuantumRegister, QuantumCircuit
from qiskit.exceptions import QiskitError
from ..standard_gates import XGate, YGate, ZGate, HGate, TGate, TdgGate, SGate, SdgGate
class MCMT(QuantumCircuit):
"""The multi-controlled multi-target gate, for an arbitrary singly controlled target gate.
For example, the H gate controlled on 3 qubits and acting on 2 target qubit is represented as:
.. parsed-literal::
───■────
│
───■────
│
───■────
┌──┴───┐
┤0 ├
│ 2-H │
┤1 ├
└──────┘
This default implementations requires no ancilla qubits, by broadcasting the target gate
to the number of target qubits and using Qiskit's generic control routine to control the
broadcasted target on the control qubits. If ancilla qubits are available, a more efficient
variant using the so-called V-chain decomposition can be used. This is implemented in
:class:`~qiskit.circuit.library.MCMTVChain`.
"""
def __init__(
self,
gate: Gate | Callable[[QuantumCircuit, Qubit, Qubit], circuit.Instruction],
num_ctrl_qubits: int,
num_target_qubits: int,
) -> None:
"""Create a new multi-control multi-target gate.
Args:
gate: The gate to be applied controlled on the control qubits and applied to the target
qubits. Can be either a Gate or a circuit method.
If it is a callable, it will be casted to a Gate.
num_ctrl_qubits: The number of control qubits.
num_target_qubits: The number of target qubits.
Raises:
AttributeError: If the gate cannot be casted to a controlled gate.
AttributeError: If the number of controls or targets is 0.
"""
if num_ctrl_qubits == 0 or num_target_qubits == 0:
raise AttributeError("Need at least one control and one target qubit.")
# set the internal properties and determine the number of qubits
self.gate = self._identify_gate(gate)
self.num_ctrl_qubits = num_ctrl_qubits
self.num_target_qubits = num_target_qubits
num_qubits = num_ctrl_qubits + num_target_qubits + self.num_ancilla_qubits
# initialize the circuit object
super().__init__(num_qubits, name="mcmt")
self._label = f"{num_target_qubits}-{self.gate.name.capitalize()}"
# build the circuit
self._build()
def _build(self):
"""Define the MCMT gate without ancillas."""
if self.num_target_qubits == 1:
# no broadcasting needed (makes for better circuit diagrams)
broadcasted_gate = self.gate
else:
broadcasted = QuantumCircuit(self.num_target_qubits, name=self._label)
for target in list(range(self.num_target_qubits)):
broadcasted.append(self.gate, [target], [])
broadcasted_gate = broadcasted.to_gate()
mcmt_gate = broadcasted_gate.control(self.num_ctrl_qubits)
self.append(mcmt_gate, self.qubits, [])
@property
def num_ancilla_qubits(self):
"""Return the number of ancillas."""
return 0
def _identify_gate(self, gate):
"""Case the gate input to a gate."""
valid_gates = {
"ch": HGate(),
"cx": XGate(),
"cy": YGate(),
"cz": ZGate(),
"h": HGate(),
"s": SGate(),
"sdg": SdgGate(),
"x": XGate(),
"y": YGate(),
"z": ZGate(),
"t": TGate(),
"tdg": TdgGate(),
}
if isinstance(gate, ControlledGate):
base_gate = gate.base_gate
elif isinstance(gate, Gate):
if gate.num_qubits != 1:
raise AttributeError("Base gate must act on one qubit only.")
base_gate = gate
elif isinstance(gate, QuantumCircuit):
if gate.num_qubits != 1:
raise AttributeError(
"The circuit you specified as control gate can only have one qubit!"
)
base_gate = gate.to_gate() # raises error if circuit contains non-unitary instructions
else:
if callable(gate): # identify via name of the passed function
name = gate.__name__
elif isinstance(gate, str):
name = gate
else:
raise AttributeError(f"Invalid gate specified: {gate}")
base_gate = valid_gates[name]
return base_gate
def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None):
"""Return the controlled version of the MCMT circuit."""
if ctrl_state is None: # TODO add ctrl state implementation by adding X gates
return MCMT(self.gate, self.num_ctrl_qubits + num_ctrl_qubits, self.num_target_qubits)
return super().control(num_ctrl_qubits, label, ctrl_state)
def inverse(self):
"""Return the inverse MCMT circuit, which is itself."""
return MCMT(self.gate, self.num_ctrl_qubits, self.num_target_qubits)
class MCMTVChain(MCMT):
"""The MCMT implementation using the CCX V-chain.
This implementation requires ancillas but is decomposed into a much shallower circuit
than the default implementation in :class:`~qiskit.circuit.library.MCMT`.
**Expanded Circuit:**
.. plot::
from qiskit.circuit.library import MCMTVChain, ZGate
from qiskit.tools.jupyter.library import _generate_circuit_library_visualization
circuit = MCMTVChain(ZGate(), 2, 2)
_generate_circuit_library_visualization(circuit.decompose())
**Examples:**
>>> from qiskit.circuit.library import HGate
>>> MCMTVChain(HGate(), 3, 2).draw()
q_0: ──■────────────────────────■──
│ │
q_1: ──■────────────────────────■──
│ │
q_2: ──┼────■──────────────■────┼──
│ │ ┌───┐ │ │
q_3: ──┼────┼──┤ H ├───────┼────┼──
│ │ └─┬─┘┌───┐ │ │
q_4: ──┼────┼────┼──┤ H ├──┼────┼──
┌─┴─┐ │ │ └─┬─┘ │ ┌─┴─┐
q_5: ┤ X ├──■────┼────┼────■──┤ X ├
└───┘┌─┴─┐ │ │ ┌─┴─┐└───┘
q_6: ─────┤ X ├──■────■──┤ X ├─────
└───┘ └───┘
"""
def _build(self):
"""Define the MCMT gate."""
control_qubits = self.qubits[: self.num_ctrl_qubits]
target_qubits = self.qubits[
self.num_ctrl_qubits : self.num_ctrl_qubits + self.num_target_qubits
]
ancilla_qubits = self.qubits[self.num_ctrl_qubits + self.num_target_qubits :]
if len(ancilla_qubits) > 0:
master_control = ancilla_qubits[-1]
else:
master_control = control_qubits[0]
self._ccx_v_chain_rule(control_qubits, ancilla_qubits, reverse=False)
for qubit in target_qubits:
self.append(self.gate.control(), [master_control, qubit], [])
self._ccx_v_chain_rule(control_qubits, ancilla_qubits, reverse=True)
@property
def num_ancilla_qubits(self):
"""Return the number of ancilla qubits required."""
return max(0, self.num_ctrl_qubits - 1)
def _ccx_v_chain_rule(
self,
control_qubits: QuantumRegister | list[Qubit],
ancilla_qubits: QuantumRegister | list[Qubit],
reverse: bool = False,
) -> None:
"""Get the rule for the CCX V-chain.
The CCX V-chain progressively computes the CCX of the control qubits and puts the final
result in the last ancillary qubit.
Args:
control_qubits: The control qubits.
ancilla_qubits: The ancilla qubits.
reverse: If True, compute the chain down to the qubit. If False, compute upwards.
Returns:
The rule for the (reversed) CCX V-chain.
Raises:
QiskitError: If an insufficient number of ancilla qubits was provided.
"""
if len(ancilla_qubits) == 0:
return
if len(ancilla_qubits) < len(control_qubits) - 1:
raise QiskitError("Insufficient number of ancilla qubits.")
iterations = list(enumerate(range(2, len(control_qubits))))
if not reverse:
self.ccx(control_qubits[0], control_qubits[1], ancilla_qubits[0])
for i, j in iterations:
self.ccx(control_qubits[j], ancilla_qubits[i], ancilla_qubits[i + 1])
else:
for i, j in reversed(iterations):
self.ccx(control_qubits[j], ancilla_qubits[i], ancilla_qubits[i + 1])
self.ccx(control_qubits[0], control_qubits[1], ancilla_qubits[0])
def inverse(self):
return MCMTVChain(self.gate, self.num_ctrl_qubits, self.num_target_qubits)
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
IBMQ.enable_account('Enter API key here')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
q = QuantumRegister(8, 'q')
c = ClassicalRegister(1, 'c')
circuit = QuantumCircuit(q, c)
circuit.x(q[0])
circuit.x(q[1])
circuit.x(q[2])
circuit.x(q[3])
circuit.ccx(q[0], q[1], q[4])
circuit.ccx(q[2], q[4], q[5])
circuit.ccx(q[3], q[5], q[6])
circuit.cx(q[6], q[7])
circuit.ccx(q[3], q[5], q[6])
circuit.ccx(q[2], q[4], q[5])
circuit.ccx(q[0], q[1], q[4])
circuit.measure(q[7], c[0])
job = execute(circuit, backend, shots=100)
job_monitor(job)
counts = job.result().get_counts()
print(circuit)
print(counts)
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.circuit.library import Permutation
from qiskit.tools.monitor import job_monitor
IBMQ.enable_account('ENTER API Key HERE')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
q = QuantumRegister(8, 'q')
c = ClassicalRegister(8, 'c')
########### PERMUTATION WITH PATTERN 7,0,6,1,5,2,4,3
circuit = QuantumCircuit(q, c)
circuit.x(q[0])
circuit.x(q[1])
circuit.x(q[2])
circuit.x(q[3])
circuit += Permutation(num_qubits = 8, pattern = [7,0,6,1,5,2,4,3])
circuit.measure(q, c)
job = execute(circuit, backend, shots=100)
job_monitor(job)
counts = job.result().get_counts()
print(circuit)
print(counts)
####### RANDOM PERMUTATION CIRCUIT
circuit = QuantumCircuit(q, c)
circuit.x(q[0])
circuit.x(q[1])
circuit.x(q[2])
circuit.x(q[3])
circuit += Permutation(num_qubits = 8)
circuit.measure(q, c)
job = execute(circuit, backend, shots=100)
job_monitor(job)
counts = job.result().get_counts()
print(circuit)
print(counts)
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import RGQFTMultiplier
IBMQ.enable_account('ENTER API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
q = QuantumRegister(8,'q')
c = ClassicalRegister(4,'c')
circuit = QuantumCircuit(q,c)
# Operand A = 10 (2)
circuit.x(q[1])
# Operand B = 11 (3)
circuit.x(q[2])
circuit.x(q[3])
circuit1 = RGQFTMultiplier(num_state_qubits=2, num_result_qubits=4)
circuit = circuit.compose(circuit1)
circuit.measure(q[4],c[0])
circuit.measure(q[5],c[1])
circuit.measure(q[6],c[2])
circuit.measure(q[7],c[3])
print(circuit)
job = execute(circuit, backend, shots=2000)
result = job.result()
counts = result.get_counts()
print('2*3')
print('---')
print(counts)
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
print('\nDevice Monitor')
print('----------------')
from qiskit import IBMQ
from qiskit.tools.monitor import backend_overview
IBMQ.enable_account('Insert API token here') # Insert your API token in to here
provider = IBMQ.get_provider(hub='ibm-q')
backend_overview() # Function to get all information back about each quantum device
print('\nPress any key to close')
input()
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
import numpy as np
IBMQ.enable_account('ENTER API KEY HERE)
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
pi = np.pi
q = QuantumRegister(1,'q')
c = ClassicalRegister(1,'c')
circuit = QuantumCircuit(q,c)
circuit.rx(pi,q[0])
circuit.measure(q,c)
print(circuit)
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
import numpy as np
IBMQ.enable_account('ENTER API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
pi = np.pi
q = QuantumRegister(1,'q')
c = ClassicalRegister(1,'c')
circuit = QuantumCircuit(q,c)
circuit.ry(pi,q[0])
circuit.measure(q,c)
print(circuit)
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
import numpy as np
pi = np.pi
IBMQ.enable_account('ENTER API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
def rz(rotation):
circuit = QuantumCircuit(q,c)
circuit.h(q[0]) # Hadamard gate
circuit.rz(rotation,q[0]) # RZ gate
circuit.h(q[0]) # Hadamard gate
circuit.measure(q,c) # Qubit Measurment
print(circuit)
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
q = QuantumRegister(1,'q')
c = ClassicalRegister(1,'c')
rotation = 0
rz(rotation)
rotation = pi/2
rz(rotation)
rotation = pi
rz(rotation)
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''
Toffoli decomposition explained in Lemma 8 from
Quantum Circuits for Isometries.
https://arxiv.org/abs/1501.06911
'''
from numpy import pi
from qiskit import QuantumCircuit
from qiskit.circuit import Gate
class Toffoli(Gate):
def __init__(self, cancel=None):
self.cancel = cancel
super().__init__('toffoli', 3, [], "Toffoli")
def _define(self):
self.definition = QuantumCircuit(3)
theta = pi / 4.
control_qubits = self.definition.qubits[:2]
target_qubit = self.definition.qubits[-1]
if self.cancel != 'left':
self.definition.u(theta=-theta, phi=0., lam=0., qubit=target_qubit)
self.definition.cx(control_qubits[0], target_qubit)
self.definition.u(theta=-theta, phi=0., lam=0., qubit=target_qubit)
self.definition.cx(control_qubits[1], target_qubit)
if self.cancel != 'right':
self.definition.u(theta=theta, phi=0., lam=0., qubit=target_qubit)
self.definition.cx(control_qubits[0], target_qubit)
self.definition.u(theta=theta, phi=0., lam=0., qubit=target_qubit)
@staticmethod
def ccx(circuit, controls=None, target=None, cancel=None):
if controls is None or target is None:
circuit.append(Toffoli(cancel), circuit.qubits[:3])
else:
circuit.append(Toffoli(cancel), [*controls, target])
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
print('\nPhase Flip Code')
print('----------------')
from qiskit import QuantumRegister
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
IBMQ.enable_account('Enter API key here')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
q = QuantumRegister(3,'q')
c = ClassicalRegister(1,'c')
circuit = QuantumCircuit(q,c)
circuit.cx(q[0],q[1])
circuit.cx(q[0],q[2])
circuit.h(q[0])
circuit.h(q[1])
circuit.h(q[2])
circuit.z(q[0]) #Add this to simulate a phase flip error
circuit.h(q[0])
circuit.h(q[1])
circuit.h(q[2])
circuit.cx(q[0],q[1])
circuit.cx(q[0],q[2])
circuit.ccx(q[2],q[1],q[0])
circuit.measure(q[0],c[0])
job = execute(circuit, backend, shots=1000)
job_monitor(job)
counts = job.result().get_counts()
print("\nPhase flip code with error")
print("----------------------")
print(counts)
input()
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumRegister
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
print('\nPhase Flip Code')
print('----------------')
IBMQ.enable_account('ENTER API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
q = QuantumRegister(3,'q')
c = ClassicalRegister(1,'c')
circuit = QuantumCircuit(q,c)
circuit.cx(q[0],q[1])
circuit.cx(q[0],q[2])
circuit.h(q[0])
circuit.h(q[1])
circuit.h(q[2])
circuit.z(q[0]) #Add this to simulate a phase flip error
circuit.h(q[0])
circuit.h(q[1])
circuit.h(q[2])
circuit.cx(q[0],q[1])
circuit.cx(q[0],q[2])
circuit.ccx(q[2],q[1],q[0])
circuit.measure(q[0],c[0])
job = execute(circuit, backend, shots=1000)
job_monitor(job)
counts = job.result().get_counts()
print("\nPhase flip code with error")
print("----------------------")
print(counts)
input()
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
print('\nShor Code')
print('--------------')
from qiskit import QuantumRegister
from qiskit import ClassicalRegister
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
IBMQ.enable_account(‘ENTER API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
q = QuantumRegister(1,'q')
c = ClassicalRegister(1,'c')
circuit = QuantumCircuit(q,c)
circuit.h(q[0])
####error here############
circuit.x(q[0])#Bit flip error
circuit.z(q[0])#Phase flip error
############################
circuit.h(q[0])
circuit.barrier(q)
circuit.measure(q[0],c[0])
job = execute(circuit, backend, shots=1000)
job_monitor(job)
counts = job.result().get_counts()
print("\n Uncorrected bit flip and phase error")
print("--------------------------------------")
print(counts)
#####Shor code starts here ########
q = QuantumRegister(9,'q')
c = ClassicalRegister(1,'c')
circuit = QuantumCircuit(q,c)
circuit.cx(q[0],q[3])
circuit.cx(q[0],q[6])
circuit.h(q[0])
circuit.h(q[3])
circuit.h(q[6])
circuit.cx(q[0],q[1])
circuit.cx(q[3],q[4])
circuit.cx(q[6],q[7])
circuit.cx(q[0],q[2])
circuit.cx(q[3],q[5])
circuit.cx(q[6],q[8])
circuit.barrier(q)
####error here############
circuit.x(q[0])#Bit flip error
circuit.z(q[0])#Phase flip error
############################
circuit.barrier(q)
circuit.cx(q[0],q[1])
circuit.cx(q[3],q[4])
circuit.cx(q[6],q[7])
circuit.cx(q[0],q[2])
circuit.cx(q[3],q[5])
circuit.cx(q[6],q[8])
circuit.ccx(q[1],q[2],q[0])
circuit.ccx(q[4],q[5],q[3])
circuit.ccx(q[8],q[7],q[6])
circuit.h(q[0])
circuit.h(q[3])
circuit.h(q[6])
circuit.cx(q[0],q[3])
circuit.cx(q[0],q[6])
circuit.ccx(q[6],q[3],q[0])
circuit.barrier(q)
circuit.measure(q[0],c[0])
circuit.draw(output='mpl',filename='shorcode.png') #Draws an image of the circuit
job = execute(circuit, backend, shots=1000)
job_monitor(job)
counts = job.result().get_counts()
print("\nShor code with bit flip and phase error")
print("----------------------------------------")
print(counts)
input()
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import logging
import sys
import numpy as np
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.tools import parallel_map
from qiskit.tools.events import TextProgressBar
from qiskit.aqua import aqua_globals
from qiskit.aqua.algorithms import QuantumAlgorithm
from qiskit.aqua import AquaError, Pluggable, PluggableType, get_pluggable_class
from qiskit.aqua.algorithms.many_sample.qsvm._qsvm_binary import _QSVM_Binary
from qiskit.aqua.algorithms.many_sample.qsvm._qsvm_multiclass import _QSVM_Multiclass
from qiskit.aqua.algorithms.many_sample.qsvm._qsvm_estimator import _QSVM_Estimator
from qiskit.aqua.utils.dataset_helper import get_feature_dimension, get_num_classes
from qiskit.aqua.utils import split_dataset_to_data_and_labels
logger = logging.getLogger(__name__)
class QSVM(QuantumAlgorithm):
"""
Quantum SVM method.
Internally, it will run the binary classification or multiclass classification
based on how many classes the data have.
"""
CONFIGURATION = {
'name': 'QSVM',
'description': 'QSVM Algorithm',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'QSVM_schema',
'type': 'object',
'properties': {
},
'additionalProperties': False
},
'problems': ['classification'],
'depends': [
{'pluggable_type': 'multiclass_extension'},
{'pluggable_type': 'feature_map',
'default': {
'name': 'SecondOrderExpansion',
'depth': 2
}
},
],
}
BATCH_SIZE = 1000
def __init__(self, feature_map, training_dataset, test_dataset=None, datapoints=None,
multiclass_extension=None):
"""Constructor.
Args:
feature_map (FeatureMap): feature map module, used to transform data
training_dataset (dict): training dataset.
test_dataset (Optional[dict]): testing dataset.
datapoints (Optional[numpy.ndarray]): prediction dataset.
multiclass_extension (Optional[MultiExtension]): if number of classes > 2 then
a multiclass scheme is needed.
Raises:
ValueError: if training_dataset is None
AquaError: use binary classifer for classes > 3
"""
super().__init__()
if training_dataset is None:
raise ValueError('Training dataset must be provided')
is_multiclass = get_num_classes(training_dataset) > 2
if is_multiclass:
if multiclass_extension is None:
raise AquaError('Dataset has more than two classes. '
'A multiclass extension must be provided.')
else:
if multiclass_extension is not None:
logger.warning("Dataset has just two classes. "
"Supplied multiclass extension will be ignored")
self.training_dataset, self.class_to_label = split_dataset_to_data_and_labels(
training_dataset)
if test_dataset is not None:
self.test_dataset = split_dataset_to_data_and_labels(test_dataset,
self.class_to_label)
else:
self.test_dataset = None
self.label_to_class = {label: class_name for class_name, label
in self.class_to_label.items()}
self.num_classes = len(list(self.class_to_label.keys()))
if datapoints is not None and not isinstance(datapoints, np.ndarray):
datapoints = np.asarray(datapoints)
self.datapoints = datapoints
self.feature_map = feature_map
self.num_qubits = self.feature_map.num_qubits
if multiclass_extension is None:
qsvm_instance = _QSVM_Binary(self)
else:
qsvm_instance = _QSVM_Multiclass(self, multiclass_extension)
self.instance = qsvm_instance
@classmethod
def init_params(cls, params, algo_input):
"""Constructor from params."""
feature_dimension = get_feature_dimension(algo_input.training_dataset)
fea_map_params = params.get(Pluggable.SECTION_KEY_FEATURE_MAP)
fea_map_params['feature_dimension'] = feature_dimension
feature_map = get_pluggable_class(PluggableType.FEATURE_MAP,
fea_map_params['name']).init_params(params)
multiclass_extension = None
multiclass_extension_params = params.get(Pluggable.SECTION_KEY_MULTICLASS_EXTENSION)
if multiclass_extension_params is not None:
multiclass_extension_params['params'] = [feature_map]
multiclass_extension_params['estimator_cls'] = _QSVM_Estimator
multiclass_extension = get_pluggable_class(PluggableType.MULTICLASS_EXTENSION,
multiclass_extension_params['name']).init_params(params)
logger.info("Multiclass classifier based on {}".format(multiclass_extension_params['name']))
return cls(feature_map, algo_input.training_dataset, algo_input.test_dataset,
algo_input.datapoints, multiclass_extension)
@staticmethod
def _construct_circuit(x, num_qubits, feature_map, measurement):
x1, x2 = x
if x1.shape[0] != x2.shape[0]:
raise ValueError("x1 and x2 must be the same dimension.")
q = QuantumRegister(num_qubits, 'q')
c = ClassicalRegister(num_qubits, 'c')
qc = QuantumCircuit(q, c)
# write input state from sample distribution
qc += feature_map.construct_circuit(x1, q)
qc += feature_map.construct_circuit(x2, q, inverse=True)
if measurement:
qc.barrier(q)
qc.measure(q, c)
return qc
@staticmethod
def _compute_overlap(idx, results, is_statevector_sim, measurement_basis):
if is_statevector_sim:
temp = results.get_statevector(idx)[0]
# |<0|Psi^daggar(y) x Psi(x)|0>|^2,
kernel_value = np.dot(temp.T.conj(), temp).real
else:
result = results.get_counts(idx)
kernel_value = result.get(measurement_basis, 0) / sum(result.values())
return kernel_value
def construct_circuit(self, x1, x2, measurement=False):
"""
Generate inner product of x1 and x2 with the given feature map.
The dimension of x1 and x2 must be the same.
Args:
x1 (numpy.ndarray): data points, 1-D array, dimension is D
x2 (numpy.ndarray): data points, 1-D array, dimension is D
measurement (bool): add measurement gates at the end
"""
return QSVM._construct_circuit((x1, x2), self.num_qubits,
self.feature_map, measurement)
def construct_kernel_matrix(self, x1_vec, x2_vec=None, quantum_instance=None):
"""
Construct kernel matrix, if x2_vec is None, self-innerproduct is conducted.
Args:
x1_vec (numpy.ndarray): data points, 2-D array, N1xD, where N1 is the number of data,
D is the feature dimension
x2_vec (numpy.ndarray): data points, 2-D array, N2xD, where N2 is the number of data,
D is the feature dimension
quantum_instance (QuantumInstance): quantum backend with all setting
Returns:
numpy.ndarray: 2-D matrix, N1xN2
"""
self._quantum_instance = self._quantum_instance \
if quantum_instance is None else quantum_instance
from .qsvm import QSVM
if x2_vec is None:
is_symmetric = True
x2_vec = x1_vec
else:
is_symmetric = False
is_statevector_sim = self.quantum_instance.is_statevector
measurement = not is_statevector_sim
measurement_basis = '0' * self.num_qubits
mat = np.ones((x1_vec.shape[0], x2_vec.shape[0]))
# get all indices
if is_symmetric:
mus, nus = np.triu_indices(x1_vec.shape[0], k=1) # remove diagonal term
else:
mus, nus = np.indices((x1_vec.shape[0], x2_vec.shape[0]))
mus = np.asarray(mus.flat)
nus = np.asarray(nus.flat)
for idx in range(0, len(mus), QSVM.BATCH_SIZE):
to_be_computed_list = []
to_be_computed_index = []
for sub_idx in range(idx, min(idx + QSVM.BATCH_SIZE, len(mus))):
i = mus[sub_idx]
j = nus[sub_idx]
x1 = x1_vec[i]
x2 = x2_vec[j]
if not np.all(x1 == x2):
to_be_computed_list.append((x1, x2))
to_be_computed_index.append((i, j))
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Building circuits:")
TextProgressBar(sys.stderr)
circuits = parallel_map(QSVM._construct_circuit,
to_be_computed_list,
task_args=(self.num_qubits, self.feature_map,
measurement),
num_processes=aqua_globals.num_processes)
results = self.quantum_instance.execute(circuits)
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Calculating overlap:")
TextProgressBar(sys.stderr)
matrix_elements = parallel_map(QSVM._compute_overlap, range(len(circuits)),
task_args=(results, is_statevector_sim, measurement_basis),
num_processes=aqua_globals.num_processes)
for idx in range(len(to_be_computed_index)):
i, j = to_be_computed_index[idx]
mat[i, j] = matrix_elements[idx]
if is_symmetric:
mat[j, i] = mat[i, j]
return mat
def train(self, data, labels, quantum_instance=None):
"""
Train the svm.
Args:
data (numpy.ndarray): NxD array, where N is the number of data,
D is the feature dimension.
labels (numpy.ndarray): Nx1 array, where N is the number of data
quantum_instance (QuantumInstance): quantum backend with all setting
"""
self._quantum_instance = self._quantum_instance \
if quantum_instance is None else quantum_instance
self.instance.train(data, labels)
def test(self, data, labels, quantum_instance=None):
"""
Test the svm.
Args:
data (numpy.ndarray): NxD array, where N is the number of data,
D is the feature dimension.
labels (numpy.ndarray): Nx1 array, where N is the number of data
quantum_instance (QuantumInstance): quantum backend with all setting
Returns:
float: accuracy
"""
self._quantum_instance = self._quantum_instance \
if quantum_instance is None else quantum_instance
return self.instance.test(data, labels)
def predict(self, data, quantum_instance=None):
"""
Predict using the svm.
Args:
data (numpy.ndarray): NxD array, where N is the number of data,
D is the feature dimension.
quantum_instance (QuantumInstance): quantum backend with all setting
Returns:
numpy.ndarray: predicted labels, Nx1 array
"""
self._quantum_instance = self._quantum_instance \
if quantum_instance is None else quantum_instance
return self.instance.predict(data)
def _run(self):
return self.instance.run()
@property
def ret(self):
return self.instance.ret
@ret.setter
def ret(self, new_value):
self.instance.ret = new_value
def load_model(self, file_path):
"""Load a model from a file path.
Args:
file_path (str): tthe path of the saved model.
"""
self.instance.load_model(file_path)
def save_model(self, file_path):
"""Save the model to a file path.
Args:
file_path (str): a path to save the model.
"""
self.instance.save_model(file_path)
|
https://github.com/microsoft/qiskit-qir
|
microsoft
|
import qiskit_qasm2
project = 'Qiskit OpenQASM 2 Tools'
copyright = '2022, Jake Lishman'
author = 'Jake Lishman'
version = qiskit_qasm2.__version__
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
]
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# Document the docstring for the class and the __init__ method together.
autoclass_content = "both"
html_theme = 'alabaster'
intersphinx_mapping = {
"qiskit-terra": ("https://qiskit.org/documentation", None),
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.