repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/Gopal-Dahale/qiskit-qulacs
|
Gopal-Dahale
|
"""Tests for qulacs backend."""
from unittest import TestCase
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.circuit.random import random_circuit
from qiskit.result import Result
from qiskit_aer import Aer
from qiskit_qulacs.qulacs_backend import QulacsBackend
from tests.utils import dicts_almost_equal
_EPS = 1e-10 # global variable used to chop very small numbers to zero
class TestQulacsBackend(TestCase):
"""Tests BraketBackend."""
def setUp(self):
self.aer_backend = Aer.get_backend("aer_simulator_statevector")
def test_qulacs_backend_output(self):
"""Test qulacs backend output"""
qulacs_backend = QulacsBackend()
self.assertEqual(qulacs_backend.name(), "qulacs_simulator")
def test_qulacs_backend_circuit(self):
"""Tests qulacs backend with circuit."""
backend = QulacsBackend()
circuits = []
# Circuit 0
q_c = QuantumCircuit(2)
q_c.x(0)
q_c.cx(0, 1)
circuits.append(q_c)
# Circuit 1
q_c = QuantumCircuit(2)
q_c.h(0)
q_c.cx(0, 1)
circuits.append(q_c)
results = []
for circuit in circuits:
results.append(backend.run(circuit).result())
# Result 0
self.assertTrue(
(
np.linalg.norm(results[0].get_statevector() - np.array([0, 0, 0, 1]))
< _EPS
)
)
# Result 1
_00 = np.abs(results[1].get_statevector()[0]) ** 2
_11 = np.abs(results[1].get_statevector()[-1]) ** 2
self.assertTrue(np.allclose([_00, _11], [0.5, 0.5]))
def test_random_circuits(self):
"""Tests with random circuits."""
qulacs_backend = QulacsBackend()
for i in range(1, 10):
with self.subTest(f"Random circuit with {i} qubits."):
qiskit_circuit = random_circuit(i, 5, seed=42)
transpiled_qiskit_circuit = transpile(qiskit_circuit, qulacs_backend)
qulacs_result = (
qulacs_backend.run(transpiled_qiskit_circuit)
.result()
.get_statevector()
)
transpiled_qiskit_circuit.save_statevector()
aer_result = (
self.aer_backend.run(transpiled_qiskit_circuit)
.result()
.get_statevector()
.data
)
self.assertTrue(np.linalg.norm(qulacs_result - aer_result) < _EPS)
def test_single_shot(self):
"""Test single shot run."""
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
shots = 1
qulacs_backend = QulacsBackend()
result = qulacs_backend.run(bell, shots=shots, seed_simulator=10).result()
self.assertEqual(result.success, True)
def test_against_reference(self):
"""Test data counts output for single circuit run against reference."""
qulacs_backend = QulacsBackend()
shots = 1024
threshold = 0.04 * shots
qc = QuantumCircuit(6)
qc.h(range(6))
qc.cx([0, 1, 2], [3, 4, 5])
counts = (
qulacs_backend.run(qc, shots=shots, seed_simulator=10).result().get_counts()
)
counts = {i: j / shots for i, j in counts.items()}
qc.save_statevector()
target = (
self.aer_backend.run(qc, shots=shots, seed_simulator=10)
.result()
.get_counts()
)
error_msg = dicts_almost_equal(counts, target, threshold)
if error_msg:
msg = self._formatMessage(None, error_msg)
raise self.failureException(msg)
def test_options(self):
"""Test for options"""
backend_options = {
"shots": 3000,
"seed_simulator": 42,
"device": "CPU",
"qco_enable": True,
"qco_method": "greedy",
"qco_max_block_size": 5,
}
with self.subTest("set_options"):
qulacs_backend = QulacsBackend()
qulacs_backend.set_options(**backend_options)
self.assertEqual(qulacs_backend.options.get("shots"), 3000)
self.assertEqual(qulacs_backend.options.get("seed_simulator"), 42)
self.assertEqual(qulacs_backend.options.get("device"), "CPU")
self.assertEqual(qulacs_backend.options.get("qco_enable"), True)
self.assertEqual(qulacs_backend.options.get("qco_method"), "greedy")
self.assertEqual(qulacs_backend.options.get("qco_max_block_size"), 5)
with self.subTest("run"):
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
qulacs_backend = QulacsBackend()
result = qulacs_backend.run(
[bell],
qco_enable=True,
qco_method="light",
).result()
self.assertIsInstance(result, Result)
np.testing.assert_allclose(
result.get_statevector(),
(1 / np.sqrt(2)) * np.array([1.0, 0.0, 0.0, 1.0]),
)
def test_repr(self):
"""Test string repr"""
qulacs_backend = QulacsBackend()
self.assertEqual(str(qulacs_backend), "qulacs_simulator")
|
https://github.com/DaisukeIto-ynu/KosakaQ
|
DaisukeIto-ynu
|
# -*- 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.
"""
Simulator command to snapshot internal simulator representation.
"""
import warnings
from qiskit import QuantumCircuit
from qiskit.circuit import CompositeGate
from qiskit import QuantumRegister
from qiskit.circuit import Instruction
from qiskit.extensions.exceptions import ExtensionError
class Snapshot(Instruction):
"""Simulator snapshot instruction."""
def __init__(self,
label,
snapshot_type='statevector',
num_qubits=0,
num_clbits=0,
params=None):
"""Create new snapshot instruction.
Args:
label (str): the snapshot label for result data.
snapshot_type (str): the type of the snapshot.
num_qubits (int): the number of qubits for the snapshot type [Default: 0].
num_clbits (int): the number of classical bits for the snapshot type [Default: 0].
params (list or None): the parameters for snapshot_type [Default: None].
Raises:
ExtensionError: if snapshot label is invalid.
"""
if not isinstance(label, str):
raise ExtensionError('Snapshot label must be a string.')
self._label = label
self._snapshot_type = snapshot_type
if params is None:
params = []
super().__init__('snapshot', num_qubits, num_clbits, params)
def assemble(self):
"""Assemble a QasmQobjInstruction"""
instruction = super().assemble()
instruction.label = self._label
instruction.snapshot_type = self._snapshot_type
return instruction
def inverse(self):
"""Special case. Return self."""
return Snapshot(self.num_qubits, self.num_clbits, self.params[0],
self.params[1])
@property
def snapshot_type(self):
"""Return snapshot type"""
return self._snapshot_type
@property
def label(self):
"""Return snapshot label"""
return self._label
@label.setter
def label(self, name):
"""Set snapshot label to name
Args:
name (str or None): label to assign unitary
Raises:
TypeError: name is not string or None.
"""
if isinstance(name, str):
self._label = name
else:
raise TypeError('label expects a string')
def snapshot(self,
label,
snapshot_type='statevector',
qubits=None,
params=None):
"""Take a statevector snapshot of the internal simulator representation.
Works on all qubits, and prevents reordering (like barrier).
For other types of snapshots use the Snapshot extension directly.
Args:
label (str): a snapshot label to report the result
snapshot_type (str): the type of the snapshot.
qubits (list or None): the qubits to apply snapshot to [Default: None].
params (list or None): the parameters for snapshot_type [Default: None].
Returns:
QuantumCircuit: with attached command
Raises:
ExtensionError: malformed command
"""
# Convert label to string for backwards compatibility
if not isinstance(label, str):
warnings.warn(
"Snapshot label should be a string, "
"implicit conversion is depreciated.", DeprecationWarning)
label = str(label)
# If no qubits are specified we add all qubits so it acts as a barrier
# This is needed for full register snapshots like statevector
if isinstance(qubits, QuantumRegister):
qubits = qubits[:]
if not qubits:
tuples = []
if isinstance(self, QuantumCircuit):
for register in self.qregs:
tuples.append(register)
if not tuples:
raise ExtensionError('no qubits for snapshot')
qubits = []
for tuple_element in tuples:
if isinstance(tuple_element, QuantumRegister):
for j in range(tuple_element.size):
qubits.append((tuple_element, j))
else:
qubits.append(tuple_element)
return self.append(
Snapshot(
label,
snapshot_type=snapshot_type,
num_qubits=len(qubits),
params=params), qubits)
# Add to QuantumCircuit and CompositeGate classes
QuantumCircuit.snapshot = snapshot
CompositeGate.snapshot = snapshot
|
https://github.com/Qiskit/feedback
|
Qiskit
|
from qiskit_ibm_experiment import IBMExperimentService
from qiskit_experiments.framework.json import ExperimentDecoder, ExperimentEncoder
from IPython.display import SVG, display
IBMExperimentService.save_account(token="MY_API_TOKEN")
IBMExperimentService.save_account(name="staging", token="MY_STAGING_API_TOKEN", url='https://api-dev.quantum-computing.ibm.com')
service = IBMExperimentService()
service.experiments()
exp_id = 'b4bebb95-66d4-461b-9287-1441443a3336'
service.experiment(exp_id)
service.experiments(experiment_type='readout_test')
service.analysis_results(experiment_id = exp_id)
fig = service.figure(exp_id, 'figure_b4bebb95_2022-03-30T11:40:21.656059_0.svg')
display(SVG(fig))
service = IBMExperimentService(name="staging")
service.experiments()
from qiskit.providers.ibmq import IBMQ, least_busy
provider = IBMQ.enable_account(url='https://api-dev.quantum-computing.ibm.com/v2', token="c0026ac13d5f10513555e5f396f20b60f97eabf85ba8591a3415ebcfb54e4961c8c095938a29ff4b657a725fa48e301d993ef509a7699ceddc891b0d1eddb137")
backend = least_busy(provider.backends(simulator=False, min_num_qubits=5))
exp_id = service.create_experiment(experiment_type="demo_day",
backend_name = backend.name(),
provider=provider,
metadata = {'complex_number': 3+2j},
json_encoder=ExperimentEncoder
)
exp_id
service.experiment(exp_id, json_decoder=ExperimentDecoder)
for i in range(30):
service.create_analysis_result(exp_id,
result_data = {'100': 100-i, '010': 24+i},
result_type = f'result{i}'
)
service.analysis_results(experiment_id = exp_id)
service.analysis_results(experiment_id = exp_id,
result_type = 'result1',
result_type_operator='like')
fig_name, _ = service.create_figure(exp_id, fig)
new_fig = service.figure(exp_id, fig_name)
display(SVG(new_fig))
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main')
device = provider.get_backend('ibmq_lima')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from qiskit.quantum_info import state_fidelity
def qc_qft(n):
qr = QuantumRegister(n); qc = QuantumCircuit(qr, name = 'QFT')
for l in range(0, n):
qc.h(qr[l])
if l < n-1:
for q in range(l+1, n):
lb = 2*math.pi*2**(-q+l-1)
qc.cp(lb, qr[q], qr[l])
#qc.barrier()
#qc.barrier()
if n%2 == 0:
ul = n//2
else:
ul = (n-1)//2
for p in range(0, ul):
qc.swap(p, n-1-p)
return qc
n = 4; qc_qft_ = qc_qft(n); qc_qft_.draw(output='mpl')
def qc_iqft(n):
qr = QuantumRegister(n); qc = QuantumCircuit(qr, name = 'IQFT')
if n%2 == 0:
ul = n//2
else:
ul = (n-1)//2
for p in range(ul-1, -1, -1):
qc.swap(p, n-1-p)
#qc.barrier()
for l in range(n-1, -1, -1):
if l < n-1:
for q in range(n-1, l+1-1, -1):
lb = -2*math.pi*2**(-q+l-1)#; print(lb)
qc.cp(lb, qr[q], qr[l])
qc.h(qr[l])
#qc.barrier()
return qc
n = 4; qc_iqft_ = qc_iqft(n); qc_iqft_.draw(output='mpl')
#x0 = 1 + 0*1j; x1 = 0 + 0*1j # estado |0>
#x0 = 0 + 0*1j; x1 = 1 + 0*1j # estado |1>
x0 = 1/math.sqrt(2) + 0*1j; x1 = 1/math.sqrt(2) + 0*1j # estado |+>
mx0 = math.sqrt(x0.real**2 + x0.imag**2)
if x0.real != 0:
ph0 = math.atan(x0.imag/x0.real)
elif x0.real == 0 and x0.imag != 0:
ph0 = math.pi/2
elif x0.real == 0 and x0.imag == 0:
ph0 = 0
mx1 = math.sqrt(x1.real**2 + x1.imag**2)
if x1.real != 0:
ph1 = math.atan(x1.imag/x1.real)
elif x1.real == 0 and x1.imag != 0:
ph1 = math.pi/2
elif x1.real == 0 and x1.imag == 0:
ph1 = 0
print('|x0|=',mx0,', ph0=', ph0,', |x1|=', mx1,', ph1=', ph1)
th = 2*math.acos(mx1); ph = ph1-ph0+math.pi; lb = ph0-math.pi
print('th=',th,', ph=', ph,', lb=', lb)
n = 1
qr = QuantumRegister(n); qc = QuantumCircuit(qr)
qc.x(qr[0]); qc.u(th, ph, lb, qr[0]); qc.barrier()
qc_qft_ = qc_qft(n); qft = qc_qft_.to_gate(); qc.append(qft, [0])
qc.draw(output='mpl')
svsimulator = Aer.get_backend('statevector_simulator')
job = execute(qc, backend = svsimulator, shots = 1, memory = True)
print(job.result().get_statevector(qc))
def tfc(x): # classical discrete Fourier transform
d = len(x)
y = np.zeros(d, dtype = complex)
for k in range(0, d):
for j in range(0, d):
y[k] += x[j]*(math.cos(2*math.pi*j*k/d) + 1j*math.sin(2*math.pi*j*k/d))
return y/math.sqrt(d)
d = 4; x = np.zeros(d, dtype = complex);
#x = [1/2, 1/2, 1/2, 1/2]
x = [-1/2, -1/2, 1/2, 1/2]
y = tfc(x); print(y)
n = 2
qr = QuantumRegister(n); qc = QuantumCircuit(qr)
#qc.h([0,1]); qc.barrier() # ok
qc.x([0]); qc.h([0,1]); qc.barrier() # ok a menos de uma fase global de pi
qc_qft_ = qc_qft(n); qft = qc_qft_.to_gate(); qc.append(qft, [0,1])
qc.draw(output='mpl')
svsimulator = Aer.get_backend('statevector_simulator')
job = execute(qc, backend = svsimulator, shots = 1, memory = True)
print(job.result().get_statevector(qc)) # para >1 qubit tem a questao da ordem da bc
d = 4; x = np.zeros(d, dtype = complex);
x = [math.sqrt(1/6), math.sqrt(1/6), math.sqrt(2/3), 0]
y = tfc(x); print(y)
n = 3
qr = QuantumRegister(n); cr = ClassicalRegister(n); qc = QuantumCircuit(qr, cr)
qc.x([0,2]); qc.barrier()
qc_qft_ = qc_qft(n); qft = qc_qft_.to_gate(); qc.append(qft, [0,1,2]); qc.barrier()
qc_iqft_ = qc_iqft(n); iqft = qc_iqft_.to_gate(); qc.append(iqft, [0,1,2]); qc.barrier()
qc.measure([0,1,2],[0,1,2])
qc.draw(output='mpl')
job_sim = execute(qc, backend = simulator, shots = nshots)
job_exp = execute(qc, backend = device, shots = nshots)
job_monitor(job_exp)
plot_histogram([job_sim.result().get_counts(), job_exp.result().get_counts()],
legend = ['sim', 'exp'])
|
https://github.com/duartefrazao/Quantum-Finance-Algorithms
|
duartefrazao
|
"""
Test Script
"""
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
qrx = QuantumRegister(1, 'q0')
qry = QuantumRegister(1, 'q1')
cr = ClassicalRegister(1, 'c')
qc = QuantumCircuit(qrx, qry, cr)
qc.h(qrx)
qc.x(qry)
qc.h(qry)
qc.barrier()
qc.x(qry)
qc.barrier()
qc.h(qrx)
qc.h(qry)
qc.measure(qrx, cr)
qc.draw("mpl")
from qiskit import execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
sim = AerSimulator()
job = execute(qc, backend = sim, shots = 1000)
result = job.result()
counts = result.get_counts(qc)
print("Counts: ", counts)
plot_histogram(counts)
|
https://github.com/OccumRazor/implement-quantum-algotirhms-with-qiskit
|
OccumRazor
|
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>)
out of four possible values."""
#import numpy and plot library
import matplotlib.pyplot as plt
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.quantum_info import Statevector
# import basic plot tools
from qiskit.visualization import plot_histogram
# define variables, 1) initialize qubits to zero
n = 2
grover_circuit = QuantumCircuit(n)
#define initialization function
def initialize_s(qc, qubits):
'''Apply a H-gate to 'qubits' in qc'''
for q in qubits:
qc.h(q)
return qc
### begin grovers circuit ###
#2) Put qubits in equal state of superposition
grover_circuit = initialize_s(grover_circuit, [0,1])
# 3) Apply oracle reflection to marked instance x_0 = 3, (|11>)
grover_circuit.cz(0,1)
statevec = job_sim.result().get_statevector()
from qiskit_textbook.tools import vector2latex
vector2latex(statevec, pretext="|\\psi\\rangle =")
# 4) apply additional reflection (diffusion operator)
grover_circuit.h([0,1])
grover_circuit.z([0,1])
grover_circuit.cz(0,1)
grover_circuit.h([0,1])
# 5) measure the qubits
grover_circuit.measure_all()
# Load IBM Q account and get the least busy backend device
provider = IBMQ.load_account()
device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and
not x.configuration().simulator and x.status().operational==True))
print("Running on current least busy device: ", device)
from qiskit.tools.monitor import job_monitor
job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3)
job_monitor(job, interval = 2)
results = job.result()
answer = results.get_counts(grover_circuit)
plot_histogram(answer)
#highest amplitude should correspond with marked value x_0 (|11>)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
qc.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.library import MCXGate
gate = MCXGate(4)
from qiskit import QuantumCircuit
circuit = QuantumCircuit(5)
circuit.append(gate, [0, 1, 4, 2, 3])
circuit.draw('mpl')
|
https://github.com/GroenteLepel/qiskit-quantum-knn
|
GroenteLepel
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
from qiskit_quantum_knn.qknn import QKNeighborsClassifier
from qiskit_quantum_knn.encoding import analog
from sklearn import datasets
import qiskit as qk
from qiskit.utils import QuantumInstance
# initialising the quantum instance
backend = qk.BasicAer.get_backend('qasm_simulator')
instance = QuantumInstance(backend, shots=10000)
# initialising the qknn model
qknn = QKNeighborsClassifier(
n_neighbors=3,
quantum_instance=instance
)
n_variables = 2 # should be positive power of 2
n_train_points = 4 # can be any positive integer
n_test_points = 2 # can be any positive integer
# use iris dataset
iris = datasets.load_iris()
labels = iris.target
data_raw = iris.data
# encode data
encoded_data = analog.encode(data_raw[:, :n_variables])
# now pick these indices from the data
train_data = encoded_data[:n_train_points]
train_labels = labels[:n_train_points]
test_data = encoded_data[n_train_points:(n_train_points+n_test_points), :n_variables]
test_labels = labels[n_train_points:(n_train_points+n_test_points)]
qknn.fit(train_data, train_labels)
qknn_prediction = qknn.predict(test_data)
print(qknn_prediction)
print(test_labels)
# In[2]:
from qiskit_quantum_knn.qknn.qknn_construction import create_qknn
test_data = [1, 0]
train_data = [
[1, 0],
[1, 0]
]
circuit = create_qknn(test_data, train_data, add_measurement=True)
print(circuit.draw())
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/clement-boisson/kagome-vqe-on-heavy-hex
|
clement-boisson
|
import numpy as np
from qiskit import IBMQ, Aer
from qiskit.algorithms import QAOA, VQE, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance, algorithm_globals
from qiskit.providers.aer.noise.noise_model import NoiseModel
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization.converters import QuadraticProgramToQubo
import qiskit.test.mock as Fake
IBMQ.load_account()
IBMQ.providers()
algorithm_globals.massive = True
quadprog = QuadraticProgram("test")
quadprog.integer_var(name="x_1", lowerbound=0, upperbound=4)
quadprog.integer_var(name="x_2", lowerbound=-2, upperbound=2)
quadprog.integer_var(name="x_3", lowerbound=-2, upperbound=4)
quadprog.minimize(
linear={"x_3": -6},
quadratic={("x_1", "x_1"): 1, ("x_2", "x_2"): 1, ("x_1", "x_2"): -1}
)
quadprog.linear_constraint(linear={"x_1": 1, "x_2": 1}, sense="=", rhs=2)
quadprog.quadratic_constraint(quadratic={("x_2", "x_3"): 1}, sense=">=", rhs=1)
print(quadprog.export_as_lp_string())
def cropyield_quadratic_program(n=3):
cropyield = QuadraticProgram()
# initialize the crop types as integer variables
crops = ["Wheat", "Soybeans", "Maize", "PushPull"]
w = "Wheat"
s = "Soybeans"
m = "Maize"
p = "PushPull"
for crop in crops:
cropyield.integer_var(name=crop, lowerbound=0, upperbound=n)
l = {}
q = {}
# initialize the equation for total crop output.
# these represent how "good" each of the crop types are in terms of the final equation
# so wheat is 2x as good as soybeans and maize is 4x as good, and pushpull provides no direct benefit
l[w] = 2
l[s] = 1
l[m] = 4
# define the intercropping coefficients, aka how well certain crops will be when grown together
q[(w, s)] = 2.4
q[(w, m)] = 4
q[(w, p)] = 4
q[(s, m)] = 2
q[(s, p)] = 1
q[(m, p)] = 5
# we want to maximize the output
cropyield.maximize(linear=l, quadratic=q)
# but make sure that the sum of the number of squares is <= 3
cropyield.linear_constraint(linear={w:1, s:1, m:1, p:1}, sense="<=", rhs=n)
return cropyield
# convert the quadratic problem to a quantum problem
cropyield = cropyield_quadratic_program(n=3)
ising_operations, _ = (
QuadraticProgramToQubo()
.convert(
cropyield,
)
.to_ising()
)
print(f"Number of qubits required is {ising_operations.num_qubits}")
QuadraticProgramToQubo().convert(cropyield)
# use the Aer simulator
backend = Aer.get_backend("qasm_simulator")
algorithm_globals.random_seed = 271828
def get_classical_solution_for(quadprog: QuadraticProgram):
solver = NumPyMinimumEigensolver()
optimizer = MinimumEigenOptimizer(solver)
return optimizer.solve(quadprog)
def get_QAOA_solution_for(
quadprog: QuadraticProgram, quantumInstance: QuantumInstance, optimizer=None
):
_eval_count = 0
def callback(eval_count, parameters, mean, std):
nonlocal _eval_count
_eval_count = eval_count
solver = QAOA(
optimizer=optimizer, quantum_instance=quantumInstance, callback=callback
)
optimizer = MinimumEigenOptimizer(solver)
result = optimizer.solve(quadprog)
return result, _eval_count
def get_VQE_solution_for(
quadprog: QuadraticProgram, quantumInstance: QuantumInstance, optimizer=None,
):
_eval_count = 0
def callback(eval_count, parameters, mean, std):
nonlocal _eval_count
_eval_count = eval_count
# Create solver and optimizer
solver = VQE(
optimizer=optimizer, quantum_instance=quantumInstance, callback=callback
)
# Create optimizer for solver
optimizer = MinimumEigenOptimizer(solver)
# Get result from optimizer
result = optimizer.solve(quadprog)
return result, _eval_count
classical_result = get_classical_solution_for(cropyield)
print("Solution found using classical method:\n")
print(f"Maximum crop yield is {classical_result.fval} tons")
print("Crops used are: ")
_crops = [v.name for v in cropyield.variables]
for cropIndex, cropHectares in enumerate(classical_result.x):
print(f"\t{cropHectares} ha of {_crops[cropIndex]}")
simulator_instance = QuantumInstance(
backend=backend,
seed_simulator=algorithm_globals.random_seed,
seed_transpiler=algorithm_globals.random_seed,
)
qaoa_result, qaoa_eval_count = get_QAOA_solution_for(cropyield, simulator_instance)
print("Solution found using the QAOA method:\n")
print(f"Maximum crop-yield is {qaoa_result.fval} tons")
print(f"Crops used are: ")
for cropHectares, cropName in zip(qaoa_result.x, qaoa_result.variable_names):
print(f"\t{cropHectares} ha of {cropName}")
print(f"\nThe solution was found within {qaoa_eval_count} evaluations of QAOA.")
# Create a QuantumInstance
simulator_instance = QuantumInstance(
backend=backend,
seed_simulator=algorithm_globals.random_seed,
seed_transpiler=algorithm_globals.random_seed,
)
# Get VQE result
vqe_result, vqe_eval_count = get_VQE_solution_for(
cropyield, simulator_instance)
# Format and print result
print("Solution found using the VQE method:\n")
print(f"Maximum crop-yield is {vqe_result.fval} tons")
print(f"Crops used are: ")
for cropHectares, cropName in zip(vqe_result.x, vqe_result.variable_names):
print(f"\t{cropHectares} ha of {cropName}")
print(f"\nThe solution was found within {vqe_eval_count} evaluations of VQE")
problem = cropyield_quadratic_program(n=50)
for _backend in IBMQ.get_provider(hub='ibm-q', group='open', project='main').backends():
print(_backend.name())
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
backend_real = provider.get_backend('ibmq_qasm_simulator')
quantum_instance_real = QuantumInstance(backend_real, shots=2048)
optimizer = COBYLA(maxiter=1)
## Get result from real device with VQE
vqe_result_real, vqe_eval_count_real = get_VQE_solution_for(
problem, quantum_instance_real, optimizer=optimizer
)
# Format and print result
print("Solution found using the VQE method:\n")
print(f"Maximum crop-yield is {vqe_result_real.fval} tons")
print(f"Crops used are: ")
for cropHectares, cropName in zip(vqe_result_real.x, vqe_result_real.variable_names):
print(f"\t{cropHectares} ha of {cropName}")
print(
f"\nThe solution was found within {vqe_eval_count_real} evaluations of VQE")
|
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
from qiskit import QuantumCircuit, Aer,execute, IBMQ,transpile
from qiskit.visualization import *
from qiskit.test.mock import FakeVigo
qc=QuantumCircuit(3)
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
qc.measure_all()
qc.draw(output="mpl")
qc.depth()
# on the ideal simulator
backend=Aer.get_backend('qasm_simulator')
job=execute(qc,backend,shots=1024)
result=job.result()
counts=result.get_counts()
print(counts)
backend = FakeVigo()
job=execute(qc,backend,shots=1024)
result=job.result()
counts=result.get_counts()
print(counts)
transpile_circuit=transpile(qc,backend)
job=backend.run(transpile_circuit)
result=job.result()
counts=result.get_counts()
print(counts)
transpile_circuit.draw(output="mpl")
transpile_circuit.depth()
plot_circuit_layout(transpile_circuit, backend)
transpile_circuit_new=transpile(qc,backend,optimization_level=2,initial_layout=[0,1,2])
job=backend.run(transpile_circuit_new)
result=job.result()
counts=result.get_counts()
print(counts)
transpile_circuit_new.draw(output="mpl")
transpile_circuit_new.depth()
plot_circuit_layout(transpile_circuit_new,backend)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# begin with importing essential libraries for IBM Q
from qiskit import IBMQ, BasicAer
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
# set up Quantum Register and Classical Register for 3 qubits
q = QuantumRegister(3)
c = ClassicalRegister(3)
# Create a Quantum Circuit
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw()
def answer(result):
for key in result.keys():
state = key
print('The Quantum 8-ball says:')
if state == '000':
print('It is certain.')
elif state == '001':
print('Without a doubt.')
elif state == '010':
print('Yes - definitely.')
elif state == '011':
print('Most likely.')
elif state == '100':
print("Don't count on it.")
elif state == '101':
print('My reply is no.')
elif state == '110':
print('Very doubtful.')
else:
print('Concentrate and ask again.')
from qiskit import execute
job = execute(qc, backend=BasicAer.get_backend('qasm_simulator'), shots=1)
result = job.result().get_counts(qc)
answer(result)
# load IBM Q account
IBMQ.load_accounts()
# define the least busy device
from qiskit.providers.ibmq import least_busy
backend = least_busy(IBMQ.backends(simulator=False))
print("The least busy device:",backend.name())
job = execute(qc, backend=backend, shots=1)
result = job.result().get_counts(qc)
answer(result)
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../utils/")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling
print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
# from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
print(str(backend))
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
#! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# we have to feed initial_layout to calibration matrix
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
meas_calibs[0].draw("mpl")
dt_now = datetime.datetime.now()
print(dt_now)
filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl"
print(filename)
with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open(filename, "wb") as f:
pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
filename = "job_ids_ibmq_jakarta_100step_20220413_030821_.pkl" # change here
with open(filename, "rb") as f:
job_ids_dict = pickle.load(f)
job_ids = job_ids_dict["job_ids"]
cal_job_id = job_ids_dict["cal_job_id"]
retrieved_jobs = []
for job_id in job_ids:
retrieved_jobs.append(backend.retrieve_job(job_id))
retrieved_cal_job = backend.retrieve_job(cal_job_id)
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
|
ronitd2002
|
# imports
import numpy as np
from typing import List, Callable
from scipy.optimize import minimize
from scipy.optimize._optimize import OptimizeResult
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector, Operator, SparsePauliOp
from qiskit.primitives import StatevectorSampler, PrimitiveJob
from qiskit.circuit.library import TwoLocal
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit.visualization import plot_histogram
from qiskit_ibm_runtime.fake_provider import FakeSherbrooke
from qiskit_ibm_runtime import Session, EstimatorV2 as Estimator
from qiskit_aer import AerSimulator
# Setup the grader
from qc_grader.challenges.iqc_2024 import (
grade_lab1_ex1,
grade_lab1_ex2,
grade_lab1_ex3,
grade_lab1_ex4,
grade_lab1_ex5,
grade_lab1_ex6,
grade_lab1_ex7,
)
# Build a circuit to form a psi-minus Bell state
# Apply gates to the provided QuantumCircuit, qc
qc = QuantumCircuit(2)
### Write your code below here ###
qc.h(0)
qc.cx(0,1)
qc.z(1)
qc.x(1)
### Don't change any code past this line ###
qc.measure_all()
qc.draw('mpl')
# Submit your answer using following code
grade_lab1_ex1(qc) # Expected result type: QuantumCircuit
qc.measure_all()
### Write your code below here ###
sampler = StatevectorSampler() #Add your code here
pub = (qc)#Add your code here
job_sampler = sampler.run([pub])#Add your code here
### Don't change any code past this line ###
result_sampler = job_sampler.result()
counts_sampler = result_sampler[0].data.meas.get_counts()
print(counts_sampler)
# Submit your answer using following code
grade_lab1_ex2(job_sampler) # Expected result type: PrimitiveJob
plot_histogram(counts_sampler)
# Step 1
qc = QuantumCircuit(3) #your_code_here
# Step 2 (provided)
qc.ry(1.91063324, 0)
# Add steps 3-6 below
qc.ch(0,1)
qc.cx(1,2)
qc.cx(0,1)
qc.x(0)
### Don't change any code past this line ###
qc.measure_all()
qc.draw('mpl')
# Submit your answer using following code
grade_lab1_ex3(qc) # Expected result type: # Expected result type: QuantumCircuit
sampler = StatevectorSampler()
pub = (qc)
job_sampler = sampler.run([pub], shots=10000)
result_sampler = job_sampler.result()
counts_sampler = result_sampler[0].data.meas.get_counts()
print(counts_sampler)
plot_histogram(counts_sampler)
pauli_op = SparsePauliOp(['ZII', 'IZI', 'IIZ'])
print(pauli_op.to_matrix())
num_qubits = 3#Add your code here
rotation_blocks = ['ry','rz'] #Add your code here
entanglement_blocks = 'cz' #Add your code here
entanglement = 'full' #Add your code here
reps= 1
insert_barriers=True
ansatz = TwoLocal(num_qubits= num_qubits, rotation_blocks= rotation_blocks, entanglement_blocks= entanglement_blocks, entanglement= entanglement, reps=reps , insert_barriers= insert_barriers) #Add your code here
### Don't change any code past this line ###
ansatz.decompose().draw('mpl')
# Submit your answer using following code
grade_lab1_ex4(num_qubits, rotation_blocks, entanglement_blocks, entanglement) # Expected result type: int, List[str], str, str
num_params = ansatz.num_parameters
num_params
backend_answer = FakeSherbrooke() #Add your code
optimization_level_answer = 0 #Add your code
pm = generate_preset_pass_manager(backend=backend_answer,optimization_level=optimization_level_answer)
isa_circuit = pm.run(ansatz) # Add your code
# Submit your answer using following code
grade_lab1_ex5(isa_circuit) # Expected result type: QuantumCircuit
isa_circuit.draw('mpl', idle_wires=False,)
# Define our Hamiltonian
hamiltonian_isa = pauli_op.apply_layout(layout=isa_circuit.layout)
def cost_func(params, ansatz, hamiltonian, estimator, callback_dict):
"""Return estimate of energy from estimator
Parameters:
params (ndarray): Array of ansatz parameters
ansatz (QuantumCircuit): Parameterized ansatz circuit
hamiltonian (SparsePauliOp): Operator representation of Hamiltonian
estimator (EstimatorV2): Estimator primitive instance
Returns:
float: Energy estimate
"""
pub = (ansatz, [hamiltonian], [params]) #Add your code
result = estimator.run(pubs=[pub]).result() #Add your code
energy = result[0].data.evs[0] #Add your code
callback_dict["iters"] += 1 #Add your code
callback_dict["prev_vector"] = params #Add your code
callback_dict["cost_history"].append(energy) #Add your code
### Don't change any code past this line ###
print(energy)
return energy, result
# Submit your answer using following code
grade_lab1_ex6(cost_func) # Expected result type: Callable
callback_dict = {
"prev_vector": None,
"iters": 0,
"cost_history": [],
}
x0 = 2 * np.pi * np.random.random(num_params)
x0
### Select a Backend
## Use FakeSherbrooke to simulate with noise that matches closer to the real experiment. This will run slower.
## Use AerSimulator to simulate without noise to quickly iterate. This will run faster.
backend = FakeSherbrooke()
# backend = AerSimulator()
# ### Don't change any code past this line ###
# Here we have updated the cost function to return only the energy to be compatible with recent scipy versions (>=1.10)
def cost_func_2(*args, **kwargs):
energy, result = cost_func(*args, **kwargs)
return energy
with Session(backend=backend) as session:
estimator = Estimator(session=session)
res = minimize(
cost_func_2,
x0,
args=(isa_circuit, hamiltonian_isa, estimator, callback_dict),
method="cobyla",
options={'maxiter': 30})
# Submit your answer using following code
grade_lab1_ex7(res) # Expected result type: OptimizeResult
fig, ax = plt.subplots()
plt.plot(range(callback_dict["iters"]), callback_dict["cost_history"],'--',color = 'k')
plt.xlabel("Energy")
plt.ylabel("Cost")
plt.draw()
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
nshots = 500;
Npt = 7 # Número de passos de Trotter
ph = 2*math.pi # ângulo para a transformação de simetria
t = math.pi
for j in range(0, Npt): # muda o No. de passos de Trotter
# teórico
U12 = UHxxx12_num(t/(j+1)); U23 = UHxxx23_num(t/(j+1))
B = np.dot(U12, U23); U = np.linalg.matrix_power(B, j+1); psit = np.dot(U, psi0_)
F_teo = qiskit.quantum_info.state_fidelity(psi0_, psit)
# circuit q
qc = QuantumCircuit(3)
qc_psi0_ = qc_psi0(); qc.append(qc_psi0_, [0, 1, 2]) # estado inicial
qc_Bj_ = qc_Bj(t/(j+1))
for k in range(0, j+1):
qc.rz(ph/(j+1), [0, 1, 2]) # transformação de simetria
qc.append(qc_Bj_, [0, 1, 2])
qc.rz(-ph, [0, 1, 2]) # revertendo a transformação de simetria
if j == 1:
qc.draw(output = 'mpl')
qstc = state_tomography_circuits(qc, [0, 1, 2])
# simulação
job = qiskit.execute(qstc, backend = simulator, shots = nshots)
qstf = StateTomographyFitter(job.result(), qstc)
rho = qstf.fit(method = 'lstsq')
F_sim = qiskit.quantum_info.state_fidelity(psi0__, rho)
# experimento
jobE = qiskit.execute(qstc, backend = device, shots = nshots)
print(jobE.job_id()); job_monitor(jobE)
qstfE = StateTomographyFitter(jobE.result(), qstc)
rhoE = qstfE.fit(method = 'lstsq')
F_exp = qiskit.quantum_info.state_fidelity(psi0__, rhoE)
print('No. passos=', j+1, ',F_teo=', F_teo, ',F_sim=', F_sim, ',F_exp=', F_exp)
qc.draw(output = 'mpl')
|
https://github.com/tanmaybisen31/Quantum-Teleportation
|
tanmaybisen31
|
from qiskit import *
IBMQ.load_account()
cr=ClassicalRegister(2)
qr=QuantumRegister(2)
circuit=QuantumCircuit(qr,cr)
%matplotlib inline
circuit.draw()
circuit.h(qr[0])
circuit.draw(output='mpl')
circuit.cx(qr[0],qr[1])
circuit.draw(output='mpl')
circuit.measure(qr,cr)
circuit.draw()
simulator=Aer.get_backend('qasm_simulator')
result=execute(circuit,backend=simulator).result()
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
from qiskit.visualization import plot_state_qsphere
from qiskit.visualization import plot_bloch_multivector
statevector_simulator = Aer.get_backend('statevector_simulator')
result=execute(circuit,statevector_simulator).result()
statevector_results=result.get_statevector(circuit)
plot_bloch_multivector(statevector_results)
plot_state_qsphere(statevector_results)
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""A solver for time-evolution problems."""
from typing import List
from qiskit_nature.second_q.operators import FermionicOp
from qiskit_nature.second_q.mappers import (
JordanWignerMapper,
BravyiKitaevMapper,
ParityMapper,
)
from qiskit import QuantumRegister
from qiskit import QuantumCircuit
from qiskit.algorithms import TimeEvolutionProblem
from qiskit.algorithms.time_evolvers import TrotterQRTE
from qiskit.quantum_info import Statevector
from qiskit_cold_atom.applications.fermionic_evolution_problem import (
FermionicEvolutionProblem,
)
from qiskit_cold_atom.fermions.base_fermion_backend import BaseFermionBackend
class TimeEvolutionSolver:
"""
Solver class that solves time evolution problem by either analog simulation on fermionic
hardware or trotterized time evolution on qubit hardware. The computation that this time
evolution solver will do depends on the type of the backend.
"""
MAPPER_DICT = {
"bravyi_kitaev": BravyiKitaevMapper(),
"jordan_wigner": JordanWignerMapper(),
"parity": ParityMapper(),
}
def __init__(
self,
backend,
map_type: str = None,
trotter_steps: int = None,
shots: int = 1000,
):
"""
Initialize a time evolution solver
Args:
backend: The backend on which to execute the problem, may be qubit or fermionic.
map_type: The fermion-to-qubit mapping required if a qubit backend is given
trotter_steps: The amount of trotter steps to approximate time evolution on
qubit backends
shots: number of measurements taken of the constructed circuits
"""
self.backend = backend
self.map_type = map_type
self.trotter_steps = trotter_steps
self.shots = shots
def solve(self, problem: FermionicEvolutionProblem) -> List[float]:
"""Solve the problem using the provided backend
Args:
problem: The FermionicEvolutionProblem to solve.
Returns:
A list of expectation values of the observable of the problem. This list has the
same length as the list of times for which to compute the time evolution.
"""
if isinstance(self.backend, BaseFermionBackend):
qc_load = self.backend.initialize_circuit(problem.initial_state.occupations)
circuits = problem.circuits(qc_load)
observable_evs = self.backend.measure_observable_expectation(
circuits, problem.observable, self.shots
)
else:
# use qubit pipeline
circuits = self.construct_qubit_circuits(problem)
mapper = self.MAPPER_DICT[self.map_type]
qubit_observable = mapper.map(problem.observable)
observable_evs = [
Statevector(qc).expectation_value(qubit_observable) for qc in circuits
]
return observable_evs
def construct_qubit_circuits(self, problem: FermionicEvolutionProblem) -> List[QuantumCircuit]:
"""Convert the problem to a trotterized qubit circuit using the specified map_type
Args:
problem: The fermionic evolution problem specifying the system, evolution-time
and observable to be measured
Returns:
a list of quantum circuits that simulate the time evolution.
There is one circuit for each evolution time specified in the problem'
"""
psi_0 = problem.initial_state
system = problem.system
hamiltonian = system.to_fermionic_op()
mapper = self.MAPPER_DICT[self.map_type]
circuits = []
# construct circuit of initial state:
label = {f"+_{i}": 1.0 for i, bit in enumerate(psi_0.occupations_flat) if bit}
bitstr_op = FermionicOp(label, num_spin_orbitals=len(psi_0.occupations_flat))
qubit_op = mapper.map(bitstr_op)[0]
init_circ = QuantumCircuit(QuantumRegister(qubit_op.num_qubits, "q"))
for i, pauli_label in enumerate(qubit_op.paulis.to_labels()[0][::-1]):
if pauli_label == "X":
init_circ.x(i)
elif pauli_label == "Y":
init_circ.y(i)
elif pauli_label == "Z":
init_circ.z(i)
for time in problem.evolution_times:
# map fermionic hamiltonian to qubits
qubit_hamiltonian = mapper.map(hamiltonian)
# construct trotterization circuits
evolution_problem = TimeEvolutionProblem(qubit_hamiltonian, time, init_circ)
trotter_qrte = TrotterQRTE(num_timesteps=self.trotter_steps)
evolved_state = trotter_qrte.evolve(evolution_problem).evolved_state
circuits.append(evolved_state)
return circuits
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
from collections import OrderedDict
import time
import logging, warnings
from qiskit.optimization.algorithms import CplexOptimizer
from qiskit.optimization.algorithms.optimization_algorithm import OptimizationResultStatus
from random_lp.lp_random_gen import create_models
from utilities.helpers import create_qaoa_meo
logger = logging.getLogger()
logger.setLevel(logging.INFO)
warnings.filterwarnings("ignore", category=DeprecationWarning)
DIR = 'TEST_DATA' + "/" + time.strftime("%d_%m_%Y")
DIR
qps = create_models([DIR + "/DENSE/", DIR + "/SPARSE/"])
print(qps.keys())
cplex = CplexOptimizer()
qaoa = create_qaoa_meo()
max_qubits = qaoa.min_eigen_solver.quantum_instance.backend.configuration().to_dict()['n_qubits']
max_qubits
results = OrderedDict()
for qp_name, qp in qps.items() :
print(qp_name)
print("number of qubits: ", qp.qubo.get_num_vars())
if qp.qubo.get_num_vars() > max_qubits:
print("Too many qubits!")
break
res = qaoa.solve(qp)
results[qp_name] = res
if res.status == OptimizationResultStatus.SUCCESS:
print("success")
cres = cplex.solve(qp)
if res.fval != cres.fval:
print("\n optimal value QAOA "+str(res.fval) + " , cplex:"+ str(cres.fval))
else:
print(res.status)
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
# General tools
import numpy as np
import matplotlib.pyplot as plt
# Qiskit Circuit Functions
from qiskit import execute,QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile
import qiskit.quantum_info as qi
# Tomography functions
from qiskit.ignis.verification.tomography import process_tomography_circuits, ProcessTomographyFitter
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
import warnings
warnings.filterwarnings('ignore')
target = QuantumCircuit(2)
#target = # YOUR CODE HERE
target.h(0)
target.h(1)
target.rx(np.pi/2,0)
target.rx(np.pi/2,1)
target.cx(0,1)
target.p(np.pi,1)
target.cx(0,1)
target_unitary = qi.Operator(target)
target.draw('mpl')
from qc_grader import grade_lab5_ex1
# Note that the grading function is expecting a quantum circuit with no measurements
grade_lab5_ex1(target)
simulator = Aer.get_backend('qasm_simulator')
qpt_circs = process_tomography_circuits(target,measured_qubits=[0,1])# YOUR CODE HERE
qpt_job = execute(qpt_circs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192)
qpt_result = qpt_job.result()
# YOUR CODE HERE
qpt_tomo= ProcessTomographyFitter(qpt_result,qpt_circs)
Choi_qpt= qpt_tomo.fit(method='lstsq')
fidelity = qi.average_gate_fidelity(Choi_qpt,target_unitary)
from qc_grader import grade_lab5_ex2
# Note that the grading function is expecting a floating point number
grade_lab5_ex2(fidelity)
# T1 and T2 values for qubits 0-3
T1s = [15000, 19000, 22000, 14000]
T2s = [30000, 25000, 18000, 28000]
# Instruction times (in nanoseconds)
time_u1 = 0 # virtual gate
time_u2 = 50 # (single X90 pulse)
time_u3 = 100 # (two X90 pulses)
time_cx = 300
time_reset = 1000 # 1 microsecond
time_measure = 1000 # 1 microsecond
from qiskit.providers.aer.noise import thermal_relaxation_error
from qiskit.providers.aer.noise import NoiseModel
# QuantumError objects
errors_reset = [thermal_relaxation_error(t1, t2, time_reset)
for t1, t2 in zip(T1s, T2s)]
errors_measure = [thermal_relaxation_error(t1, t2, time_measure)
for t1, t2 in zip(T1s, T2s)]
errors_u1 = [thermal_relaxation_error(t1, t2, time_u1)
for t1, t2 in zip(T1s, T2s)]
errors_u2 = [thermal_relaxation_error(t1, t2, time_u2)
for t1, t2 in zip(T1s, T2s)]
errors_u3 = [thermal_relaxation_error(t1, t2, time_u3)
for t1, t2 in zip(T1s, T2s)]
errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand(
thermal_relaxation_error(t1b, t2b, time_cx))
for t1a, t2a in zip(T1s, T2s)]
for t1b, t2b in zip(T1s, T2s)]
# Add errors to noise model
noise_thermal = NoiseModel()
for j in range(4):
noise_thermal.add_quantum_error(errors_measure[j],'measure',[j])
noise_thermal.add_quantum_error(errors_reset[j],'reset',[j])
noise_thermal.add_quantum_error(errors_u3[j],'u3',[j])
noise_thermal.add_quantum_error(errors_u2[j],'u2',[j])
noise_thermal.add_quantum_error(errors_u1[j],'u1',[j])
for k in range(4):
noise_thermal.add_quantum_error(errors_cx[j][k],'cx',[j,k])
# YOUR CODE HERE
from qc_grader import grade_lab5_ex3
# Note that the grading function is expecting a NoiseModel
grade_lab5_ex3(noise_thermal)
np.random.seed(0)
noise_qpt_circs = process_tomography_circuits(target,measured_qubits=[0,1])# YOUR CODE HERE
noise_qpt_job = execute(noise_qpt_circs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192,noise_model=noise_thermal)
noise_qpt_result = noise_qpt_job.result()
# YOUR CODE HERE
noise_qpt_tomo= ProcessTomographyFitter(noise_qpt_result,noise_qpt_circs)
noise_Choi_qpt= noise_qpt_tomo.fit(method='lstsq')
fidelity = qi.average_gate_fidelity(noise_Choi_qpt,target_unitary)
from qc_grader import grade_lab5_ex4
# Note that the grading function is expecting a floating point number
grade_lab5_ex4(fidelity)
np.random.seed(0)
# YOUR CODE HERE
#qr = QuantumRegister(2)
qubit_list = [0,1]
meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list)
meas_calibs_job = execute(meas_calibs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192,noise_model=noise_thermal)
cal_results = meas_calibs_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, qubit_list=qubit_list)
Cal_result = meas_fitter.filter.apply(noise_qpt_result)
# YOUR CODE HERE
Cal_qpt_tomo= ProcessTomographyFitter(Cal_result,noise_qpt_circs)
Cal_Choi_qpt= Cal_qpt_tomo.fit(method='lstsq')
fidelity = qi.average_gate_fidelity(Cal_Choi_qpt,target_unitary)
from qc_grader import grade_lab5_ex5
# Note that the grading function is expecting a floating point number
grade_lab5_ex5(fidelity)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 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.
"""Size pass testing"""
import unittest
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.passes import Size
from qiskit.test import QiskitTestCase
class TestSizePass(QiskitTestCase):
"""Tests for Depth analysis methods."""
def test_empty_dag(self):
"""Empty DAG has 0 size"""
circuit = QuantumCircuit()
dag = circuit_to_dag(circuit)
pass_ = Size()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["size"], 0)
def test_just_qubits(self):
"""A dag with 8 operations and no classic bits"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[1], qr[0])
dag = circuit_to_dag(circuit)
pass_ = Size()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["size"], 8)
def test_depth_one(self):
"""A dag with operations in parallel and size 2"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
dag = circuit_to_dag(circuit)
pass_ = Size()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["size"], 2)
def test_size_control_flow(self):
"""A DAG with control flow still gives an estimate."""
qc = QuantumCircuit(5, 1)
qc.h(0)
qc.measure(0, 0)
with qc.if_test((qc.clbits[0], True)) as else_:
qc.x(1)
qc.cx(2, 3)
with else_:
qc.x(1)
with qc.for_loop(range(3)):
qc.z(2)
with qc.for_loop((4, 0, 1)):
qc.z(2)
with qc.while_loop((qc.clbits[0], True)):
qc.h(0)
qc.measure(0, 0)
pass_ = Size(recurse=True)
pass_(qc)
self.assertEqual(pass_.property_set["size"], 19)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-nature-pyscf
|
qiskit-community
|
import qiskit_qasm3_import
project = 'Qiskit OpenQASM 3 Importer'
copyright = '2022, Jake Lishman'
author = 'Jake Lishman'
version = qiskit_qasm3_import.__version__
release = qiskit_qasm3_import.__version__
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
"reno.sphinxext",
'qiskit_sphinx_theme',
]
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# Document the docstring for the class and the __init__ method together.
autoclass_content = "both"
html_theme = "qiskit-ecosystem"
html_title = f"{project} {release}"
intersphinx_mapping = {
"qiskit-terra": ("https://docs.quantum.ibm.com/api/qiskit/", None),
}
|
https://github.com/AlphaMiyaL/Qiskit-Quantum-Journey
|
AlphaMiyaL
|
import qiskit
qiskit.__qiskit_version__
from qiskit import IBMQ
IBMQ.save_account('46fd3c15ef48cd5f5d6e4a8ae48748af512d2a57b1647282d61d7e98fda97a54d4be4ab8ff433fccd6613f9e30b3819a1aef9d6262f4980804cb2cd3952f7850')
IBMQ.load_account()
from qiskit import *
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr,cr)
%matplotlib inline
circuit.draw()
circuit.h(qr[0]) #hadamard gate
circuit.draw(output = 'mpl')
circuit.cx(qr[0],qr[1]) #controlled X gate
circuit.draw(output = 'mpl')
circuit.measure(qr,cr)
circuit.draw(output = 'mpl')
#setting up simulator
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend = simulator).result()
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
provider = IBMQ.get_provider('ibm-q')
# Get a list of available backends
backends = provider.backends()
# Print the names of available backends
print("Available Backends:", [backend.name() for backend in backends])
qcomp = provider.get_backend('ibm_osaka')
job = execute(circuit, backend = qcomp)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
results = job.result()
plot_histogram(results.get_counts(circuit))
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
from qiskit import *
from qiskit.circuit import Gate
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
from pprint import pprint
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
# unused for this file
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../../solutions/utils/")
import circuit_utils, zne_utils, tomography_utils
importlib.reload(circuit_utils)
importlib.reload(zne_utils) # unused for this file
importlib.reload(tomography_utils) # unused for this file
from circuit_utils import *
from zne_utils import zne_wrapper, zne_decoder
from tomography_utils import expvals_to_valid_rho
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps_list = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100]
print("trotter step list: ", num_steps_list)
scale_factors = [1.0, 2.0, 3.0] # unused for this file
shots = 1 << 13
reps = 8 # unused
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
# QREM
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# we have to feed initial_layout to calibration matrix
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
retrieved_cal_job = cal_job
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
qrem_fid_list = []
qrem_stddev_list = []
for num_steps in num_steps_list:
print("trotter steps: ", num_steps)
t1 = time.perf_counter()
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = t3_st_qcs
# zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False)
# print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
jobs = []
for _ in range(reps):
#! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
jobs.append(job)
retrieved_jobs = jobs
qrem_fids = []
for job in retrieved_jobs:
raw_results = job.result()
mit_results = meas_fitter.filter.apply(raw_results)
qrem_rho = StateTomographyFitter(mit_results, t3_zne_qcs).fit(method='lstsq')
qrem_fids.append(state_fidelity(qrem_rho, target_state))
qrem_fid_list.append(np.mean(qrem_fids))
qrem_stddev_list.append(np.std(qrem_fids))
t2 = time.perf_counter()
print('qrem state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(qrem_fids), np.std(qrem_fids)))
print("time:", t2 - t1)
print()
with open("e2d2_qrem.pkl", "wb") as f:
pickle.dump({"num_steps_list": num_steps_list, "fid": qrem_fid_list, "stddev": qrem_stddev_list}, f)
import qiskit.tools.jupyter
%qiskit_version_table
plt.plot(num_steps_list, qrem_fid_list)
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
print(qiskit.__version__)
from qiskit.aqua.algorithms import Shor
from qiskit.aqua import QuantumInstance
import numpy as np
from qiskit import QuantumCircuit, Aer, execute
from qiskit.tools.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend=backend, shots=1024)
my_shor = Shor(N=2189,a=4,quantum_instance=quantum_instance)
Shor.run(my_shor)
|
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
from qiskit import QuantumCircuit,IBMQ,execute, transpile,Aer
from qiskit.visualization import plot_circuit_layout
qc=QuantumCircuit(1)
qc.h(0)
qc.draw(output="mpl")
transpile_circuit=transpile(qc)
transpile_circuit.draw(output="mpl")
provider=IBMQ.load_account()
#Get the backend
backend=provider.get_backend('ibmq_bogota')
transpile_circuit=transpile(qc,backend)
transpile_circuit.draw(output="mpl")
backend.configuration().basis_gates
plot_circuit_layout(transpile_circuit, backend)
qc=QuantumCircuit(3)
qc.h(0)
qc.x(1)
qc.cx(0,2)
qc.draw(output="mpl")
qc.depth()
transpile_circuit=transpile(qc,backend)
transpile_circuit.draw(output="mpl")
transpile_circuit.depth()
plot_circuit_layout(transpile_circuit, backend)
transpile_circuit_0=transpile(qc,backend,optimization_level=0)
transpile_circuit_0.draw(output="mpl")
plot_circuit_layout(transpile_circuit_0, backend)
transpile_circuit_0.depth()
transpile_circuit_1=transpile(qc,backend,optimization_level=1)
transpile_circuit_1.draw(output="mpl")
plot_circuit_layout(transpile_circuit_1, backend)
transpile_circuit_1.depth()
transpile_circuit_2=transpile(qc,backend,optimization_level=2)
transpile_circuit_2.draw(output="mpl")
plot_circuit_layout(transpile_circuit_2, backend)
transpile_circuit_2.depth()
transpile_circuit_3=transpile(qc,backend,optimization_level=3)
transpile_circuit_3.draw(output="mpl")
plot_circuit_layout(transpile_circuit_3, backend)
transpile_circuit_3.depth()
from qiskit.tools.jupyter import *
backend
transpile_circuit_new=transpile(qc,backend,optimization_level=3,initial_layout=[2,3,4])
transpile_circuit_new.draw(output="mpl")
plot_circuit_layout(transpile_circuit_new, backend)
transpile_circuit_new=transpile(qc,backend,optimization_level=3,initial_layout=[0,2,3])
transpile_circuit_new.draw(output="mpl")
plot_circuit_layout(transpile_circuit_new, backend)
transpile_circuit_new.depth()
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
number = 5 # integer
real = -3.4 # float
name = 'Asja' # string
surname = "Sarkana" # string
boolean1 = True # Boolean
boolean2 = False # Boolean
a = 13
b = 5
print("a =",a)
print("b =",b)
print()
# basics operators
print("a + b =",a+b)
print("a - b =",a-b)
print("a * b =",a*b)
print("a / b =",a/b)
a = 13
b = 5
print("a =",a)
print("b =",b)
print()
print("integer division:")
print("a//b =",a//b)
print("modulus operator:")
print("a mod b =",a % b)
b = 5
print("b =",b)
print()
print("b*b =",b**2)
print("b*b*b =",b**3)
print("sqrt(b)=",b**0.5)
# list
mylist = [10,8,6,4,2]
print(mylist)
# tuple
mytuple=(1,4,5,'Asja')
print(mytuple)
# dictionary
mydictionary = {
'name' : "Asja",
'surname':'Sarkane',
'age': 23
}
print(mydictionary)
print(mydictionary['surname'])
# list of the other objects or variables
list_of_other_objects =[
mylist,
mytuple,
3,
"Asja",
mydictionary
]
print(list_of_other_objects)
# length of a string
print(len("Asja Sarkane"))
# size of a list
print(len([1,2,3,4]))
# size of a dictionary
mydictionary = { 'name' : "Asja", 'surname':'Sarkane', 'age': 23}
print(len(mydictionary))
i = 10
while i>0: # while condition(s):
print(i)
i = i - 1
for i in range(10): # i is in [0,1,...,9]
print(i)
for i in range(-5,6): # i is in [-5,-4,...,0,...,4,5]
print(i)
for i in range(0,23,4): # i is in [0,4,8,12,16,20]
print(i)
for i in [3,8,-5,11]:
print(i)
for i in "Sarkane":
print(i)
# dictionary
mydictionary = {
'name' : "Asja",
'surname':'Sarkane',
'age': 23,
}
for key in mydictionary:
print("key is",key,"and its value is",mydictionary[key])
for a in range(4,7):
# if condition(s)
if a<5:
print(a,"is less than 5")
# elif conditions(s)
elif a==5:
print(a,"is equal to 5")
# else
else:
print(a,"is greater than 5")
# Logical operator "and"
i = -3
j = 4
if i<0 and j > 0:
print(i,"is negative AND",j,"is positive")
# Logical operator "or"
i = -2
j = 2
if i==2 or j == 2:
print("i OR j is 2: (",i,",",j,")")
# Logical operator "not"
i = 3
if not (i==2):
print(i,"is NOT equal to 2")
# Operator "equal to"
i = -1
if i == -1:
print(i,"is EQUAL TO -1")
# Operator "not equal to"
i = 4
if i != 3:
print(i,"is NOT EQUAL TO 3")
# Operator "not equal to"
i = 2
if i <= 5:
print(i,"is LESS THAN OR EQUAL TO 5")
# Operator "not equal to"
i = 5
if i >= 1:
print(i,"is GREATER THAN OR EQUAL TO 3")
A =[
[1,2,3],
[-2,-4,-6],
[3,6,9]
]
# print all
print(A)
print()
# print each list in a new line
for list in A:
print(list)
list1 = [1,2,3]
list2 = [4,5,6]
#concatenation of two lists
list3 = list1 + list2
print(list3)
list4 = list2 + list1
print(list4)
list = [0,1,2]
list.append(3)
print(list)
list = list + [4]
print(list)
def summation_of_integers(n):
summation = 0
for integer in range(n+1):
summation = summation + integer
return summation
print(summation_of_integers(10))
print(summation_of_integers(20))
from random import randrange
print(randrange(10),"is picked randomly between 0 and 9")
print(randrange(-9,10),"is picked randomly between -9 and 9")
print(randrange(0,20,3),"is picked randomly from the list [0,3,6,9,12,15,18]")
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
import os
from qiskit import BasicAer
from qiskit.aqua import QuantumInstance, aqua_globals
from qiskit.aqua.algorithms import QAOA
from qiskit.aqua.components.optimizers import COBYLA
from qiskit.optimization.algorithms import MinimumEigenOptimizer, CplexOptimizer
from qiskit.optimization.algorithms.optimization_algorithm import OptimizationResultStatus
from qiskit.optimization import QuadraticProgram
Q_SEED = 10598 # as used in most issues
aqua_globals.random_seed = Q_SEED
shots = 4096
# select linear program to solve
path = os.path.dirname(__file__) + "/test_8.lp"
qp = QuadraticProgram()
qp.read_from_lp_file(path)
# init classical Optimizers
optimizer = COBYLA()
cplex = CplexOptimizer()
# solve classically
print(cplex.solve(qp))
# solve qp with Minimum Eigen Optimizer QAOA
backend = BasicAer.get_backend("qasm_simulator")
quantum_instance = QuantumInstance(
backend, seed_simulator=Q_SEED, seed_transpiler=Q_SEED, shots=shots
)
# QAOA
qaoa_mes = QAOA(quantum_instance=quantum_instance, optimizer=optimizer)
qaoa = MinimumEigenOptimizer(qaoa_mes)
res = qaoa.solve(qp)
print(res)
print(qp.is_feasible(res.x))
|
https://github.com/avkhadiev/schwinger-vqe
|
avkhadiev
|
from qiskit import *
import qiskit.tools.jupyter
import numpy as np
IBMQ.load_account()
from qiskit.aqua.components.variational_forms import VariationalForm
from qiskit.aqua.components.initial_states import Zero, VarFormBased
from qiskit.aqua.operators import MatrixOperator, TPBGroupedWeightedPauliOperator
from qiskit.aqua.operators.op_converter import to_tpb_grouped_weighted_pauli_operator
from qiskit.aqua.components.optimizers import SPSA
from qiskit.aqua.algorithms.adaptive import VQE
from scipy.sparse import *
from scipy import *
num_qubits = 3
num_var_params = 6
var_form_depth = 1
initial_params = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
class ConcatenatedSchwingerAnsatz(VariationalForm):
""" Variational Layer from Martin's Paper """
CONFIGURATION = {
'name': 'Schwinger Ansatz',
'description': 'Variational Form for Schwinger VQE',
'input_schema': {
'$schema': 'http://json-schema.org/draft-07/schema#',
'id': 'schwinger_schema',
'type': 'object',
'properties': {
'depth': {
'type': 'integer',
'default': 3,
'minimum': 1
},
'entangler_map': {
'type': ['array', 'null'],
'default': None
},
'entanglement_gate': {
'type': 'string',
'default': 'cx',
'enum': ['cx']
},
},
'additionalProperties': False
},
'depends': [
{
'pluggable_type': 'initial_state',
'default': {
'name': 'ZERO',
}
},
],
}
def __init__(self, depth=3, entangler_map=None, initial_state=None):
"""
Constructor.
Args:
depth (int) : number of rotation layers
entangler_map (list[list]): describe the connectivity of qubits, each list describes
[source, target], or None for full entanglement.
Note that the order is the list is the order of
applying the two-qubit gate.
initial_state (InitialState): an initial state object
"""
self.validate(locals())
super().__init__()
#_support_parameterized_circuit = True
# hard-coded, first pass through FIXME
num_qubits = 3
num_parameters = 6
entanglement='full'
entanglement_gate='cx'
skip_unentangled_qubits = False
self._num_qubits = num_qubits
self._depth = depth
if entangler_map is None:
self._entangler_map = VariationalForm.get_entangler_map(entanglement, num_qubits)
else:
self._entangler_map = VariationalForm.validate_entangler_map(entangler_map, num_qubits)
# determine the entangled qubits
all_qubits = []
for src, targ in self._entangler_map:
all_qubits.extend([src, targ])
self._entangled_qubits = sorted(list(set(all_qubits)))
self._initial_state = initial_state
self._entanglement_gate = entanglement_gate
self._skip_unentangled_qubits = skip_unentangled_qubits
# for the first layer
self._num_parameters = num_parameters
# for repeated block
self._num_parameters += num_parameters * (depth-1)
self._bounds = [(-np.pi, np.pi)] * self._num_parameters
def construct_circuit(self, parameters, q=None):
"""
Construct the variational form, given its parameters.
Args:
parameters (numpy.ndarray): circuit parameters
q (QuantumRegister): Quantum Register for the circuit.
Returns:
QuantumCircuit: a quantum circuit with given `parameters`
Raises:
ValueError: the number of parameters is incorrect.
"""
if len(parameters) != self._num_parameters:
raise ValueError('The number of parameters has to be {}'.format(self._num_parameters))
if q is None:
q = QuantumRegister(self._num_qubits, name='q')
if self._initial_state is not None:
circuit = self._initial_state.construct_circuit('circuit', q)
else:
circuit = QuantumCircuit(q)
#
param_idx = 0
def angle(theta=0., phi=0., lam=0.):
return [theta, phi, lam]
for _ in range(self._depth):
# get variational parameters for this layer
t0_1 = parameters[param_idx] # theta-angle values
t1_1 = parameters[param_idx+1]
t2_1 = parameters[param_idx+2]
t0_2 = parameters[param_idx] # theta-angle values
t1_2 = parameters[param_idx+1]
t2_3 = parameters[param_idx+2]
t1 = [angle(t_i) for t_i in [t0_1, t1_1, t2_1]]
t2 = [angle(t_i) for t_i in [t0_1, t1_1, t2_1]]
# FIRST
circuit.u3(*(t1[1]), 1) # u3(*angles, q)
circuit.u3(*(t1[0]), 2)
circuit.cx(1, 2) # entangling qubit cx(ctrl, tgt)
circuit.u3(*(t1[0]), 1)
circuit.cx(1, 2) # entangling qubit cx(ctrl, tgt)
circuit.u3(*(t1[2]), 2)
circuit.barrier(range(3))
# SECOND
circuit.cx(0,2)
#
circuit.u3(*(t2[1]), 1) # u3(*angles, q)
circuit.u3(*(t2[0]), 2)
circuit.cx(1, 2) # entangling qubit cx(ctrl, tgt)
circuit.u3(*(t2[0]), 1)
circuit.cx(1, 2) # entangling qubit cx(ctrl, tgt)
circuit.u3(*(t1[2]), 2)
#
circuit.cx(0,2)
circuit.barrier(range(3))
return circuit
schwinger_form = ConcatenatedSchwingerAnsatz(var_form_depth)
vqs_circ = schwinger_form.construct_circuit(initial_params)
vqs_circ.draw(output='latex', scale=0.5)
#qiskit.compiler.transpile(qc, basis_gates=['u3', 'cx'], optimization_level=3).draw(output='latex')
# even space
# [0.13028114, -1.18048464, 0.17737505]
# [ 0.12398951, -1.18068356, 0.15356187]
t0_1 = 0.13028114 # theta-angle values
t1_1 = -1.18048464
t2_1 = 0.17737505
# odd space
# [-0.30306561, -1.02142291, 0.15013751
# [ 2.8238186 , -5.22031494, 0.16478762]
t0_2 = 2.8238186
t1_2 = -5.22031494
t2_2 = 0.16478762
def angle(theta=0., phi=0., lam=0.):
return [theta, phi, lam]
t1 = [angle(t_i) for t_i in [t0_1, t1_1, t2_1]]
t2 = [angle(t_i) for t_i in [t0_2, t1_2, t2_2]]
# create registers
q = QuantumRegister(3, name="q")
c = ClassicalRegister(3, name="c")
regs = [q, c]
circ = QuantumCircuit(*regs, name="super+")
# FIRST
circ.u3(*(t1[1]), 1) # u3(*angles, q)
circ.u3(*(t1[0]), 2)
circ.cx(1, 2) # entangling qubit cx(ctrl, tgt)
circ.u3(*(t1[0]), 1)
circ.cx(1, 2) # entangling qubit cx(ctrl, tgt)
circ.u3(*(t1[2]), 2)
circ.barrier(range(3))
# SECOND
circ.cx(0,2)
#
circ.u3(*(t2[1]), 1) # u3(*angles, q)
circ.u3(*(t2[0]), 2)
circ.cx(1, 2) # entangling qubit cx(ctrl, tgt)
circ.u3(*(t2[0]), 1)
circ.cx(1, 2) # entangling qubit cx(ctrl, tgt)
circ.u3(*(t1[2]), 2)
#
circ.cx(0,2)
circ.barrier(range(3))
# MEAS
meas = QuantumCircuit(*regs, name="meas")
meas.measure(q, c)# map qubits to clbits
# Full circuit
qc = circ + meas
qc.draw(output='latex', scale=0.5, filename='my_circuit.png', plot_barriers=True, fold=40)
fiducial_state = Zero(num_qubits)
fid_circ = fiducial_state.construct_circuit()
fid_circ.draw(output='latex', scale=0.5)
var_form_wavefunction = VarFormBased(schwinger_form, initial_params)
var_form_wavefunction.construct_circuit().draw(output='latex', scale=0.5)
# these correspond to L=2 spatial sites.
# They have slightly different truncations so that the dimensions of the matrices are the same.
h = np.array([
[-0.20036, 1.19976, 0., 0., 0., 0., 0., 0.], #1
[1.19976, 1., 0.848358, 0., 0., 0., 0., 0.], #2
[0., 0.848358, 2.20036, 0.848358, 0., 0., 0., 0.], #3
[0., 0., 0.848358, 3., 0., 0., 0., 0.], #4
[0., 0., 0., 0., 1., 0.848358, 0., 0.], #5
[0., 0., 0., 0., 0.848358, 2.20036, -0.848358, 0.], #6
[0., 0., 0., 0., 0., -0.848358, 3., -0.848358], #7
[0., 0., 0., 0., 0., 0., -0.848358, 3.79964] #8
])
# trying different ordering?
h = np.array([
[-0.20036, 1.19976, 0., 0., 0., 0., 0., 0.], #1
[0., 0., 0., 0., 1., 0.848358, 0., 0.], #5
[0., 0.848358, 2.20036, 0.848358, 0., 0., 0., 0.], #3
[0., 0., 0., 0., 0., -0.848358, 3., -0.848358], #7
[1.19976, 1., 0.848358, 0., 0., 0., 0., 0.], #2
[0., 0., 0.848358, 3., 0., 0., 0., 0.], #4
[0., 0., 0., 0., 0.848358, 2.20036, -0.848358, 0.], #6
[0., 0., 0., 0., 0., 0., -0.848358, 3.79964] #8
])
H_mat = csr_matrix(h)
H_MatrixOperator = MatrixOperator(H_mat)
H_Operator = to_tpb_grouped_weighted_pauli_operator(H_MatrixOperator,
TPBGroupedWeightedPauliOperator.sorted_grouping)
print(H_Operator.print_details())
operator_mode=None
input_circuit=var_form_wavefunction.construct_circuit()
backend=None
qr=None
cr=None
use_simulator_operator_mode=False
use_simulator_snapshot_mode=False
wave_function=fid_circ
statevector_mode=False
input_circuit.draw(output='latex')
H_circs = H_Operator.construct_evaluation_circuit(input_circuit, # wavefunction
statevector_mode,
qr,
cr,
use_simulator_snapshot_mode)
H_circs[0].draw(output='latex', scale=0.5)
max_trials = 500
optimizer = qiskit.aqua.components.optimizers.SPSA(max_trials)
print(optimizer.setting)
# a callback that can access the intermediate data
# during the optimization.
# Internally, four arguments are provided as follows
# the index of evaluation, parameters of variational form,
# evaluated mean, evaluated standard deviation.
def simple_callback(eval_count, parameter_set, mean, std):
if eval_count % 1 == 0:
print('Energy evaluation %s returned %4f +/- %4f' % (eval_count, np.real(mean), np.real(std)))
# classVQE(operator, var_form, optimizer,
# operator_mode=None, initial_point=None,
# max_evals_grouped=1,
# aux_operators=None, callback=None,
# auto_conversion=True)
operator_mode = None
initial_point = initial_params
max_evals_grouped=1 # max number of evaluations performed simultaneously
aux_operators = None
auto_conversion=False
sim = VQE(H_Operator, schwinger_form, optimizer,
# operator_mode, not needed in the most recent version
initial_point,
max_evals_grouped,
aux_operators,
simple_callback,
auto_conversion)
backend = None
use_simulator_operator_mode=False
# is backend from AerProvider,
# if True and mode is paulis, single circuit is generated.
use_simulator_snapshot_mode=True
statevector_mode=False
sim_circs = sim.construct_circuit(initial_params,
statevector_mode,
use_simulator_snapshot_mode)
backend_sim = Aer.get_backend('qasm_simulator')
from qiskit.aqua import QuantumInstance
nshots = 1024
my_quantum_instance = QuantumInstance(backend_sim, nshots)
print(my_quantum_instance)
print(sim.print_settings())
res = sim.run(my_quantum_instance)
res
sim.get_optimal_vector()
sim.get_optimal_cost()
energy_eval = sim.get_optimal_cost()
energy_eval_err = 0.011
sim._ret['opt_params']
sim._energy_evaluation(sim._ret['opt_params'])
sim._energy_evaluation(sim._ret['opt_params'])
sim._energy_evaluation(sim._ret['opt_params'])
sim._energy_evaluation(sim._ret['opt_params'])
sim._energy_evaluation(sim._ret['opt_params'])
sim.quantum_instance.backend
sim.quantum_instance.run_config.shots
sim.quantum_instance.set_config(shots=1024, memory=True)
sim.quantum_instance.run_config
from qiskit.aqua.utils.run_circuits import find_regs_by_name
opt_circ = sim.get_optimal_circuit()
c = ClassicalRegister(opt_circ.width(), name='c')
q = find_regs_by_name(opt_circ, 'q')
opt_circ.add_register(c)
opt_circ.barrier(q)
opt_circ.measure(q, c)
opt_circ.draw(output='latex', filename='example_gate.png', scale=1.0)
# takes in results from a single circuit
# with memory=True, and estimates
# the uncertanities on the probability of each outcome
# (currently with bootstrap)
# returns outcome:(pba, std) dictionary
def compute_stats(res, invert_qubit_order = False):
# check that there is a single circuit in the results
# (ambiguous otherwise)
assert(len(res.results)==1)
# generates all possible outcomes given \
# the number of qubits
def _generate_bitstrings(nqubits, invert_qubit_order):
# (recursive, modifies all_strings in place)
def _generate_bitstrings_rec(nqubits, all_strings, a_string, irecur):
# base
if irecur == nqubits:
all_strings.append(''.join([bit for bit in a_string]))
return
# append 0
_generate_bitstrings_rec(nqubits, all_strings, a_string + ['0'], irecur + 1)
# append 1
_generate_bitstrings_rec(nqubits, all_strings, a_string + ['1'], irecur + 1)
all_strings = []
_generate_bitstrings_rec(nqubits, all_strings, [], 0)
if (invert_qubit_order):
# pesky Qiskit messes up qubit ordering... this may or may not be necessary to translate the results.
all_strings = [''.join(reversed(bitstring)) for bitstring in all_strings]
return all_strings
# bootstrap specific?
# given ensembles of outcomes and a particular outcome
# calculates the statistics of that outcome:
# returns outcome:(pba, std) estimates for the outcome
def _calc_outcome_stats(ensembles, nshots, outcome):
cts = np.count_nonzero(ensembles==outcome, axis=0)
pba = np.mean(cts)/nshots
std = np.std(cts/nshots, ddof = 1) # use unbiased estimator
return (pba, std)
nqubits = int(np.log2(len(res.get_counts(0)))) # pull number of qubits from results
outcomes = _generate_bitstrings(nqubits, invert_qubit_order)
mem = res.get_memory(0)
nshots = sum(list(res.get_counts(0).values()))
nens = nshots # choose number of ensemles = number of samples
nsam = nshots
ensembles = np.random.choice(mem, (nens, nsam))
stats = map(lambda outcome: (outcome, _calc_outcome_stats(ensembles, nshots, outcome)), outcomes)
return dict(stats)
sim.quantum_instance.set_config(shots=8*1024, memory=True)
opt_res = sim.quantum_instance.execute(opt_circ)
sim.quantum_instance.set_config(shots=8*1024, memory=False) # reset to no memory! saves resources?
from qiskit.visualization import plot_histogram
plot_histogram(opt_res.get_counts(opt_circ))
transp_circ = transpile(opt_circ, sim.quantum_instance.backend, optimization_level=3)
transp_circ.draw(output='latex', scale=0.5)
opt_circ.decompose().draw(output='latex', scale=0.5)
measured_coeffs =compute_stats(opt_res, False)
measured_coeffs
# compare with Mathematica's expectations
mathematica_res = -1.01162 # Even
mathematica_res2 = 0.486204 # Odd
# odd coefficients
even_coeffs = [0.669069, 0.305919, 0.023941, 0.00107068]
even_coeffs_at_theta = [0.664109, 0.309821, 0.0236388, 0.00243079]
odd_coeffs = [0.7041621406145364, 0.2582831083289985, 0.03524433188695736, 0.002310419169507747]
import matplotlib.pyplot as plt
outcomes = list(measured_coeffs.keys())
outcomes_bars = np.arange(len(outcomes))
avgs = [measured_coeffs[outcome][0] for outcome in outcomes]
stds = [measured_coeffs[outcome][1] for outcome in outcomes]
fig, ax = plt.subplots()
ax.bar(outcomes_bars, avgs, yerr=stds,
align='center', alpha=0.5, ecolor='black',
edgecolor='k',
error_kw=dict(lw=0.5, capsize=10, capthick=2.0),
label='IBM sim')
ax.set_ylabel(r'$|c_i|^2$', fontsize=16)
ax.set_xlabel(r'outcome', fontsize=16)
ax.set_xticks(outcomes_bars)
ax.set_xticklabels(outcomes)
ax.set_title('ibmqx2: $E \\pm \\Delta E = %.3f \\pm %.3f$\n($E = %.3f$ exact),\n nshots=%d'
% (energy_eval, energy_eval_err, mathematica_res,
sim.quantum_instance.run_config.shots), fontsize=16)
for icoeff in range(len(even_coeffs)):
ax.axhline(y = even_coeffs[icoeff], color ='red', linewidth = 0.5,
label=r'exact $|c_{%d}|^2 = %.3f$' % (icoeff+1, even_coeffs[icoeff]))
ax.axhline(y = even_coeffs_at_theta[icoeff], color ='green', linewidth = 0.5,
label=r'exact $|c(\theta)_{%d}|^2 = %.3f$''\n'r'vs measured $%.3f \pm %.3f$' % (icoeff+1, even_coeffs_at_theta[icoeff], *list(measured_coeffs.values())[icoeff]))
ax.set_yscale('log')
# plt.tight_layout()
plt.legend(frameon=False, fontsize=16, bbox_to_anchor=(1.04,1), loc="upper left")
plt.savefig("ibmqx2_log.png", dpi=300)
|
https://github.com/C2QA/bosonic-qiskit
|
C2QA
|
import numpy
import qiskit
import qiskit_aer
import scipy.linalg
import c2qa
# Define parameters
num_qubits_per_qumode = 2
cutoff = 2**num_qubits_per_qumode
alpha = numpy.sqrt(numpy.pi)
def displacement_operator(arg):
"""Create displacement operator matrix"""
a = numpy.diag(numpy.sqrt(range(1, cutoff)), k=1)
a_dag = a.conj().T
return scipy.linalg.expm((arg * a_dag) - (numpy.conjugate(arg) * a))
def displacemnt_gate(circuit, arg, qumode):
circuit.unitary(displacement_operator(arg), qumode)
def conditional_displacement_gate(circuit, arg_0, arg_1, qbit, qumode):
"""Append a conditional displacement to the circuit
Displace by arg_0 if qbit is 0, by arg_1 if qbit is 1."""
op_0 = displacement_operator(arg_0)
op_1 = displacement_operator(arg_1)
circuit.append(
qiskit.circuit.library.UnitaryGate(op_0).control(num_ctrl_qubits=1, ctrl_state=0),
[qbit] + qumode,
)
circuit.append(
qiskit.circuit.library.UnitaryGate(op_1).control(num_ctrl_qubits=1, ctrl_state=1),
[qbit] + qumode,
)
def qumode_initialize(circuit, fock_state, qumode):
"""Initialize the qumode to a Fock state."""
value = numpy.zeros((cutoff,))
value[fock_state] = 1
circuit.initialize(value, qumode)
def run_displacement_calibration(enable_measure):
"""
Run the simulation that has different state vector results on Windows vs Linux.
- Create the qumode register as a QuantumRegiser where n qubits represent a qumode.
- Create a QuantumRegister(1) to represent the control qubit.
- Initialize the qubits.
- Simulate the circuit.
"""
# Instantiate QisKit registers & circuit
qmr = qiskit.QuantumRegister(num_qubits_per_qumode) # qumode register
qr = qiskit.QuantumRegister(1)
cr = qiskit.ClassicalRegister(1)
circuit = qiskit.QuantumCircuit(qmr, qr, cr)
# Initialize the qumode Fock state
# qr[0] and cr[0] will init to zero
qumode_initialize(circuit, 0, qmr[0:])
circuit.h(qr[0])
conditional_displacement_gate(circuit, alpha, -alpha, qr[0], qmr[0:])
displacemnt_gate(circuit, 1j * alpha, qmr[0:])
conditional_displacement_gate(circuit, -alpha, alpha, qr[0], qmr[0:])
displacemnt_gate(circuit, -1j * alpha, qmr[0:])
circuit.h(qr[0])
circuit.save_statevector()
if enable_measure:
circuit.measure(qr[0], cr[0])
backend = qiskit_aer.AerSimulator()
circuit = qiskit.transpile(circuit, backend)
job = backend.run(circuit)
result = job.result()
state = result.get_statevector(circuit)
counts = result.get_counts(circuit)
assert state.dim > 0
assert counts
# print(state)
# print(counts.int_outcomes())
def test_displacement_calibration(capsys):
with capsys.disabled():
run_displacement_calibration(False)
run_displacement_calibration(True)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.drivers.second_quantization import GaussianForcesDriver
from qiskit_nature.problems.second_quantization import VibrationalStructureProblem
from qiskit_nature.settings import settings
settings.dict_aux_operators = True
driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
problem = VibrationalStructureProblem(driver, num_modals=[2, 2, 3, 4], truncation_order=2)
# Note: at this point, `driver.run()` has NOT been called yet. We can trigger this indirectly like so:
second_q_ops = problem.second_q_ops()
hamiltonian = second_q_ops["VibrationalEnergy"]
print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."]))
from qiskit_nature.second_q.drivers import GaussianForcesDriver
from qiskit_nature.second_q.problems import HarmonicBasis
driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
basis = HarmonicBasis(num_modals=[2, 2, 3, 4])
# this is now done explicitly and already requires the basis
problem = driver.run(basis=basis)
problem.hamiltonian.truncation_order = 2
hamiltonian = problem.hamiltonian.second_q_op()
print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."]))
from qiskit_nature.drivers.second_quantization import GaussianLogResult
from qiskit_nature.properties.second_quantization.vibrational.bases import HarmonicBasis
from qiskit_nature.settings import settings
settings.dict_aux_operators = True
log_result = GaussianLogResult("aux_files/CO2_freq_B3LYP_631g.log")
hamiltonian = log_result.get_vibrational_energy()
print(hamiltonian)
hamiltonian.basis = HarmonicBasis([2, 2, 3, 4])
op = hamiltonian.second_q_ops()["VibrationalEnergy"]
print("\n".join(str(op).splitlines()[:10] + ["..."]))
from qiskit_nature.second_q.drivers import GaussianLogResult
from qiskit_nature.second_q.formats import watson_to_problem
from qiskit_nature.second_q.problems import HarmonicBasis
log_result = GaussianLogResult("aux_files/CO2_freq_B3LYP_631g.log")
watson = log_result.get_watson_hamiltonian()
print(watson)
basis = HarmonicBasis(num_modals=[2, 2, 3, 4])
problem = watson_to_problem(watson, basis)
hamiltonian = problem.hamiltonian.second_q_op()
print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."]))
from qiskit_nature.drivers.second_quantization import GaussianForcesDriver
from qiskit_nature.problems.second_quantization import VibrationalStructureProblem
driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
problem = VibrationalStructureProblem(driver, num_modals=[2, 2, 3, 4], truncation_order=2)
# we trigger driver.run() implicitly like so:
second_q_ops = problem.second_q_ops()
hamiltonian_op = second_q_ops.pop("VibrationalEnergy")
aux_ops = second_q_ops
from qiskit_nature.second_q.drivers import GaussianForcesDriver
from qiskit_nature.second_q.problems import HarmonicBasis
driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
basis = HarmonicBasis(num_modals=[2, 2, 3, 4])
problem = driver.run(basis=basis)
problem.hamiltonian.truncation_order = 2
hamiltonian_op, aux_ops = problem.second_q_ops()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
| |
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
from qiskit import QuantumCircuit
qc=QuantumCircuit(3,3)
qc.h(0)
qc.x(1)
qc.cx(0,1)
qc.h(1)
qc.ccx(0,1,2)
qc.draw()
qc.draw(output='text')
qc.draw(output='mpl')
qc.draw(output='latex_source')
qc=QuantumCircuit(3,3)
qc.h(0)
qc.barrier()
qc.x(1)
qc.cx(0,1)
qc.h(1)
qc.barrier()
qc.ccx(0,1,2)
qc.draw(output="mpl")
qc=QuantumCircuit(3,3)
qc.h(0)
qc.barrier()
qc.x(1)
qc.cx(0,1)
qc.h(1)
qc.barrier()
qc.ccx(0,1,2)
qc.draw(output="mpl",plot_barriers=False)
qc=QuantumCircuit(3,3)
qc.h(0)
qc.barrier()
qc.x(1)
qc.cx(0,1)
qc.h(1)
qc.barrier()
qc.ccx(0,1,2)
qc.draw(output="mpl")
qc=QuantumCircuit(3,3)
qc.h(0)
qc.barrier()
qc.x(1)
qc.cx(0,1)
qc.h(1)
qc.barrier()
qc.ccx(0,1,2)
qc.draw(output="mpl",reverse_bits=True)
print(qc)
qc=QuantumCircuit(3,3)
qc.h(0)
qc.barrier()
qc.x(1)
qc.cx(0,1)
qc.h(1)
qc.barrier()
qc.ccx(0,1,2)
qc.draw(output="mpl",initial_state=True)
|
https://github.com/theflyingrahul/qiskitsummerschool2020
|
theflyingrahul
|
# -*- 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/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/rubenandrebarreiro/summer-school-on-quantum-computing-software-for-near-term-quantum-devices-2020
|
rubenandrebarreiro
|
# useful additional packages
import matplotlib.pyplot as plt
import copy
%matplotlib inline
import numpy as np
from qiskit import Aer
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE
from qiskit.circuit.library import TwoLocal
from qiskit.aqua.components.optimizers import SPSA
from qiskit.chemistry.core import Hamiltonian, TransformationType, QubitMappingType
from qiskit.chemistry.drivers import HDF5Driver
import warnings
warnings.filterwarnings('ignore')
# setup qiskit.chemistry logging
import logging
from qiskit.chemistry import set_qiskit_chemistry_logging
set_qiskit_chemistry_logging(logging.ERROR) # choose among DEBUG, INFO, WARNING, ERROR, CRITICAL and NOTSET
# from qiskit import IBMQ
# provider = IBMQ.load_account()
# First, we use classical eigendecomposition to get ground state energy (including nuclear repulsion energy) as reference.
driver = HDF5Driver('H2/H2_equilibrium_0.735_sto-3g.hdf5')
molecule = driver.run()
operator = Hamiltonian(transformation=TransformationType.FULL,
qubit_mapping=QubitMappingType.PARITY,
two_qubit_reduction=True,
freeze_core=False,
orbital_reduction=None)
qubit_op, aux_ops = operator.run(molecule)
result = NumPyMinimumEigensolver(qubit_op).run()
print('Ground state energy (classical): {:.12f}'.format(result.eigenvalue.real))
# Second, we use variational quantum eigensolver (VQE)
var_form = TwoLocal(qubit_op.num_qubits, ['ry', 'rz'], 'cz', reps=3, entanglement='full')
optimizer = SPSA(max_trials=350)
algo = VQE(qubit_op, var_form, optimizer, max_evals_grouped=1)
result = algo.run(QuantumInstance(Aer.get_backend('statevector_simulator')))
result = operator.process_algorithm_result(result)
print('Ground state energy (quantum) : {:.12f}'.format(result.energy))
print("====================================================")
# You can also print out other info
print(result)
# select H2 or LiH to experiment with
molecule='H2'
if molecule == 'LiH':
mol_distances = np.arange(0.6, 5.1, 0.1)
else:
mol_distances = np.arange(0.2, 4.1, 0.1)
algos = ['NumPyMinimumEigensolver', 'VQE']
energy = np.zeros((len(algos), len(mol_distances)))
for j, algo_name in enumerate(algos):
print("Using {}".format(algo_name))
for i, dis in enumerate(mol_distances):
print("Processing atomic distance: {:1.1f} Angstrom".format(dis), end='\r')
if molecule == 'LiH':
operator = Hamiltonian(transformation=TransformationType.FULL,
qubit_mapping=QubitMappingType.PARITY,
two_qubit_reduction=True,
freeze_core=True,
orbital_reduction=[-3, -2])
else:
operator = Hamiltonian(transformation=TransformationType.FULL,
qubit_mapping=QubitMappingType.PARITY,
two_qubit_reduction=True,
freeze_core=False,
orbital_reduction=None)
driver = HDF5Driver("{}/{:1.1f}_sto-3g.hdf5".format(molecule, dis))
qubit_op, aux_ops = operator.run(driver.run())
if algo_name == 'VQE':
if molecule == 'LiH':
var_form = TwoLocal(qubit_op.num_qubits, ['ry', 'rz'], 'cz', reps=5, entanglement='full')
optimizer = SPSA(max_trials=2500)
else:
var_form = TwoLocal(qubit_op.num_qubits, ['ry', 'rz'], 'cz', reps=3, entanglement='full')
optimizer = SPSA(max_trials=350)
algo = VQE(qubit_op, var_form, optimizer, max_evals_grouped=1)
result = algo.run(QuantumInstance(Aer.get_backend('qasm_simulator'), shots=1024))
else:
result = NumPyMinimumEigensolver(qubit_op).run()
result = operator.process_algorithm_result(result)
energy[j][i] = result.energy
print("\n")
for i, algo in enumerate(algos):
plt.plot(mol_distances, energy[i], label=algo)
plt.xlabel('Atomic distance (Angstrom)')
plt.ylabel('Energy')
plt.legend()
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/lynnlangit/learning-quantum
|
lynnlangit
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from numpy import pi
qreg_alice = QuantumRegister(1, 'alice')
qreg_fiber = QuantumRegister(1, 'fiber')
qreg_bob = QuantumRegister(1, 'bob')
creg_ahad = ClassicalRegister(1, 'ahad')
creg_aval = ClassicalRegister(1, 'aval')
creg_fval = ClassicalRegister(1, 'fval')
creg_bhad = ClassicalRegister(1, 'bhad')
creg_bval = ClassicalRegister(1, 'bval')
circuit = QuantumCircuit(qreg_alice, qreg_fiber, qreg_bob, creg_ahad, creg_aval, creg_fval, creg_bhad, creg_bval)
circuit.reset(qreg_alice[0])
circuit.h(qreg_alice[0])
circuit.measure(qreg_alice[0], creg_ahad[0])
circuit.reset(qreg_alice[0])
circuit.h(qreg_alice[0])
circuit.measure(qreg_alice[0], creg_aval[0])
circuit.reset(qreg_alice[0])
circuit.x(qreg_alice[0]).c_if(creg_aval, 1)
circuit.h(qreg_alice[0]).c_if(creg_ahad, 1)
circuit.swap(qreg_alice[0], qreg_fiber[0])
circuit.barrier(qreg_alice[0], qreg_fiber[0], qreg_bob[0])
circuit.h(qreg_fiber[0])
circuit.measure(qreg_fiber[0], creg_fval[0])
circuit.reset(qreg_fiber[0])
circuit.x(qreg_fiber[0]).c_if(creg_fval, 1)
circuit.h(qreg_fiber[0])
circuit.barrier(qreg_alice[0], qreg_fiber[0], qreg_bob[0])
circuit.reset(qreg_bob[0])
circuit.h(qreg_bob[0])
circuit.measure(qreg_bob[0], creg_bhad[0])
circuit.swap(qreg_fiber[0], qreg_bob[0])
circuit.h(qreg_bob[0]).c_if(creg_bhad, 1)
circuit.measure(qreg_bob[0], creg_bval[0])
editor = CircuitComposer(circuit=circuit)
editor
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
# Create a circuit with a register of three qubits
circ = QuantumCircuit(3)
# H gate on qubit 0, putting this qubit in a superposition of |0> + |1>.
circ.h(0)
# A CX (CNOT) gate on control qubit 0 and target qubit 1 generating a Bell state.
circ.cx(0, 1)
# CX (CNOT) gate on control qubit 0 and target qubit 2 resulting in a GHZ state.
circ.cx(0, 2)
# Draw the circuit
circ.draw('mpl')
|
https://github.com/Simultonian/hamilutor-qiskit
|
Simultonian
|
import pytest
from qiskit import QuantumCircuit
from ..trotter.simple import trotter
from ..utils import circuit_eq
from .bitwise_simple import bitwise_simple
import itertools
def test_bitwise_simple_single_group():
group = {"ix": 1.0, "xi": -1.0}
# Checking for multiple number of repetitions
for reps in range(1, 5):
result = bitwise_simple(group, t=1.0, reps=reps)
expected = QuantumCircuit(2)
for _ in range(reps):
# Rotation
expected.h(0)
expected.h(1)
# Exponentiate
circuit = trotter({"iz": 1.0, "zi": -1.0}, t=1.0 / reps)
expected = expected.compose(circuit)
# Anti-rotation
expected.h(0)
expected.h(1)
assert circuit_eq(result, expected)
two_group_hams = [
{"xx": 1.0, "zz": 2.0},
{"xx": 1.0, "zz": 2.0, "zi": 3.0},
{"xx": 1.0, "zz": 2.0, "zi": 3.0, "xy": 4.0},
]
two_group_groups = [
[
{"xx": 1.0},
{"zz": 2.0},
],
[
{"xx": 1.0},
{"zz": 2.0, "zi": 3.0},
],
[{"xx": 1.0}, {"zz": 2.0, "zi": 3.0}, {"xy": 4.0}],
]
two_num_qubits = [2, 2]
@pytest.mark.parametrize(
"h,groups,qubits", zip(two_group_hams, two_group_groups, two_num_qubits)
)
def test_bitwise_simple_multiple_groups(h, groups, qubits):
# Checking for multiple number of repetitions.
for reps in range(1, 5):
result = bitwise_simple(h, t=1.0, reps=reps)
# Runs reps loop and trotters individual group.
check = False
for order in itertools.permutations(groups):
expected = QuantumCircuit(qubits)
for _ in range(reps):
for group in order:
circuit = trotter(group, t=1.0 / reps)
expected = expected.compose(circuit)
check = check or circuit_eq(result, expected)
assert check
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test OptimizeSwapBeforeMeasure pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import OptimizeSwapBeforeMeasure, DAGFixedPoint
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TestOptimizeSwapBeforeMeasure(QiskitTestCase):
"""Test swap-followed-by-measure optimizations."""
def test_optimize_1swap_1measure(self):
"""Remove a single swap
qr0:--X--m-- qr0:----
| |
qr1:--X--|-- ==> qr1:--m-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.swap(qr[0], qr[1])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[1], cr[0])
pass_ = OptimizeSwapBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1swap_2measure(self):
"""Remove a single swap affecting two measurements
qr0:--X--m-- qr0:--m----
| | |
qr1:--X--|--m ==> qr1:--|--m-
| | | |
cr0:-----.--|-- cr0:--|--.-
cr1:--------.-- cr1:--.----
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.swap(qr[0], qr[1])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[1], cr[0])
expected.measure(qr[0], cr[1])
pass_ = OptimizeSwapBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_nswap_nmeasure(self):
"""Remove severals swap affecting multiple measurements
┌─┐ ┌─┐
q_0: ─X──X─────X────┤M├───────────────────────────────── q_0: ──────┤M├───────────────
│ │ │ └╥┘ ┌─┐ ┌─┐└╥┘
q_1: ─X──X──X──X──X──╫─────X────┤M├───────────────────── q_1: ───┤M├─╫────────────────
│ │ ║ │ └╥┘ ┌─┐ ┌─┐└╥┘ ║
q_2: ───────X──X──X──╫──X──X─────╫──X────┤M├──────────── q_2: ┤M├─╫──╫────────────────
│ ║ │ ║ │ └╥┘┌─┐ └╥┘ ║ ║ ┌─┐
q_3: ─X─────X──X─────╫──X──X──X──╫──X─────╫─┤M├───────── q_3: ─╫──╫──╫────┤M├─────────
│ │ ║ │ │ ║ ║ └╥┘┌─┐ ║ ║ ║ └╥┘ ┌─┐
q_4: ─X──X──X──X─────╫──X──X──X──╫──X─────╫──╫─┤M├────── ==> q_4: ─╫──╫──╫─────╫───────┤M├
│ │ ║ │ ║ │ ║ ║ └╥┘┌─┐ ║ ║ ║ ┌─┐ ║ └╥┘
q_5: ────X──X──X──X──╫──X──X─────╫──X──X──╫──╫──╫─┤M├─── q_5: ─╫──╫──╫─┤M├─╫────────╫─
│ │ ║ │ ║ │ ║ ║ ║ └╥┘┌─┐ ║ ║ ║ └╥┘ ║ ┌─┐ ║
q_6: ─X──X──X──X──X──╫──X──X─────╫─────X──╫──╫──╫──╫─┤M├ q_6: ─╫──╫──╫──╫──╫─┤M├────╫─
│ │ │ ║ │ ┌─┐ ║ ║ ║ ║ ║ └╥┘ ║ ║ ║ ║ ║ └╥┘┌─┐ ║
q_7: ─X──X─────X─────╫──X─┤M├────╫────────╫──╫──╫──╫──╫─ q_7: ─╫──╫──╫──╫──╫──╫─┤M├─╫─
║ └╥┘ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ └╥┘ ║
c: 8/════════════════╩═════╩═════╩════════╩══╩══╩══╩══╩═ c: 8/═╩══╩══╩══╩══╩══╩══╩══╩═
0 7 1 2 3 4 5 6 0 1 2 3 4 5 6 7
"""
circuit = QuantumCircuit(8, 8)
circuit.swap(3, 4)
circuit.swap(6, 7)
circuit.swap(0, 1)
circuit.swap(6, 7)
circuit.swap(4, 5)
circuit.swap(0, 1)
circuit.swap(5, 6)
circuit.swap(3, 4)
circuit.swap(1, 2)
circuit.swap(6, 7)
circuit.swap(4, 5)
circuit.swap(2, 3)
circuit.swap(0, 1)
circuit.swap(5, 6)
circuit.swap(1, 2)
circuit.swap(6, 7)
circuit.swap(4, 5)
circuit.swap(2, 3)
circuit.swap(3, 4)
circuit.swap(3, 4)
circuit.swap(5, 6)
circuit.swap(1, 2)
circuit.swap(4, 5)
circuit.swap(2, 3)
circuit.swap(5, 6)
circuit.measure(range(8), range(8))
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(8, 8)
expected.measure(0, 2)
expected.measure(1, 1)
expected.measure(2, 0)
expected.measure(3, 4)
expected.measure(4, 7)
expected.measure(5, 3)
expected.measure(6, 5)
expected.measure(7, 6)
pass_ = OptimizeSwapBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_cannot_optimize(self):
"""Cannot optimize when swap is not at the end in all of the successors
qr0:--X-----m--
| |
qr1:--X-[H]-|--
|
cr0:--------.--
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.swap(qr[0], qr[1])
circuit.h(qr[1])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
pass_ = OptimizeSwapBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(circuit), after)
def test_if_else(self):
"""Test that the pass recurses into a simple if-else."""
pass_ = OptimizeSwapBeforeMeasure()
base_test = QuantumCircuit(2, 1)
base_test.swap(0, 1)
base_test.measure(0, 0)
base_expected = QuantumCircuit(2, 1)
base_expected.measure(1, 0)
test = QuantumCircuit(2, 1)
test.if_else(
(test.clbits[0], True), base_test.copy(), base_test.copy(), test.qubits, test.clbits
)
expected = QuantumCircuit(2, 1)
expected.if_else(
(expected.clbits[0], True),
base_expected.copy(),
base_expected.copy(),
expected.qubits,
expected.clbits,
)
self.assertEqual(pass_(test), expected)
def test_nested_control_flow(self):
"""Test that the pass recurses into nested control flow."""
pass_ = OptimizeSwapBeforeMeasure()
base_test = QuantumCircuit(2, 1)
base_test.swap(0, 1)
base_test.measure(0, 0)
base_expected = QuantumCircuit(2, 1)
base_expected.measure(1, 0)
body_test = QuantumCircuit(2, 1)
body_test.for_loop((0,), None, base_expected.copy(), body_test.qubits, body_test.clbits)
body_expected = QuantumCircuit(2, 1)
body_expected.for_loop(
(0,), None, base_expected.copy(), body_expected.qubits, body_expected.clbits
)
test = QuantumCircuit(2, 1)
test.while_loop((test.clbits[0], True), body_test, test.qubits, test.clbits)
expected = QuantumCircuit(2, 1)
expected.while_loop(
(expected.clbits[0], True), body_expected, expected.qubits, expected.clbits
)
self.assertEqual(pass_(test), expected)
class TestOptimizeSwapBeforeMeasureFixedPoint(QiskitTestCase):
"""Test swap-followed-by-measure optimizations in a transpiler, using fixed point."""
def test_optimize_undone_swap(self):
"""Remove redundant swap
qr0:--X--X--m-- qr0:--m---
| | | |
qr1:--X--X--|-- ==> qr1:--|--
| |
cr0:--------.-- cr0:--.--
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.swap(qr[0], qr[1])
circuit.swap(qr[0], qr[1])
circuit.measure(qr[0], cr[0])
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_manager = PassManager()
pass_manager.append(
[OptimizeSwapBeforeMeasure(), DAGFixedPoint()],
do_while=lambda property_set: not property_set["dag_fixed_point"],
)
after = pass_manager.run(circuit)
self.assertEqual(expected, after)
def test_optimize_overlap_swap(self):
"""Remove two swaps that overlap
qr0:--X-------- qr0:--m--
| |
qr1:--X--X----- qr1:--|--
| ==> |
qr2:-----X--m-- qr2:--|--
| |
cr0:--------.-- cr0:--.--
"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.swap(qr[0], qr[1])
circuit.swap(qr[1], qr[2])
circuit.measure(qr[2], cr[0])
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_manager = PassManager()
pass_manager.append(
[OptimizeSwapBeforeMeasure(), DAGFixedPoint()],
do_while=lambda property_set: not property_set["dag_fixed_point"],
)
after = pass_manager.run(circuit)
self.assertEqual(expected, after)
def test_no_optimize_swap_with_condition(self):
"""Do not remove swap if it has a condition
qr0:--X--m-- qr0:--X--m--
| | | |
qr1:--X--|-- ==> qr1:--X--|--
| | | |
cr0:--1--.-- cr0:--1--.--
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.swap(qr[0], qr[1]).c_if(cr, 1)
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.swap(qr[0], qr[1]).c_if(cr, 1)
expected.measure(qr[0], cr[0])
pass_ = OptimizeSwapBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
import matplotlib.pyplot as plt
try:
import cplex
from cplex.exceptions import CplexError
except:
print("Warning: Cplex not found.")
import math
from qiskit.utils import algorithm_globals
from qiskit.algorithms.minimum_eigensolvers import SamplingVQE
from qiskit.algorithms.optimizers import SPSA
from qiskit.circuit.library import RealAmplitudes
from qiskit.primitives import Sampler
# Initialize the problem by defining the parameters
n = 3 # number of nodes + depot (n+1)
K = 2 # number of vehicles
# Get the data
class Initializer:
def __init__(self, n):
self.n = n
def generate_instance(self):
n = self.n
# np.random.seed(33)
np.random.seed(1543)
xc = (np.random.rand(n) - 0.5) * 10
yc = (np.random.rand(n) - 0.5) * 10
instance = np.zeros([n, n])
for ii in range(0, n):
for jj in range(ii + 1, n):
instance[ii, jj] = (xc[ii] - xc[jj]) ** 2 + (yc[ii] - yc[jj]) ** 2
instance[jj, ii] = instance[ii, jj]
return xc, yc, instance
# Initialize the problem by randomly generating the instance
initializer = Initializer(n)
xc, yc, instance = initializer.generate_instance()
class ClassicalOptimizer:
def __init__(self, instance, n, K):
self.instance = instance
self.n = n # number of nodes
self.K = K # number of vehicles
def compute_allowed_combinations(self):
f = math.factorial
return f(self.n) / f(self.K) / f(self.n - self.K)
def cplex_solution(self):
# refactoring
instance = self.instance
n = self.n
K = self.K
my_obj = list(instance.reshape(1, n**2)[0]) + [0.0 for x in range(0, n - 1)]
my_ub = [1 for x in range(0, n**2 + n - 1)]
my_lb = [0 for x in range(0, n**2)] + [0.1 for x in range(0, n - 1)]
my_ctype = "".join(["I" for x in range(0, n**2)]) + "".join(
["C" for x in range(0, n - 1)]
)
my_rhs = (
2 * ([K] + [1 for x in range(0, n - 1)])
+ [1 - 0.1 for x in range(0, (n - 1) ** 2 - (n - 1))]
+ [0 for x in range(0, n)]
)
my_sense = (
"".join(["E" for x in range(0, 2 * n)])
+ "".join(["L" for x in range(0, (n - 1) ** 2 - (n - 1))])
+ "".join(["E" for x in range(0, n)])
)
try:
my_prob = cplex.Cplex()
self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs)
my_prob.solve()
except CplexError as exc:
print(exc)
return
x = my_prob.solution.get_values()
x = np.array(x)
cost = my_prob.solution.get_objective_value()
return x, cost
def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs):
n = self.n
prob.objective.set_sense(prob.objective.sense.minimize)
prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype)
prob.set_log_stream(None)
prob.set_error_stream(None)
prob.set_warning_stream(None)
prob.set_results_stream(None)
rows = []
for ii in range(0, n):
col = [x for x in range(0 + n * ii, n + n * ii)]
coef = [1 for x in range(0, n)]
rows.append([col, coef])
for ii in range(0, n):
col = [x for x in range(0 + ii, n**2, n)]
coef = [1 for x in range(0, n)]
rows.append([col, coef])
# Sub-tour elimination constraints:
for ii in range(0, n):
for jj in range(0, n):
if (ii != jj) and (ii * jj > 0):
col = [ii + (jj * n), n**2 + ii - 1, n**2 + jj - 1]
coef = [1, 1, -1]
rows.append([col, coef])
for ii in range(0, n):
col = [(ii) * (n + 1)]
coef = [1]
rows.append([col, coef])
prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs)
# Instantiate the classical optimizer class
classical_optimizer = ClassicalOptimizer(instance, n, K)
# Print number of feasible solutions
print("Number of feasible solutions = " + str(classical_optimizer.compute_allowed_combinations()))
# Solve the problem in a classical fashion via CPLEX
x = None
z = None
try:
x, classical_cost = classical_optimizer.cplex_solution()
# Put the solution in the z variable
z = [x[ii] for ii in range(n**2) if ii // n != ii % n]
# Print the solution
print(z)
except:
print("CPLEX may be missing.")
# Visualize the solution
def visualize_solution(xc, yc, x, C, n, K, title_str):
plt.figure()
plt.scatter(xc, yc, s=200)
for i in range(len(xc)):
plt.annotate(i, (xc[i] + 0.15, yc[i]), size=16, color="r")
plt.plot(xc[0], yc[0], "r*", ms=20)
plt.grid()
for ii in range(0, n**2):
if x[ii] > 0:
ix = ii // n
iy = ii % n
plt.arrow(
xc[ix],
yc[ix],
xc[iy] - xc[ix],
yc[iy] - yc[ix],
length_includes_head=True,
head_width=0.25,
)
plt.title(title_str + " cost = " + str(int(C * 100) / 100.0))
plt.show()
if x is not None:
visualize_solution(xc, yc, x, classical_cost, n, K, "Classical")
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.algorithms import MinimumEigenOptimizer
class QuantumOptimizer:
def __init__(self, instance, n, K):
self.instance = instance
self.n = n
self.K = K
def binary_representation(self, x_sol=0):
instance = self.instance
n = self.n
K = self.K
A = np.max(instance) * 100 # A parameter of cost function
# Determine the weights w
instance_vec = instance.reshape(n**2)
w_list = [instance_vec[x] for x in range(n**2) if instance_vec[x] > 0]
w = np.zeros(n * (n - 1))
for ii in range(len(w_list)):
w[ii] = w_list[ii]
# Some variables I will use
Id_n = np.eye(n)
Im_n_1 = np.ones([n - 1, n - 1])
Iv_n_1 = np.ones(n)
Iv_n_1[0] = 0
Iv_n = np.ones(n - 1)
neg_Iv_n_1 = np.ones(n) - Iv_n_1
v = np.zeros([n, n * (n - 1)])
for ii in range(n):
count = ii - 1
for jj in range(n * (n - 1)):
if jj // (n - 1) == ii:
count = ii
if jj // (n - 1) != ii and jj % (n - 1) == count:
v[ii][jj] = 1.0
vn = np.sum(v[1:], axis=0)
# Q defines the interactions between variables
Q = A * (np.kron(Id_n, Im_n_1) + np.dot(v.T, v))
# g defines the contribution from the individual variables
g = (
w
- 2 * A * (np.kron(Iv_n_1, Iv_n) + vn.T)
- 2 * A * K * (np.kron(neg_Iv_n_1, Iv_n) + v[0].T)
)
# c is the constant offset
c = 2 * A * (n - 1) + 2 * A * (K**2)
try:
max(x_sol)
# Evaluates the cost distance from a binary representation of a path
fun = (
lambda x: np.dot(np.around(x), np.dot(Q, np.around(x)))
+ np.dot(g, np.around(x))
+ c
)
cost = fun(x_sol)
except:
cost = 0
return Q, g, c, cost
def construct_problem(self, Q, g, c) -> QuadraticProgram:
qp = QuadraticProgram()
for i in range(n * (n - 1)):
qp.binary_var(str(i))
qp.objective.quadratic = Q
qp.objective.linear = g
qp.objective.constant = c
return qp
def solve_problem(self, qp):
algorithm_globals.random_seed = 10598
vqe = SamplingVQE(sampler=Sampler(), optimizer=SPSA(), ansatz=RealAmplitudes())
optimizer = MinimumEigenOptimizer(min_eigen_solver=vqe)
result = optimizer.solve(qp)
# compute cost of the obtained result
_, _, _, level = self.binary_representation(x_sol=result.x)
return result.x, level
# Instantiate the quantum optimizer class with parameters:
quantum_optimizer = QuantumOptimizer(instance, n, K)
# Check if the binary representation is correct
try:
if z is not None:
Q, g, c, binary_cost = quantum_optimizer.binary_representation(x_sol=z)
print("Binary cost:", binary_cost, "classical cost:", classical_cost)
if np.abs(binary_cost - classical_cost) < 0.01:
print("Binary formulation is correct")
else:
print("Error in the binary formulation")
else:
print("Could not verify the correctness, due to CPLEX solution being unavailable.")
Q, g, c, binary_cost = quantum_optimizer.binary_representation()
print("Binary cost:", binary_cost)
except NameError as e:
print("Warning: Please run the cells above first.")
print(e)
qp = quantum_optimizer.construct_problem(Q, g, c)
quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp)
print(quantum_solution, quantum_cost)
# Put the solution in a way that is compatible with the classical variables
x_quantum = np.zeros(n**2)
kk = 0
for ii in range(n**2):
if ii // n != ii % n:
x_quantum[ii] = quantum_solution[kk]
kk += 1
# visualize the solution
visualize_solution(xc, yc, x_quantum, quantum_cost, n, K, "Quantum")
# and visualize the classical for comparison
if x is not None:
visualize_solution(xc, yc, x, classical_cost, n, K, "Classical")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit.circuit.library import LinearAmplitudeFunction
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import LogNormalDistribution
# number of qubits to represent the uncertainty
num_uncertainty_qubits = 3
# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity
# resulting parameters for log-normal distribution
mu = (r - 0.5 * vol**2) * T + np.log(S)
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2 / 2)
variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3 * stddev)
high = mean + 3 * stddev
# construct A operator for QAE for the payoff function by
# composing the uncertainty model and the objective
uncertainty_model = LogNormalDistribution(
num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high)
)
# plot probability distribution
x = uncertainty_model.values
y = uncertainty_model.probabilities
plt.bar(x, y, width=0.2)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.grid()
plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15)
plt.ylabel("Probability ($\%$)", size=15)
plt.show()
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price = 2.126
# set the approximation scaling for the payoff function
rescaling_factor = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [low, strike_price]
slopes = [-1, 0]
offsets = [strike_price - low, 0]
f_min = 0
f_max = strike_price - low
european_put_objective = LinearAmplitudeFunction(
num_uncertainty_qubits,
slopes,
offsets,
domain=(low, high),
image=(f_min, f_max),
breakpoints=breakpoints,
rescaling_factor=rescaling_factor,
)
# construct A operator for QAE for the payoff function by
# composing the uncertainty model and the objective
european_put = european_put_objective.compose(uncertainty_model, front=True)
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = uncertainty_model.values
y = np.maximum(0, strike_price - x)
plt.plot(x, y, "ro-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value (normalized to the [0, 1] interval)
exact_value = np.dot(uncertainty_model.probabilities, y)
exact_delta = -sum(uncertainty_model.probabilities[x <= strike_price])
print("exact expected value:\t%.4f" % exact_value)
print("exact delta value: \t%.4f" % exact_delta)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=european_put,
objective_qubits=[num_uncertainty_qubits],
post_processing=european_put_objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % exact_value)
print("Estimated value: \t%.4f" % (result.estimation_processed))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
# setup piecewise linear objective fcuntion
breakpoints = [low, strike_price]
slopes = [0, 0]
offsets = [1, 0]
f_min = 0
f_max = 1
european_put_delta_objective = LinearAmplitudeFunction(
num_uncertainty_qubits,
slopes,
offsets,
domain=(low, high),
image=(f_min, f_max),
breakpoints=breakpoints,
)
# construct circuit for payoff function
european_put_delta = european_put_delta_objective.compose(uncertainty_model, front=True)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=european_put_delta, objective_qubits=[num_uncertainty_qubits]
)
# construct amplitude estimation
ae_delta = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_delta = ae_delta.estimate(problem)
conf_int = -np.array(result_delta.confidence_interval)[::-1]
print("Exact delta: \t%.4f" % exact_delta)
print("Esimated value: \t%.4f" % -result_delta.estimation)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
import os
from qiskit import (QuantumCircuit,
QuantumRegister,
ClassicalRegister,
execute,
BasicAer)
from scipy.optimize import minimize
import matplotlib.pyplot as plt
from matplotlib.pyplot import plot, draw, show
import numpy as np
os.environ["QT_QPA_PLATFORM"] = "xcb"
def ansatz_H(theta):
qc = QuantumCircuit(2,2)
qc.x(0)
qc.ry(theta[0],0)
qc.rx(theta[0]+2*np.pi,1)
qc.cx(0,1)
qc.rz(theta[1],0)
qc.cx(0,1)
qc.ry(theta[0]+2*np.pi,0)
qc.rx(theta[0],1)
return qc
def expectation_H(theta):
# See DOI: 10.1103/PhysRevX.6.031007
# Here, we use parameters given for H2 at R=0.75A
g0 = -0.4804
g1 = +0.3435
g2 = -0.4347
g3 = +0.5716
g4 = +0.0910
g5 = +0.0910
energy = g0
qc = ansatz_H(theta)
qc.measure(0,0)
qc.measure(1,1)
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(qc, backend=backend, shots=shots).result()
counts = results.get_counts()
for key in counts.keys():
if(key[0]=='0'):
energy += g1*counts[key]/shots
else:
energy += -g1*counts[key]/shots
if(key[1]=='0'):
energy += g2*counts[key]/shots
else:
energy += -g2*counts[key]/shots
if(key[0]==key[1]):
energy += g3*counts[key]/shots
else:
energy += -g3*counts[key]/shots
qc = ansatz_H(theta)
qc.h(0)
qc.h(1)
qc.s(0)
qc.s(1)
qc.measure(0,0)
qc.measure(1,1)
results = execute(qc, backend=backend, shots=shots).result()
counts = results.get_counts()
for key in counts.keys():
if(key[0]==key[1]):
energy += g4*counts[key]/shots
else:
energy += -g4*counts[key]/shots
qc = ansatz_H(theta)
qc.h(0)
qc.h(1)
qc.measure(0,0)
qc.measure(1,1)
results = execute(qc, backend=backend, shots=shots).result()
counts = results.get_counts()
for key in counts.keys():
if(key[0]==key[1]):
energy += g5*counts[key]/shots
else:
energy += -g5*counts[key]/shots
return energy
nuclear_repulsion = 0.7055696146
theta = [4*np.pi*np.random.uniform(), 4*np.pi*np.random.uniform()]
result = minimize(expectation_H,theta, method='Nelder-Mead')
theta = result.x
val = result.fun
print("VQE: ")
print(" [+] theta1: {:+2.8} rad, theta2: {:+2.8} rad".format(theta[0],theta[1]))
print(" [+] energy: {:+2.8} Eh".format(val + nuclear_repulsion))
'''
import numpy as np
from scipy.linalg import block_diag
from scipy.optimize import minimize
np.set_printoptions(precision=4,suppress=True)
# Pauli matrices
I = np.array([[ 1, 0],
[ 0, 1]])
Sx = np.array([[ 0, 1],
[ 1, 0]])
Sy = np.array([[ 0,-1j],
[1j, 0]])
Sz = np.array([[ 1, 0],
[ 0,-1]])
# Hadamard matrix
H = (1/np.sqrt(2))*np.array([[ 1, 1],
[ 1,-1]])
# Phase matrix
S = np.array([[ 1, 0],
[ 0,1j]])
# single qubit basis states |0> and |1>
q0 = np.array([[1],
[0]])
q1 = np.array([[0],
[1]])
# Projection matrices |0><0| and |1><1|
P0 = np.dot(q0,q0.conj().T)
P1 = np.dot(q1,q1.conj().T)
# Rotation matrices as a function of theta, e.g. Rx(theta), etc.
Rx = lambda theta : np.array([[ np.cos(theta/2),-1j*np.sin(theta/2)],
[-1j*np.sin(theta/2), np.cos(theta/2)]])
Ry = lambda theta : np.array([[ np.cos(theta/2), -np.sin(theta/2)],
[ np.sin(theta/2), np.cos(theta/2)]])
Rz = lambda theta : np.array([[np.exp(-1j*theta/2), 0.0],
[ 0.0, np.exp(1j*theta/2)]])
# CNOTij, where i is control qubit and j is target qubit
CNOT10 = np.kron(P0,I) + np.kron(P1,Sx) # control -> q1, target -> q0
CNOT01 = np.kron(I,P0) + np.kron(Sx,P1) # control -> q0, target -> q1
SWAP = block_diag(1,Sx,1)
# See DOI: 10.1103/PhysRevX.6.031007
# Here, we use parameters given for H2 at R=0.75A
g0 = -0.4804
g1 = +0.3435
g2 = -0.4347
g3 = +0.5716
g4 = +0.0910
g5 = +0.0910
nuclear_repulsion = 0.7055696146
Hmol = (g0 * np.kron( I, I) + # g0 * I
g1 * np.kron( I,Sz) + # g1 * Z0
g2 * np.kron(Sz, I) + # g2 * Z1
g3 * np.kron(Sz,Sz) + # g3 * Z0Z1
g4 * np.kron(Sy,Sy) + # g4 * Y0Y1
g5 * np.kron(Sx,Sx)) # g5 * X0X1
electronic_energy = np.linalg.eigvalsh(Hmol)[0] # take the lowest value
print("Classical diagonalization: {:+2.8} Eh".format(electronic_energy + nuclear_repulsion))
print("Exact (from G16): {:+2.8} Eh".format(-1.1457416808))
# initial basis, put in |01> state with Sx operator on q0
psi0 = np.zeros((4,1))
psi0[0] = 1
psi0 = np.dot(np.kron(I,Sx),psi0)
# read right-to-left (bottom-to-top?)
ansatz = lambda theta: (np.dot(np.dot(np.kron(-Ry(np.pi/2),Rx(np.pi/2)),
np.dot(CNOT10,
np.dot(np.kron(I,Rz(theta)),
CNOT10))),
np.kron(Ry(np.pi/2),-Rx(np.pi/2))))
def projective_expected(theta,ansatz,psi0):
# this will depend on the hard-coded Hamiltonian + coefficients
circuit = ansatz(theta[0])
psi = np.dot(circuit,psi0)
# for 2 qubits, assume we can only take Pauli Sz measurements (Sz \otimes I)
# we just apply the right unitary for the desired Pauli measurement
measureZ = lambda U: np.dot(np.conj(U).T,np.dot(np.kron(Sz,I),U))
energy = 0.0
# although the paper indexes the hamiltonian left-to-right (0-to-1)
# qubit-1 is always the top qubit for us, so the tensor pdt changes
# e.g. compare with the "exact Hamiltonian" we explicitly diagonalized
# <I1 I0>
energy += g0 # it is a constant
# <I1 Sz0>
U = SWAP
energy += g1*np.dot(psi.conj().T,np.dot(measureZ(U),psi))
# <Sz1 I0>
U = np.kron(I,I)
energy += g2*np.dot(psi.conj().T,np.dot(measureZ(U),psi))
# <Sz1 Sz0>
U = CNOT01
energy += g3*np.dot(psi.conj().T,np.dot(measureZ(U),psi))
# <Sx1 Sx0>
U = np.dot(CNOT01,np.kron(H,H))
energy += g4*np.dot(psi.conj().T,np.dot(measureZ(U),psi))
# <Sy1 Sy0>
U = np.dot(CNOT01,np.kron(np.dot(H,S.conj().T),np.dot(H,S.conj().T)))
energy += g5*np.dot(psi.conj().T,np.dot(measureZ(U),psi))
return np.real(energy)[0,0]
theta = [0.0]
result = minimize(projective_expected,theta,args=(ansatz,psi0))
theta = result.x[0]
val = result.fun
# check it works...
#assert np.allclose(val + nuclear_repulsion,-1.1456295)
print("VQE: ")
print(" [+] theta: {:+2.8} deg".format(theta))
print(" [+] energy: {:+2.8} Eh".format(val + nuclear_repulsion))
'''
|
https://github.com/drobiu/quantum-project
|
drobiu
|
from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit
from Rui.query import query_cd
from src.arithmetic.counter import count
from src.arithmetic.increment import control_decrement
from src.logic.find_color_positions import FCP
from src.logic.oracles import oracle_a, oracle_b
from src.util.util import run_qc
q = QuantumRegister(3)
a = QuantumRegister(3)
c = ClassicalRegister(3)
qc = QuantumCircuit(q, a, c)
qc.x(a[0])
qc.x(a[2])
qc = count(qc, q, a)
# Should equal 010
qc.measure(q[:], c[:])
run_qc(qc)
qc.draw(output="mpl")
q = QuantumRegister(3)
a = QuantumRegister(8)
c = ClassicalRegister(3)
qc = QuantumCircuit(q, a, c)
qc.x(a[2:5])
qc.barrier()
qc = oracle_a(qc, a, q, [0, 1, 2, 3])
# Should equal 110
qc.measure(q[:], c[:])
run_qc(qc, with_QI=False)
qc.draw(output="mpl")
q = QuantumRegister(4)
a = QuantumRegister(3)
c = ClassicalRegister(3)
qc = QuantumCircuit(q, a, c)
qc.barrier()
qc = control_decrement(qc, a, q)
# Should equal 110
qc.measure(a[:], c[:])
run_qc(qc)
qc.draw(output="mpl")
query_cd().draw(output='text')
qy = QuantumRegister(8, name='qy')
y = QuantumRegister(4, name='y')
s = QuantumRegister(3)
c = ClassicalRegister(4)
qc = QuantumCircuit(y, qy, s, c)
# qc.x(qy[0])
qc = FCP(qc, y, qy, s, [0, 1, 1, 1], 2, 0)
qc.barrier()
qc.measure(y[:], c[:])
run_qc(qc, with_QI=False)
qc.draw(output="mpl")
q = QuantumRegister(8)
b = QuantumRegister(3)
c = ClassicalRegister(3)
qc = QuantumCircuit(q, b, c)
# 10, 11, 11, 11
qc.x(q[1])
qc.x(q[7])
qc.barrier()
# [0, 0, 0, 1] = 11, 11, 11, 10
qc.compose(oracle_b(qc, q, b, [0, 0, 0, 1]).to_gate(label='oracle_b'))
# Should equal 110
qc.measure(b[:], c[:])
run_qc(qc, with_QI=False)
qc.draw(output="mpl")
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 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.
# pylint: disable=invalid-name
"""Tests for Choi quantum channel representation class."""
import copy
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import QiskitError
from qiskit.quantum_info.states import DensityMatrix
from qiskit.quantum_info.operators.channel import Choi
from .channel_test_case import ChannelTestCase
class TestChoi(ChannelTestCase):
"""Tests for Choi channel representation."""
def test_init(self):
"""Test initialization"""
mat4 = np.eye(4) / 2.0
chan = Choi(mat4)
assert_allclose(chan.data, mat4)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
mat8 = np.eye(8) / 2.0
chan = Choi(mat8, input_dims=4)
assert_allclose(chan.data, mat8)
self.assertEqual(chan.dim, (4, 2))
self.assertIsNone(chan.num_qubits)
chan = Choi(mat8, input_dims=2)
assert_allclose(chan.data, mat8)
self.assertEqual(chan.dim, (2, 4))
self.assertIsNone(chan.num_qubits)
mat16 = np.eye(16) / 4
chan = Choi(mat16)
assert_allclose(chan.data, mat16)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(chan.num_qubits, 2)
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, Choi, mat8, input_dims=[4], output_dims=[4])
def test_circuit_init(self):
"""Test initialization from a circuit."""
circuit, target = self.simple_circuit_no_measure()
op = Choi(circuit)
target = Choi(target)
self.assertEqual(op, target)
def test_circuit_init_except(self):
"""Test initialization from circuit with measure raises exception."""
circuit = self.simple_circuit_with_measure()
self.assertRaises(QiskitError, Choi, circuit)
def test_equal(self):
"""Test __eq__ method"""
mat = self.rand_matrix(4, 4)
self.assertEqual(Choi(mat), Choi(mat))
def test_copy(self):
"""Test copy method"""
mat = np.eye(2)
with self.subTest("Deep copy"):
orig = Choi(mat)
cpy = orig.copy()
cpy._data[0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = Choi(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_clone(self):
"""Test clone method"""
mat = np.eye(4)
orig = Choi(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_is_cptp(self):
"""Test is_cptp method."""
self.assertTrue(Choi(self.depol_choi(0.25)).is_cptp())
# Non-CPTP should return false
self.assertFalse(Choi(1.25 * self.choiI - 0.25 * self.depol_choi(1)).is_cptp())
def test_conjugate(self):
"""Test conjugate method."""
# Test channel measures in Z basis and prepares in Y basis
# Zp -> Yp, Zm -> Ym
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Yp, Ym = np.array([[1, -1j], [1j, 1]]) / 2, np.array([[1, 1j], [-1j, 1]]) / 2
chan = Choi(np.kron(Zp, Yp) + np.kron(Zm, Ym))
# Conjugate channel swaps Y-basis states
targ = Choi(np.kron(Zp, Ym) + np.kron(Zm, Yp))
chan_conj = chan.conjugate()
self.assertEqual(chan_conj, targ)
def test_transpose(self):
"""Test transpose method."""
# Test channel measures in Z basis and prepares in Y basis
# Zp -> Yp, Zm -> Ym
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Yp, Ym = np.array([[1, -1j], [1j, 1]]) / 2, np.array([[1, 1j], [-1j, 1]]) / 2
chan = Choi(np.kron(Zp, Yp) + np.kron(Zm, Ym))
# Transpose channel swaps basis
targ = Choi(np.kron(Yp, Zp) + np.kron(Ym, Zm))
chan_t = chan.transpose()
self.assertEqual(chan_t, targ)
def test_adjoint(self):
"""Test adjoint method."""
# Test channel measures in Z basis and prepares in Y basis
# Zp -> Yp, Zm -> Ym
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Yp, Ym = np.array([[1, -1j], [1j, 1]]) / 2, np.array([[1, 1j], [-1j, 1]]) / 2
chan = Choi(np.kron(Zp, Yp) + np.kron(Zm, Ym))
# Ajoint channel swaps Y-basis elements and Z<->Y bases
targ = Choi(np.kron(Ym, Zp) + np.kron(Yp, Zm))
chan_adj = chan.adjoint()
self.assertEqual(chan_adj, targ)
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, Choi(np.eye(4)).compose, Choi(np.eye(8)))
self.assertRaises(QiskitError, Choi(np.eye(4)).compose, 2)
def test_compose(self):
"""Test compose method."""
# UnitaryChannel evolution
chan1 = Choi(self.choiX)
chan2 = Choi(self.choiY)
chan = chan1.compose(chan2)
targ = Choi(self.choiZ)
self.assertEqual(chan, targ)
# 50% depolarizing channel
chan1 = Choi(self.depol_choi(0.5))
chan = chan1.compose(chan1)
targ = Choi(self.depol_choi(0.75))
self.assertEqual(chan, targ)
# Measure and rotation
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Xp, Xm = np.array([[1, 1], [1, 1]]) / 2, np.array([[1, -1], [-1, 1]]) / 2
chan1 = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
chan2 = Choi(self.choiX)
# X-gate second does nothing
targ = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
self.assertEqual(chan1.compose(chan2), targ)
self.assertEqual(chan1 & chan2, targ)
# X-gate first swaps Z states
targ = Choi(np.kron(Zm, Xp) + np.kron(Zp, Xm))
self.assertEqual(chan2.compose(chan1), targ)
self.assertEqual(chan2 & chan1, targ)
# Compose different dimensions
chan1 = Choi(np.eye(8) / 4, input_dims=2, output_dims=4)
chan2 = Choi(np.eye(8) / 2, input_dims=4, output_dims=2)
chan = chan1.compose(chan2)
self.assertEqual(chan.dim, (2, 2))
chan = chan2.compose(chan1)
self.assertEqual(chan.dim, (4, 4))
def test_dot(self):
"""Test dot method."""
# UnitaryChannel evolution
chan1 = Choi(self.choiX)
chan2 = Choi(self.choiY)
targ = Choi(self.choiZ)
self.assertEqual(chan1.dot(chan2), targ)
self.assertEqual(chan1 @ chan2, targ)
# 50% depolarizing channel
chan1 = Choi(self.depol_choi(0.5))
targ = Choi(self.depol_choi(0.75))
self.assertEqual(chan1.dot(chan1), targ)
self.assertEqual(chan1 @ chan1, targ)
# Measure and rotation
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Xp, Xm = np.array([[1, 1], [1, 1]]) / 2, np.array([[1, -1], [-1, 1]]) / 2
chan1 = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
chan2 = Choi(self.choiX)
# X-gate second does nothing
targ = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
self.assertEqual(chan2.dot(chan1), targ)
self.assertEqual(chan2 @ chan1, targ)
# X-gate first swaps Z states
targ = Choi(np.kron(Zm, Xp) + np.kron(Zp, Xm))
self.assertEqual(chan1.dot(chan2), targ)
self.assertEqual(chan1 @ chan2, targ)
# Compose different dimensions
chan1 = Choi(np.eye(8) / 4, input_dims=2, output_dims=4)
chan2 = Choi(np.eye(8) / 2, input_dims=4, output_dims=2)
chan = chan1.dot(chan2)
self.assertEqual(chan.dim, (4, 4))
chan = chan1 @ chan2
self.assertEqual(chan.dim, (4, 4))
chan = chan2.dot(chan1)
self.assertEqual(chan.dim, (2, 2))
chan = chan2 @ chan1
self.assertEqual(chan.dim, (2, 2))
def test_compose_front(self):
"""Test front compose method."""
# UnitaryChannel evolution
chan1 = Choi(self.choiX)
chan2 = Choi(self.choiY)
chan = chan1.compose(chan2, front=True)
targ = Choi(self.choiZ)
self.assertEqual(chan, targ)
# 50% depolarizing channel
chan1 = Choi(self.depol_choi(0.5))
chan = chan1.compose(chan1, front=True)
targ = Choi(self.depol_choi(0.75))
self.assertEqual(chan, targ)
# Measure and rotation
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Xp, Xm = np.array([[1, 1], [1, 1]]) / 2, np.array([[1, -1], [-1, 1]]) / 2
chan1 = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
chan2 = Choi(self.choiX)
# X-gate second does nothing
chan = chan2.compose(chan1, front=True)
targ = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
self.assertEqual(chan, targ)
# X-gate first swaps Z states
chan = chan1.compose(chan2, front=True)
targ = Choi(np.kron(Zm, Xp) + np.kron(Zp, Xm))
self.assertEqual(chan, targ)
# Compose different dimensions
chan1 = Choi(np.eye(8) / 4, input_dims=2, output_dims=4)
chan2 = Choi(np.eye(8) / 2, input_dims=4, output_dims=2)
chan = chan1.compose(chan2, front=True)
self.assertEqual(chan.dim, (4, 4))
chan = chan2.compose(chan1, front=True)
self.assertEqual(chan.dim, (2, 2))
def test_expand(self):
"""Test expand method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = Choi(self.choiI)
chan2 = Choi(self.choiX)
# X \otimes I
chan = chan1.expand(chan2)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan2.expand(chan1)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
chan_dep = Choi(self.depol_choi(1))
chan = chan_dep.expand(chan_dep)
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_tensor(self):
"""Test tensor method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = Choi(self.choiI)
chan2 = Choi(self.choiX)
# X \otimes I
rho_targ = DensityMatrix(np.kron(rho1, rho0))
chan = chan2.tensor(chan1)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan2 ^ chan1
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
rho_targ = DensityMatrix(np.kron(rho0, rho1))
chan = chan1.tensor(chan2)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan1 ^ chan2
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
chan_dep = Choi(self.depol_choi(1))
chan = chan_dep.tensor(chan_dep)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan_dep ^ chan_dep
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_power(self):
"""Test power method."""
# 10% depolarizing channel
p_id = 0.9
depol = Choi(self.depol_choi(1 - p_id))
# Compose 3 times
p_id3 = p_id**3
chan3 = depol.power(3)
targ3 = Choi(self.depol_choi(1 - p_id3))
self.assertEqual(chan3, targ3)
def test_add(self):
"""Test add method."""
mat1 = 0.5 * self.choiI
mat2 = 0.5 * self.depol_choi(1)
chan1 = Choi(mat1)
chan2 = Choi(mat2)
targ = Choi(mat1 + mat2)
self.assertEqual(chan1._add(chan2), targ)
self.assertEqual(chan1 + chan2, targ)
targ = Choi(mat1 - mat2)
self.assertEqual(chan1 - chan2, targ)
def test_add_qargs(self):
"""Test add method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = Choi(mat)
op0 = Choi(mat0)
op1 = Choi(mat1)
op01 = op1.tensor(op0)
eye = Choi(self.choiI)
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op + op01([0, 1])
target = op + eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op + op01([1, 0])
target = op + eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op + op01([0, 2])
target = op + op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op + op01([2, 0])
target = op + op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_sub_qargs(self):
"""Test subtract method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = Choi(mat)
op0 = Choi(mat0)
op1 = Choi(mat1)
op01 = op1.tensor(op0)
eye = Choi(self.choiI)
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op - op01([0, 1])
target = op - eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op - op01([1, 0])
target = op - eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op - op01([0, 2])
target = op - op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op - op01([2, 0])
target = op - op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_add_except(self):
"""Test add method raises exceptions."""
chan1 = Choi(self.choiI)
chan2 = Choi(np.eye(8))
self.assertRaises(QiskitError, chan1._add, chan2)
self.assertRaises(QiskitError, chan1._add, 5)
def test_multiply(self):
"""Test multiply method."""
chan = Choi(self.choiI)
val = 0.5
targ = Choi(val * self.choiI)
self.assertEqual(chan._multiply(val), targ)
self.assertEqual(val * chan, targ)
targ = Choi(self.choiI * val)
self.assertEqual(chan * val, targ)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
chan = Choi(self.choiI)
self.assertRaises(QiskitError, chan._multiply, "s")
self.assertRaises(QiskitError, chan.__rmul__, "s")
self.assertRaises(QiskitError, chan._multiply, chan)
self.assertRaises(QiskitError, chan.__rmul__, chan)
def test_negate(self):
"""Test negate method"""
chan = Choi(self.choiI)
targ = Choi(-1 * self.choiI)
self.assertEqual(-chan, targ)
if __name__ == "__main__":
unittest.main()
|
https://github.com/TanveshT/IBM-Quantum-Challenge
|
TanveshT
|
from may4_challenge.ex4 import get_unitary
U = get_unitary()
print(U)
print("U has shape", U.shape)
from qiskit import QuantumCircuit, Aer, QuantumRegister
from may4_challenge.ex4 import check_circuit, submit_circuit
from qiskit.compiler import transpile
from qiskit.extensions.quantum_initializer.isometry import Isometry
from qiskit.quantum_info import Operator
import numpy as np
from scipy.linalg import hadamard
from qiskit.quantum_info.operators.predicates import is_isometry
##### build your quantum circuit here
qc = QuantumCircuit(4)
# apply operations to your quantum circuit here
def recursiveKronecker(k, hmat):
if 2**(k-1) == 1:
return hmat
else:
return np.kron(hmat, recursiveKronecker(k-1, hmat))
h2 = np.matrix([[1,1],[1,-1]])
h2 = h2/(2**0.5)
h = recursiveKronecker(4, h2)
v = h*U*h
qc.h([0,1,2,3])
qc.isometry(v,[0,1,2,3],[])
qc.h([0,1,2,3])
sim = Aer.get_backend('qasm_simulator')
new_qc = transpile(qc,
backend = sim,
seed_transpiler=11,
optimization_level=2,
basis_gates = ['u3','cx'])
qc_basis = new_qc.decompose()
qc.draw()
##### check your quantum circuit by running the next line
check_circuit(qc_basis)
# Send the circuit as the final answer, can re-submit at any time
submit_circuit(qc_basis)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 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.
"""Tests for the converters."""
import math
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import Gate, Qubit
from qiskit.quantum_info import Operator
from qiskit.test import QiskitTestCase
from qiskit.exceptions import QiskitError
class TestCircuitToGate(QiskitTestCase):
"""Test QuantumCircuit to Gate"""
def test_simple_circuit(self):
"""test simple circuit"""
qr1 = QuantumRegister(4, "qr1")
qr2 = QuantumRegister(3, "qr2")
qr3 = QuantumRegister(3, "qr3")
circ = QuantumCircuit(qr1, qr2, qr3)
circ.cx(qr1[1], qr2[2])
gate = circ.to_gate()
q = QuantumRegister(10, "q")
self.assertIsInstance(gate, Gate)
self.assertEqual(gate.definition[0].qubits, (q[1], q[6]))
def test_circuit_with_registerless_bits(self):
"""Test a circuit with registerless bits can be converted to a gate."""
qr1 = QuantumRegister(2)
qubits = [Qubit(), Qubit(), Qubit()]
qr2 = QuantumRegister(3)
circ = QuantumCircuit(qr1, qubits, qr2)
circ.cx(3, 5)
gate = circ.to_gate()
self.assertIsInstance(gate, Gate)
self.assertEqual(gate.num_qubits, len(qr1) + len(qubits) + len(qr2))
gate_definition = gate.definition
cx = gate_definition.data[0]
self.assertEqual(cx.qubits, (gate_definition.qubits[3], gate_definition.qubits[5]))
self.assertEqual(cx.clbits, ())
def test_circuit_with_overlapping_registers(self):
"""Test that the conversion works when the given circuit has bits that are contained in more
than one register."""
qubits = [Qubit() for _ in [None] * 10]
qr1 = QuantumRegister(bits=qubits[:6])
qr2 = QuantumRegister(bits=qubits[4:])
circ = QuantumCircuit(qubits, qr1, qr2)
circ.cx(3, 5)
gate = circ.to_gate()
self.assertIsInstance(gate, Gate)
self.assertEqual(gate.num_qubits, len(qubits))
gate_definition = gate.definition
cx = gate_definition.data[0]
self.assertEqual(cx.qubits, (gate_definition.qubits[3], gate_definition.qubits[5]))
self.assertEqual(cx.clbits, ())
def test_raises(self):
"""test circuit which can't be converted raises"""
circ1 = QuantumCircuit(3)
circ1.x(0)
circ1.cx(0, 1)
circ1.barrier()
circ2 = QuantumCircuit(1, 1)
circ2.measure(0, 0)
circ3 = QuantumCircuit(1)
circ3.x(0)
circ3.reset(0)
with self.assertRaises(QiskitError): # TODO: accept barrier
circ1.to_gate()
with self.assertRaises(QiskitError): # measure and reset are not valid
circ2.to_gate()
def test_generated_gate_inverse(self):
"""Test inverse of generated gate works."""
qr1 = QuantumRegister(2, "qr1")
circ = QuantumCircuit(qr1)
circ.cx(qr1[1], qr1[0])
gate = circ.to_gate()
out_gate = gate.inverse()
self.assertIsInstance(out_gate, Gate)
def test_to_gate_label(self):
"""Test label setting."""
qr1 = QuantumRegister(2, "qr1")
circ = QuantumCircuit(qr1, name="a circuit name")
circ.cx(qr1[1], qr1[0])
gate = circ.to_gate(label="a label")
self.assertEqual(gate.label, "a label")
def test_zero_operands(self):
"""Test that a gate can be created, even if it has zero operands."""
base = QuantumCircuit(global_phase=math.pi)
gate = base.to_gate()
self.assertEqual(gate.num_qubits, 0)
self.assertEqual(gate.num_clbits, 0)
self.assertEqual(gate.definition, base)
compound = QuantumCircuit(1)
compound.append(gate, [], [])
np.testing.assert_allclose(-np.eye(2), Operator(compound), atol=1e-16)
|
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
|
ronitd2002
|
from qiskit import QuantumCircuit
# Create a new circuit with a single qubit
qc = QuantumCircuit(1)
# Add a Not gate to qubit 0
qc.x(0)
# Return a drawing of the circuit using MatPlotLib ("mpl"). This is the
# last line of the cell, so the drawing appears in the cell output.
qc.draw("mpl")
### CHECK QISKIT VERSION
import qiskit
qiskit.__version__
### CHECK OTHER DEPENDENCIES
%pip show pylatexenc matplotlib qc_grader
#qc-grader should be 0.18.8 (or higher)
### Imports
from qiskit import QuantumCircuit
from qiskit.quantum_info import SparsePauliOp
from qiskit_ibm_runtime import EstimatorV2 as Estimator
from qiskit_aer import AerSimulator
import matplotlib.pyplot as plt
from qc_grader.challenges.iqc_2024 import grade_lab0_ex1
# Create a new circuit with two qubits
qc = QuantumCircuit(2)
# Add a Hadamard gate to qubit 0
qc.h(0)
# Perform a CNOT gate on qubit 1, controlled by qubit 0
qc.cx(0, 1)
# Return a drawing of the circuit using MatPlotLib ("mpl"). This is the
# last line of the cell, so the drawing appears in the cell output.
qc.draw("mpl")
# The ZZ applies a Z operator on qubit 0, and a Z operator on qubit 1
ZZ = SparsePauliOp('ZZ')
# The ZI applies a Z operator on qubit 0, and an Identity operator on qubit 1
ZI = SparsePauliOp('ZI')
# The IX applies an Identity operator on qubit 0, and an X operator on qubit 1
IX = SparsePauliOp('IX')
### Write your code below here ###
IZ = SparsePauliOp('IZ')
XX = SparsePauliOp('XX')
XI = SparsePauliOp('XI')
### Follow the same naming convention we used above
## Don't change any code past this line, but remember to run the cell.
observables = [IZ, IX, ZI, XI, ZZ, XX]
# Submit your answer using following code
grade_lab0_ex1(observables)
# Set up the Estimator
estimator = Estimator(backend=AerSimulator())
# Submit the circuit to Estimator
pub = (qc, observables)
job = estimator.run(pubs=[pub])
# Collect the data
data = ['IZ', 'IX', 'ZI', 'XI', 'ZZ', 'XX']
values = job.result()[0].data.evs
# Set up our graph
container = plt.plot(data, values, '-o')
# Label each axis
plt.xlabel('Observables')
plt.ylabel('Values')
# Draw the final graph
plt.show()
container = plt.bar(data, values, width=0.8)
plt.xlabel('Observables')
plt.ylabel('Values')
plt.show()
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
from crypto.six_state.participant import Participant
from qiskit import QuantumCircuit
from numpy.random import rand
from qiskit import transpile
## The Receiver entity in the Six-State implementation
## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html
class Receiver(Participant):
## Constructor
def __init__(self, name='', original_bits_size=0):
super().__init__(name, original_bits_size)
## Decode the message measuring the circuit (density-dependent)
def decode_quantum_message(self, message, density, backend):
## The values of the participant
self.values = []
for i, qc in enumerate(message):
qc.barrier()
if rand() < density:
if self.axes[i] == 1:
qc.h(0)
elif self.axes[i] == 2:
qc.append(self.hy, [0])
qc.measure(0, 0)
transpiled_qc = transpile(qc, backend=backend)
result = backend.run(transpiled_qc, shots=1, memory=True).result()
measured_bit = int(result.get_memory()[0])
self.values.append(measured_bit)
else:
self.values.append(-1)
return message
|
https://github.com/Alice-Bob-SW/qiskit-alice-bob-provider
|
Alice-Bob-SW
|
import pytest
from qiskit import QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit_alice_bob_provider.local.quantum_errors import (
build_quantum_error_passes,
)
from qiskit_alice_bob_provider.processor.description import (
ProcessorDescription,
)
from .processor_fixture import (
AllToAllProcessorWithQubitInstruction,
QubitProcessorWithAllToAllInstruction,
SimpleAllToAllProcessor,
SimpleProcessor,
)
def test_noise_not_on_all_qubits() -> None:
circ = QuantumCircuit(3)
for i in range(3):
circ.y(i)
pm = PassManager(build_quantum_error_passes(SimpleProcessor()))
transpiled = pm.run(circ)
# Y noise was only activated on qubits 0 and 1
y_errors = transpiled.get_instructions('y_error')
assert len(y_errors) == 2
qubits = {circ.find_bit(e.qubits[0])[0] for e in y_errors}
assert qubits == {0, 1}
@pytest.mark.parametrize(
'proc', [SimpleProcessor(), SimpleAllToAllProcessor()]
)
def test_noise_on_initialize(proc: ProcessorDescription) -> None:
circ = QuantumCircuit(3)
circ.initialize('+', 0)
circ.initialize('-', 1)
circ.initialize('0', 2)
pm = PassManager(build_quantum_error_passes(proc))
transpiled = pm.run(circ)
for label, n_qubits, index in [
('p+_error', 1, 0),
('p-_error', 0, 0),
('p0_error', 1, 2),
('p1_error', 0, 0),
]:
errors = transpiled.get_instructions(label)
assert len(errors) == n_qubits
if n_qubits == 1:
qubit = circ.find_bit(errors[0].qubits[0]).index
assert qubit == index
@pytest.mark.parametrize(
'proc', [SimpleProcessor(), SimpleAllToAllProcessor()]
)
def test_noise_on_mx(proc: ProcessorDescription) -> None:
circ = QuantumCircuit(3, 3)
circ.measure_x(0, 0)
circ.measure_x(1, 1)
circ.measure(2, 2)
pm = PassManager(build_quantum_error_passes(proc))
transpiled = pm.run(circ)
# Only qubits 0 and 1 had a measure in the x basis
mx_errors = transpiled.get_instructions('mx_error')
assert len(mx_errors) == 2
qubits = {circ.find_bit(e.qubits[0])[0] for e in mx_errors}
assert qubits == {0, 1}
@pytest.mark.parametrize(
'proc', [SimpleProcessor(), SimpleAllToAllProcessor()]
)
def test_pass_with_none_chi_matrix(proc: ProcessorDescription) -> None:
circ = QuantumCircuit(10)
circ.x(0)
pm = PassManager(build_quantum_error_passes(proc))
transpiled = pm.run(circ)
assert len(transpiled.get_instructions('x_error')) == 0
@pytest.mark.parametrize(
'proc', [SimpleProcessor(), SimpleAllToAllProcessor()]
)
def test_chi_vs_pauli_errors(proc: ProcessorDescription) -> None:
pm = PassManager(build_quantum_error_passes(proc))
# Circuit with diagonal chi matrix -> quantum channel of Pauli errors
circ = QuantumCircuit(10)
circ.y(0)
transpiled = pm.run(circ)
assert len(transpiled.decompose().get_instructions('quantum_channel')) == 1
# Circuit with none diagonal chi matrix -> Kraus map
circ = QuantumCircuit(10)
circ.h(0)
transpiled = pm.run(circ)
print(transpiled.decompose())
assert len(transpiled.decompose().get_instructions('kraus')) == 1
@pytest.mark.parametrize(
'proc',
[
AllToAllProcessorWithQubitInstruction(),
QubitProcessorWithAllToAllInstruction(),
],
)
def test_bad_instruction_with_processor_type(
proc: ProcessorDescription,
) -> None:
with pytest.raises(ValueError):
PassManager(build_quantum_error_passes(proc))
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit.circuit import Parameter
from qiskit import pulse
from qiskit.test.mock.backends.almaden import *
phase = Parameter('phase')
with pulse.build(FakeAlmaden()) as phase_test_sched:
pulse.shift_phase(phase, pulse.drive_channel(0))
phase_test_sched.instructions # ()
|
https://github.com/hritiksauw199/Qiskit-textbook-solutions
|
hritiksauw199
|
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, transpile, assemble
from qiskit.visualization import plot_histogram
from qiskit_textbook.tools import simon_oracle
# The function simon_oracle (imported above) creates a Simon oracle for the bitstring b
# Simon_Oracle
def simon_gen_oracle(b):
# to create copies of first register to second register
for i in range(n):
circ.cx(i, n+i) #change the name of variable 'circ' depending on what you name your circuit
# appying cx based on b
k=0
for i in range(n-1, -1, -1): #reading the character of b in reverse order
if b[i] == '1': #if there is a '1' in b, because if there is a '0' we leave it unchanged
m = n #we assign the value of n to some variable m
for j in range(n-1, -1, -1):
if b[j] == '1': #if we encounter '1' then we implement cx with respect to those b which are '1'
circ.cx(k, m)
m+=1
break
k+=1 # when the bitstring is not '1', we increment k by 1 and go to next bit
n = 4
b = '1001'
circ = QuantumCircuit(n*2, n)
circ.h(range(n))
circ.barrier()
simon_gen_oracle(b)
circ.barrier()
circ.h(range(n))
circ.measure(range(n), range(n))
circ.draw()
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
shots = 1024
qobj = assemble(circ, shots=shots)
results = aer_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
# Calculate the dot product of the results
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_1 = '1001'
n = len(b_1)
simon_circuit = QuantumCircuit(n*2, n)
# Apply Hadamard gates before querying the oracle
simon_circuit.h(range(n))
# Apply barrier for visual separation
simon_circuit.barrier()
simon_circuit += simon_oracle(b_1)
# Apply barrier for visual separation
simon_circuit.barrier()
# Apply Hadamard gates to the input register
simon_circuit.h(range(n))
# Measure qubits
simon_circuit.measure(range(n), range(n))
simon_circuit.draw()
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
shots = 1024
qobj = assemble(simon_circuit, shots=shots)
results = aer_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
# Calculate the dot product of the results
def bdotz(b_1, z):
accum = 0
for i in range(len(b_1)):
accum += int(b_1[i]) * int(z[i])
return (accum % 2)
for z in counts:
print( '{}.{} = {} (mod 2)'.format(b_1, z, bdotz(b_1,z), ) )
|
https://github.com/eleyeth/Quantum-computing
|
eleyeth
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
# Build
#------
# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(2, 2)
# Add a H gate on qubit 0
circuit.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(0, 1)
# Map the quantum measurement to the classical bits
circuit.measure([0,1], [0,1])
# Execute
#--------
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator
job = execute(circuit, simulator, shots=1000)
# Grab results from the job
result = job.result()
# Return counts
counts = result.get_counts(circuit)
print("\nTotal count for 00 and 11 are:",counts)
# Analyze
#--------
# Draw the circuit
circuit.draw()
# Analyze
#--------
# Plot a histogram
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-dell-runtime
|
qiskit-community
|
from dell_runtime import DellRuntimeProvider
from qiskit import QuantumCircuit
import logging
import requests
import time
import os
RUNTIME_PROGRAM = """
# This code is part of qiskit-runtime.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
from qiskit.compiler import transpile, schedule
def main(
backend,
user_messenger,
circuits,
**kwargs,
):
circuits = transpile(
circuits,
)
user_messenger.publish({'results': 'intermittently'}, final=False)
if not isinstance(circuits, list):
circuits = [circuits]
# Compute raw results using either simulator or QPU backend.
result = backend.run(circuits, **kwargs).result()
user_messenger.publish(result.to_dict(), final=True)
"""
RUNTIME_PROGRAM_METADATA = {
"max_execution_time": 600,
"description": "Qiskit test program"
}
PROGRAM_PREFIX = 'qiskit-test'
REMOTE_RUNTIME = os.getenv("SERVER_URL")
logging.basicConfig(level=logging.DEBUG)
provider = DellRuntimeProvider()
program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA)
print(f"PROGRAM ID: {program_id}")
programs = provider.runtime.pprint_programs(refresh=True)
provider.runtime.update_program(program_id, description="IBM/Dell Updated Qiskit Runtime Program")
programs = provider.runtime.pprint_programs(refresh=True)
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
program_inputs = {
'circuits': qc,
}
job = provider.runtime.run(program_id, options=None, inputs=program_inputs)
results = job.result(timeout=60)
print(results)
def callback_function(msg):
print(f'******************\n\n\nFrom Callback Function: {msg}\n\n\n******************')
job = provider.runtime.run(program_id, inputs=program_inputs, options=None, callback=callback_function)
program_inputs['backend_name'] = 'emulator'
job = provider.runtime.run(program_id, inputs=program_inputs, options=None, callback=callback_function)
from dell_runtime import DellRuntimeProvider
from qiskit import QuantumCircuit
import logging
import requests
import time
import os
RUNTIME_PROGRAM = """
# This code is part of qiskit-runtime.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
from qiskit.compiler import transpile, schedule
def main(
backend,
user_messenger,
circuits,
**kwargs,
):
circuits = transpile(
circuits,
)
user_messenger.publish({'results': 'intermittently'}, final=False)
if not isinstance(circuits, list):
circuits = [circuits]
# Compute raw results
result = backend.run(circuits, **kwargs).result()
user_messenger.publish(result.to_dict(), final=True)
"""
RUNTIME_PROGRAM_METADATA = {
"max_execution_time": 600,
"description": "Qiskit test program"
}
PROGRAM_PREFIX = 'qiskit-test'
REMOTE_RUNTIME = os.getenv("SERVER_URL")
logging.basicConfig(level=logging.DEBUG)
provider = DellRuntimeProvider()
provider.remote(REMOTE_RUNTIME)
text_program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA)
print(f"PROGRAM ID: {text_program_id}")
programs = provider.runtime.pprint_programs(refresh=True)
provider.runtime.update_program(text_program_id, description="IBM/Dell Updated Qiskit Runtime Program")
programs = provider.runtime.pprint_programs(refresh=True)
file_program_id = provider.runtime.upload_program("qka.py", description="File Upload to Orchestrator")
dir_program_id = provider.runtime.upload_program("./qkad", description="Directory Upload to Orchestrator")
provider.runtime.pprint_programs(refresh=True)
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
program_inputs = {
'circuits': qc,
}
job = provider.runtime.run(text_program_id, options=None, inputs=program_inputs)
results = job.result(timeout=60)
print(results)
program_inputs['backend_name'] = 'emulator'
job = provider.runtime.run(text_program_id, inputs=program_inputs, options=None, callback=callback_function)
results = job.result(timeout=600)
print(results)
from dell_runtime import DellRuntimeProvider
from qiskit import QuantumCircuit
import pandas as pd
from time import sleep
import os
import base64
import shutil
import json
provider = DellRuntimeProvider()
RUNTIME_PROGRAM_METADATA = {
"max_execution_time": 600,
"description": "Qiskit test program"
}
provider.remote(os.getenv("SERVER_URL"))
here = os.path.dirname(os.path.realpath(__file__))
program_id = provider.runtime.upload_program(here + "../examples/programs/qkad", metadata=RUNTIME_PROGRAM_METADATA)
job = provider.runtime.run(program_id, options=None, inputs={})
res = job.result(timeout=1000)
print(res)
from qiskit.opflow import Z, I
from qiskit.circuit.library import EfficientSU2
import numpy as np
from qiskit.algorithms.optimizers import SPSA
from dell_runtime import DellRuntimeProvider
import os
from time import sleep
from datetime import datetime, timedelta
num_qubits = 4
hamiltonian = (Z ^ Z) ^ (I ^ (num_qubits - 2))
target_energy = -1
# the rotation gates are chosen randomly, so we set a seed for reproducibility
ansatz = EfficientSU2(num_qubits, reps=1, entanglement='linear', insert_barriers=True)
# ansatz.draw('mpl', style='iqx')
optimizer = SPSA(maxiter=50)
np.random.seed(10) # seed for reproducibility
initial_point = np.random.random(ansatz.num_parameters)
intermediate_info = {
'nfev': [],
'parameters': [],
'energy': [],
'stddev': []
}
timestamps = []
def raw_callback(*args):
(nfev, parameters, energy, stddev) = args[0]
intermediate_info['nfev'].append(nfev)
intermediate_info['parameters'].append(parameters)
intermediate_info['energy'].append(energy)
intermediate_info['stddev'].append(stddev)
vqe_inputs = {
'ansatz': ansatz,
'operator': hamiltonian,
'optimizer': {'name': 'SPSA', 'maxiter': 15}, # let's only do a few iterations!
'initial_point': initial_point,
'measurement_error_mitigation': True,
'shots': 1024,
# Include this parameter to use the snapshot instruction and return the ideal outcome
# that has no shot noise and avoids using the statevector simulator.
# 'include_custom': True
}
provider = DellRuntimeProvider()
provider.remote(os.getenv("SERVER_URL"))
program_id = provider.runtime.upload_program("vqe.py", description="Variational Quantum Eigensolver Program")
job = provider.runtime.run(
program_id=program_id,
inputs=vqe_inputs,
options=None,
callback=raw_callback
)
print('Job ID:', job.job_id)
result = job.result()
while not result:
print('no result yet.')
sleep(0.5)
result = job.result()
print(f"Intermediate Results: {intermediate_info}")
print(f'Reached {result["optimal_value"]} after {result["optimizer_evals"]} evaluations.')
print('Available keys:', list(result.keys()))
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.wrapper import available_backends, get_backend
from qiskit.wrapper import execute as q_execute
q = QuantumRegister(2, name='q')
c = ClassicalRegister(2, name='c')
qc = QuantumCircuit(q,c)
qc.h(q[0])
qc.h(q[1])
qc.cx(q[0], q[1])
qc.measure(q, c)
z = 0.995004165 + 1j * 0.099833417
z = z / abs(z)
u_error = np.array([[1, 0], [0, z]])
noise_params = {'U':
{'gate_time': 1,
'p_depol': 0.001,
'p_pauli': [0, 0, 0.01],
'U_error': u_error
}
}
config = {"noise_params": noise_params}
ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config)
ret = ret.result()
print(ret.get_counts())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.measure(0, 0)
qc.x(0).c_if(cr, 0)
qc.measure(0, 0)
qc.draw('mpl')
|
https://github.com/drithidavuluri/Implementation-of-Algorithm-using-Qiskit
|
drithidavuluri
|
# initialization
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, execute
from qiskit.tools.jupyter import *
provider = IBMQ.load_account()
# import basic plot tools
from qiskit.visualization import plot_histogram
def dj_oracle(case, n):
# Making a quantum circuit with n+1 qubit(size of input + output)
oracle_qc = QuantumCircuit(n+1)
# oracle is balanced
if case == "balanced":
# apply controlled-not gate for each qubit using output qubit as the target
for qubit in range(n):
oracle_qc.cx(qubit, n) # acts as parity checker(even number of 1s = 0, odd = 1), to make sure half of the input map to zero and half maps to 1.
# oracle is constant
if case == "constant":
# decide a random integer between 0 or 1
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle"
return oracle_gate
def dj_algorithm(n, case = 'random'):
dj_circuit = QuantumCircuit(n+1, n) # n+1 qubit, n calssical bits
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.x(n)
dj_circuit.h(n)
if case == 'random':
random = np.random.randint(2)
if random == 0:
case = 'constant'
else:
case = 'balanced'
oracle = dj_oracle(case, n)
dj_circuit.append(oracle, range(n+1))
for i in range(n):
dj_circuit.h(i)
dj_circuit.measure(i,i)
return dj_circuit
n = 4
dj_circuit = dj_algorithm(n)
dj_circuit.draw("mpl")
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
dj_circuit = dj_algorithm(n, 'constant')
results = execute(dj_circuit, backend=backend, shots=1).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/qiskit-community/qiskit-qcgpu-provider
|
qiskit-community
|
import unittest
import math
from qiskit_qcgpu_provider import QCGPUProvider
from qiskit import execute, QuantumRegister, QuantumCircuit, BasicAer
from qiskit.quantum_info import state_fidelity
from .case import MyTestCase
class TestStatevectorSimulator(MyTestCase):
"""Test the state vector simulator"""
def test_computations(self):
for n in range(2, 10):
circ = self.random_circuit(n, 5)
self._compare_outcomes(circ)
def _compare_outcomes(self, circ):
Provider = QCGPUProvider()
backend_qcgpu = Provider.get_backend('statevector_simulator')
statevector_qcgpu = execute(circ, backend_qcgpu).result().get_statevector()
backend_qiskit = BasicAer.get_backend('statevector_simulator')
statevector_qiskit = execute(circ, backend_qiskit).result().get_statevector()
self.assertAlmostEqual(state_fidelity(statevector_qcgpu, statevector_qiskit), 1, 5)
if __name__ == '__main__':
unittest.main()
|
https://github.com/kdk/qiskit-timeline-debugger
|
kdk
|
from qiskit import QuantumCircuit
from qiskit.converters import dag_to_circuit, circuit_to_dag
from numpy import zeros, uint16
# make the global DP array
LCS_DP = zeros((2000, 2000), dtype=uint16)
class CircuitComparator:
@staticmethod
def get_moments(dag):
moments = [l["graph"] for l in list(dag.layers())]
return moments
@staticmethod
def make_LCS(moments1, moments2) -> None:
# moments1 : list of lists
# m2 : list of lists
# clear for the base cases of dp
for i in range(2000):
LCS_DP[i][0], LCS_DP[0][i] = 0, 0
n, m = len(moments1), len(moments2)
for i in range(1, n + 1):
for j in range(1, m + 1):
# if the layers are isomorphic then okay
if moments1[i - 1] == moments2[j - 1]:
LCS_DP[i][j] = 1 + LCS_DP[i - 1][j - 1]
else:
LCS_DP[i][j] = max(LCS_DP[i - 1][j], LCS_DP[i][j - 1])
@staticmethod
def compare(prev_circ, curr_circ) -> QuantumCircuit:
if prev_circ is None:
return (False, curr_circ)
# update by reference as there is no qasm now
prev_dag = circuit_to_dag(prev_circ)
curr_dag = circuit_to_dag(curr_circ)
moments1 = CircuitComparator.get_moments(prev_dag)
moments2 = CircuitComparator.get_moments(curr_dag)
CircuitComparator.make_LCS(moments1, moments2)
(n, m) = (len(moments1), len(moments2))
id_set = set()
i = n
j = m
while i > 0 and j > 0:
if moments1[i - 1] == moments2[j - 1]:
# just want diff for second one
id_set.add(j - 1)
i -= 1
j -= 1
else:
if LCS_DP[i - 1][j] > LCS_DP[i][j - 1]:
# means the graph came from the
# first circuit , go up
i -= 1
else:
# if equal or small, go left
j -= 1
# if the whole circuit has not changed
fully_changed = len(id_set) == 0
if not fully_changed:
for id2, l in enumerate(list(curr_dag.layers())):
if id2 not in id_set:
# this is not an LCS node -> highlight it
for node in l["graph"].front_layer():
node.name = node.name + " "
return (fully_changed, dag_to_circuit(curr_dag))
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from math import pi
def circuit1(qc,theta,L,repeat):
#circuit 1
#theta is list of the parameters
#theta length is 8L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],i)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
if repeat!=0:
for l in range(L):
for i in range(4):
qc.rz(theta[count],i)
count=count+1
for i in range(4):
qc.rx(theta[count],i)
count=count+1
return qc
def circuit2(qc,theta,L,repeat):
#circuit 2
#theta is list of the parameters
#theta length is 8L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],i)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
qc.cx(3,2)
qc.cx(2,1)
qc.cx(1,0)
if repeat!=0:
for l in range(L):
qc.cx(1,0)
qc.cx(2,1)
qc.cx(3,2)
for i in range(4):
qc.rz(theta[count],i)
count=count+1
for i in range(4):
qc.rx(theta[count],i)
count=count+1
return qc
def circuit3(qc,theta,L,repeat):
#circuit 3
#theta is list of the parameters
#theta length is (11)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],i)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
qc.crz(theta[count],3,2)
count=count+1
qc.crz(theta[count],2,1)
count=count+1
qc.crz(theta[count],1,0)
count=count+1
if repeat!=0:
for l in range(L):
qc.crz(theta[count],1,0)
count=count+1
qc.crz(theta[count],2,1)
count=count+1
qc.crz(theta[count],3,2)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
for i in range(4):
qc.rx(theta[count],i)
count=count+1
return qc
def circuit4(qc,theta,L,repeat):
#circuit 4
#theta is list of the parameters
#theta length is (11)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],i)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
qc.crx(theta[count],3,2)
count=count+1
qc.crx(theta[count],2,1)
count=count+1
qc.crx(theta[count],1,0)
count=count+1
if repeat!=0:
for l in range(L):
qc.crx(theta[count],1,0)
count=count+1
qc.crx(theta[count],2,1)
count=count+1
qc.crx(theta[count],3,2)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
for i in range(4):
qc.rx(theta[count],i)
count=count+1
return qc
def circuit5(qc,theta,L,repeat):
#circuit 5
#theta is list of the parameters
#theta length is (28)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],i)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
for j in range(4):
for i in range(4):
if i!=j:
qc.crz(theta[count],3-j,3-i)
count=count+1
for i in range(4):
qc.rx(theta[count],i)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
if repeat!=0:
for l in range(L):
for i in range(4):
qc.rz(theta[count],i)
count=count+1
for i in range(4):
qc.rx(theta[count],i)
count=count+1
for j in range(4):
for i in range(4):
if i!=j:
qc.crz(theta[count],j,i)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
for i in range(4):
qc.rx(theta[count],i)
count=count+1
return qc
def circuit6(qc,theta,L,repeat):
#circuit 6
#theta is list of the parameters
#theta length is (28)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],i)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
for j in range(4):
for i in range(4):
if i!=j:
qc.crx(theta[count],3-j,3-i)
count=count+1
for i in range(4):
qc.rx(theta[count],i)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
if repeat!=0:
for l in range(L):
for i in range(4):
qc.rz(theta[count],i)
count=count+1
for i in range(4):
qc.rx(theta[count],i)
count=count+1
for j in range(4):
for i in range(4):
if i!=j:
qc.crx(theta[count],j,i)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
for i in range(4):
qc.rx(theta[count],i)
count=count+1
return qc
def circuit7(qc,theta,L,repeat):
#circuit 7
#theta is list of the parameters
#theta length is (19)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],i)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
qc.crz(theta[count],1,0)
count=count+1
qc.crz(theta[count],3,2)
count=count+1
for i in range(4):
qc.rx(theta[count],i)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
qc.crz(theta[count],2,1)
count=count+1
if repeat!=0:
for l in range(L):
qc.crz(theta[count],2,1)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
for i in range(4):
qc.rx(theta[count],i)
count=count+1
qc.crz(theta[count],3,2)
count=count+1
qc.crz(theta[count],1,0)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
for i in range(4):
qc.rx(theta[count],i)
count=count+1
return qc
def circuit8(qc,theta,L,repeat):
#circuit 8
#theta is list of the parameters
#theta length is (19)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],i)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
qc.crx(theta[count],1,0)
count=count+1
qc.crx(theta[count],3,2)
count=count+1
for i in range(4):
qc.rx(theta[count],i)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
qc.crx(theta[count],2,1)
count=count+1
if repeat!=0:
for l in range(L):
qc.crx(theta[count],2,1)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
for i in range(4):
qc.rx(theta[count],i)
count=count+1
qc.crx(theta[count],3,2)
count=count+1
qc.crx(theta[count],1,0)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
for i in range(4):
qc.rx(theta[count],i)
count=count+1
return qc
def circuit9(qc,theta,L,repeat):
#circuit 9
#theta is list of the parameters
#theta length is (4)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.h(i)
qc.cz(3,2)
qc.cz(2,1)
qc.cz(1,0)
for i in range(4):
qc.rx(theta[count],i)
count=count+1
if repeat!=0:
for l in range(L):
for i in range(4):
qc.rx(theta[count],i)
count=count+1
qc.cz(1,0)
qc.cz(2,1)
qc.cz(3,2)
for i in range(4):
qc.h(i)
return qc
def circuit10(qc,theta,L,repeat):
#circuit 10
#theta is list of the parameters
#theta length is (4)L+4
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for i in range(4):
qc.ry(theta[count],i)
count=count+1
for l in range(L):
qc.cz(3,2)
qc.cz(2,1)
qc.cz(1,0)
qc.cz(3,0)
for i in range(4):
qc.ry(theta[count],i)
count=count+1
if repeat!=0:
for l in range(L):
for i in range(4):
qc.ry(theta[count],i)
count=count+1
qc.cz(3,0)
qc.cz(1,0)
qc.cz(2,1)
qc.cz(3,2)
for i in range(4):
qc.ry(theta[count],i)
count=count+1
return qc
def circuit11(qc,theta,L,repeat):
#circuit 11
#theta is list of the parameters
#theta length is (12)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.ry(theta[count],i)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
qc.cx(1,0)
qc.cx(3,2)
qc.ry(theta[count],1)
count=count+1
qc.ry(theta[count],2)
count=count+1
qc.rz(theta[count],1)
count=count+1
qc.rz(theta[count],2)
count=count+1
qc.cx(2,1)
if repeat!=0:
for l in range(L):
qc.cx(2,1)
qc.rz(theta[count],2)
count=count+1
qc.rz(theta[count],1)
count=count+1
qc.ry(theta[count],2)
count=count+1
qc.ry(theta[count],1)
count=count+1
qc.cx(3,2)
qc.cx(1,0)
for i in range(4):
qc.rz(theta[count],i)
count=count+1
for i in range(4):
qc.ry(theta[count],i)
count=count+1
return qc
def circuit12(qc,theta,L,repeat):
#circuit 12
#theta is list of the parameters
#theta length is (12)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.ry(theta[count],i)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
qc.cz(1,0)
qc.cz(3,2)
qc.ry(theta[count],1)
count=count+1
qc.ry(theta[count],2)
count=count+1
qc.rz(theta[count],1)
count=count+1
qc.rz(theta[count],2)
count=count+1
qc.cz(2,1)
if repeat!=0:
for l in range(L):
qc.cz(2,1)
qc.rz(theta[count],2)
count=count+1
qc.rz(theta[count],1)
count=count+1
qc.ry(theta[count],2)
count=count+1
qc.ry(theta[count],1)
count=count+1
qc.cz(3,2)
qc.cz(1,0)
for i in range(4):
qc.rz(theta[count],i)
count=count+1
for i in range(4):
qc.ry(theta[count],i)
count=count+1
return qc
def circuit13(qc,theta,L,repeat):
#circuit 13
#theta is list of the parameters
#theta length is (16)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.ry(theta[count],i)
count=count+1
qc.crz(theta[count],3,0)
count=count+1
qc.crz(theta[count],2,3)
count=count+1
qc.crz(theta[count],1,2)
count=count+1
qc.crz(theta[count],0,1)
count=count+1
for i in range(4):
qc.ry(theta[count],i)
count=count+1
qc.crz(theta[count],3,2)
count=count+1
qc.crz(theta[count],0,3)
count=count+1
qc.crz(theta[count],1,0)
count=count+1
qc.crz(theta[count],2,1)
count=count+1
if repeat!=0:
for l in range(L):
qc.crz(theta[count],2,1)
count=count+1
qc.crz(theta[count],1,0)
count=count+1
qc.crz(theta[count],0,3)
count=count+1
qc.crz(theta[count],3,2)
count=count+1
for i in range(4):
qc.ry(theta[count],i)
count=count+1
qc.crz(theta[count],0,1)
count=count+1
qc.crz(theta[count],1,2)
count=count+1
qc.crz(theta[count],2,3)
count=count+1
qc.crz(theta[count],3,0)
count=count+1
for i in range(4):
qc.ry(theta[count],i)
count=count+1
return qc
def circuit14(qc,theta,L,repeat):
#circuit 14
#theta is list of the parameters
#theta length is (16)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.ry(theta[count],i)
count=count+1
qc.crx(theta[count],3,0)
count=count+1
qc.crx(theta[count],2,3)
count=count+1
qc.crx(theta[count],1,2)
count=count+1
qc.crx(theta[count],0,1)
count=count+1
for i in range(4):
qc.ry(theta[count],i)
count=count+1
qc.crx(theta[count],3,2)
count=count+1
qc.crx(theta[count],0,3)
count=count+1
qc.crx(theta[count],1,0)
count=count+1
qc.crx(theta[count],2,1)
count=count+1
if repeat!=0:
for l in range(L):
qc.crx(theta[count],2,1)
count=count+1
qc.crx(theta[count],1,0)
count=count+1
qc.crx(theta[count],0,3)
count=count+1
qc.crx(theta[count],3,2)
count=count+1
for i in range(4):
qc.ry(theta[count],i)
count=count+1
qc.crx(theta[count],0,1)
count=count+1
qc.crx(theta[count],1,2)
count=count+1
qc.crx(theta[count],2,3)
count=count+1
qc.crx(theta[count],3,0)
count=count+1
for i in range(4):
qc.ry(theta[count],i)
count=count+1
return qc
def circuit15(qc,theta,L,repeat):
#circuit 15
#theta is list of the parameters
#theta length is (8)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.ry(theta[count],i)
count=count+1
qc.cx(3,0)
qc.cx(2,3)
qc.cx(1,2)
qc.cx(0,1)
for i in range(4):
qc.ry(theta[count],i)
count=count+1
qc.cx(3,2)
qc.cx(0,3)
qc.cx(1,0)
qc.cx(2,1)
if repeat!=0:
for l in range(L):
qc.cx(2,1)
qc.cx(1,0)
qc.cx(0,3)
qc.cx(3,2)
for i in range(4):
qc.ry(theta[count],i)
count=count+1
qc.cx(0,1)
qc.cx(1,2)
qc.cx(2,3)
qc.cx(3,0)
for i in range(4):
qc.ry(theta[count],i)
count=count+1
return qc
def circuit16(qc,theta,L,repeat):
#circuit 16
#theta is list of the parameters
#theta length is (11)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],i)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
qc.crz(theta[count],1,0)
count=count+1
qc.crz(theta[count],3,2)
count=count+1
qc.crz(theta[count],2,1)
count=count+1
if repeat!=0:
for l in range(L):
qc.crz(theta[count],2,1)
count=count+1
qc.crz(theta[count],3,2)
count=count+1
qc.crz(theta[count],1,0)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
for i in range(4):
qc.rx(theta[count],i)
count=count+1
return qc
def circuit17(qc,theta,L,repeat):
#circuit 17
#theta is list of the parameters
#theta length is (11)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],i)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
qc.crx(theta[count],1,0)
count=count+1
qc.crx(theta[count],3,2)
count=count+1
qc.crx(theta[count],2,1)
count=count+1
if repeat!=0:
for l in range(L):
qc.crx(theta[count],2,1)
count=count+1
qc.crx(theta[count],3,2)
count=count+1
qc.crx(theta[count],1,0)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
for i in range(4):
qc.rx(theta[count],i)
count=count+1
return qc
def circuit18(qc,theta,L,repeat):
#circuit 18
#theta is list of the parameters
#theta length is (12)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],i)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
qc.crz(theta[count],3,0)
count=count+1
qc.crz(theta[count],2,3)
count=count+1
qc.crz(theta[count],1,2)
count=count+1
qc.crz(theta[count],0,1)
count=count+1
if repeat!=0:
for l in range(L):
qc.crz(theta[count],0,1)
count=count+1
qc.crz(theta[count],1,2)
count=count+1
qc.crz(theta[count],2,3)
count=count+1
qc.crz(theta[count],3,0)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
for i in range(4):
qc.rx(theta[count],i)
count=count+1
return qc
def circuit19(qc,theta,L,repeat):
#circuit 1
#theta is list of the parameters
#theta length is (12)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],i)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
qc.crx(theta[count],3,0)
count=count+1
qc.crx(theta[count],2,3)
count=count+1
qc.crx(theta[count],1,2)
count=count+1
qc.crx(theta[count],0,1)
count=count+1
if repeat!=0:
for l in range(L):
qc.crx(theta[count],0,1)
count=count+1
qc.crx(theta[count],1,2)
count=count+1
qc.crx(theta[count],2,3)
count=count+1
qc.crx(theta[count],3,0)
count=count+1
for i in range(4):
qc.rz(theta[count],i)
count=count+1
for i in range(4):
qc.rx(theta[count],i)
count=count+1
return qc
|
https://github.com/DRA-chaos/Solutions-to-the-Lab-Exercises---IBM-Qiskit-Summer-School-2021
|
DRA-chaos
|
# General tools
import numpy as np
import matplotlib.pyplot as plt
# Qiskit Circuit Functions
from qiskit import execute,QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile
import qiskit.quantum_info as qi
# Tomography functions
from qiskit.ignis.verification.tomography import process_tomography_circuits, ProcessTomographyFitter
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
import warnings
warnings.filterwarnings('ignore')
target = QuantumCircuit(2)
#target = # YOUR CODE HERE
target.h(0)
target.h(1)
target.rx(np.pi/2,0)
target.rx(np.pi/2,1)
target.cx(0,1)
target.p(np.pi,1)
target.cx(0,1)
target_unitary = qi.Operator(target)
target.draw('mpl')
from qc_grader import grade_lab5_ex1
# Note that the grading function is expecting a quantum circuit with no measurements
grade_lab5_ex1(target)
simulator = Aer.get_backend('qasm_simulator')
qpt_circs = process_tomography_circuits(target,measured_qubits=[0,1])# YOUR CODE HERE
qpt_job = execute(qpt_circs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192)
qpt_result = qpt_job.result()
# YOUR CODE HERE
qpt_tomo= ProcessTomographyFitter(qpt_result,qpt_circs)
Choi_qpt= qpt_tomo.fit(method='lstsq')
fidelity = qi.average_gate_fidelity(Choi_qpt,target_unitary)
from qc_grader import grade_lab5_ex2
# Note that the grading function is expecting a floating point number
grade_lab5_ex2(fidelity)
# T1 and T2 values for qubits 0-3
T1s = [15000, 19000, 22000, 14000]
T2s = [30000, 25000, 18000, 28000]
# Instruction times (in nanoseconds)
time_u1 = 0 # virtual gate
time_u2 = 50 # (single X90 pulse)
time_u3 = 100 # (two X90 pulses)
time_cx = 300
time_reset = 1000 # 1 microsecond
time_measure = 1000 # 1 microsecond
from qiskit.providers.aer.noise import thermal_relaxation_error
from qiskit.providers.aer.noise import NoiseModel
# QuantumError objects
errors_reset = [thermal_relaxation_error(t1, t2, time_reset)
for t1, t2 in zip(T1s, T2s)]
errors_measure = [thermal_relaxation_error(t1, t2, time_measure)
for t1, t2 in zip(T1s, T2s)]
errors_u1 = [thermal_relaxation_error(t1, t2, time_u1)
for t1, t2 in zip(T1s, T2s)]
errors_u2 = [thermal_relaxation_error(t1, t2, time_u2)
for t1, t2 in zip(T1s, T2s)]
errors_u3 = [thermal_relaxation_error(t1, t2, time_u3)
for t1, t2 in zip(T1s, T2s)]
errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand(
thermal_relaxation_error(t1b, t2b, time_cx))
for t1a, t2a in zip(T1s, T2s)]
for t1b, t2b in zip(T1s, T2s)]
# Add errors to noise model
noise_thermal = NoiseModel()
for j in range(4):
noise_thermal.add_quantum_error(errors_measure[j],'measure',[j])
noise_thermal.add_quantum_error(errors_reset[j],'reset',[j])
noise_thermal.add_quantum_error(errors_u3[j],'u3',[j])
noise_thermal.add_quantum_error(errors_u2[j],'u2',[j])
noise_thermal.add_quantum_error(errors_u1[j],'u1',[j])
for k in range(4):
noise_thermal.add_quantum_error(errors_cx[j][k],'cx',[j,k])
# YOUR CODE HERE
from qc_grader import grade_lab5_ex3
# Note that the grading function is expecting a NoiseModel
grade_lab5_ex3(noise_thermal)
np.random.seed(0)
noise_qpt_circs = process_tomography_circuits(target,measured_qubits=[0,1])# YOUR CODE HERE
noise_qpt_job = execute(noise_qpt_circs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192,noise_model=noise_thermal)
noise_qpt_result = noise_qpt_job.result()
# YOUR CODE HERE
noise_qpt_tomo= ProcessTomographyFitter(noise_qpt_result,noise_qpt_circs)
noise_Choi_qpt= noise_qpt_tomo.fit(method='lstsq')
fidelity = qi.average_gate_fidelity(noise_Choi_qpt,target_unitary)
from qc_grader import grade_lab5_ex4
# Note that the grading function is expecting a floating point number
grade_lab5_ex4(fidelity)
np.random.seed(0)
# YOUR CODE HERE
#qr = QuantumRegister(2)
qubit_list = [0,1]
meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list)
meas_calibs_job = execute(meas_calibs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192,noise_model=noise_thermal)
cal_results = meas_calibs_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, qubit_list=qubit_list)
Cal_result = meas_fitter.filter.apply(noise_qpt_result)
# YOUR CODE HERE
Cal_qpt_tomo= ProcessTomographyFitter(Cal_result,noise_qpt_circs)
Cal_Choi_qpt= Cal_qpt_tomo.fit(method='lstsq')
fidelity = qi.average_gate_fidelity(Cal_Choi_qpt,target_unitary)
from qc_grader import grade_lab5_ex5
# Note that the grading function is expecting a floating point number
grade_lab5_ex5(fidelity)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.measure(0, 0)
qc.x(0).c_if(cr, 0)
qc.measure(0, 0)
qc.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Clifford, random_clifford
qc = QuantumCircuit(3)
cliff = random_clifford(2)
qc.append(cliff, [0, 1])
qc.ccx(0, 1, 2)
qc.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeBoeblingen
backend = FakeBoeblingen()
ghz = QuantumCircuit(5)
ghz.h(0)
ghz.cx(0,range(1,5))
circ = transpile(ghz, backend, scheduling_method="asap")
circ.draw(output='mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a DensityMatrix
state = DensityMatrix(qc)
plot_state_city(state)
|
https://github.com/mberna/qce22-qiskit-runtime-tutorial
|
mberna
|
# define Hamiltonian
from qiskit.opflow import PauliSumOp
H = PauliSumOp.from_list([('XYII', 1), ('IYZI', 2), ('IIZX', 3), ('XIII', 4), ('IYII', 5)])
print(H)
from qiskit.circuit.library import EfficientSU2
qc = EfficientSU2(num_qubits=H.num_qubits, reps=1)
qc_with_meas = qc.measure_all(inplace=False)
qc_with_meas.decompose().draw(fold=120)
# define a set of (random) parameter values for the ansatz circuit
import numpy as np
theta = np.random.rand(qc.num_parameters)
# use the Sampler to sample from this circuit
from qiskit.primitives import Sampler
sampler = Sampler([qc_with_meas])
s_result = sampler([qc_with_meas], [theta])
print(s_result)
from qiskit.primitives import Estimator
estimator = Estimator([qc], [H])
e_result = estimator([qc], [H], [theta])
print(e_result)
from qiskit.algorithms import NumPyEigensolver
exact_solver = NumPyEigensolver(k=2) # find the first two '2' eigenvalues
exact_result = exact_solver.compute_eigenvalues(H)
print(exact_result.eigenvalues)
# define objective as expectation value of Hamiltonian with circuit ansatz
objective = lambda x: estimator([qc], [H], [x]).values[0]
# instantiate optimizer
from qiskit.algorithms.optimizers import SPSA
optimizer = SPSA(maxiter=500)
# define initial values for our circuit parameters
x0 = np.random.rand(qc.num_parameters)
# minimize the objective function
result = optimizer.minimize(objective, x0=x0)
# store ground state parameters for later
ground_state_params = result.x
# print the resulting ground state energy
print(result.fun)
from qiskit.algorithms import MinimumEigensolver, VQEResult
class CustomVQE(MinimumEigensolver):
def __init__(self, estimator, circuit, optimizer, callback=None):
self._estimator = estimator
self._circuit = circuit
self._optimizer = optimizer
self._callback = callback
def compute_minimum_eigenvalue(self, operator, aux_operators=None):
# define objective
def objective(x):
e_job = self._estimator([self._circuit], [operator], [x])
value = e_job.values[0]
if self._callback:
self._callback(value)
return value
# run optimization
x0 = np.random.rand(self._circuit.num_parameters)
res = self._optimizer.minimize(objective, x0=x0)
# populate results
result = VQEResult()
result.cost_function_evals = res.nfev
result.eigenvalue = res.fun
result.optimal_parameters = res.x
return result
# run the custom VQE function
custom_vqe = CustomVQE(estimator, qc, optimizer)
result = custom_vqe.compute_minimum_eigenvalue(H)
print(result)
from qiskit.circuit import ParameterVector
class Fidelity():
def __init__(self, sampler):
""" Instantiate fidelity estimator. """
#self._sampler = sampler
def run(self, circuit_1, circuit_2, param_values_1, param_values_2):
""" Estimate fidelity between two states defined by given parameter values."""
# prepare circuit
circuit_1_ = circuit_1.remove_final_measurements(inplace=False)
circuit_2_ = circuit_2.remove_final_measurements(inplace=False)
x = ParameterVector("x", circuit_1_.num_parameters)
y = ParameterVector("y", circuit_2_.num_parameters)
circuit = circuit_1_.assign_parameters(x).compose(circuit_2_.inverse().assign_parameters(y))
circuit.measure_all()
# run circuit and get probabilities
param_values = np.append(param_values_1, param_values_2)
sampler = Sampler([circuit])
s_job = sampler([circuit], [param_values])
probabilities = s_job.quasi_dists[0]
# estimate fidelity: |<0|U_1^dag U_2|0>|^2 clipped to [0, 1]
fidelity = np.minimum(1.0, np.maximum(0.0, probabilities.get(0, 0.0)))
return fidelity
# instantiate fidelity
fidelity = Fidelity(sampler)
# interpolation between parameters
ts = np.linspace(0, 1)
fidelities = [fidelity.run(qc, qc, ground_state_params, ground_state_params + t*theta) for t in ts]
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 4))
plt.plot(ts, fidelities)
plt.xlabel('t', fontsize=20)
plt.ylabel('fidelity', fontsize=20)
plt.show()
# set penalty weight for overlap term
penalty = 25
# define objective for VQD
vqd_objective = lambda x: objective(x) + penalty*fidelity.run(qc, qc, ground_state_params, x)
# run optimization to get first excited state
result = optimizer.minimize(vqd_objective, ground_state_params)
print(result)
# determine energy
e_job = estimator([qc], [H], [result.x])
print(e_job)
fid = fidelity.run(qc, qc, result.x, ground_state_params);
print(fid)
from qiskit.algorithms import Eigensolver, EigensolverResult
class VQD(Eigensolver):
def __init__(self, estimator, fidelity, circuit, optimizer, penalty=25, callback=None):
# self._estimator = estimator
self._fidelity = fidelity
self._circuit = circuit
self._optimizer = optimizer
self._penalty = penalty
self._callback = callback
def compute_eigenvalues(self, operator, aux_operators=None):
# compute ground state
estimator = Estimator([self._circuit], [operator])
energy = lambda x: estimator([self._circuit], [operator], [x]).values[0]
x0 = np.random.rand(self._circuit.num_parameters)
res_1 = self._optimizer.minimize(energy, x0)
# compute first excited states
overlap = lambda x: self._fidelity.run(self._circuit, self._circuit, res_1.x, x)
def objective(x):
value = energy(x) + self._penalty * overlap(x)
if self._callback:
self._callback(value)
return value
res_2 = self._optimizer.minimize(objective, res_1.x)
# populate results
result = EigensolverResult()
result.eigenvalues = [estimator([self._circuit], [operator], [res_1.x]),
estimator([self._circuit], [operator], [res_2.x])]
return result
vqd = VQD(estimator, fidelity, qc, optimizer=SPSA(maxiter=1000))
result = vqd.compute_eigenvalues(H)
print(result)
from qiskit_ibm_runtime import (Session, Options, QiskitRuntimeService,
Sampler as RuntimeSampler,
Estimator as RuntimeEstimator)
service = QiskitRuntimeService(channel='ibm_quantum')
from qiskit.algorithms.optimizers import COBYLA
optimizer = COBYLA(maxiter=400)
with Session(service=service, backend='ibmq_qasm_simulator') as session:
# prepare primitives
rt_estimator = RuntimeEstimator(session=session)
rt_sampler = RuntimeSampler(session=session)
rt_fidelity = Fidelity(rt_sampler)
# set up algorithm
rt_vqd = VQD(rt_estimator, rt_fidelity, qc, optimizer)
# run algorithm
result = rt_vqd.compute_eigenvalues(H)
print(result)
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
%qiskit_copyright
|
https://github.com/ShabaniLab/q-camp
|
ShabaniLab
|
import numpy as np
from qiskit import *
# Create a Quantum Circuit acting on a quantum register of two qubits
circ = QuantumCircuit(2, 2)
circ = QuantumCircuit(4, 4)
# Add a H gate on qubit 0, putting this qubit in superposition.
circ.x(0)
circ.x(1)
circ.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
circ.cx(0, 1)
circ.cz(1, 0)
circ.swap(0, 1)
circ.barrier()
circ.y(2)
circ.measure(0, 0)
# circ.measure(1, 1)
circ.draw()
# Create a Quantum Circuit acting on a quantum register of three qubits
circ = QuantumCircuit(3)
# Add a H gate on qubit 0, putting this qubit in superposition.
circ.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
circ.cx(0, 1)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting
# the qubits in a GHZ state.
circ.cx(0, 2)
circ.draw('mpl')
# Import Aer
from qiskit import Aer
# Run the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
# Create a Quantum Program for execution
job = execute(circ, backend)
result = job.result()
outputstate = result.get_statevector(circ, decimals=3)
print(outputstate)
from qiskit.visualization import plot_state_city
plot_state_city(outputstate)
# Run the quantum circuit on a unitary simulator backend
backend = Aer.get_backend('unitary_simulator')
job = execute(circ, backend)
result = job.result()
# Show the results
print(result.get_unitary(circ, decimals=3))
# Create a Quantum Circuit
meas = QuantumCircuit(2, 2)
meas.barrier(range(2))
# map the quantum measurement to the classical bits
meas.measure(range(2), range(2))
# The Qiskit circuit object supports composition using
# the addition operator.
qc = circ + meas
#drawing the circuit
qc.draw()
# Use Aer's qasm_simulator
backend_sim = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
circ.measure(0, 0)
circ.measure(1, 1)
job_sim = execute(circ, backend_sim, shots=1024)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(circ)
print(counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/khalilguy/QiskitHackathon
|
khalilguy
|
%matplotlib notebook
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "2"
from tracker3d import utils
from tracker3d import metrics
from tracker3d import loader
import numpy as np
import pandas as pd
import keras
order = ("phi", "r", "z")
train, target = loader.from_file("datasets/npz/unif25_prz_n10.npz")
#test = train[int(0.2 * len(train)):]
#train = train[:int(0.2 * len(train))]
#print(test.shape)
#print(train.shape)
#testTarget = target[int(0.2 * len(target)):]
#target = target[:int(0.2 * len(target))]
#print(testTarget.shape)
#print(target.shape)
test, testTarget = loader.from_file("datasets/npz/ramp_prz_n10.npz")
event = 1025
utils.display_side_by_side(train[event], target[event], order=order)
from keras.layers import Dense, LSTM, Dropout, GRU, TimeDistributed, Bidirectional
from keras.models import Sequential
from keras.regularizers import l1, l2, l1_l2
input_shape = train[0].shape # Shape of an event.
output_shape = len(target[0][0]) # Number of tracks per event
batch_size = 32
epochs = 32
valsplit = .1
opt = 'rmsprop' # optimizer
model = Sequential()
model.add(Bidirectional(GRU(256, return_sequences=True, recurrent_dropout=0.4, implementation=2, bias_regularizer=l2(0.02)), input_shape=input_shape, merge_mode="mul"))
model.add(Dropout(0.4))
model.add(Bidirectional(GRU(256, return_sequences=True, recurrent_dropout=0.4, implementation=2, bias_regularizer=l2(0.02)), merge_mode="mul"))
model.add(Dropout(0.4))
model.add(Bidirectional(GRU(256, return_sequences=True, recurrent_dropout=0.4, implementation=2, bias_regularizer=l2(0.02)), merge_mode="mul"))
model.add(Dropout(0.4))
model.add(TimeDistributed(Dense(output_shape, activation='softmax')))
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
model.summary()
%%time
modelpath = 'simple.h5'
hist = model.fit(train, target, epochs=epochs, batch_size=batch_size,
verbose=1, validation_split=valsplit,
#callbacks=[keras.callbacks.ModelCheckpoint(filepath=modelpath, verbose=0)]
)
predictions = model.predict(test, batch_size=batch_size)
utils.print_scores(model, train, target, batch_size)
utils.graph_losses([("Categorical Cross Entropy", hist)])
tracks, acc = metrics.accuracy_vs_tracks(predictions, testTarget, has_noise=True, has_padding=True)
np.save("testTarget.npy", testTarget)
np.save("predictions.npy", predictions)
print(metrics.discrete_accuracy_all(test, testTarget, predictions))
print(acc)
%matplotlib inline
import matplotlib.pyplot as plt
plt.figure(2)
fig = plt.scatter(tracks, acc)
plt.show(fig)
numTracks = int(np.amax(tracks))
accuracy = np.zeros(numTracks)
for i in range(numTracks):
tot_acc = 0
count = 0
for j, track in enumerate(tracks):
print(acc[j])
if track == i + 1:
tot_acc = tot_acc + acc[j]
count += 1
if count > 0:
accuracy[i] = tot_acc/count
track = np.zeros(numTracks)
for i in range(numTracks):
track[i] = i + 1
print(accuracy)
print(track)
plt.scatter(track, accuracy)
plt.plot(np.unique(track), np.poly1d(np.polyfit(track, accuracy, 1))(np.unique(track)))
plt.title("Average Accuracy vs. Number of Tracks")
plt.xlabel("Number of Tracks")
plt.ylabel("Accuracy")
plt.show(fig)
for i, cell in enumerate(acc):
if cell < 0.3:
print(cell)
print(tracks[i])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Necessary imports
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import clear_output
from qiskit import QuantumCircuit
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import ZFeatureMap, RealAmplitudes
from qiskit.utils import algorithm_globals
from sklearn.datasets import make_classification
from sklearn.preprocessing import MinMaxScaler
from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier
from qiskit_machine_learning.neural_networks import EffectiveDimension, LocalEffectiveDimension
from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN
# set random seed
algorithm_globals.random_seed = 42
num_qubits = 3
# create a feature map
feature_map = ZFeatureMap(feature_dimension=num_qubits, reps=1)
# create a variational circuit
ansatz = RealAmplitudes(num_qubits, reps=1)
# combine feature map and ansatz into a single circuit
qc = QuantumCircuit(num_qubits)
qc.append(feature_map, range(num_qubits))
qc.append(ansatz, range(num_qubits))
qc.decompose().draw("mpl")
# parity maps bitstrings to 0 or 1
def parity(x):
return "{:b}".format(x).count("1") % 2
output_shape = 2 # corresponds to the number of classes, possible outcomes of the (parity) mapping.
# construct QNN
qnn = SamplerQNN(
circuit=qc,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
interpret=parity,
output_shape=output_shape,
sparse=False,
)
# we can set the total number of input samples and weight samples for random selection
num_input_samples = 10
num_weight_samples = 10
global_ed = EffectiveDimension(
qnn=qnn, weight_samples=num_weight_samples, input_samples=num_input_samples
)
# we can also provide user-defined samples and parameters
input_samples = algorithm_globals.random.normal(0, 1, size=(10, qnn.num_inputs))
weight_samples = algorithm_globals.random.uniform(0, 1, size=(10, qnn.num_weights))
global_ed = EffectiveDimension(qnn=qnn, weight_samples=weight_samples, input_samples=input_samples)
# finally, we will define ranges to test different numbers of data, n
n = [5000, 8000, 10000, 40000, 60000, 100000, 150000, 200000, 500000, 1000000]
global_eff_dim_0 = global_ed.get_effective_dimension(dataset_size=n[0])
d = qnn.num_weights
print("Data size: {}, global effective dimension: {:.4f}".format(n[0], global_eff_dim_0))
print(
"Number of weights: {}, normalized effective dimension: {:.4f}".format(d, global_eff_dim_0 / d)
)
global_eff_dim_1 = global_ed.get_effective_dimension(dataset_size=n)
print("Effective dimension: {}".format(global_eff_dim_1))
print("Number of weights: {}".format(d))
# plot the normalized effective dimension for the model
plt.plot(n, np.array(global_eff_dim_1) / d)
plt.xlabel("Number of data")
plt.ylabel("Normalized GLOBAL effective dimension")
plt.show()
num_inputs = 3
num_samples = 50
X, y = make_classification(
n_samples=num_samples,
n_features=num_inputs,
n_informative=3,
n_redundant=0,
n_clusters_per_class=1,
class_sep=2.0,
)
X = MinMaxScaler().fit_transform(X)
y = 2 * y - 1 # labels in {-1, 1}
estimator_qnn = EstimatorQNN(
circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters
)
# callback function that draws a live plot when the .fit() method is called
def callback_graph(weights, obj_func_eval):
clear_output(wait=True)
objective_func_vals.append(obj_func_eval)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
# construct classifier
initial_point = algorithm_globals.random.random(estimator_qnn.num_weights)
estimator_classifier = NeuralNetworkClassifier(
neural_network=estimator_qnn,
optimizer=COBYLA(maxiter=80),
initial_point=initial_point,
callback=callback_graph,
)
# create empty array for callback to store evaluations of the objective function (callback)
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
estimator_classifier.fit(X, y)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
estimator_classifier.score(X, y)
trained_weights = estimator_classifier.weights
# get Local Effective Dimension for set of trained weights
local_ed_trained = LocalEffectiveDimension(
qnn=estimator_qnn, weight_samples=trained_weights, input_samples=X
)
local_eff_dim_trained = local_ed_trained.get_effective_dimension(dataset_size=n)
print(
"normalized local effective dimensions for trained QNN: ",
local_eff_dim_trained / estimator_qnn.num_weights,
)
# get Local Effective Dimension for set of untrained weights
local_ed_untrained = LocalEffectiveDimension(
qnn=estimator_qnn, weight_samples=initial_point, input_samples=X
)
local_eff_dim_untrained = local_ed_untrained.get_effective_dimension(dataset_size=n)
print(
"normalized local effective dimensions for untrained QNN: ",
local_eff_dim_untrained / estimator_qnn.num_weights,
)
# plot the normalized effective dimension for the model
plt.plot(n, np.array(local_eff_dim_trained) / estimator_qnn.num_weights, label="trained weights")
plt.plot(
n, np.array(local_eff_dim_untrained) / estimator_qnn.num_weights, label="untrained weights"
)
plt.xlabel("Number of data")
plt.ylabel("Normalized LOCAL effective dimension")
plt.legend()
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_hinton
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3 , 0)
qc.rx(np.pi/5, 1)
state = DensityMatrix(qc)
plot_state_hinton(state, title="New Hinton Plot")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.measure(0, 0)
qc.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
# Create a circuit with a register of three qubits
circ = QuantumCircuit(3)
# H gate on qubit 0, putting this qubit in a superposition of |0> + |1>.
circ.h(0)
# A CX (CNOT) gate on control qubit 0 and target qubit 1 generating a Bell state.
circ.cx(0, 1)
# CX (CNOT) gate on control qubit 0 and target qubit 2 resulting in a GHZ state.
circ.cx(0, 2)
# Draw the circuit
circ.draw('mpl')
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
# the initial state
initial = [0.5, 0, 0.5, 0]
# probabilistic operator for symbol a
A = [
[0.5, 0, 0, 0],
[0.25, 1, 0, 0],
[0, 0, 1, 0],
[0.25, 0, 0, 1]
]
# probabilistic operator for symbol b
B = [
[1, 0, 0, 0],
[0, 1, 0.25, 0],
[0, 0, 0.5, 0],
[0, 0, 0.25, 1]
]
#
# your solution is here
#
# for random number generation
from random import randrange
# we will use evolve function
def evolve(Op,state):
newstate=[]
for i in range(len(Op)): # for each row
newstate.append(0)
for j in range(len(state)): # for each element in state
newstate[i] = newstate[i] + Op[i][j] * state[j] # summation of pairwise multiplications
return newstate # return the new probabilistic state
# the initial state
state = [0.5, 0, 0.5, 0]
# probabilistic operator for symbol a
A = [
[0.5, 0, 0, 0],
[0.25, 1, 0, 0],
[0, 0, 1, 0],
[0.25, 0, 0, 1]
]
# probabilistic operator for symbol b
B = [
[1, 0, 0, 0],
[0, 1, 0.25, 0],
[0, 0, 0.5, 0],
[0, 0, 0.25, 1]
]
#
# your solution is here
#
length = 40
total = 50
# total = 1000 # we will also test our code for 1000 strings
# we will check 5 cases
# let's use a list
cases = [0,0,0,0,0]
for i in range(total): # total number of strings
Na = 0
Nb = 0
string = ""
state = [0.5, 0, 0.5, 0]
for j in range(length): # generate random string
if randrange(2) == 0:
Na = Na + 1 # new symbol is a
string = string + "a"
state = evolve(A,state) # update the probabilistic state by A
else:
Nb = Nb + 1 # new symbol is b
string = string + "b"
state = evolve(B,state) # update the probabilistic state by B
# now we have the final state
p0 = state[0] + state[1] # the probabilities of being in 00 and 01
p1 = state[2] + state[3] # the probabilities of being in 10 and 11
print() # print an empty line
print("(Na-Nb) is",Na-Nb,"and","(p0-p1) is",p0-p1)
# let's check possible different cases
# start with the case in which both are nonzero
# then their multiplication is nonzero
# let's check the sign of their multiplication
if (Na-Nb) * (p0-p1) < 0:
print("they have opposite sign")
cases[0] = cases[0] + 1
elif (Na-Nb) * (p0-p1) > 0:
print("they have the same sign")
cases[1] = cases[1] + 1
# one of them should be zero
elif (Na-Nb) == 0:
if (p0-p1) == 0:
print("both are zero")
cases[2] = cases[2] + 1
else:
print("(Na-Nb) is zero, but (p0-p1) is nonzero")
cases[3] = cases[3] + 1
elif (p0-p1) == 0:
print("(Na-Nb) is nonzero, while (p0-p1) is zero")
cases[4] = cases[4] + 1
# check the case(s) that are observed and the case(s) that are not observed
print() # print an empty line
print(cases)
|
https://github.com/pragyakatyayan/Playing-with-parametrized-quantum-gates
|
pragyakatyayan
|
%matplotlib inline
%config InlineBackend.figure_format = 'svg'
from IPython.display import clear_output
from qiskit import QuantumCircuit
circuit = QuantumCircuit(1)
circuit.u3(f"$\\theta$",f"$\\phi$",f"$\\lambda$", 0)
circuit.draw('mpl')
from numpy import pi
circuit = QuantumCircuit(1)
circuit.u3(2*pi/3, pi/2, 0, 0)
circuit.draw('mpl')
from qiskit import execute, Aer
from qiskit.visualization import plot_bloch_multivector
backend = Aer.get_backend("statevector_simulator")
job = execute(circuit,backend=backend)
statevector = job.result().get_statevector()
print(statevector)
plot_bloch_multivector(statevector)
from qiskit.visualization import plot_histogram
results = execute(circuit,backend).result().get_counts()
plot_histogram(results, color='midnightblue')
# initial circuit
from qiskit import QuantumCircuit
from numpy import pi
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.x(1)
circuit.draw('mpl')
# transformed circuit
circuit.cu3(0,3*pi/2, 0, 0, 1)
circuit.draw('mpl')
from qiskit import execute, Aer
from qiskit.visualization import plot_bloch_multivector
backend = Aer.get_backend("statevector_simulator")
job = execute(circuit,backend=backend)
statevector = job.result().get_statevector()
print(statevector)
plot_bloch_multivector(statevector)
from qiskit.visualization import plot_state_qsphere
from qiskit.quantum_info import Statevector
sv = Statevector.from_label('00').evolve(circuit)
plot_state_qsphere(sv.data, show_state_phases=True)
circuit2 = QuantumCircuit(2)
circuit2.h(0)
circuit2.x(1)
circuit2.cu3(0, 0, 3*pi/2, 0, 1)
circuit2.draw('mpl')
job = execute(circuit2,backend=backend)
statevector = job.result().get_statevector()
print(statevector)
plot_bloch_multivector(statevector)
circuit3 = QuantumCircuit(2)
circuit3.h(0)
circuit3.x(1)
circuit3.cu3(0, pi, pi/2, 0, 1)
circuit3.draw('mpl')
job = execute(circuit3,backend=backend)
statevector = job.result().get_statevector()
print(statevector)
plot_bloch_multivector(statevector)
circuit4 = QuantumCircuit(2)
circuit4.h(0)
circuit4.x(1)
circuit4.cu3(0, pi/2, pi, 0, 1)
circuit4.draw('mpl')
job = execute(circuit4,backend=backend)
statevector = job.result().get_statevector()
print(statevector)
plot_bloch_multivector(statevector)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/steffencruz/FockWits
|
steffencruz
|
import os
import sys
sys.path.append("/home/artix41/Toronto/qiskit-terra/")
import qiskit
print(qiskit.__file__)
import matplotlib.pyplot as plt
import numpy as np
from qiskit.tools.visualization._circuit_visualization import circuit_drawer
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import Aer, execute
from CVGates import CVGates
class CVCircuit:
def __init__(self, circuit, qr, n_qubits_per_mode=2):
self.n_qubits_per_mode = n_qubits_per_mode
self.n_qumodes = len(circuit)
self.circuit = circuit
self.qr = qr
self.gates = CVGates(n_qubits_per_mode)
def initialize(self, fock_states):
for qumode, n in enumerate(fock_states):
if n >= 2**self.n_qubits_per_mode:
raise ValueError("The parameter n should be lower than the cutoff")
vector = np.zeros((2**self.n_qubits_per_mode,))
vector[n] = 1
start_qumode = self.n_qubits_per_mode * qumode
self.circuit.initialize(vector, [self.qr[i] for i in range(start_qumode, start_qumode+self.n_qubits_per_mode)])
def DGate(self, alpha, qumode):
start_qumode = self.n_qubits_per_mode * qumode
self.circuit.unitary(self.gates.D(alpha), *(self.qr[i] for i in range(start_qumode, start_qumode+self.n_qubits_per_mode)))
def SGate(self, z, qumode):
start_qumode = self.n_qubits_per_mode * qumode
self.circuit.unitary(self.gates.S(z), *(self.qr[i] for i in range(start_qumode, start_qumode+self.n_qubits_per_mode)))
def RGate(self, phi, qumode):
start_qumode = self.n_qubits_per_mode * qumode
self.circuit.unitary(self.gates.R(phi), *(self.qr[i] for i in range(start_qumode, start_qumode+self.n_qubits_per_mode)))
def KGate(self, kappa, qumode):
start_qumode = self.n_qubits_per_mode * qumode
self.circuit.unitary(self.gates.K(kappa), *(self.qr[i] for i in range(start_qumode, start_qumode+self.n_qubits_per_mode)))
def BSGate(self, phi, qumodes):
start_qumodes = [self.n_qubits_per_mode * qumodes[0], self.n_qubits_per_mode * qumodes[1]]
self.circuit.unitary(self.gates.BS(phi), *([self.qr[i] for i in range(start_qumodes[0], start_qumodes[0]+self.n_qubits_per_mode)] +
[self.qr[i] for i in range(start_qumodes[1], start_qumodes[1]+self.n_qubits_per_mode)]))
def S2Gate(self, z, qumodes):
start_qumodes = [self.n_qubits_per_mode * qumodes[0], self.n_qubits_per_mode * qumodes[1]]
self.circuit.unitary(self.gates.S2(z), *([self.qr[i] for i in range(start_qumodes[0], start_qumodes[0]+self.n_qubits_per_mode)] +
[self.qr[i] for i in range(start_qumodes[1], start_qumodes[1]+self.n_qubits_per_mode)]))
if __name__ == '__main__':
# ===== Constants =====
n_qubits_per_mode = 3
n_qumodes = 2
alpha = 1
phi = np.pi/2
# ==== Initialize circuit =====
qr = QuantumRegister(n_qubits_per_mode*n_qumodes)
cr = ClassicalRegister(n_qubits_per_mode*n_qumodes)
circuit = QuantumCircuit(qr, cr)
cv_circuit = CVCircuit(circuit, qr, n_qubits_per_mode)
# ==== Build circuit ====
cv_circuit.initialize([0,0])
cv_circuit.DGate(alpha, 0)
cv_circuit.BSGate(phi, (0,1))
# cv_circuit.BSGate(theta, phi, 0, 1)
# circuit.measure(qr, cr)
print(circuit)
# ==== Compilation =====
backend = Aer.get_backend('statevector_simulator')
job = execute(circuit, backend)
result = job.result()
state = job.result().get_statevector(circuit)
# ==== Tests ====
print(state)
prob = np.abs(state)**2
plt.plot(prob,'-o')
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# useful additional packages
import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
from qiskit_aer import Aer
from qiskit.tools.visualization import plot_histogram
from qiskit.circuit.library import TwoLocal
from qiskit_optimization.applications import Maxcut, Tsp
from qiskit.algorithms.minimum_eigensolvers import SamplingVQE, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import SPSA
from qiskit.utils import algorithm_globals
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
# Generating a graph of 4 nodes
n = 4 # Number of nodes in graph
G = nx.Graph()
G.add_nodes_from(np.arange(0, n, 1))
elist = [(0, 1, 1.0), (0, 2, 1.0), (0, 3, 1.0), (1, 2, 1.0), (2, 3, 1.0)]
# tuple is (i,j,weight) where (i,j) is the edge
G.add_weighted_edges_from(elist)
colors = ["r" for node in G.nodes()]
pos = nx.spring_layout(G)
def draw_graph(G, colors, pos):
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_color=colors, node_size=600, alpha=0.8, ax=default_axes, pos=pos)
edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
draw_graph(G, colors, pos)
# Computing the weight matrix from the random graph
w = np.zeros([n, n])
for i in range(n):
for j in range(n):
temp = G.get_edge_data(i, j, default=0)
if temp != 0:
w[i, j] = temp["weight"]
print(w)
best_cost_brute = 0
for b in range(2**n):
x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))]
cost = 0
for i in range(n):
for j in range(n):
cost = cost + w[i, j] * x[i] * (1 - x[j])
if best_cost_brute < cost:
best_cost_brute = cost
xbest_brute = x
print("case = " + str(x) + " cost = " + str(cost))
colors = ["r" if xbest_brute[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
print("\nBest solution = " + str(xbest_brute) + " cost = " + str(best_cost_brute))
max_cut = Maxcut(w)
qp = max_cut.to_quadratic_program()
print(qp.prettyprint())
qubitOp, offset = qp.to_ising()
print("Offset:", offset)
print("Ising Hamiltonian:")
print(str(qubitOp))
# solving Quadratic Program using exact classical eigensolver
exact = MinimumEigenOptimizer(NumPyMinimumEigensolver())
result = exact.solve(qp)
print(result.prettyprint())
# Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
ee = NumPyMinimumEigensolver()
result = ee.compute_minimum_eigenvalue(qubitOp)
x = max_cut.sample_most_likely(result.eigenstate)
print("energy:", result.eigenvalue.real)
print("max-cut objective:", result.eigenvalue.real + offset)
print("solution:", x)
print("solution objective:", qp.objective.evaluate(x))
colors = ["r" if x[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
algorithm_globals.random_seed = 123
seed = 10598
# construct SamplingVQE
optimizer = SPSA(maxiter=300)
ry = TwoLocal(qubitOp.num_qubits, "ry", "cz", reps=5, entanglement="linear")
vqe = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=optimizer)
# run SamplingVQE
result = vqe.compute_minimum_eigenvalue(qubitOp)
# print results
x = max_cut.sample_most_likely(result.eigenstate)
print("energy:", result.eigenvalue.real)
print("time:", result.optimizer_time)
print("max-cut objective:", result.eigenvalue.real + offset)
print("solution:", x)
print("solution objective:", qp.objective.evaluate(x))
# plot results
colors = ["r" if x[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
# create minimum eigen optimizer based on SamplingVQE
vqe_optimizer = MinimumEigenOptimizer(vqe)
# solve quadratic program
result = vqe_optimizer.solve(qp)
print(result.prettyprint())
colors = ["r" if result.x[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
# Generating a graph of 3 nodes
n = 3
num_qubits = n**2
tsp = Tsp.create_random_instance(n, seed=123)
adj_matrix = nx.to_numpy_array(tsp.graph)
print("distance\n", adj_matrix)
colors = ["r" for node in tsp.graph.nodes]
pos = [tsp.graph.nodes[node]["pos"] for node in tsp.graph.nodes]
draw_graph(tsp.graph, colors, pos)
from itertools import permutations
def brute_force_tsp(w, N):
a = list(permutations(range(1, N)))
last_best_distance = 1e10
for i in a:
distance = 0
pre_j = 0
for j in i:
distance = distance + w[j, pre_j]
pre_j = j
distance = distance + w[pre_j, 0]
order = (0,) + i
if distance < last_best_distance:
best_order = order
last_best_distance = distance
print("order = " + str(order) + " Distance = " + str(distance))
return last_best_distance, best_order
best_distance, best_order = brute_force_tsp(adj_matrix, n)
print(
"Best order from brute force = "
+ str(best_order)
+ " with total distance = "
+ str(best_distance)
)
def draw_tsp_solution(G, order, colors, pos):
G2 = nx.DiGraph()
G2.add_nodes_from(G)
n = len(order)
for i in range(n):
j = (i + 1) % n
G2.add_edge(order[i], order[j], weight=G[order[i]][order[j]]["weight"])
default_axes = plt.axes(frameon=True)
nx.draw_networkx(
G2, node_color=colors, edge_color="b", node_size=600, alpha=0.8, ax=default_axes, pos=pos
)
edge_labels = nx.get_edge_attributes(G2, "weight")
nx.draw_networkx_edge_labels(G2, pos, font_color="b", edge_labels=edge_labels)
draw_tsp_solution(tsp.graph, best_order, colors, pos)
qp = tsp.to_quadratic_program()
print(qp.prettyprint())
from qiskit_optimization.converters import QuadraticProgramToQubo
qp2qubo = QuadraticProgramToQubo()
qubo = qp2qubo.convert(qp)
qubitOp, offset = qubo.to_ising()
print("Offset:", offset)
print("Ising Hamiltonian:")
print(str(qubitOp))
result = exact.solve(qubo)
print(result.prettyprint())
# Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
ee = NumPyMinimumEigensolver()
result = ee.compute_minimum_eigenvalue(qubitOp)
print("energy:", result.eigenvalue.real)
print("tsp objective:", result.eigenvalue.real + offset)
x = tsp.sample_most_likely(result.eigenstate)
print("feasible:", qubo.is_feasible(x))
z = tsp.interpret(x)
print("solution:", z)
print("solution objective:", tsp.tsp_value(z, adj_matrix))
draw_tsp_solution(tsp.graph, z, colors, pos)
algorithm_globals.random_seed = 123
seed = 10598
optimizer = SPSA(maxiter=300)
ry = TwoLocal(qubitOp.num_qubits, "ry", "cz", reps=5, entanglement="linear")
vqe = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=optimizer)
result = vqe.compute_minimum_eigenvalue(qubitOp)
print("energy:", result.eigenvalue.real)
print("time:", result.optimizer_time)
x = tsp.sample_most_likely(result.eigenstate)
print("feasible:", qubo.is_feasible(x))
z = tsp.interpret(x)
print("solution:", z)
print("solution objective:", tsp.tsp_value(z, adj_matrix))
draw_tsp_solution(tsp.graph, z, colors, pos)
algorithm_globals.random_seed = 123
seed = 10598
# create minimum eigen optimizer based on SamplingVQE
vqe_optimizer = MinimumEigenOptimizer(vqe)
# solve quadratic program
result = vqe_optimizer.solve(qp)
print(result.prettyprint())
z = tsp.interpret(x)
print("solution:", z)
print("solution objective:", tsp.tsp_value(z, adj_matrix))
draw_tsp_solution(tsp.graph, z, colors, pos)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/marcoparadina/Qiskit_Hackathon_ETH
|
marcoparadina
|
# Write your code here
import numpy as np
import matplotlib.pyplot as plt
#Parameters of the distribution
mu = 0.1
sigma = 0.2
S0 = 50
#We want to simulate npaths=10000 paths of the r.v
#for tha we discretize the time from t=0 to T=10 in n=100 steps
n = 100
npaths=10000
T=10
dt =T/n
np.random.seed(1)
s = np.exp(
(mu - sigma ** 2 / 2) * dt
+ sigma * np.random.normal(0, np.sqrt(dt), size=(npaths,n)).T
)
s = np.vstack([np.ones(npaths), s])
s = S0 * s.cumprod(axis=0)
#This is for scaling the x axis correctly to 0 to T=10 in 100 steps
time=np.linspace(0,T,n+1)
t=np.full(shape=(npaths,n+1),fill_value=time).T
#Plot the paths
plt.plot(t,s)
plt.xlabel("$t$")
plt.ylabel("$x$")
plt.title(
"10000 paths of GBM for $\mu=0.1$ and $\sigma=0.2$"
)
plt.show()
#We calculate the expectation by averaging over the samples
expectation_numerical=sum(s[100])/npaths
expectation_numerical
# E_ST
#We compare with the theoretical result given by the analytical solution
#E=S_0*exp(mu*t)
expectation_analytical=S0*np.exp(mu*10)
expectation_analytical
#As we can see we get quite similar results
%matplotlib inline
from qiskit import QuantumCircuit, IBMQ
from qiskit import Aer
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Estimator, Options
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem, MaximumLikelihoodAmplitudeEstimation
from qiskit.circuit.library import LinearAmplitudeFunction
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import LogNormalDistribution
# Loading your IBM Q account(s)
IBMQ.save_account('a68087d9c262053b5e20eea6f7d5dd9a02252efbc722cc8774bde7a6b69f71b9b077e3cd8541be84c5841c130f3d8f1c4d3940bf42ccbd3f1caae0d843c42976')
# Write your code here
# number of qubits to represent the uncertainty
num_samples_qubits = 4
# parameters for considered random distribution
S0 = 50
T = 10
#parameters for log-normal distribution
mu = 0.1
sigma = 0.2
mean = np.exp(mu + sigma**2 / 2)
variance = (np.exp(sigma*2) - 1) * np.exp(2 * mu + sigma*2)
stddev = np.sqrt(variance)
#lowest and highest value considered
low = np.maximum(0, mean - 3 * stddev)
high = mean + 3* stddev
#We construct a circuit to load a log-normal random distribution into a quantum state.
preparation_model = LogNormalDistribution(
num_samples_qubits, mu=mu, sigma=sigma**2, bounds=(low, high)
)
preparation_model.num_qubits
# plot probability distribution
x = preparation_model.values
y = preparation_model.probabilities
plt.bar(x, y, width=0.2)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.grid()
plt.xlabel("$S_T$", size=15)
plt.ylabel("Probability", size=15)
plt.show()
# Write your code here
sim=Aer.get_backend('qasm_simulator')
num_samples_qubits = 4 #this number should be a power of 2
num_qubits = num_samples_qubits + 1 #add the target qubit that we will measure
circuit = QuantumCircuit(num_qubits)
circuit.append(preparation_model, range(num_samples_qubits))
def controlled_rotations(num_control_qubits, angle):
qc = QuantumCircuit(num_control_qubits+1)
#do the controlled rotations
for i in range(num_control_qubits-1, -1, -1):
qc.cry(2**(num_control_qubits-1-i)*angle, control_qubit=i,target_qubit=num_control_qubits)
return qc.to_gate()
#The bounds of the support of f(x)
x_l = 0.01
x_u = 0.3*sigma
num_fourier_terms = 4
P = (x_u-x_l) #period of the periodic function
delta = (x_u-x_l)/(2**num_samples_qubits-1) #step in the discretized space
#Initialize sampler to run circuits
#service = QiskitRuntimeService(channel='ibm_quantum')
#backend = service.backend('ibmq_qasm_simulator') #choose the simulator or device
sampler = Sampler()
#Arrays where fourier terms are stored
fourier_terms_cos = []
fourier_terms_sin = []
for n in range(num_fourier_terms):
w = 2*np.pi/P #phase of the fourier terms
theta = n*w*delta
alpha_cos=2*(np.pi)*x_l
alpha_sin=2*(np.pi)*x_l+np.pi/2
#circuit must be reinitialized everytime
circuit_fourier=circuit.copy()
#distinguish two cases:
#If we want to estimate the cos term:
circuit_sin=circuit_fourier.copy()
circuit_sin.ry(alpha_cos,num_samples_qubits)
circuit_sin.append(controlled_rotations(num_samples_qubits,theta),range(num_qubits))
#run QAE for the cos term
problem = EstimationProblem(circuit_sin, objective_qubits = num_samples_qubits)
mlae = MaximumLikelihoodAmplitudeEstimation(evaluation_schedule = 3, sampler = sampler)
mlae_result = mlae.estimate(problem)
fourier_terms_cos.append(1-2*mlae_result.estimation)
print("Estimate of a_",n+1,"is",1-2*mlae_result.estimation)
#If we want to estimate the sin term:
circuit_cos=circuit_fourier.copy()
circuit_cos.ry(alpha_sin,num_samples_qubits)
circuit_cos.append(controlled_rotations(num_samples_qubits,theta),range(num_qubits))
#run QAE for the sin term
problem = EstimationProblem(circuit_cos, num_samples_qubits)
mlae = MaximumLikelihoodAmplitudeEstimation(evaluation_schedule = 3, sampler = sampler)
mlae_result = mlae.estimate(problem)
fourier_terms_sin.append(1-2*mlae_result.estimation)
print("Estimate of b_",n+1,"is",1-2*mlae_result.estimation,"\n")
circuit_sin.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
#New version to compute coefficients
import numpy as np
import scipy.integrate as spi
import matplotlib.pyplot as plt
#x = np.linspace(45, 144, 100)
#y = np.piecewise(x, [((x >= 45) & (x <= 100)), ((x >= 100) & (x < 145))], [0, lambda x: x-100])
#plt.plot(x, y)
def f(x):
return np.piecewise(x, [((x >= 45) & (x <= 100)), ((x >= 100) & (x < 145))], [0, lambda x: x-100])
#t is the independent variable
x_l = 50
x_u = 107
P = (x_u-x_l) #period value
BT=0. #initian value of t (begin time)
ET=10. #final value of t (end time)
FS=100 #number of discrete values of t between BT and ET
#all discrete values of t in the interval from BT and ET
t_range = np.linspace(BT, ET, FS)
y_true = f(t_range) #the true f(t)
#function that computes the real fourier couples of coefficients (a0, 0), (a1, b1)...(aN, bN)
def compute_real_fourier_coeffs(func, N):
result = []
for n in range(N+1):
an = (2./P) * spi.quad(lambda t: func(t) * np.cos(2 * np.pi * n * t / P), 0, P)[0]
bn = (2./P) * spi.quad(lambda t: func(t) * np.sin(2 * np.pi * n * t / P), 0, P)[0]
result.append((an, bn))
return np.array(result)
def fit_func_by_fourier_series_with_real_coeffs(t, AB):
result = 0.
A = AB[:,0]
B = AB[:,1]
for n in range(0, len(AB)):
if n > 0:
result += A[n] * fourier_terms_cos[n] + B[n]* fourier_terms_sin[n]
else:
result += A[0]
return result
def f(t):
return max(np.exp(mu*t) - 100, 0)
AB = compute_real_fourier_coeffs(f,num_fourier_terms-1 )
est = fit_func_by_fourier_series_with_real_coeffs(0, AB)
print(est)
#The results for different values of n (precission of Fourier)
#44.698394965554456 for n=4
#41.10875168637083 for n=8
#48.88444858978799 for n=12
#37.715743030433934 for n=16
#45.077490680927184 for n=20
#48.90604298278019 for n=32
#We choose the Maximum Likelihood Amplitude estimation because it is one of the fastest ones and it is
#also subject to paralelization for a more efficient use
# Write your code here
# Write your code here
# Build your presentation and rehearse your pitch!
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
import qiskit
from qiskit import *
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
nshots = 8192
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_belem')
from qiskit.tools.monitor import job_monitor
def state_prep_psip():
qr = QuantumRegister(2); qc = QuantumCircuit(qr, name = 'sprep')
qc.h(qr[0]); qc.cx(qr[0],qr[1]); qc.x(qr[1]) # prepara psi+_01
return qc
state_prep_psip_ = state_prep_psip(); state_prep_psip_.draw(output = 'mpl')
def qc_dfp():
qr = QuantumRegister(2); qc = QuantumCircuit(qr, name='DFP')
qc.cz(qr[0],qr[1]); qc.cy(qr[0], qr[1])
return qc
qc_dfp_ = qc_dfp(); qc_dfp_.draw(output = 'mpl')
def qc_df():
qr = QuantumRegister(1); qc = QuantumCircuit(qr, name='DF')
qc.s(qr[0]); qc.h(qr[0]); qc.s(qr[0])
return qc
qc_df_ = qc_df(); qc_df_.draw(output = 'mpl')
def qc_pmo():
qr = QuantumRegister(2); qc = QuantumCircuit(qr, name='PMO')
qc.cx(qr[1],qr[0])
return qc
qc_pmo_ = qc_pmo(); qc_pmo_.draw(output = 'mpl')
def qc_pqo():
qr = QuantumRegister(1); qc = QuantumCircuit(qr, name='PQO')
qc.h(qr[0]); qc.s(qr[0])
return qc
qc_pqo_ = qc_pqo(); qc_pqo_.draw(output = 'mpl')
def qc_espelho():
qr = QuantumRegister(1); qc = QuantumCircuit(qr, name='espelho')
qc.z(qr[0]); qc.y(qr[0])
return qc
qc_espelho_ = qc_espelho(); qc_espelho_.draw(output = 'mpl')
import math
def qc_fase(ph):
qr = QuantumRegister(1); qc = QuantumCircuit(qr, name='fase')
qc.p(ph, qr[0])
return qc
qc_fase_ = qc_fase(math.pi); qc_fase_.draw(output = 'mpl')
def qc_apagador(ph):
qr = QuantumRegister(3); qc = QuantumCircuit(qr, name = 'apagador')
state_prep_psip_ = state_prep_psip(); qc.append(state_prep_psip_, [qr[0],qr[1]]) # sprep
qc.barrier()
qc_dfp_ = qc_dfp(); qc.append(qc_dfp_, [qr[1],qr[2]]) # DFP
qc_pmo_ = qc_pmo(); qc.append(qc_pmo_, [qr[1],qr[2]]) # PMO
qc_pqo_ = qc_pqo(); qc.append(qc_pqo_, [qr[0]]) # PQO
qc_espelho_ = qc_espelho(); qc.append(qc_espelho_, [qr[2]]) # espelho
qc_fase_ = qc_fase(ph); qc.append(qc_fase_, [qr[2]]) # fase
qc_df_ = qc_df(); qc.append(qc_df_, [qr[2]]) # DF
return qc
qc_apagador_ = qc_apagador(math.pi/3)
qc_apagador_.draw(output = 'mpl')
qc_apagador_.decompose().draw(output = 'mpl')
import numpy as np
from numpy import random
phmax = 2*math.pi; dph = phmax/20; ph = np.arange(0, phmax+dph, dph)#; ph
d = ph.shape[0]; PD0teo = np.zeros(d); PD0sim = np.zeros(d); PD0exp = np.zeros(d)
ri = random.randint(0,d)
for j in range(0, d):
PD0teo[j] = 1/2 # theoretical
qr = QuantumRegister(3); qc = QuantumCircuit(qr)
qc_apagador_ = qc_apagador(ph[j]); qc.append(qc_apagador_, [qr[0],qr[1],qr[2]]) # apagador q
qstc = state_tomography_circuits(qc, qr[2]) # circuit for state tomography
job = qiskit.execute(qstc, Aer.get_backend('qasm_simulator'), shots=nshots)
qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq')
PD0sim[j] = rho[0,0].real
#if j == ri:
# print(rho)
# 1º fiz as simulações, só depois adicionei o código para os experimentos
'''job = qiskit.execute(qstc, backend = device, shots = nshots)
print(job.job_id()); job_monitor(job)
qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq')
PD0exp[j] = rho[0,0].real'''
import matplotlib
from matplotlib import pyplot as plt
matplotlib.rcParams.update({'font.size':12}); plt.figure(figsize = (6,4), dpi = 100)
plt.plot(ph, PD0teo, label = r'$P_{teo}(D_{0})$')
plt.plot(ph, PD0sim, 'o', label = r'$P_{sim}(D_{0})$')
#plt.plot(ph, PD0exp, '*', label = r'$P_{exp}(D_{0})$')
plt.legend(); plt.xlabel(r'$\phi$'); plt.ylim(-0.02,1.02);
plt.title('IMZ com info de caminho'); plt.show()
# Nesse caso, não foram feitas medidas projetivas para obtenção de informação de caminho
qr = QuantumRegister(1); cr = ClassicalRegister(1); qc = QuantumCircuit(qr,cr)
qc.h(qr[0]); qc.measure(qr[0],cr[0])
job = qiskit.execute(qc, Aer.get_backend('qasm_simulator'), shots=10)
res = job.result().get_counts()
if '0' in res:
print('z = 0, ', res, ', ', res['0'])
elif '1' in res:
print('z = 1, ', res, ', ', res['1'])
qc.draw(output = 'mpl')
for j in range(0,1):
qr = QuantumRegister(2); cr = ClassicalRegister(2); qc = QuantumCircuit(qr,cr)
qc.h(qr[0]);
qc.measure(qr[0],cr[0])
qc.h(qr[1]); qc.measure(qr[1],cr[1])
job = qiskit.execute(qc, Aer.get_backend('qasm_simulator'), shots=10)
res = job.result().get_counts()
print(res)
if '00' in res:
P00 = 1; print('P00',P00)
elif '01' in res:
P01 = 1; print('P01',P01)
qc.draw(output = 'mpl')
# O apagador quântico mesmo, com as medidas
def apagadorM(ph):
qr = QuantumRegister(3); cr = ClassicalRegister(2); qc = QuantumCircuit(qr, cr)
qc_apagador_ = qc_apagador(ph); qc.append(qc_apagador_, [qr[0],qr[1],qr[2]])
qc.measure(qr[0],cr[0]) # medida da polarização de A
qc.measure(qr[2],cr[1]) # medida do caminho de B
return qc
apagadorM_ = apagadorM(math.pi/8); apagadorM_.draw(output = 'mpl')
qc = apagadorM(math.pi/8)
job = qiskit.execute(qc, Aer.get_backend('qasm_simulator'), shots=1)
res = job.result().get_counts(); print(res)
nshots = 1000
phmax = 2*math.pi; dph = phmax/20; ph = np.arange(0, phmax+dph, dph); d = ph.shape[0]
PD0teo0 = np.zeros(d); PD0sim0 = np.zeros(d); PD0exp0 = np.zeros(d)
PD0teo1 = np.zeros(d); PD0sim1 = np.zeros(d); PD0exp1 = np.zeros(d)
for j in range(0, d):
PD0teo0[j] = (1 + math.cos(ph[j]))/2; PD0teo1[j] = (1 - math.cos(ph[j]))/2
qc = apagadorM(ph[j])
N0 = 0; N1 = 0; N0e = 0; N1e = 0
for k in range(0, nshots): # não usar esse loop
job = qiskit.execute(qc, Aer.get_backend('qasm_simulator'), shots=1)
res = job.result().get_counts()#; print(res)
if '00' in res or '10' in res:
N0 += 1
elif '01' in res or '11' in res:
N1 += 1
if '00' in res:
PD0sim0[j] += 1
elif '01' in res:
PD0sim1[j] += 1
'''job = qiskit.execute(qc, Aer.get_backend(device), shots=1)
res = job.result().get_counts()
if '00' in res or '10' in res:
N0e += 1
elif '01' in res or '11' in res:
N1e += 1
if '00' in res:
PD0exp0[j] += 1
elif '01' in res:
PD0exp1[j] += 1'''
PD0sim0 = PD0sim0/N0; PD0sim1 = PD0sim1/N1
#PD0exp0 = PD0exp0/N0e; PD0exp1 = PD0exp1/N1e
# sem o loop em k
matplotlib.rcParams.update({'font.size':12}); plt.figure(figsize = (5,3.3), dpi = 100)
plt.plot(ph, PD0teo0, '-', label = r'$P_{teo}(0,0)$')
plt.plot(ph, PD0teo1, '-.', label = r'$P_{teo}(1,0)$')
plt.plot(ph, PD0sim0, 'o', label = r'$2P_{sim}(0,0)$')
plt.plot(ph, PD0sim1, '*', label = r'$2P_{sim}(1,0)$')
#plt.plot(ph, PD0exp0, '+', label = r'$2P_{exp}(0,0)$')
#plt.plot(ph, PD0exp1, 'd', label = r'$2P_{exp}(1,0)$')
plt.legend(bbox_to_anchor=(1.05, 1.0), loc='upper left')
plt.xlabel(r'$\phi$'); plt.ylim(-0.05,1.05);
plt.title('IMZ com apagador de info de caminho'); plt.show()
def qc_MBB():
qr = QuantumRegister(2); qc = QuantumCircuit(qr)
qc.h(qr[0]); qc.cx(qr[0],qr[1])
return qc
qc_MBB_ = qc_MBB(); qc_MBB_.draw(output = 'mpl')
def qc_apagadorE(ph):
qr = QuantumRegister(3); qc = QuantumCircuit(qr, name = 'apagador')
state_prep_psip_ = state_prep_psip(); qc.append(state_prep_psip_, [qr[0],qr[1]]) # sprep
qc_dfp_ = qc_dfp(); qc.append(qc_dfp_, [qr[1],qr[2]]) # DFP
qc_pmo_ = qc_pmo(); qc.append(qc_pmo_, [qr[1],qr[2]]) # PMO
qc_pqo_ = qc_pqo(); qc.append(qc_pqo_, [qr[0]]) # PQO
qc_espelho_ = qc_espelho(); qc.append(qc_espelho_, [qr[2]]) # espelho
qc_fase_ = qc_fase(ph); qc.append(qc_fase_, [qr[2]]) # fase
qc_df_ = qc_df(); qc.append(qc_df_, [qr[2]]) # DF
return qc
qc_apagador_ = qc_apagador(math.pi/3); qc_apagador_.draw(output = 'mpl')
|
https://github.com/matheusmtta/Quantum-Computing
|
matheusmtta
|
import numpy as np
from numpy import linalg as LA
from scipy.linalg import expm, sinm, cosm
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import math
from scipy import stats
%matplotlib inline
from IPython.display import Image, display, Math, Latex
sns.set(color_codes=True)
#number of vertices
n = 4
#Define adjacency matrix A_Cn
A = np.zeros((n, n))
for i in range(n):
j1 = (i - 1)%n
j2 = (i + 1)%n
A[i][j1] = 1
A[i][j2] = 1
#Define our initial state Psi_a
psi_a = np.zeros(n)
psi_a[3] = 1
#Define the time t >= 0
t = math.pi/2
#Exponentiate or hamiltonian
U_t = expm(1j*t*A)
U_mt = expm(1j*(-t)*A)
#Compute Psi_t
psi_t = U_t @ psi_a
#Compute the probabilities
prob_t = abs(psi_t)**2
M_t = U_t*U_mt
M_t = np.around(M_t, decimals = 3)
M_t
x = M_t[:, 0].real
plt.bar(range(len(x)), x, tick_label=[0, 1, 2, 3])
plt.xlabel('Vertices')
plt.ylabel('Probability')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can choose different colors for the real and imaginary parts of the density matrix.
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = DensityMatrix(qc)
plot_state_city(state, color=['midnightblue', 'crimson'], title="New State City")
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import *
qc = QuantumCircuit(2)
qc.h(i)
qc.crz (PI/4, 0, 1)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Necessary imports
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import clear_output
from qiskit import QuantumCircuit
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import ZFeatureMap, RealAmplitudes
from qiskit.utils import algorithm_globals
from sklearn.datasets import make_classification
from sklearn.preprocessing import MinMaxScaler
from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier
from qiskit_machine_learning.neural_networks import EffectiveDimension, LocalEffectiveDimension
from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN
# set random seed
algorithm_globals.random_seed = 42
num_qubits = 3
# create a feature map
feature_map = ZFeatureMap(feature_dimension=num_qubits, reps=1)
# create a variational circuit
ansatz = RealAmplitudes(num_qubits, reps=1)
# combine feature map and ansatz into a single circuit
qc = QuantumCircuit(num_qubits)
qc.append(feature_map, range(num_qubits))
qc.append(ansatz, range(num_qubits))
qc.decompose().draw("mpl")
# parity maps bitstrings to 0 or 1
def parity(x):
return "{:b}".format(x).count("1") % 2
output_shape = 2 # corresponds to the number of classes, possible outcomes of the (parity) mapping.
# construct QNN
qnn = SamplerQNN(
circuit=qc,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
interpret=parity,
output_shape=output_shape,
sparse=False,
)
# we can set the total number of input samples and weight samples for random selection
num_input_samples = 10
num_weight_samples = 10
global_ed = EffectiveDimension(
qnn=qnn, weight_samples=num_weight_samples, input_samples=num_input_samples
)
# we can also provide user-defined samples and parameters
input_samples = algorithm_globals.random.normal(0, 1, size=(10, qnn.num_inputs))
weight_samples = algorithm_globals.random.uniform(0, 1, size=(10, qnn.num_weights))
global_ed = EffectiveDimension(qnn=qnn, weight_samples=weight_samples, input_samples=input_samples)
# finally, we will define ranges to test different numbers of data, n
n = [5000, 8000, 10000, 40000, 60000, 100000, 150000, 200000, 500000, 1000000]
global_eff_dim_0 = global_ed.get_effective_dimension(dataset_size=n[0])
d = qnn.num_weights
print("Data size: {}, global effective dimension: {:.4f}".format(n[0], global_eff_dim_0))
print(
"Number of weights: {}, normalized effective dimension: {:.4f}".format(d, global_eff_dim_0 / d)
)
global_eff_dim_1 = global_ed.get_effective_dimension(dataset_size=n)
print("Effective dimension: {}".format(global_eff_dim_1))
print("Number of weights: {}".format(d))
# plot the normalized effective dimension for the model
plt.plot(n, np.array(global_eff_dim_1) / d)
plt.xlabel("Number of data")
plt.ylabel("Normalized GLOBAL effective dimension")
plt.show()
num_inputs = 3
num_samples = 50
X, y = make_classification(
n_samples=num_samples,
n_features=num_inputs,
n_informative=3,
n_redundant=0,
n_clusters_per_class=1,
class_sep=2.0,
)
X = MinMaxScaler().fit_transform(X)
y = 2 * y - 1 # labels in {-1, 1}
estimator_qnn = EstimatorQNN(
circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters
)
# callback function that draws a live plot when the .fit() method is called
def callback_graph(weights, obj_func_eval):
clear_output(wait=True)
objective_func_vals.append(obj_func_eval)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
# construct classifier
initial_point = algorithm_globals.random.random(estimator_qnn.num_weights)
estimator_classifier = NeuralNetworkClassifier(
neural_network=estimator_qnn,
optimizer=COBYLA(maxiter=80),
initial_point=initial_point,
callback=callback_graph,
)
# create empty array for callback to store evaluations of the objective function (callback)
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
estimator_classifier.fit(X, y)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
estimator_classifier.score(X, y)
trained_weights = estimator_classifier.weights
# get Local Effective Dimension for set of trained weights
local_ed_trained = LocalEffectiveDimension(
qnn=estimator_qnn, weight_samples=trained_weights, input_samples=X
)
local_eff_dim_trained = local_ed_trained.get_effective_dimension(dataset_size=n)
print(
"normalized local effective dimensions for trained QNN: ",
local_eff_dim_trained / estimator_qnn.num_weights,
)
# get Local Effective Dimension for set of untrained weights
local_ed_untrained = LocalEffectiveDimension(
qnn=estimator_qnn, weight_samples=initial_point, input_samples=X
)
local_eff_dim_untrained = local_ed_untrained.get_effective_dimension(dataset_size=n)
print(
"normalized local effective dimensions for untrained QNN: ",
local_eff_dim_untrained / estimator_qnn.num_weights,
)
# plot the normalized effective dimension for the model
plt.plot(n, np.array(local_eff_dim_trained) / estimator_qnn.num_weights, label="trained weights")
plt.plot(
n, np.array(local_eff_dim_untrained) / estimator_qnn.num_weights, label="untrained weights"
)
plt.xlabel("Number of data")
plt.ylabel("Normalized LOCAL effective dimension")
plt.legend()
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
#Create the random probability Vector
import numpy as np
np.random.seed(999999)
target_distr = np.random.rand(2)
#print (target_distr)
# We now convert the random vector into a valid probability vector
target_distr /= sum(target_distr)
print (target_distr) #This is our original state, we want our result close to this
#This block of code is to make a function that takes the parameters of our single U3 variational form as argument
#and returns the corresponding quantum circuit
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
def get_var_form(params):
qr = QuantumRegister(1, name="q")
cr = ClassicalRegister(1, name='c')
qc = QuantumCircuit(qr, cr)
qc.u3(params[0], params[1], params[2], qr[0])
qc.measure(qr, cr[0])
return qc
#Now specify the objective function which takes as input a list of the variational form's parameter and returns
#the cost associated with those parameters(how much the final state is differ from intial state)
from qiskit import Aer, execute
backend = Aer.get_backend("qasm_simulator")
NUM_SHOTS = 10000
def get_probability_distribution(counts):
output_distr = [v / NUM_SHOTS for v in counts.values()]
#print("Counts",counts)
print ("Count Values",counts.values())
#print("Output_distr",output_distr)
#print("Target_distr",target_distr)
if len(output_distr) == 1:
output_distr.append(0)
return output_distr
def objective_function(params):
# Obtain a quantum circuit instance from the paramters
qc = get_var_form(params)
# Execute the quantum circuit to obtain the probability distribution associated with the current parameters
result = execute(qc, backend, shots=NUM_SHOTS).result()
print("Results",result.get_counts(qc))
# Obtain the counts for each measured state, and convert those counts into a probability vector
output_distr = get_probability_distribution(result.get_counts(qc))
# Calculate the cost as the distance between the output distribution and the target distribution
cost = sum([np.abs(output_distr[i] - target_distr[i]) for i in range(2)])
#display(qc.draw('mpl'))
print('Input_distr:',target_distr)
print('Output_distr:',output_distr)
print('Cost',cost)
print('-------------')
return cost #This step is similar as to get the minimum energy state using variational principle
#Finally COBYLA optimizer is used and run the algorithm.
from qiskit.aqua.components.optimizers import COBYLA
# Constrained Optimization by Linear Approximation optimizer (COBYLA)
# Initialize the COBYLA optimizer
optimizer = COBYLA(maxiter=500, disp=True,tol=0.0001)
# Create the initial parameters (noting that our single qubit variational form has 3 parameters)
params = np.random.rand(3)
print ('Input parameters:->',params)
ret = optimizer.optimize(num_vars=3, objective_function=objective_function, initial_point=params)
#print("ret==>",ret)
# Obtain the output distribution using the final parameters
qc = get_var_form(ret[0])
counts = execute(qc, backend, shots=NUM_SHOTS).result().get_counts(qc)
output_distr = get_probability_distribution(counts)
print("Target Distribution:", target_distr)
print("Obtained Distribution:", output_distr)
print("Output Error (Manhattan Distance):", ret[1])
print("Parameters Found:", ret[0])
from qiskit.aqua.algorithms import VQE, NumPyEigensolver
import matplotlib.pyplot as plt
import numpy as np
from qiskit.chemistry.components.variational_forms import UCCSD
from qiskit.chemistry.components.initial_states import HartreeFock
from qiskit.circuit.library import EfficientSU2
from qiskit.aqua.components.optimizers import COBYLA, SPSA, SLSQP
from qiskit.aqua.operators import Z2Symmetries
from qiskit import IBMQ, BasicAer, Aer
from qiskit.chemistry.drivers import PySCFDriver, UnitsType
from qiskit.chemistry import FermionicOperator
from qiskit import IBMQ
from qiskit.aqua import QuantumInstance
from qiskit.ignis.mitigation.measurement import CompleteMeasFitter
from qiskit.providers.aer.noise import NoiseModel
def get_qubit_op(dist):
#Step 1: Define a molecule
#Here, we use LiH in the sto3g basis with the PySCF driver as an example.
#The molecule object records the information from the PySCF driver.
driver = PySCFDriver(atom="Li .0 .0 .0; H .0 .0 " + str(dist), unit=UnitsType.ANGSTROM,
charge=0, spin=0, basis='sto3g')
#sto3g-> small toy model
molecule = driver.run()
#ferOp_nofreeze=FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals)
freeze_list = [0]
remove_list = [-3, -2]
repulsion_energy = molecule.nuclear_repulsion_energy
#under Born Opperhiemer Approximation all the nuclei are stationary
#so their contribution to the ground state energy is only nuclear repulsion.
#print(repulsion_energy) #in Hatree Unit
num_particles = molecule.num_alpha + molecule.num_beta #number of electrons in the system
#print("number of particles==>",num_particles) #4
num_spin_orbitals = molecule.num_orbitals * 2 #number of spin orbital is twice of that space orbitals
print("number of spin orbitals",num_spin_orbitals)
#as spin degeneracy is 2
remove_list = [x % molecule.num_orbitals for x in remove_list]
#% in interpreted language: Reminder=dividend-divisor*floor(quotient)
#==> R_0 = -3 -6*(-1) = +3 and R_1= -2-6*(-1) = +4
#print ('freeze_list=>',freeze_list) #[0]
#print ('Remove list=>',remove_list) #[3,4]
freeze_list = [x % molecule.num_orbitals for x in freeze_list]
remove_list = [x - len(freeze_list) for x in remove_list]
#print ('freeze_list=>',freeze_list) #[0]
#print ('Remove list=>',remove_list) #[2,3]
remove_list += [x + molecule.num_orbitals - len(freeze_list) for x in remove_list]
freeze_list += [x + molecule.num_orbitals for x in freeze_list]
print ('Remove list=>',remove_list) #[2,3,7,8]
print ('freeze_list=>',freeze_list) #[0,6]
#Define Fermionic Operator
ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals)
ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list)# the frozen electron(2 inner electron from Li+)
#do not interact with other electrons but contribute by a constant term to the total ground state energy
num_spin_orbitals -= len(freeze_list) #rescale num_spin_orbiatls after freeze list
num_particles -= len(freeze_list)
print("number of particles==>",num_particles) #print=>2
ferOp = ferOp.fermion_mode_elimination(remove_list)
h1=molecule.one_body_integrals
h2=molecule.two_body_integrals
#print('one body integral=>')
#print (ferOp_nofreeze.h1) #intialially it has 12
#print('one body integral after freezeing and removing')
#print(ferOp.h1) # after applying freeze and remove it drop down to 6
#print('-------------------------------------------')
#print('two body integrals=>')
#print(ferOp.h2)
#print ('------------------------------')
num_spin_orbitals -= len(remove_list)
#print("========================Fermionic Operator After applying freezing and removing list==================")
#print (ferOp)
#Create a Qubit Operator
qubitOp = ferOp.mapping(map_type='parity', threshold=0.00000001)
#print ("=====Qubit Operator berfore applying parity========")
print(qubitOp) # qubits is 6 which is same as fermionic operator after applying freezing and removing list
print(Z2Symmetries.find_Z2_symmetries(qubitOp))#Show spin and charge symmetries, so two conserved quantities
#which will further helps to reduce the qubitOp
qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles)
shift = energy_shift + repulsion_energy
#shift is the enegy comming from repulsion energy of two nuclei under Born–Oppenheimer approximation and
#and freezing two electrons
#print("-----------------Qubit Operator after appying parity---------------------")
#print (qubitOp) # give type of operator(paulis) working on number of qubits(6) and number of paulis operator
#print(qubitOp.print_details())
return qubitOp, num_particles, num_spin_orbitals, shift
backend = BasicAer.get_backend("statevector_simulator")
#distances=[1.6]
distances = np.arange(0.5, 4.0, 0.1)
exact_energies = []
vqe_energies = []
optimizer = SLSQP(maxiter=5)
#Sequential Least SQuares Programming optimizer (SLSQP)
for dist in distances:
qubitOp, num_particles, num_spin_orbitals, shift = get_qubit_op(dist) #Returing multiple values in python function
result = NumPyEigensolver(qubitOp).run() #Just to check with result obtained from VQE
exact_energies.append(np.real(result.eigenvalues) + shift)
#Create initial Guess state(Ansatz)
initial_state = HartreeFock(
num_spin_orbitals,
num_particles,
qubit_mapping='parity'
)
print(initial_state.bitstr)
HF_circuit=initial_state.construct_circuit('circuit')
display(HF_circuit.decompose().draw(output='mpl')) #inital Hatree Fock state
#UCCSD is used as problem has one and two body integral
var_form = UCCSD(
num_orbitals=num_spin_orbitals,
num_particles=num_particles,
initial_state=initial_state,
qubit_mapping='parity'
)
#print(var_form.single_excitations)
print("Number of Parameters",var_form.num_parameters)
#var_circuit=var_form.construct_circuit([2])
#display(var_circuit.decompose().draw('mpl'))
vqe = VQE(qubitOp, var_form, optimizer)
vqe_result = np.real(vqe.run(backend)['eigenvalue'] + shift)
vqe_energies.append(vqe_result)
print("Interatomic Distance:", np.round(dist, 2), "VQE Result:", vqe_result, "Exact Energy:", exact_energies[-1])
print("All energies have been calculated")
plt.plot(distances, exact_energies, label="Exact Energy")
#plt.plot(distances, vqe_energies, label="VQE Energy")
plt.xlabel('Atomic distance (Angstrom)')
plt.ylabel('Energy')
plt.legend()
plt.show()
init_state=HartreeFock(num_orbitals=4,num_particles=2,qubit_mapping='jordan_wigner')
print(init_state.bitstr) #give fermionic mode on which particle are occupied
HF_circuit=init_state.construct_circuit('circuit')
display(HF_circuit.decompose().draw('mpl'))
UCCSD_var_form=UCCSD(num_orbitals=4,num_particles=2,qubit_mapping='jordan_wigner',excitation_type='s',
method_singles='beta',initial_state=init_state,two_qubit_reduction=False,reps=1)
var_circuit=UCCSD_var_form.construct_circuit([1])
var_circuit.decompose().draw(output='mpl')
#print(UCCSD_var_form.single_excitations)
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
import matplotlib.pyplot as plt
import numpy as np
from qiskit import Aer
from qiskit.ml.datasets import breast_cancer
from qiskit.circuit.library import ZZFeatureMap
from qiskit.circuit.library.n_local.two_local import TwoLocal
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import VQC
from qiskit.aqua.components.optimizers import COBYLA
feature_map = ZZFeatureMap(feature_dimension=2, reps=1, entanglement='linear')
feature_map.draw(output="mpl")
var_form = TwoLocal(num_qubits=2, rotation_blocks = 'ry', entanglement_blocks = 'cx', entanglement = 'linear', reps = 1)
var_form.draw(output="mpl")
sample_Total, training_input, test_input, class_labels = breast_cancer(
training_size=100,
test_size=10,
n=2,
plot_data=True
)
backend = Aer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend)
optimizer = COBYLA()
vqc = VQC(optimizer = optimizer, feature_map = feature_map, var_form = var_form,
training_dataset = training_input, test_dataset = test_input)
result = vqc.run(quantum_instance)
print(result)
feature_map = ZZFeatureMap(feature_dimension=2, reps=2, entanglement='linear')
feature_map.draw(output="mpl")
var_form = TwoLocal(num_qubits=2, rotation_blocks = 'ry', entanglement_blocks = 'cx', entanglement = 'linear', reps = 2)
var_form.draw(output="mpl")
vqc = VQC(optimizer = optimizer, feature_map = feature_map, var_form = var_form,
training_dataset = training_input, test_dataset = test_input)
result = vqc.run(quantum_instance)
print(result)
|
https://github.com/apcarrik/qiskit-dev
|
apcarrik
|
from qiskit import QuantumCircuit
from qiskit.compiler import transpile
from qiskit.transpiler import PassManager
# Create simple circuit with toffoli gate
circ = QuantumCircuit(3)
circ.ccx(0,1,2)
circ.draw('mpl').show()
# Unroll circuit (show base gates)
from qiskit.transpiler.passes import Unroller
pass_ = Unroller(['u1', 'u2', 'u3', 'cx'])
pm = PassManager(pass_)
new_circ = pm.run(circ)
new_circ.draw('mpl').show()
# Show transpiler pass options
from qiskit.transpiler import passes
qis_passes = [pass_ for pass_ in dir(passes) if pass_[0].isupper()]
print(qis_passes)
### Different Variants of the Same Pass
from qiskit.transpiler import CouplingMap, Layout
from qiskit.transpiler.passes import BasicSwap, LookaheadSwap, StochasticSwap
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
circuit = QuantumCircuit(7)
circuit.h(3)
circuit.cx(0, 6)
circuit.cx(6, 0)
circuit.cx(0, 1)
circuit.cx(3, 1)
circuit.cx(3, 0)
circuit.draw('mpl').show()
coupling_map = CouplingMap(couplinglist=coupling)
bs = BasicSwap(coupling_map=coupling_map)
pass_manager = PassManager(bs)
basic_circ = pass_manager.run(circuit)
basic_circ.draw('mpl').show()
ls = LookaheadSwap(coupling_map=coupling_map)
pass_manager = PassManager(ls)
lookahead_circ = pass_manager.run(circuit)
lookahead_circ.draw('mpl').show()
ss = StochasticSwap(coupling_map=coupling_map)
pass_manager = PassManager(ss)
stochastic_circ = pass_manager.run(circuit)
stochastic_circ.draw('mpl').show()
### Preset Pass Managers
# Optimizes circuit baed on 4 optimization levels (0-3)
import math
from qiskit.test.mock import FakeTokyo
backend = FakeTokyo()
qc = QuantumCircuit(10)
random_state = [
1 / math.sqrt(4) * complex(0,1),
1 / math.sqrt(8) * complex(0,1),
0,
0,
0,
0,
0,
0,
1 / math.sqrt(8) * complex(1,0),
1 / math.sqrt(8) * complex(0,1),
0,
0,
0,
0,
1 / math.sqrt(4) * complex(1,0),
1 / math.sqrt(8) * complex(1,0)
]
qc.initialize(random_state, range(4))
qc.draw('mpl').show()
# Map to 20 qubit Tokyo device with different optimization levels
optimized_0 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=0)
print('Optimization level: 0')
print('gates = ', optimized_0.count_ops())
print('depth = ', optimized_0.depth())
optimized_1 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=1)
print('Optimization level: 1')
print('gates = ', optimized_1.count_ops())
print('depth = ', optimized_1.depth())
optimized_2 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=2)
print('Optimization level: 2')
print('gates = ', optimized_2.count_ops())
print('depth = ', optimized_2.depth())
optimized_3 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=3)
print('Optimization level: 3')
print('gates = ', optimized_3.count_ops())
print('depth = ', optimized_3.depth())
##### Introducing the DAG #####
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c,2)
circ.draw('mpl').show()
# Show the DAG representation of circuit
from qiskit.converters import circuit_to_dag
from qiskit.tools.visualization import dag_drawer
dag = circuit_to_dag(circ)
dag_drawer(dag)
# Get all op nodes in DAG & examine Node details
op_nodes = dag.op_nodes()
print(op_nodes)
for i,node in enumerate(dag.op_nodes()):
print('node ', i)
print('node name: ', node.name)
print('node op: ', node.op)
print('node qargs: ', node.qargs)
print('node cargs: ', node.cargs)
print('node condition: ', node.condition)
# Add an operation to the back
from qiskit.circuit.library import HGate
dag.apply_operation_back(HGate(), qargs=[q[0]])
dag_drawer(dag)
# Add an operation to the front
from qiskit.circuit.library import CCXGate
dag.apply_operation_front(CCXGate(), qargs=[q[0], q[1], q[2]], cargs=[])
dag_drawer(dag)
# Substitute a node within a circuit
from qiskit.circuit.library import CHGate, U2Gate, CXGate
mini_dag = DAGCircuit()
p = QuantumRegister(2, "p")
mini_dag.add_qreg(p)
mini_dag.apply_operation_back(CHGate(), qargs=[p[0], p[1]])
mini_dag.apply_operation_back(U2Gate(0.1,0.2), qargs=[ p[1]])
# Substitute the cx node with above mini-dag
cx_node = dag.op_nodes(op=CXGate).pop()
dag.substitute_node_with_dag(node=cx_node, input_dag=mini_dag, wires=[p[0], p[1]])
dag_drawer(dag)
# Convert back to regular QuantumCircuit object
from qiskit.converters import dag_to_circuit
circuit = dag_to_circuit(dag)
circuit.draw('mpl').show()
### Implementing a BasicMapper Pass
from copy import copy
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.transpiler import Layout
from qiskit.circuit.library import SwapGate
class BasicSwap(TransformationPass):
""" Maps (with minimum effort) a DAGCircuit onto a `coupling_map` adding swap gates."""
def __init__(self,
coupling_map,
initial_layout=None):
"""Maps a DAGCircuit onto a `coupling_map` using swap gates.
Args:
coupling_map (CouplingMap): Directed graph representing a coupling map.
initial_layout (Layout): initial layout of qubits in mapping.
"""
super().__init__()
self.coupling_map = coupling_map
self.initial_layout = initial_layout
def run(self,
dag):
"""Runs the BasicSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
Raises:
TranspilerError: if the coupling map or the layout are not
compatible with the DAG.
"""
new_dag = DAGCircuit()
for qreg in dag.qregs.values():
new_dag.add_qreg(qreg)
for creg in dag.cregs.values():
new_dag.add_creg(creg)
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
if len(dag.qubits) != len(self.initial_layout):
raise TranspilerError("The layout does not match the amount of qubits in the DAG")
if len(self.coupling_map.physical_qubits) != len(self.initial_layout):
raise TranspilerError("Mappers require to have the layout to be the same size as the coupling map")
canonical_register = dag.qregs['q']
trivial_layout = Layout.generate_trivial_layout(canonical_register)
current_layout = trivial_layout.copy()
for layer in dag.serial_layers():
subdag = layer['graph']
for gate in subdag.two_qubit_ops():
physical_q0 = current_layout[gate.qargs[0]]
physical_q1 = current_layout[gate.qargs[1]]
if self.coupling_map.distance(physical_q0, physical_q1) != 1:
# Insert a new layer with the SWAP(s).
swap_layer = DAGCircuit()
swap_layer.add_qreg(canonical_register)
path = self.coupling_map.shortest_undirected_path(physical_q0,physical_q1)
for swap in range(len(path) - 2):
connected_wire_1 = path[swap]
connected_wire_2 = path[swap+1]
qubit_1 = current_layout[connected_wire_1]
qubit_2 = current_layout[connected_wire_2]
# create the swap operation
swap_layer.apply_operation_back(SwapGate(),
qargs=[qubit_1, qubit_2],
cargs=[])
# layer insertion
order = current_layout.reorder_bits(new_dag.qubits)
new_dag.compose(swap_layer, qubits=order)
# update current_layout
for swap in range(len(path) - 2):
current_layout.swap(path[swap], path[swap+1])
order = current_layout.reorder_bits(new_dag.qubits)
new_dag.compose(subdag, qubits=order)
return new_dag
### Test pass on example circuit
q = QuantumRegister(7, 'q')
in_circ = QuantumCircuit(q)
in_circ.h(q[0])
in_circ.cx(q[0], q[4])
in_circ.cx(q[2], q[3])
in_circ.cx(q[6], q[1])
in_circ.cx(q[5], q[0])
in_circ.rz(0.1, q[2])
in_circ.cx(q[5], q[0])
# Create pass manager, pass example circuit to it, and obtain transformed circuit
from qiskit.transpiler import PassManager
from qiskit.transpiler import CouplingMap
from qiskit import BasicAer
pm = PassManager()
coupling = [[0,1], [1,2], [2,3], [3,4], [4,5], [5,6]]
coupling_map = CouplingMap(couplinglist=coupling)
pm.append([BasicSwap(coupling_map)])
out_circ = pm.run(in_circ)
in_circ.draw('mpl').show()
out_circ.draw('mpl').show()
### Transpiler Logging
# Set up Python logging
import logging
logging.basicConfig(level='DEBUG')
# Make test circuit to see debug log statements
from qiskit.test.mock import FakeTenerife
log_circ = QuantumCircuit(2,2)
log_circ.h(0)
log_circ.h(1)
log_circ.h(1)
log_circ.x(1)
log_circ.cx(0,1)
log_circ.measure([0,1], [0,1])
backend = FakeTenerife()
transpile(log_circ,backend)
# Adjust log level for the transpiler
logging.getLogger('qiskit.transpiler').setLevel('INFO')
transpile(log_circ, backend)
# Setting up logging to deal with parallel execution (naieve way)
logging.getLogger('qiskit_transpiler').setLevel('DEBUG')
circuits = [log_circ, log_circ, log_circ]
transpile(circuits, backend)
# Format logging to deal with parallel execution better
formatter = logging.Formatter('%(name)s - %(processName)-10s - %(levelname)s: %(message)s')
handler = logging.getLogger().handlers[0]
handler.setFormatter(formatter)
transpile(circuits, backend)
|
https://github.com/qiskit-community/qiskit-aqt-provider
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Alpine Quantum Technologies GmbH 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.
from math import isclose, pi
from typing import Callable
import pytest
import qiskit
from qiskit.circuit import Parameter, QuantumCircuit
from qiskit.primitives import (
BackendEstimator,
BackendSampler,
BaseEstimatorV1,
BaseSamplerV1,
Sampler,
)
from qiskit.providers import Backend, BackendV2
from qiskit.quantum_info import SparsePauliOp
from qiskit.transpiler.exceptions import TranspilerError
from qiskit_aqt_provider.primitives import AQTSampler
from qiskit_aqt_provider.primitives.estimator import AQTEstimator
from qiskit_aqt_provider.test.circuits import assert_circuits_equal
from qiskit_aqt_provider.test.fixtures import MockSimulator
@pytest.fixture(scope="module")
def assert_all_responses_were_requested() -> bool:
"""Disable pytest-httpx check that all mocked responses are used for this module.
Some tests in this module request the offline_simulator_no_noise_direct_access
fixture without using it, thus not calling the mocked HTTP responses it contains.
# TODO: use alternative HTTPXMock setup when available.
# See: https://github.com/Colin-b/pytest_httpx/issues/137
"""
return False
def test_backend_primitives_are_v1() -> None:
"""Check that `BackendSampler` and `BackendEstimator` have primitives V1 interfaces.
As of 2024-02-20, there are no backend primitives that provide V2 interfaces.
If this test fails, the `AQTSampler` and `AQTEstimator` docs as well as the user
guide must be updated.
An interface mismatch may be detected at other spots. This makes the detection explicit.
"""
assert issubclass(BackendSampler, BaseSamplerV1)
assert issubclass(BackendEstimator, BaseEstimatorV1)
@pytest.mark.parametrize(
"get_sampler",
[
# Reference implementation
lambda _: Sampler(),
# The AQT transpilation plugin doesn't support transpiling unbound parametric circuits
# and the BackendSampler doesn't fallback to transpiling the bound circuit if
# transpiling the unbound circuit failed (like the opflow sampler does).
# Sampling a parametric circuit with the generic BackendSampler is therefore not supported.
pytest.param(
lambda backend: BackendSampler(backend), marks=pytest.mark.xfail(raises=TranspilerError)
),
# The specialized implementation of the Sampler primitive for AQT backends delays the
# transpilation passes that require bound parameters.
lambda backend: AQTSampler(backend),
],
)
def test_circuit_sampling_primitive(
get_sampler: Callable[[Backend], BaseSamplerV1], any_offline_simulator_no_noise: BackendV2
) -> None:
"""Check that a `Sampler` primitive using an AQT backend can sample parametric circuits."""
theta = Parameter("θ")
qc = QuantumCircuit(2)
qc.rx(theta, 0)
qc.ry(theta, 0)
qc.rz(theta, 0)
qc.rxx(theta, 0, 1)
qc.measure_all()
assert qc.num_parameters > 0
sampler = get_sampler(any_offline_simulator_no_noise)
sampled = sampler.run(qc, [pi]).result().quasi_dists
assert sampled == [{3: 1.0}]
@pytest.mark.parametrize("theta", [0.0, pi])
def test_operator_estimator_primitive_trivial_pauli_x(
theta: float, offline_simulator_no_noise: MockSimulator
) -> None:
"""Use the Estimator primitive to verify that <0|X|0> = <1|X|1> = 0.
Define the parametrized circuit that consists of the single gate Rx(θ) with
θ=0,π. Applied to |0>, this creates the states |0>,|1>. The Estimator primitive
is then used to evaluate the expectation value of the Pauli X operator on the
state produced by the circuit.
"""
offline_simulator_no_noise.simulator.options.seed_simulator = 0
estimator = AQTEstimator(offline_simulator_no_noise, options={"shots": 200})
qc = QuantumCircuit(1)
qc.rx(theta, 0)
op = SparsePauliOp("X")
result = estimator.run(qc, op).result()
assert abs(result.values[0]) < 0.1
def test_operator_estimator_primitive_trivial_pauli_z(
offline_simulator_no_noise: MockSimulator,
) -> None:
"""Use the Estimator primitive to verify that:
<0|Z|0> = 1
<1|Z|1> = -1
<ψ|Z|ψ> = 0 with |ψ> = (|0> + |1>)/√2.
The sampled circuit is always Rx(θ) with θ=0,π,π/2 respectively.
The θ values are passed into a single call to the estimator, thus also checking
that the AQTEstimator can deal with parametrized circuits.
"""
offline_simulator_no_noise.simulator.options.seed_simulator = 0
estimator = AQTEstimator(offline_simulator_no_noise, options={"shots": 200})
theta = Parameter("θ")
qc = QuantumCircuit(1)
qc.rx(theta, 0)
op = SparsePauliOp("Z")
result = estimator.run([qc] * 3, [op] * 3, [[0], [pi], [pi / 2]]).result()
z0, z1, z01 = result.values
assert isclose(z0, 1.0) # <0|Z|0>
assert isclose(z1, -1.0) # <1|Z|1>
assert abs(z01) < 0.1 # <ψ|Z|ψ>, |ψ> = (|0> + |1>)/√2
@pytest.mark.parametrize(
"theta",
[
pi / 3,
-pi / 3,
pi / 2,
-pi / 2,
3 * pi / 4,
-3 * pi / 4,
15 * pi / 8,
-15 * pi / 8,
33 * pi / 16,
-33 * pi / 16,
],
)
def test_aqt_sampler_transpilation(theta: float, offline_simulator_no_noise: MockSimulator) -> None:
"""Check that the AQTSampler passes the same circuit to the backend as a call to
`backend.run` with the same transpiler call on the bound circuit would.
"""
theta_param = Parameter("θ")
# define a circuit with unbound parameters
qc = QuantumCircuit(2)
qc.rx(pi / 3, 0)
qc.rxx(theta_param, 0, 1)
qc.measure_all()
assert qc.num_parameters > 0
# sample the circuit, passing parameter assignments
sampler = AQTSampler(offline_simulator_no_noise)
sampler.run(qc, [theta]).result()
# the sampler was only called once
assert len(offline_simulator_no_noise.submitted_circuits) == 1
# get the circuit passed to the backend
((transpiled_circuit,),) = offline_simulator_no_noise.submitted_circuits
# compare to the circuit obtained by binding the parameters and transpiling at once
expected = qc.assign_parameters({theta_param: theta})
tr_expected = qiskit.transpile(expected, offline_simulator_no_noise)
assert_circuits_equal(transpiled_circuit, tr_expected)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
"""Imports for the notebook."""
_req = """This notebook is written for
qiskit-aqua==0.6.0
Your code may not execute properly.
"""
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import warnings
import qiskit
if "0.6" not in qiskit.__qiskit_version__.get("qiskit-aqua"):
warnings.warn(_req)
"""Optional: Turn off warnings for the notebook."""
warnings.filterwarnings("ignore")
"""Specific imports for QAOA with MaxCut."""
# Import the QAOA object
from qiskit.aqua.algorithms.adaptive import QAOA
# Import tools for the MaxCut problem
from qiskit.aqua.translators.ising.max_cut import (
get_max_cut_qubitops, max_cut_value, random_graph
)
from qiskit.aqua.operators.weighted_pauli_operator import (
Pauli, WeightedPauliOperator
)
# Import optimizers in Qiskit for finding the best parameters in the QAOA circuit
from qiskit.aqua.components.optimizers import ADAM, AQGD, COBYLA, POWELL
"""Helper function for drawing weighted graphs.
You don't need to know how this function works. You will see how to use it below.
"""
def draw_weighted(graph: nx.Graph,
pos_color: str = "blue",
neg_color: str = "red",
scale: float = 2.0,
**kwargs) -> None:
"""Shows a visual of a graph with edges scaled by weight and colored by sign.
Args:
graph: The weighted graph to visualize.
pos_color: Color for edges with a positive weight.
neg_color: Color for edges with a negative weight.
scale: Floating point value to scale edge weights by
in the visualization.
Keyword Args:
cut (List[Int]): A list of 0, 1 values specifying which
nodes are in which class. The number of
values must be equal to the number of
nodes in the graph.
"""
pos = nx.spring_layout(graph)
if "cut" in kwargs.keys():
keys = kwargs["cut"]
if len(keys) != len(graph.nodes):
raise ValueError(
f"ecolor_key has length {len(keys)} but graph has {len(graph.nodes)} nodes."
)
nx.draw_networkx_nodes(graph, pos, node_size=700, node_color=keys, cmap=plt.cm.Greens)
else:
nx.draw_networkx_nodes(graph, pos, node_size=700)
col = lambda sgn: pos_color if sgn > 0 else neg_color
for edge in graph.edges:
weight = graph.get_edge_data(*edge)["weight"]
sgn = np.sign(weight)
size = abs(weight)
nx.draw_networkx_edges(graph,
pos,
edgelist=[edge],
width=scale * size,
edge_color=col(sgn),
alpha=0.5)
nx.draw_networkx_labels(graph, pos, font_size=20)
plt.axis("off")
plt.show()
"""Define the graph for MaxCut via an adjacency matrix."""
nodes = 6 # Vary the number of nodes here
matrix = random_graph(n=nodes, edge_prob=0.5, seed=2)
print("The adjacency matrix is:")
print(matrix)
"""Convert the adjacency matrix to a (weighted) graph and visualize it."""
graph = nx.from_numpy_array(matrix, parallel_edges=False)
draw_weighted(graph)
"""TODO: Put a list of 1s and 0s to assign vertex sets and see
what the value of your cut is.
"""
cut = np.array([0, 1, 0, 0, 0, 0]) ### <-- Your code here!
print("The value of this cut is:", max_cut_value(cut, matrix))
"""Visualize the cut by coloring nodes in distinct vertex sets different colors."""
draw_weighted(graph, cut=[0, 0, 0, 1, 1, 1])
"""Pauli operators from matrix."""
op, shift = get_max_cut_qubitops(matrix)
"""Inspect the Pauli operators."""
print("Edge set of the graph:")
for edge in graph.edges:
print("Weight:", graph.get_edge_data(*edge)["weight"], "Edge:", edge)
print("\nWeighted Pauli operators.")
for pauli in op.paulis:
print(2 * np.real(pauli[0]), "*", pauli[1].to_label()[::-1])
"""Make the QAOA instance."""
qaoa = QAOA(op, POWELL(), p=1)
"""See the settings of the QAOA object."""
print(qaoa.print_settings())
"""Inspect the circuits."""
backend = qiskit.BasicAer.get_backend("qasm_simulator")
circs = qaoa.construct_circuit([1, 2], backend=backend)
print(f"There are {len(circs)} circuits.")
print(circs[0])
"""Set the number of points N to define the grid. Larger N ==> longer runtime."""
N = 10
gammas = np.linspace(-np.pi, np.pi, N)
betas = np.linspace(-np.pi, np.pi, N)
"""Minor hacks for the QAOA instance to make the grid search possible.
Run this cell without too much thought -- this is necessary because the way Aqua is set up.
"""
quantum_instance = qiskit.aqua.QuantumInstance(backend=qiskit.BasicAer.get_backend("qasm_simulator"))
qaoa._quantum_instance = quantum_instance
qaoa._use_simulator_operator_mode = True
"""Do the grid search and display the progress."""
import progressbar
bar = progressbar.ProgressBar(maxval=N**2)
costs = np.zeros((len(gammas), len(betas)), dtype=float)
bar.start()
for (ii, gamma) in enumerate(gammas):
for (jj, beta) in enumerate(betas):
costs[ii][jj] = qaoa._energy_evaluation(np.array([gamma, beta]))
bar.update(N * ii + jj)
bar.finish()
"""Visualize the landscape."""
plt.figure(figsize=(7, 7));
plt.imshow(costs, origin=(0, 0));
plt.xlabel("Gammas")
plt.ylabel("Betas")
plt.colorbar();
"""Your code here!"""
"""Write code to answer the above question here."""
print("Min cost =", np.min(costs)) # Your code here!
"""Get a quantum instance and run the algorithm."""
qaoa._optimizer = POWELL()
result = qaoa.run(quantum_instance)
"""View the optimal cost."""
qaoa.get_optimal_cost()
"""Get the circuit with optimal parameters."""
circ = qaoa.get_optimal_circuit()
qreg = circ.qregs[0]
creg = qiskit.ClassicalRegister(6)
circ.add_register(creg)
circ.measure(qreg, creg)
print(circ)
"""Execute the circuit to sample from it."""
job = qiskit.execute(circ, backend=backend, shots=100000)
res = job.result()
counts = res.get_counts()
"""Visualize the statistics."""
qiskit.visualization.plot_histogram(counts, figsize=(17, 6))
"""Get the top sampled bit strings."""
import operator
ntop = 10
top_cuts = sorted(counts, key=operator.itemgetter(1))
print(f"Top {ntop} sampled cuts.")
for cut in top_cuts[:ntop]:
print(cut[::-1])
"""Select a sampled cut and see its value."""
cut = np.array([1, 1, 0, 0, 0, 1]) ### <-- Your answer here!
print("The value of this cut is:", max_cut_value(cut, matrix))
"""Brute force search for the maximum cut."""
import itertools
high = -np.inf
conf = np.zeros(nodes)
cuts = itertools.product(*[[0, 1]] * nodes)
for cut in cuts:
cur = max_cut_value(np.array(cut), matrix)
if cur > high:
conf = np.array(cut)
high = cur
print("Value of maximum cut:", high)
print("Optimal cut:", conf)
"""Visualize the graph to see the maximum cut."""
draw_weighted(graph, cut=conf)
|
https://github.com/Alternat3/Quantum-Bitcoin
|
Alternat3
|
from qiskit import *
#provider = IBMQ.enable_account('YOUR API KEY HERE')
#backend = provider.get_backend('ibm_oslo')
def applyHadamard(qc, qubits):
for q in qubits:
qc.h(q)
return qc
def createBooleanOracle(input):
oracle_circuit = QuantumCircuit(4,name="boolean oracle")
for x in range(3):
if input[x] == '0':
oracle_circuit.x(x)
oracle_circuit.mct([0,1,2], 3)
for x in range(3):
if input[x] == '0':
oracle_circuit.x(x)
return oracle_circuit.to_gate()
def createPhaseOracle(input):
oracle_circuit = QuantumCircuit(3,name="phase oracle")
for x in range(3):
if input[x] == '0':
oracle_circuit.x(x)
oracle_circuit.ccz(0,1,2)
for x in range(3):
if input[x] == '0':
oracle_circuit.x(x)
return oracle_circuit.to_gate()
def amplificationGate():
ampGate = QuantumCircuit(3,name="amplification gate")
for x in range(3):
ampGate.x(x)
ampGate.ccz(0,1,2)
for x in range(3):
ampGate.x(x)
for x in range(3):
ampGate.h(x)
return ampGate.to_gate()
def runSimulator(grover_circuit): # >70% accuracy mine until 78% accuracy??????
backend = BasicAer.get_backend('qasm_simulator')
job = execute(grover_circuit, backend, shots=8192)
result = job.result()
counts = result.get_counts()
return counts
def runReal(grover_circuit): # <50% accuracy
job = execute(grover_circuit, backend, shots=8192)
result = job.result()
counts = result.get_counts()
return counts
def mine(input, type_choice):
grover_circuit = QuantumCircuit(4,3)
grover_circuit.initialize('0000', grover_circuit.qubits)
grover_circuit = applyHadamard(grover_circuit, [0,1,2,3])
#grover_circuit.append(createBooleanOracle(input), [0,1,2,3])
grover_circuit.append(createPhaseOracle(input), [0,1,2])
grover_circuit = applyHadamard(grover_circuit, [0,1,2,3])
grover_circuit.append(amplificationGate(), [0,1,2])
grover_circuit.measure([0,1,2], [0,1,2])
if type_choice == "1":
counts = runSimulator(grover_circuit)
if type_choice == "2":
counts = runReal(grover_circuit)
searchFor = input[::-1]
accuracy = (counts[searchFor] / 8192) * 100
return accuracy
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeAuckland
backend = FakeAuckland()
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
ghz.draw(output='mpl')
|
https://github.com/qclib/qclib
|
qclib
|
# 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.
"""
todo
"""
import numpy as np
import qiskit
from qiskit.circuit.library import UCGate
from qiskit.quantum_info import Operator
from qclib.state_preparation.ucg import UCGInitialize
def _repetition_verify(base, d, mux, mux_cpy):
i = 0
next_base = base + d
while i < d:
if not np.allclose(mux[base], mux[next_base]):
return False
mux_cpy[next_base] = None
base, next_base, i = base + 1, next_base + 1, i + 1
return True
def _repetition_search(mux, n, mux_cpy):
dont_carry = []
for i in range(1, len(mux) // 2 + 1):
d = i
entanglement = False
if np.log2(d).is_integer() and np.allclose(mux[i], mux[0]):
mux_org = mux_cpy[:]
repetitions = len(mux) // (2 * d)
base = 0
while repetitions:
repetitions -= 1
valid = _repetition_verify(base, d, mux, mux_cpy)
base += 2 * d
if not valid:
mux_cpy[:] = mux_org
break
if repetitions == 0:
entanglement = True
if entanglement:
dont_carry.append(n + int(np.log2(d)) + 1)
return dont_carry
class UCGEInitialize(UCGInitialize):
""" todo """
def __init__(self, params, label=None, opt_params=None):
super().__init__(params, label=label, opt_params=opt_params)
def _define_initialize(self):
children = self.params
parent = self._update_parent(children)
tree_level = self.num_qubits
r_gate = self.target_state // 2
while tree_level > 0:
bit_target, ucg = self._disentangle_qubit(
children, parent, r_gate, tree_level
)
children = self._apply_diagonal(bit_target, parent, ucg)
parent = self._update_parent(children)
# prepare next iteration
r_gate = r_gate // 2
tree_level -= 1
return self.circuit.inverse()
def _disentangle_qubit(
self,
children: "list[float]",
parent: "list[float]",
r_gate: int,
tree_level: int,
):
"""Apply UCGate to disentangle qubit target"""
bit_target = self.str_target[self.num_qubits - tree_level]
old_mult, old_controls, target = self._define_mult(children, parent, tree_level)
nc, mult = self._simplify(old_mult, tree_level)
mult_controls = [x for x in old_controls if x not in nc]
if self.preserve:
self._preserve_previous(mult, mult_controls, r_gate, target)
ucg = self._apply_ucg(mult, mult_controls, target)
ucg.dont_carry = nc
ucg.controls = mult_controls
return bit_target, ucg
def _simplify(self, mux, level):
mux_cpy = mux.copy()
dont_carry = []
if len(mux) > 1:
n = self.num_qubits - level
dont_carry = _repetition_search(mux, n, mux_cpy)
new_mux = [matrix for matrix in mux_cpy if matrix is not None]
return dont_carry, new_mux
def _apply_diagonal(
self,
bit_target: str,
parent: "list[float]",
ucg: UCGate
):
children = parent
if bit_target == "1":
diagonal = np.conj(ucg._get_diagonal())[
1::2
] # pylint: disable=protected-access
else:
diagonal = np.conj(ucg._get_diagonal())[
::2
] # pylint: disable=protected-access
if ucg.dont_carry:
ucg.controls.reverse()
size_required = len(ucg.dont_carry) + len(ucg.controls)
ctrl_qc = [self.num_qubits - 1 - x for x in ucg.controls]
unitary_diagonal = np.diag(diagonal)
qc = qiskit.QuantumCircuit(size_required)
qc.unitary(unitary_diagonal, ctrl_qc)
matrix = Operator(qc).to_matrix()
diagonal = np.diag(matrix)
children = children * diagonal
return children
@staticmethod
def initialize(q_circuit, state, qubits=None, opt_params=None):
gate = UCGEInitialize(state, opt_params=opt_params)
if qubits is None:
q_circuit.append(gate.definition, q_circuit.qubits)
else:
q_circuit.append(gate.definition, qubits)
|
https://github.com/abhishekchak52/quantum-computing-course
|
abhishekchak52
|
# %pip install numpy==1.19 qiskit==0.20 pylatexenc # Please uncomment this line if you are running on Google Colab or uncomment and run once if you are running locally.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, execute
from qiskit.providers.aer import QasmSimulator
from qiskit.visualization import *
import qiskit
from packaging.version import parse as parse_version
assert parse_version(np.__version__) >= parse_version('1.19'), "Please install the correct version of numpy using the command 'pip install --upgrade numpy==1.19'"
assert parse_version(qiskit.__qiskit_version__['qiskit-terra']) >= parse_version('0.15'), "Please make sure you have the correct version of Qiskit installed or run this on IBM Quantum Experience"
assert parse_version(qiskit.__qiskit_version__['qiskit-aer']) >= parse_version('0.6'), "Please make sure you have the correct version of Qiskit installed or run this on IBM Quantum Experience"
assert parse_version(qiskit.__qiskit_version__['qiskit']) >= parse_version('0.20'),"Please make sure you have the correct version of Qiskit installed or run this on IBM Quantum Experience"
from cryptography.fernet import Fernet
import base64
basis_gates = ['id', 'x', 'y', 'z', 's', 't', 'sdg', 'tdg', 'h', 'p', 'sx' ,'r', 'rx', 'ry', 'rz', 'u', 'u1', 'u2', 'u3', 'cx', 'barrier', 'measure']
secret_message = b'gAAAAABfevgMDRKfpM75bCBMUfAvaUW_Fjs2PxFYkYOSCldJTUnl8oLKVZRaiPitXqwQwbMTx4YwSCf_n0HQ-RIBvLa58AN4Pi7Fp9hFxGtjwzIpWUXIUr-BGE_9SLvjUGgsQCyrhK9ZJ5Yy9R5F6w4Me0Csr19UU3IqQQIP3ffhInE5o68_CI_URCjHXpBUnztJoDmlBnZz3Ka5NykfUN22iulaFvXOyw=='
print(f"The secret message is {secret_message.decode()}")
num_qubits = 64
rng = np.random.default_rng(seed=10)
alice_state = rng.integers(0, 2, size=num_qubits)
bob_basis = rng.integers(0, 2, size=num_qubits)
print(f"Alice's State:\t {np.array2string(alice_state, separator='')}")
print(f"Bob's Bases:\t {np.array2string(bob_basis, separator='')}")
def make_b92_circ(enc_state, meas_basis):
'''
A function that makes a B92 QKD protocol simulation circuit
enc_state: array of 0s and 1s denoting the state to be encoded using the following scheme:
0 -> |0>
1 -> |+>
meas_basis: array of 0s and 1s denoting the basis to be used for measurement
0 -> Hadamard Basis
1 -> Computational Basis
Note that both enc_state and meas_basis are arrays of integers, so if you are using them in
if statements, compare them to integer values like 0 and 1 (without quotes).
Since this is a function, you only have access to the variables enc_state and meas_basis.
You may define other local variables. One such variable, num_qubits has been defined for you.
This is the number of qubits in the B92 simulation QuantumCircuit()
'''
num_qubits = len(enc_state)
b92 = QuantumCircuit(num_qubits)
# Sender prepares qubits
# Add code below to encode the state in qubits
b92.barrier()
# Receiver measures the received qubits
# Add code below to change basis for measurements. DO NOT add a measure() or measure_all()
# Do not change below this line
b92.measure_all()
return b92
try:
b92_circ = make_b92_circ(alice_state, bob_basis)
assert list(b92_circ.count_ops()) != [], "Circuit cannot be empty"
assert set(b92_circ.count_ops().keys()).difference(basis_gates) == set(), f"Only the following basic gates are allowed: {basis_gates}"
assert all([type(gate[0]) == qiskit.circuit.measure.Measure for gate in b92_circ.data[-b92_circ.num_qubits:len(b92_circ.data)]]), "Measurement must be the last operation in a circuit."
assert b92_circ.count_ops()['measure'] == b92_circ.num_qubits, "Please do not add or remove measurements."
temp_key = execute(
b92_circ.reverse_bits(),
backend=QasmSimulator(),
shots=1,
seed_simulator=10
).result().get_counts().most_frequent()
assert temp_key == bin(16228741048440553634)[2:], "Your circuit did not perform as expected. Please check the gates again."
print(f"Bob's results:\t{temp_key}\nYour answer is correct.")
except AssertionError as e:
print(f'Your code has an error: {e.args[0]}')
except Exception as e:
print(f'This error occured: {e.args[0]}')
def b92_sifting(enc_state, meas_basis, meas_result):
'''
The function that implements key sifting for the B92 QKD protocol.
enc_state: array of 0s and 1s denoting the state to be encoded.
(Array of integers)
meas_basis: array of 0s and 1s denoting the basis to be used for measurement.
(Array of integers)
meas_result: A string of characters representing the results of measurement after the
B92 QKD protocol. Note that this is a string and its elements are characters,
so while using any if statements, compare the elements to '0' and '1' (with quotes)
Since this is a function, you only have access to the variables enc_state, meas_basis and meas_result.
You may define other local variables. num_qubits has been defined for you.
This is the number of qubits in the B92 simulation QuantumCircuit.
sender_key and receiver_key are initialised as two empty strings. You may append bits using the +=
operation as shown in the BB84 notebook. Note that you can only add characters. To change from other
data types to characters, you may use str(). Check the BB84 notebook for examples.
'''
num_qubits = len(enc_state)
sender_key = ''
receiver_key = ''
# Loop over all bits in the meas_result string and add the necessary bits to both sender_key and receiver_key
# Add your code below
# Do not change bolow this line.
return (sender_key, receiver_key)
try:
alice_key, bob_key = b92_sifting(alice_state, bob_basis, temp_key)
assert ''.join([str(x ^ y) for x, y in zip(alice_key.encode(), bob_key.encode())]) != '1'*len(alice_key), "Please check your measurement convention"
assert alice_key == bob_key, "They keys are different for Alice and Bob."
assert alice_key == bob_key == bin(49522)[2:], "They keys is incorrect. Please check your solutions."
print(f"Alice's Key: \t{alice_key}\nBob's Key: \t{bob_key}\nYour answer is correct.")
g = Fernet(base64.b64encode(bob_key.encode()*2))
print(f"The secret message is: {g.decrypt(secret_message).decode()}")
except AssertionError as e:
print(f'Your code has an error: {e.args[0]}')
except Exception as e:
print(f'This error occured: {e.args[0]}')
|
https://github.com/qiskit-community/qiskit-benchmarks
|
qiskit-community
|
from qiskit import *
from qiskit.transpiler.pass_manager_config import PassManagerConfig
from qiskit.transpiler import CouplingMap
qr = QuantumRegister(3)
circuit1 = QuantumCircuit(qr, name='circuit1')
circuit1.h(qr)
circuit1.cx(qr[0], qr[1])
circuit1.h(qr[0])
circuit1.cx(qr[0], qr[1])
qr = QuantumRegister(3)
circuit2 = QuantumCircuit(qr, name='circuit2')
circuit2.h(qr)
circuit2.cx(qr[0], qr[1])
circuit2.h(qr[0])
circuit2.cx(qr[1], qr[0])
coupling1 = [[1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4],
[5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10],
[11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12]]
coupling2 = [[1, 0], [1, 2], [2, 3], [4, 3]]
pm_config1 = PassManagerConfig(seed_transpiler=42, basis_gates=['u1', 'u2', 'u3', 'cx', 'id'],
coupling_map=CouplingMap(coupling1))
pm_config2 = PassManagerConfig(seed_transpiler=42, basis_gates=['u1', 'u2', 'u3', 'cx', 'id'],
coupling_map=CouplingMap(coupling2))
pm_config1.name = 'pm_config1'
pm_config2.name = 'pm_config2'
def get_case():
return [(circuit1, pm_config1),
(circuit2, pm_config2)]
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
"""Imports."""
import matplotlib.pyplot as plt
import numpy as np
import scipy as scp
from IPython.display import clear_output, display
import qiskit.pulse as pulse
import qiskit
"""Plotting style."""
%matplotlib inline
plt.rcParams.update({"font.size": 16, "font.weight": "bold"})
"""Load account: Only do this once."""
qiskit.IBMQ.load_account()
"""Get a provider and see available backends."""
provider = qiskit.IBMQ.get_provider(hub="ibm-q")
print("Available backends:", *provider.backends())
"""Select ibmq-poughkeepsie device to use Pulse."""
# backend = provider.get_backend("ibmq_poughkeepsie")
# config = backend.configuration()
# defaults = backend.defaults()
"""Get a pulse channel system."""
# system = pulse.PulseChannelSpec.from_backend(backend)
"""Video showing conceptual visualization of the above experiment on the Bloch sphere."""
from IPython.display import YouTubeVideo
YouTubeVideo("g10PIHQ65L4", width=640, height=360)
"""Load in the raw data."""
data = data = np.loadtxt("https://raw.githubusercontent.com/rmlarose/qcbq/master/data/t1_data.txt")
times = data[:, 1] # microseconds
measurements = data[:, 0] # probability of excited state
"""Plot the raw data."""
### Your code here!
"""Do the data fitting."""
def fit(time: float, T1: float) -> float:
### Your code here!
"""Use scipy.optimize.curve_fit to fit the data."""
### Your code here!
"""Plot your fit over the raw data here."""
### Your code here!
# Compute the fit
"""Video showing conceptual visualization of the above experiment on the Bloch sphere."""
from IPython.display import YouTubeVideo
YouTubeVideo("9Ekep8zgZHc", width=640, height=360)
"""Load in the raw data."""
t2data = np.loadtxt("https://raw.githubusercontent.com/rmlarose/qcbq/master/data/t2_data.txt")
times = t2data[:, 1] # microseconds
measurements = t2data[:, 0] # probability of ground state
"""Plot the raw data."""
### Your code here!
"""Define the fit function."""
def ramsey_fit(time: float, domega: float, T2: float) -> float:
### Your code here!
"""Do the fitting."""
### Your code here!
"""Plot the fit and data."""
### Your code here!
"""Video showing conceptual visualization of the above experiment on the Bloch sphere."""
from IPython.display import YouTubeVideo
YouTubeVideo("wkuqcCVhl04", width=640, height=360)
"""Load in the raw data."""
t2echo_data = np.loadtxt("https://raw.githubusercontent.com/rmlarose/qcbq/master/data/t2e_data.txt")
times = t2echo_data[:, 1] # microseconds
measurements = t2echo_data[:, 0] # probability of ground state
"""Plot the raw data."""
### Your code here!
"""Define a fit function."""
def hahn_fit(time: float, T2: float) -> float:
### Your code here!
"""Do the fitting."""
### Your code here!
"""Plot the fit function and data."""
### Your code here!
"""Function for the Bloch-Redfield density matrix."""
def rho(t: float,
alpha0: complex = np.sqrt(1 / 2),
beta0: complex = np.sqrt(1 / 2),
T1: float = 40,
T2: float = 70) -> np.ndarray:
return np.array([
[1 + (abs(alpha0)**2 - 1) * np.exp(- t / T1), alpha0 * np.conj(beta0) * np.exp(-t / T2)],
[np.conj(alpha0) * beta0 * np.exp(-t / T2), abs(beta0)**2 * np.exp(-t / T1)]
])
"""Visualization of the Bloch-Redfield density matrix."""
import ipywidgets
@ipywidgets.interact
def vis(time=(0, 500, 1), T1=(20, 200, 1), T2=(20, 200, 1)):
plt.title(r"$\rho_{BR}$")
plt.imshow(np.real(rho(time, T1=T1, T2=T2)), cmap="Greens", vmin=0, vmax=1)
plt.text(-0.2, 0.0, round(rho(time, T1=T1, T2=T2)[0, 0], 4))
plt.text(-0.2, 1.0, round(rho(time, T1=T1, T2=T2)[1, 0], 4))
plt.text(0.8, 0.0, round(rho(time, T1=T1, T2=T2)[0, 1], 4))
plt.text(0.8, 1.0, round(rho(time, T1=T1, T2=T2)[1, 1], 4))
plt.colorbar()
plt.axis("off")
plt.show()
"""Plot the matrix elements of rho over time."""
# Initial state
alpha = np.sqrt(0.3)
beta = np.sqrt(0.7)
# T1 and T2 times
T1 = 50
T2 = 70
# Time
time = np.linspace(0, 250, 100)
# Matrix elements
rho00 = 1 + (abs(alpha)**2 - 1) * np.exp(-time / T1)
rho01 = alpha * np.conj(beta) * np.exp(-time / T2)
rho10 = np.conj(rho01)
rho11 = 1 - rho00
# Plotting
plt.figure(figsize=(16, 5));
plt.plot(time, rho00, "--", label=r"$\rho_{00}$", linewidth=4);
plt.plot(time, np.real(rho01), "--", label=r"$\Re[\rho_{01}]$", linewidth=4);
plt.plot(time, np.real(rho10), "--", label=r"$\Re[\rho_{10}]$", linewidth=4);
plt.plot(time, rho11, "--", label=r"$\rho_{11}$", linewidth=4);
plt.grid();
plt.legend();
plt.xlabel("Time [microseconds]");
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 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.
"""Tests for DAG visualization tool."""
import unittest
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit.tools.visualization import dag_drawer
from qiskit.visualization.exceptions import VisualizationError
from qiskit.converters import circuit_to_dag
class TestDagDrawer(QiskitTestCase):
"""Qiskit DAG drawer tests."""
def setUp(self):
qr = QuantumRegister(2, 'qr')
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
self.dag = circuit_to_dag(circuit)
def test_dag_drawer_no_graphviz(self):
"""Test dag draw with no graphviz."""
with unittest.mock.patch('nxpd.pydot.find_graphviz', return_value=None) as _:
self.assertRaises(VisualizationError, dag_drawer, self.dag)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
https://github.com/Fergus-Hayes/qiskit_tools
|
Fergus-Hayes
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ
from scipy.interpolate import approximate_taylor_polynomial
from qiskit.circuit.library import RGQFTMultiplier, DraperQFTAdder, ExactReciprocal
from qiskit.circuit.library.basis_change import QFT as QFT_pre
from qiskit.extensions import HamiltonianGate
from qiskit.circuit.library.standard_gates import PhaseGate, RYGate, CSwapGate
from qiskit.circuit.library.arithmetic.integer_comparator import IntegerComparator
from qiskit.circuit.library.standard_gates import XGate
from qiskit.quantum_info.operators.pauli import Pauli
from qiskit.circuit.library.boolean_logic import OR
from qiskit.quantum_info import random_unitary
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Unroller
import itertools as it
import numpy as np
import sympy
def signmag_bin_to_dec(binary, nint=None):
mag = bin_to_dec(binary[1:], nint=nint)
sign = (-1)**(int(binary[0]))
return mag*sign
def bin_to_dec(binary, nint=None, phase=False, signmag=False):
"""
Convert a binary string to a floating point number
binary - input binary (string)
nint - number of integer bits. Default to all (int)
"""
if signmag:
return signmag_bin_to_dec(binary, nint)
basis = 0.
n = len(binary)
if phase:
if binary[0]=='1':
if nint is None:
nint_ = n-1
else:
nint_ = nint
basis = -(2.**(nint_))
binary = binary[1:]
n = len(binary)
if nint is None:
nint = n
digit = 0.
for i,bit in enumerate(np.arange(nint-n,nint)[::-1]):
digit+=(2.**bit)*int(binary[i])
return digit + basis
def my_binary_repr(digit, n, nint=None, phase=False, nround=True, overflow_error=True, signmag=False):
"""
Convert a floating point digit to binary string
digit - input number (float)
n - total number of bits (int)
nint - number of integer bits. Default to lowest required (int)
"""
if signmag and phase:
bin_out = my_binary_repr(np.abs(digit), n-1, nint=nint, phase=False, signmag=False)
if digit<0.:
return '1'+ bin_out
else:
return '0'+ bin_out
if nint is None:# or nint==n:
if phase:
nint = n - 1
else:
nint = n
if phase:
p = n - nint - 1
dmax = 2.**(nint) - 2.**(-p)
dmin = -2.**(nint)
else:
p = n - nint
dmax = 2.**(nint) - 2.**(-p)
dmin = 0.
if overflow_error:
if digit>dmax or digit<dmin:
raise ValueError('Digit '+str(digit)+' does not lie in the range:',dmin,'-',dmax,n,nint,p)
if nround:
n += 1
p += 1
value = digit
bin_out = ''
if phase:
if value<0.:
value+=2.**nint
bin_out+='1'
else:
bin_out+='0'
for i,bit in enumerate(np.arange(-p,nint)[::-1]):
bin_out+=str(int(np.floor(value/2.**bit)))
if value>=2.**bit:
value-=2.**bit
if nround:
carry = True
bin_out = np.array(list(bin_out))
for i in np.arange(n)[::-1]:
if not carry:
break
if bin_out[i]=='1':
bin_out[i]='0'
elif bin_out[i]=='0':
bin_out[i]='1'
carry = False
bin_out = ("").join(list(bin_out[:-1]))
return bin_out
def pres_est(digit, n, nint=None, phase=False):
if phase:
n -= 1
if nint is None:
nint = n
if digit==0.:
return 0.
if digit!=0.:
return (digit/np.abs(digit))*bin_to_dec(my_binary_repr(digit, n, nint=nint, phase=phase), nint=nint, phase=phase)
else:
return 0.
def twos_compliment(binary):
n = len(binary)
if np.sum(np.array(list(binary)).astype(int))==0:
compliment = binary
else:
compliment = my_binary_repr(bin_to_dec(''.join(list(np.logical_not(np.array(list(binary)).astype(bool)).astype(int).astype(str))), nint=None, phase=False) + 1, n, nint=None, phase=False, overflow_error=False)
return compliment
def get_nint(digits):
if np.array(digits).ndim==0:
digits=np.array([digits])
digits = np.where(np.abs(digits)>1.,np.modf(digits)[1],digits)
digits = digits[digits!=0.]
if len(digits)==0:
return 0
nint = int(np.ceil(np.log2(np.max(np.abs(digits)+1))))
return nint
def get_npres(digits):
if np.array(digits).ndim==0:
digits=np.array([digits])
digdecs = np.modf(digits)[0]
digdecs = digdecs[digdecs!=0]
if len(digdecs)==0:
return 0
mindec = np.min(np.abs(digdecs))
switch = True
p = 0
while switch:
if mindec%(2.**-p)==0.:
switch=False
p+=1
return p-1
def piecewise_poly(xs, coeffs, bounds_):
ys = np.array([])
bounds__ = np.copy(bounds_)
bounds__[-1] = np.inf
for i in np.arange(len(bounds__))[:-1]:
ys_ = np.array(np.polyval(coeffs[i], xs[np.greater_equal(xs,bounds__[i])&np.greater(bounds__[i+1],xs)]))
ys = np.concatenate([ys, ys_])
return ys
def get_coefficients(xs, coeffs, bounds_):
ys = np.array([])
bounds__ = np.copy(bounds_)
bounds__[-1] = np.inf
for i in np.arange(len(bounds__))[:-1]:
#print(np.where(np.greater_equal(xs,bounds[i])&np.greater(bounds[i+1],xs), coeffs[i]))
ys_ = np.ones(np.sum(np.greater_equal(xs,bounds__[i])&np.greater(bounds__[i+1],xs)))*coeffs[i]
#ys_ = np.array(np.polyval(coeffs[i], xs[np.greater_equal(xs,bounds[i])&np.greater(bounds[i+1],xs)]))
ys = np.concatenate([ys, ys_])
return ys
def get_bound_coeffs(func, bounds, norder, reterr=False):
if np.array(bounds).ndim==0:
print('Bounds must be a list of two entries!')
if len(bounds)==1:
print('Bounds must be a list of two entries!')
coeffs = []
errs = []
for i in np.arange(len(bounds))[:-1]:
coeffs_, err_ = run_remez(func, bounds[i], bounds[i+1], norder)
coeffs.append(np.array(coeffs_))
errs.append(err_)
if reterr:
return np.array(coeffs), np.array(errs)
else:
return np.array(coeffs)
def input_bits_to_qubits(binary, circ, reg, wrap=False, inverse=False, phase=False, qphase=None, label='Input'):
# Flips the qubits to match a classical bit string
n = len(binary)
if inverse:
wrap = True
if wrap:
regs = []
reg = QuantumRegister(n, 'reg')
regs.append(reg)
if qphase!=None:
qphase = QuantumRegister(1, 'phase')
regs.append(qphase)
circ = QuantumCircuit(*regs)
if phase and qphase==None:
qphase = QuantumRegister(1, 'phase')
circ.add(qphase)
for bit in np.arange(n):
if int(binary[::-1][bit])==1:
circ.x(reg[bit])
if phase<0.:
circ.x(qphase[0])
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def binary_input(data_ins, n, nint=None):
#Return the binary representation of the input number as a string
data_outs=[]
for data_in in data_ins:
data_outs.append(my_binary_repr(data_in, n, nint=nint))
return np.array(data_outs)
def qft_rotations(circuit, n):
"""Performs qft on the first n qubits in circuit (without swaps)"""
circuit.h(n)
for qubit in np.arange(n):
circuit.cp(np.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)
return circuit
def swap_registers(circuit, n):
for qubit in range(n//2):
circuit.swap(qubit, n-qubit-1)
return circuit
def qft(circuit, n):
"""QFT on the first n qubits in circuit"""
for qubit in np.arange(n)[::-1]:
circuit = qft_rotations(circuit, qubit)
swap_registers(circuit, n)
return circuit
def QFT(circ, qreg, do_swaps=True, approximation_degree=0., insert_barriers=False, wrap=False, inverse=False, label='QFT'):
n = len(qreg)
if inverse:
wrap = True
if wrap:
qreg = QuantumRegister(n, 'q_reg')
circ = QuantumCircuit(qreg)
for j in reversed(np.arange(n)):
circ.h(j)
num_entanglements = max(0, j - max(0, approximation_degree - (n - j - 1)))
for k in reversed(np.arange(j - num_entanglements, j)):
lam = np.pi * (2.0 ** (k - j))
circ.cp(lam, j, k)
if insert_barriers:
circ.barrier()
if do_swaps:
for i in np.arange(n // 2):
circ.swap(i, n - i - 1)
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def QFTAddition(circ, qreg1, qreg2, wrap=False, inverse=False, label='Add', QFT_on=True, iQFT_on=True, nint1=None, nint2=None, phase=False, signmag=False):
r"""
|qreg1>|qreg2> -> |qreg1>|qreg2 + qreg1>
"""
n1 = len(qreg1)
n2 = len(qreg2)
#if n1>n2:
# raise ValueError('First register cannot be greater than the second!',n1,n2)
if inverse:
wrap = True
if wrap:
qreg1 = QuantumRegister(n1, 'q_reg1')
qreg2 = QuantumRegister(n2, 'q_reg2')
circ = QuantumCircuit(qreg1, qreg2)
if nint1==None:
nint1 = n1
if nint2==None:
nint2 = n2
dp = (n2 - nint2) - (n1 - nint1)
dpn = 0
if dp<0:
dpn = np.abs(dp)
dp = 0
add_gate = QFTAddition_(circ, qreg1[dpn:], qreg2[dp:], wrap=True, phase=False, QFT_on=QFT_on, iQFT_on=iQFT_on, signmag=signmag)
circ.append(add_gate, [*qreg1[dpn:], *qreg2[dp:]]);
if n1!=n2 and not signmag and phase:
for i in np.arange(nint2-nint1):
circ.cx(qreg1[-1], qreg2[-i-1]);
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def QFTAddition_(circ, qreg1, qreg2, wrap=False, inverse=False, label='Add', QFT_on=True, iQFT_on=True, pm=1, phase=False, signmag=False):
r"""
|qreg1>|qreg2> -> |qreg1>|qreg2 + qreg1>
"""
n1 = len(qreg1)
n2 = len(qreg2)
if inverse:
wrap = True
if wrap:
qreg1 = QuantumRegister(n1, 'q_reg1')
qreg2 = QuantumRegister(n2, 'q_reg2')
circ = QuantumCircuit(qreg1, qreg2)
if QFT_on:
circ.append(QFT(circ, qreg2, do_swaps=False, wrap=True), qreg2[:])
jend = n1
if phase and signmag:
circ.append(TwosCompliment(circ, qreg1[:-1], wrap=True).control(1), [qreg1[-1], *qreg1[:-1]]);
jend -= 1
for j in np.arange(0,jend):
for l in np.arange(0,n2):
lam = pm*2*np.pi*2.**(j-l-1)
if lam%(2*np.pi)==0:
continue
circ.cp(lam, qreg1[j], qreg2[l])
if phase and n1!=n2 and lam%np.pi!=0:
circ.append(PhaseGate(-2.*lam).control(2), [qreg1[-1], qreg1[j], qreg2[l]]);
if phase and signmag:
circ.append(TwosCompliment(circ, qreg1[:-1], wrap=True).control(1), [qreg1[-1], *qreg1[:-1]]);
if iQFT_on:
circ.append(QFT(circ, qreg2, do_swaps=False, wrap=True, inverse=True), qreg2[:])
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def QFTSubtraction(circ, qreg1, qreg2, wrap=False, inverse=False, label='Sub', QFT_on=True, iQFT_on=True):
r"""
|qreg1>|qreg2> -> |qreg1>|qreg2 - qreg1>
"""
n1 = qreg1.size
n2 = qreg2.size
if inverse:
wrap = True
if wrap:
qreg1 = QuantumRegister(n1, 'q_reg1')
qreg2 = QuantumRegister(n2, 'q_reg2')
circ = QuantumCircuit(qreg1, qreg2)
if QFT_on:
circ.append(QFT(circ, qreg2, do_swaps=False, wrap=True), qreg2[:])
for j in np.arange(n1):
for k in np.arange(n2 - j):
lam = -np.pi / (2.**(k))
if lam%(2*np.pi)==0.:
continue
circ.cp(lam, qreg1[j], qreg2[j + k])
if iQFT_on:
circ.append(QFT(circ, qreg2, do_swaps=False, wrap=True, inverse=True), qreg2[:])
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def QFTSubtractionRHS(circ, qreg1, qreg2, wrap=False, inverse=False, label='Sub', QFT_on=True, iQFT_on=True):
r"""
|qreg1>|qreg2> -> |qreg1>|qreg1 - qreg2>
"""
n1 = qreg1.size
n2 = qreg2.size
if inverse:
wrap = True
if wrap:
qreg1 = QuantumRegister(n1, 'q_reg1')
qreg2 = QuantumRegister(n2, 'q_reg2')
circ = QuantumCircuit(qreg1, qreg2)
if QFT_on:
circ.append(QFT(circ, qreg2, do_swaps=False, wrap=True, inverse=True), qreg2[:])
for j in np.arange(n1):
for k in np.arange(n2 - j):
lam = np.pi / (2.**(k))
if lam%(2*np.pi)==0.:
continue
circ.cp(lam, qreg1[j], qreg2[j + k])
if iQFT_on:
circ.append(QFT(circ, qreg2, do_swaps=False, wrap=True, inverse=True), qreg2[:])
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def OnebitSub(circ, qbit1, qbit2, qans, wrap=True, inverse=False, label='Sub1'):
if len(qans)!=2:
print('Ancillary register must be of 2 qubits, length:', len(qans))
return 0
if inverse:
wrap = True
if wrap:
qbit1 = QuantumRegister(1, 'q_bit1')
qbit2 = QuantumRegister(1, 'q_bit2')
qans = QuantumRegister(2, 'q_ans')
circ = QuantumCircuit(qbit1, qbit2, qans)
circ.x(qbit2)
circ.ccx(qbit1, qbit2, qans[0])
circ.x(qbit1)
circ.x(qbit2)
circ.ccx(qbit1, qbit2, qans[1])
circ.x(qbit1)
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def BitStringCompare(circ, qreg1, qreg2, qans, wrap=False, inverse=False, label='BitComp'):
n = qreg1.size
if n!=qreg1.size:
print('Registers must be of equal length to compare!')
return 0
if len(qans)!=(3*n)-1:
print('Ancillary register must be 3xlength of input register - 1, length = ', len(qans))
return 0
if inverse:
wrap = True
if wrap:
qreg1 = QuantumRegister(n, 'q_reg1')
qreg2 = QuantumRegister(n, 'q_reg2')
qans = QuantumRegister((3*n)-1, 'q_ans')
circ = QuantumCircuit(qreg1, qreg2, qans)
for i in np.arange(n):
bit_gate = OnebitSub(circ, qreg1[i], qreg2[i], qans[3*i:(3*i)+2], wrap=True)
circ.append(bit_gate, [qreg1[i], qreg2[i], *qans[3*i:(3*i)+2]])
if i+1<n:
circ.x(qans[3*i])
circ.x(qans[(3*i)+1])
circ.ccx(*qans[3*i:(3*i)+3])
circ.x(qans[3*i])
circ.x(qans[(3*i)+1])
for i in np.arange(n)[1:][::-1]:
circ.ccx(qans[(3*(i-1))+2], qans[3*i], qans[3*(i-1)])
circ.ccx(qans[(3*(i-1))+2], qans[(3*i)+1], qans[(3*(i-1))+1])
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def TwosCompliment(circ, qreg, wrap=False, inverse=False, QFT_on=True, iQFT_on=True, label='comp2'):
n = len(qreg)
if inverse:
wrap = True
if wrap:
qreg = QuantumRegister(n, 'q_reg')
circ = QuantumCircuit(qreg)
for qubit in qreg:
circ.x(qubit)
inc_gate = QFTBinaryAdd(circ, qreg, ''.join(np.zeros(n-1).astype(int).astype(str))+'1', wrap=True)
circ.append(inc_gate, qreg)
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def QFTMultiply(circ, qreg1, qreg2, qreg3, A=1., wrap=False, inverse=False, nint1=None, nint2=None, nint3=None, phase=False, label='Mult', QFT_on=True, iQFT_on=True):
r"""
|qreg1>|qreg2>|qreg3> -> |qreg1>|qreg2>|qreg1 x qreg2>
"""
n1 = len(qreg1)
n2 = len(qreg2)
n3 = len(qreg3)
if n3!=n1+n2 and nint3 == None:
raise ValueError('Output register should be the combined length of both input registers if no integer bit length is specified.')
if nint1==None:
nint1=n1
if nint2==None:
nint2=n2
if nint3==None:
nint3=n3
nshift = (nint1 + nint2)-nint3
if phase:
nshift+=1
if inverse:
wrap = True
if wrap:
qreg1 = QuantumRegister(n1, 'q_reg1')
qreg2 = QuantumRegister(n2, 'q_reg2')
qreg3 = QuantumRegister(n3, 'q_reg3')
circ = QuantumCircuit(qreg1, qreg2, qreg3)
if QFT_on:
circ.append(QFT(circ, qreg3, do_swaps=False, wrap=True), qreg3[:])
for j in np.arange(1, n1 + 1):
for i in np.arange(1, n2 + 1):
for k in np.arange(1, n3 + 1):
lam = A*(2 * np.pi) / (2. ** (i + j + k - n3 - nshift))
if lam%(2*np.pi)==0.:
continue
circ.append(PhaseGate(lam).control(2),[qreg1[n1 - j], qreg2[n2 - i], qreg3[k - 1]])
if iQFT_on:
circ.append(QFT(circ, qreg3, do_swaps=False, wrap=True, inverse=True), qreg3[:])
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def QFTMultPhase(circ, qreg1, qreg2, qreg3, wrap=False, inverse=False, nint1=None, nint2=None, nint3=None, label='MultPhase', QFT_on=True, iQFT_on=True, signmag1=False, signmag2=False, signmag3=False, poszero=False):
r"""
|qreg1>|qreg2>|qreg3> -> |qreg1>|qreg2>|qreg1 x qreg2>
"""
n1 = len(qreg1)
n2 = len(qreg2)
n3 = len(qreg3)
if n3>n1+n2:
raise ValueError('The output register is greater than necessary.')
if n3!=n1+n2 and nint3 == None:
raise ValueError('Output register should be the combined length of both input registers if no integer bit length is specified.')
if nint1==None:
nint1=n1
if nint2==None:
nint2=n2
if nint3==None:
nint3=n3
if inverse:
wrap = True
if wrap:
qreg1 = QuantumRegister(n1, 'q_reg1')
qreg2 = QuantumRegister(n2, 'q_reg2')
qreg3 = QuantumRegister(n3, 'q_reg3')
circ = QuantumCircuit(qreg1, qreg2, qreg3)
# Define the twos-complement operations
tc_gate_1 = TwosCompliment(circ, qreg1[:-1], wrap=True).control(1)
tc_gate_2 = TwosCompliment(circ, qreg2[:-1], wrap=True).control(1)
tc_gate_3 = TwosCompliment(circ, qreg3[:-1], wrap=True).control(2)
# Add the twos-complement operations to convert registers 1 and 2 to sign-magnitude notation
if not signmag1:
circ.append(tc_gate_1, [qreg1[-1], *qreg1[:-1]]);
if not signmag2:
circ.append(tc_gate_2, [qreg2[-1], *qreg2[:-1]]);
# Apply simple QFT multiplication
mult_gate = QFTMultiply(circ, qreg1[:-1], qreg2[:-1], qreg3[:-1], nint1=nint1, nint2=nint2, nint3=nint3, wrap=True)
circ.append(mult_gate, [*qreg1[:-1], *qreg2[:-1], *qreg3[:-1]]);
if not signmag3:
# If register 1 is positive, but register 2 is negative, then twos-complement operator on 3
circ.x(qreg1[-1]);
circ.append(tc_gate_3, [qreg1[-1], qreg2[-1], *qreg3[:-1]]);
circ.x(qreg1[-1]);
# If register 2 is positive, but register 1 is negative, then twos-complement operator on 3
circ.x(qreg2[-1]);
circ.append(tc_gate_3, [qreg1[-1], qreg2[-1], *qreg3[:-1]]);
circ.x(qreg2[-1]);
# If 1 is negative flip phase qubit of 3, and if 2 is negative flip phase qubit of 3
circ.cx(qreg1[-1], qreg3[-1]);
circ.cx(qreg2[-1], qreg3[-1]);
if not signmag1:
# Restore register 1 to original twos-complement notation
circ.append(tc_gate_1, [qreg1[-1], *qreg1[:-1]]);
if not signmag2:
# Restore register 2 to original twos-complement notation
circ.append(tc_gate_2, [qreg2[-1], *qreg2[:-1]]);
if poszero or not signmag3:
# Flip register 1
for qubit in np.arange(n1):
circ.x(qreg1[qubit]);
# If register 1 is all zeros and phase of 2 is negative, then flip the phase of 3
circ.mcx([*qreg1, qreg2[-1]], qreg3[-1], mode='noancilla')
# Flip back register A
for qubit in np.arange(n1):
circ.x(qreg1[qubit]);
# Flip register B
for qubit in np.arange(n2):
circ.x(qreg2[qubit]);
# If register 2 is all zeros and phase of 1 is negative, then flip the phase of 3
circ.mcx([*qreg2, qreg1[-1]], qreg3[-1], mode='noancilla')
# Flip back register 2
for qubit in np.arange(n2):
circ.x(qreg2[qubit]);
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def QFTMultBinPhase(circ, qreg1, qreg3, binary, wrap=False, inverse=False, nint=None, label='MultBinPhase', QFT_on=True, iQFT_on=True):
r"""
|qreg1>|qreg2> -> |qreg1>|qreg1 x A>
"""
n1 = len(qreg1)
n2 = len(binary)
n3 = len(qreg3)
#if n3>n1+n2:
# raise ValueError('The output register is greater than necessary.')
if n3!=n1+n2 and nint == None:
raise ValueError('Output register should be the combined length of both input registers if no integer bit length is specified.')
if nint==None:
nint=n1
if inverse:
wrap = True
if wrap:
qreg1 = QuantumRegister(n1, 'q_reg1')
qreg3 = QuantumRegister(n3, 'q_reg3')
circ = QuantumCircuit(qreg1, qreg3)
comp_gate1_inv = TwosCompliment(circ, qreg1[:-1], wrap=True, inverse=True).control(1)
circ.append(comp_gate1_inv, [qreg1[-1], *qreg1[:-1]]);
if binary[0]=='1':
twoscomp = twos_compliment(binary)
else:
twoscomp = binary
mult_gate = QFTBinaryMult(circ, qreg1[:-1], qreg3[:-1], twoscomp[1:], nint=nint, wrap=True)
circ.append(mult_gate, [*qreg1[:-1], *qreg3[:-1]]);
# if reg1 was neg, but binary is pos, then flip 2comp of reg3
# then vise versa
if binary[0]=='1':
circ.x(qreg1[-1]);
comp_gate = TwosCompliment(circ, qreg3[:-1], wrap=True).control(1)
circ.append(comp_gate, [qreg1[-1], *qreg3[:-1]]);
circ.x(qreg1[-1]);
elif binary[0]=='0':
comp_gate = TwosCompliment(circ, qreg3[:-1], wrap=True).control(1)
circ.append(comp_gate, [qreg1[-1], *qreg3[:-1]]);
# if reg1(bin) is neg, flip sign of reg3
circ.cx(qreg1[-1], qreg3[-1]);
if binary[0]=='1':
circ.x(qreg3[-1]);
# reverse the twos comp
comp_gate1 = TwosCompliment(circ, qreg1[:-1], wrap=True).control(1)
circ.append(comp_gate1, [qreg1[-1], *qreg1[:-1]]);
# flip all reg1 qubits
# and all but last binary
if binary[0]=='1':
for qubit in np.arange(n1):
circ.x(qreg1[qubit]);
circ.mcx(qreg1, qreg3[-1], mode='noancilla')
for qubit in np.arange(n1):
circ.x(qreg1[qubit]);
if np.sum(np.array(list(binary)).astype(int))==0:
circ.cx(qreg1[-1], qreg3[-1]);
#for qubit in np.arange(n3-1):
# circ.x(qreg3[qubit])
#circ.mcx(qreg3[:-1], qreg3[-1], mode='noancilla')
#for qubit in np.arange(n3-1):
# circ.x(qreg3[qubit])
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def QFTBinaryAdd(circ, qreg, binary, wrap=False, inverse=False, QFT_on=True, iQFT_on=True, label='AddA'):
r"""
|qreg> -> |qreg + A>
"""
n1 = len(qreg)
n2 = len(binary)
if inverse:
wrap = True
if wrap:
qreg = QuantumRegister(n1, 'q_reg1')
circ = QuantumCircuit(qreg)
if QFT_on:
circ.append(QFT(circ, qreg, do_swaps=False, wrap=True), qreg[:])
for i in np.arange(1, n1 + 1):
for k in np.arange(1, n2 + 1):
lam = (2. * np.pi) / (2. ** (i + k - n2))
if lam%(2*np.pi)==0.:
continue
if binary[i-1]=='1':
circ.p(lam,qreg[k-1])
if iQFT_on:
circ.append(QFT(circ, qreg, do_swaps=False, wrap=True, inverse=True), qreg[:])
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def QFTBinarySub(circ, qreg, binary, wrap=False, inverse=False, label='SubA'):
r"""
|qreg> -> |qreg - A>
"""
n1 = len(qreg)
n2 = len(binary)
if inverse:
wrap = True
if wrap:
qreg = QuantumRegister(n1, 'q_reg1')
circ = QuantumCircuit(qreg)
circ.append(QFT(circ, qreg, do_swaps=False, wrap=True), qreg[:])
for i in np.arange(1, n2 + 1):
for k in np.arange(1, n1 + 1):
lam = -(2. * np.pi) / (2. ** (i + k - n1))
if lam%(2*np.pi)==0.:
continue
if binary[k-1]=='1':
circ.p(lam,qreg[i-1])
circ.append(QFT(circ, qreg, do_swaps=False, wrap=True, inverse=True), qreg[:])
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def QFTBinarySubRHS(circ, qreg, binary, wrap=False, inverse=False, label='SubA'):
r"""
|qreg> -> |A - qreg>
"""
n1 = qreg.size
n2 = len(binary)
if inverse:
wrap = True
if wrap:
qreg = QuantumRegister(n1, 'q_reg1')
circ = QuantumCircuit(qreg)
circ.append(QFT(circ, qreg, do_swaps=False, wrap=True, inverse=False), qreg[:])
for i in np.arange(1, n1 + 1):
for k in np.arange(1, n2 + 1):
lam = -(2. * np.pi) / (2. ** (i + k - n2))
if lam%(2*np.pi)==0.:
continue
if binary[i-1]=='1':
circ.p(lam,qreg[k-1])
circ.append(QFT(circ, qreg, do_swaps=False, wrap=True, inverse=True), qreg[:])
for i in np.arange(1, n2):
circ.x(qreg[i])
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def qubit_to_phase(circ, qreg, nint=None, wrap=False, inverse=False, phase=False, factor=1, label='Amp2Phase'):
r"""
|qreg> -> e^(2pi i qreg)|qreg>
"""
n = len(qreg)
if inverse:
wrap = True
if wrap:
qreg = QuantumRegister(n, 'q_reg')
circ = QuantumCircuit(qreg)
if phase:
n -= 1
if nint==None:
nint = n
for k in np.arange(1,n-nint+1):
lam = 2.*np.pi*(2.**(-k))*factor
qubit = n-nint-k
circ.p(lam,qreg[qubit])
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def CRotation(circ, qreg, qtarg, nint=None, phase=False, label='CRot', wrap=False, inverse=False):
n = len(qreg)
if nint is None:
nint = n
if inverse:
wrap = True
if wrap:
qreg = QuantumRegister(n, 'qreg')
qtarg = QuantumRegister(1, 'q_targ')
circ = QuantumCircuit(qreg, qtarg)
for i in np.arange(n):
circ.cry(2.**(i+1+nint-n), qreg[i], qtarg)
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def QFTPowerN(circ, qreg1, qreg2, N, wrap=False, inverse=False, nintx=None, nint=None, label='PowN', QFT_on=True, iQFT_on=True):
r"""
|qreg1>|qreg2> -> |qreg1>|qreg1**N>
"""
n1 = qreg1.size
n2 = qreg2.size
if n2>(n1*N):
raise ValueError('The output register is greater than necessary.')
if n2!=(n1*N) and nint == None:
raise ValueError('Output register should be '+str(N)+'x the length of the input register if no integer bit length is specified.')
if nintx==None:
nintx=0
if nint==None:
nint=0
nshift = N-1+(N*nintx)-nint
if inverse:
wrap = True
if wrap:
qreg1 = QuantumRegister(n1, 'q_reg1')
qreg2 = QuantumRegister(n2, 'q_reg2')
circ = QuantumCircuit(qreg1, qreg2)
if QFT_on:
circ.append(QFT(circ, qreg2, do_swaps=False, wrap=True), qreg2[:])
qubit_grid = np.meshgrid(*[np.arange(1,n1+1) for i in np.arange(N)], indexing='ij')
grid_shape = [n1 for i in np.arange(N)]
grid_shape.append(n2)
gridouts = np.ones(grid_shape)*np.arange(1,n2+1)
gridouts = 2*np.pi/(np.power(2.,np.sum(qubit_grid,axis=0)+gridouts.T-n2-nshift))
cond = gridouts%(2.*np.pi)!=0.
inds = np.argwhere(cond)+1
lams = gridouts[cond]
for j,ind in enumerate(inds):
k = ind[0]
ind_ = ind[1:]
cnt = len(np.unique(ind_))
cqubits = [n1-i for i in np.unique(ind_)]
cqubits = [qreg1[n1-i] for i in np.unique(ind_)]
cqubits.append(qreg2[k-1])
circ.append(PhaseGate(lams[j]).control(cnt),cqubits)
if iQFT_on:
circ.append(QFT(circ, qreg2, do_swaps=False, wrap=True, inverse=True), qreg2[:])
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'†'
return circ
def QFTDivision(circ, qreg1, qreg2, c_div, acc, backend=Aer.get_backend('qasm_simulator'), shots=10, wrap=False, inverse=False, label='DivInt'):
if inverse:
wrap = True
if wrap:
qreg1 = QuantumRegister(qreg1.size, 'q_reg1')
qreg2 = QuantumRegister(qreg2.size, 'q_reg2')
acc = QuantumRegister(acc.size, 'acc')
c_div = ClassicalRegister(c_div.size, 'c_div')
circ = QuantumCircuit(qreg1, qreg2, acc, c_div)
d = QuantumRegister(1, 'd')
circ.add_register(d)
circ.x(d[0])
c_dividend_str = '0'
while c_dividend_str[0] == '0':
print(c_dividend_str)
circ = QFTSubtraction(circ, qreg1, qreg2)
circ = QFTAddition(circ, acc, d)
circ.measure(qreg1[:], c_div[:])
result = execute(circ, backend=backend, shots=shots).result()
counts = result.get_counts()
c_dividend_str = list(counts.keys())[0]
print(c_dividend_str)
circ = QFTSubtract(circ, acc, d)
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def taylor_coeffs(f_, args=[], a=0., norders=3):
x = sympy.Symbol('x')
f = f_(x)
coeffs = []
for norder in np.arange(norders):
coeffs.append(float(sympy.diff(f, x, norder).subs(x, a) / sympy.factorial(norder)))
return np.array(coeffs)
def Gaussian_noise_amp(circ, qreg, reps=2, wrap=False, inverse=False, label='GaussNoise'):
n = qreg.size
if inverse:
wrap = True
if wrap:
qreg = QuantumRegister(n, 'q_reg')
circ = QuantumCircuit(qreg)
for level in np.arange(reps+1):
for i in np.arange(n-1):
for j in np.arange(i+1,n):
rand_op = random_unitary(4)
circ.append(rand_op,[qreg[i],qreg[j]])
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def depolarisation_channel(circ, qreg, p, wrap=False, inverse=False, label='depol_channel'):
n = qreg.size
if inverse:
wrap = True
if wrap:
qreg = QuantumRegister(n, 'q_reg')
circ = QuantumCircuit(qreg)
num_terms = 4**n
max_param = num_terms / (num_terms - 1)
if p < 0 or p > max_param:
raise NoiseError("Depolarizing parameter must be in between 0 "
"and {}.".format(max_param))
prob_iden = 1 - p / max_param
prob_pauli = p / num_terms
probs = [prob_iden] + (num_terms - 1) * [prob_pauli]
paulis = [Pauli("".join(tup)) for tup in it.product(['I', 'X', 'Y', 'Z'], repeat=n)]
gates_ind = np.random.choice(num_terms, p=probs, size=1)[0]
gates = paulis[gates_ind]
circ.append(gates, qreg[:])
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def increment_gate(circ, qreg, wrap=False, inverse=False, QFT_on=True, iQFT_on=True, ncut=0, label='inc'):
n = len(qreg)
if inverse:
wrap = True
if wrap:
qreg = QuantumRegister(n, 'q_reg')
circ = QuantumCircuit(qreg)
if n<ncut:
for i in np.arange(n)[1:][::-1]:
if i!=0:
xgate = XGate().control(i)
circ.append(xgate, [*qreg[:i+1]])
circ.x(qreg[0])
else:
bin_one = ''.join(np.zeros(n-1).astype(int).astype(str))+'1'
inc_gate = QFTBinaryAdd(circ, qreg, bin_one, wrap=True, QFT_on=QFT_on, iQFT_on=iQFT_on)
circ.append(inc_gate, qreg)
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def integer_compare(circ, qreg, qtarg, qans, value, geq=True, wrap=False, inverse=False, uncomp=True, label='intP'):
n = len(qreg)
if len(qans)!=n-1:
raise ValueError('Ancilla register must be 1 qubit fewer than input register.')
if len(qtarg)!=1:
raise ValueError('Target register must be of 1 qubit.')
if wrap:
qreg = QuantumRegister(n, 'q_reg')
qans = QuantumRegister(n, 'q_ans')
circ = QuantumCircuit(qreg, qans)
qtarg = qans[0]
qans = qans[1:]
if value<=0.:
if geq:
circ.x(qtarg);
elif value < np.power(2,n):
if n>1:
twos = np.array(list(twos_compliment(my_binary_repr(value, n=n, phase=False))))[::-1]
for i in np.arange(n):
if i==0:
if twos[i]=='1':
circ.cx(qreg[i], qans[i])
elif i<n-1:
if twos[i]=='1':
circ.compose(OR(2), [qreg[i], qans[i-1], qans[i]], inplace=True);
else:
circ.ccx(qreg[i], qans[i - 1], qans[i]);
else:
if twos[i]=='1':
circ.compose(OR(2), [qreg[i], qans[i-1], qtarg], inplace=True);
else:
circ.ccx(qreg[i], qans[i - 1], qtarg);
if not geq:
circ.x(qtarg);
if uncomp:
for i in np.arange(n-1)[::-1]:
if i==0:
if twos[i]=='1':
circ.cx(qreg[i], qans[i]);
else:
if twos[i]=='1':
circ.compose(OR(2), [qreg[i], qans[i-1], qans[i]], inplace=True);
else:
circ.ccx(qreg[i], qans[i-1], qans[i]);
else:
circ.cx(qreg[0], qtarg);
if not geq:
circ.x(qtarg);
else:
if not geq:
circ.x(qtarg);
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def inequal_cond(circ, qreg, qtarg, qans, value, nint=None, phase=False, comp2=True, geq=True, wrap=False, inverse=False, uncomp=True, xflip=True, label='P'):
n = len(qreg)
if len(qans)!=n-1:
raise ValueError('Ancilla register must be 1 qubit fewer than input register.')
if len(qtarg)!=1:
raise ValueError('Target register must be of 1 qubit.')
if phase and not comp2:
raise ValueError('Only twos-compliment representation for signed numbers is currently implemented')
if wrap:
qreg = QuantumRegister(n, 'q_reg')
qans = QuantumRegister(n-1, 'q_ans')
qtarg = QuantumRegister(1, 'q_targ')
circ = QuantumCircuit(qreg, qtarg, qans)
binary = my_binary_repr(value, n, phase=phase, nint=nint)
if phase:
if xflip:
circ.x(qreg[-1]);
if binary[0]=='0':
binary = '1'+binary[1:]
elif binary[0]=='1':
binary = '0'+binary[1:]
int_value = bin_to_dec(binary, nint=None, phase=False)
intcomp_gate = integer_compare(circ, qreg, qtarg, qans, int_value, geq=geq, wrap=wrap, inverse=inverse, uncomp=uncomp)
circ.append(intcomp_gate, [*qreg, *qtarg, *qans]);
if phase and xflip:
circ.x(qreg[-1]);
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def label_gate(circ, qreg, qtarg, qans, qlab, bounds=None, wrap=False, nint=None, inverse=False, phase=False, ncut=0, label='LABEL'):
n = len(qreg)
if nint is None:
nint = n
if phase:
nint -= 1
if inverse:
wrap = True
if bounds is None:
bounds = [0, 2**n]
nlab = int(np.ceil(np.log2(len(bounds))))
if nlab!=qlab.size:
raise ValueError('Size of label register does not match the number of bounds placed.')
if len(qans)!= n-1:
raise ValueError('Ancilla register must have one fewer qubit than input register.')
if wrap:
qreg = QuantumRegister(n, 'q_reg')
qtarg = QuantumRegister(1, 'q_targ')
qans = QuantumRegister(n-1, 'q_ans')
qlab = QuantumRegister(nlab, 'q_lab')
circ = QuantumCircuit(qreg, qtarg, qans, qlab)
circ.x(qreg[-1]);
if nlab>=ncut:
circ.append(QFT(circ, qlab, do_swaps=False, wrap=True), qlab)
for i,bound_ in enumerate(bounds):
binary = my_binary_repr(bound_, n=n, nint=nint, phase=phase)
if binary[0]=='0':
binary = '1'+binary[1:]
elif binary[0]=='1':
binary = '0'+binary[1:]
bound = bin_to_dec(binary, nint=None, phase=False)
intcomp_gate = integer_compare(circ, qreg, qtarg, qans, bound, geq=True, wrap=True, uncomp=False, label='P'+str(i))
circ.append(intcomp_gate, [*qreg, qtarg[0], *qans[:]])
inc_gate = increment_gate(circ, qlab, wrap=True, label='SET'+str(i), ncut=ncut, QFT_on=False, iQFT_on=False).control(1)
circ.append(inc_gate, [qtarg[0], *qlab[:]])
intcomp_gate_inv = integer_compare(circ, qreg, qtarg, qans, bound, geq=True, wrap=True, uncomp=False, inverse=True, label='P'+str(i))
circ.append(intcomp_gate_inv, [*qreg, qtarg[0], *qans[:]])
if nlab>=ncut:
circ.append(QFT(circ, qlab, do_swaps=False, wrap=True, inverse=True), qlab)
circ.x(qreg[-1]);
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def cin_gate(circ, qcoff, qlab, coeffs_in, nint=None, phase=False, wrap=False, inverse=False, label='X', comp2=True):
n = len(qcoff)
nlab = len(qlab)
if 2**nlab<len(coeffs_in):
print('Not enough label states to coefficents.')
return 0
if inverse:
wrap = True
if wrap:
qcoff = QuantumRegister(n, 'q_reg')
qlab = QuantumRegister(nlab, 'q_lab')
circ = QuantumCircuit(qcoff, qlab)
for i in np.arange(len(coeffs_in)):
control_bits = my_binary_repr(i, nlab, nint=nlab, phase=False)
if i>0:
control_bits_ = my_binary_repr(i-1, nlab, nint=nlab, phase=False)[::-1]
else:
control_bits_ = np.ones(nlab).astype(int).astype(str)
for j,control_bit in enumerate(control_bits[::-1]):
if control_bit=='0' and control_bits_[j]=='1':
circ.x(qlab[j])
if comp2:
input_gate = input_bits_to_qubits(my_binary_repr(coeffs_in[i], n, nint=nint, phase=phase), circ, reg=qcoff, wrap=True).control(nlab)
circ.append(input_gate, [*qlab, *qcoff]);
else:
input_gate = input_bits_to_qubits(my_binary_repr(np.abs(coeffs_in[i]), n-1, nint=nint, phase=False), circ, reg=qcoff[:-1], wrap=True).control(nlab)
circ.append(input_gate, [*qlab, *qcoff[:-1]]);
if coeffs_in[i]<0.:
circ.append(XGate().control(nlab), [*qlab, qcoff[-1]]);
if i<len(coeffs_in)-1:
control_bits_ = my_binary_repr(i+1, nlab, nint=nlab, phase=False)[::-1]
else:
control_bits_ = np.ones(nlab).astype(int).astype(str)
for j,control_bit in enumerate(control_bits[::-1]):
if control_bit=='0' and control_bits_[j]=='1':
circ.x(qlab[j])
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def classic_piecewise_function(x_, coeffs_, n, bounds, nint=None, phase=False):
nintx = int(np.ceil(np.log2(np.max(bounds))))
x = pres_est(x_, n, nint=n, phase=phase)
coeff_ind = np.argwhere(bounds>=x)[0].flatten()
if coeff_ind!=0:
coeff_ind = coeff_ind-1
coeffs_ = coeffs_.T[coeff_ind].flatten()
nintc = int(np.ceil(np.log2(np.max(np.abs(coeffs_)))))
coeffs = []
for coeff in coeffs_:
coeffs.append(pres_est(coeff, n, nint=nintc, phase=phase))
coeffs = np.array(coeffs)[::-1]
y = pres_est(x*coeffs[0], n, nint=nint, phase=phase)
y = pres_est(y + coeffs[1], n, nint=nint, phase=phase)
for i in np.arange(2,len(coeffs)):
y = pres_est(y*x, n, nint=nint, phase=phase)
y = pres_est(y + coeffs[i], n, nint=nint, phase=phase)
return y
def linear_piecewise_approx(circ, qx, qout, qlab, qcoff, coeffs, bounds, nint=None, nintx=None, nintcs=None, phase=False, wrap=False, inverse=False, unlabel=False, label='f(x)'):
m = int(np.ceil(np.log2(len(bounds))))
nx = len(qx)
n = len(qout)
n0 = len(qcoff)
Nord, Ncoeffs = coeffs.shape
if Nord!=2:
raise ValueError('Currently only working for linear piecewise approximations.')
if nint is None:
nint = n
if m!=len(qlab):
raise ValueError('Size of label register is smaller than number of bounds.')
return 0
if np.any(nintcs==None):
nintcs = []
for coeffs_ in coeffs:
nintcs.append(int(np.ceil(np.log2(np.max(np.abs(coeffs_))))))
nintcs[-1] = nint
nintcs = np.array(nintcs).astype(int)
if nintx is None:
nintx = int(np.ceil(np.log2(np.max(np.abs(bounds)))))
if inverse:
wrap = True
if wrap:
qx = QuantumRegister(nx, 'x')
qout = QuantumRegister(n, 'o')
qlab = QuantumRegister(m, 'l')
qcoff = QuantumRegister(n0, 'c')
circ = QuantumCircuit(qx, qout, qlab, qcoff)
# We can use the coefficient register as the ancillary register for
#the labelling step as before
qtarg = qcoff[0]
qans = [*qcoff[1:], *qout][:nx-1]
# Label the data with the labelling operation
l_gate = label_gate(circ, qx, qtarg, qans, qlab, bounds=bounds, nint=nintx, phase=phase, wrap=True)
circ.append(l_gate, [*qx, qtarg, *qans, *qlab]);
# Load A1 into the coefficient register conditioned on the label register
X1_gate = cin_gate(circ, qcoff, qlab, coeffs[0], nint=nintcs[0,0], phase=phase, wrap=True)
circ.append(X1_gate, [*qcoff, *qlab]);
# Multiply the coefficient and x registers and save the output on the output register
mul_gate = QFTMultPhase(circ, qcoff, qx, qout, wrap=True, nint1=nintcs[0,0], nint2=nintx, nint3=nint)
circ.append(mul_gate, [*qcoff, *qx, *qout]);
# Unload A1 from the coefficient register with the inverse load operation
X1_gate_inv = cin_gate(circ, qcoff, qlab, coeffs[0], nint=nintcs[0,0], phase=phase, wrap=True, inverse=True)
circ.append(X1_gate_inv, [*qcoff, *qlab]);
# Load A0 into the coefficient register conditioned on the label register
X0_gate = cin_gate(circ, qcoff, qlab, coeffs[1], nint=nintcs[0,1], phase=phase, wrap=True)
circ.append(X0_gate, [*qcoff, *qlab]);
# Add the coefficient register to the output register
add_gate = QFTAddition(circ, qcoff, qout, nint1=nintcs[0,1], nint2=nint, wrap=True, phase=phase)
circ.append(add_gate, [*qcoff, *qout]);
# Unload A0 to clear the coefficient register
X0_gate_inv = cin_gate(circ, qcoff, qlab, coeffs[1], nint=nintcs[0,1], phase=phase, wrap=True, inverse=True)
circ.append(X0_gate_inv, [*qcoff, *qlab]);
# Unlabel the label register
l_gate_inv = label_gate(circ, qx, qtarg, qans, qlab, bounds=bounds, nint=nintx, phase=phase, wrap=True, inverse=True)
circ.append(l_gate_inv, [*qx, qtarg, *qans, *qlab]);
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def piecewise_function_posmulti(circ, q_x, q_y, q_lab, q_coff, coeffs, bounds, nint=None, nintx=None, nintcs=None, phase=False, wrap=False, inverse=False, unlabel=False, unfirst=False, comp2=False, label='f_x'):
nlab = int(np.ceil(np.log2(len(bounds))))
nx = len(q_x)
n = len(q_y)
nc = len(q_coff)
Nord, Ncoeffs = coeffs.shape
if Nord!=2:
raise ValueError('Currently only working for linear piecewise approximations.')
if nint is None:
nint = n
if nlab!=len(q_lab):
raise ValueError('Size of label register is smaller than number of bounds.')
return 0
if np.any(nintcs==None):
nintcs = []
for coeffs_ in coeffs:
nintcs.append(int(np.ceil(np.log2(np.max(np.abs(coeffs_))))))
nintcs[-1] = nint
nintcs = np.array(nintcs).astype(int)
if nintx is None:
nintx = int(np.ceil(np.log2(np.max(np.abs(bounds)))))
if inverse:
wrap = True
if wrap:
q_x = QuantumRegister(nx, 'q_x')
q_y = QuantumRegister(n, 'q_y0')
q_lab = QuantumRegister(nlab, 'q_lab')
q_coff = QuantumRegister(nc, 'q_coff')
circ = QuantumCircuit(q_x, q_y, q_lab, q_coff)
q_ans = [*q_coff, *q_y]
if len(q_ans)<nx:
raise ValueError('Coefficient/output register must be greater than half the length of the x register.')
lab_gate = label_gate(circ, q_x, q_ans[0], q_ans[1:nx+2], q_lab, bounds=bounds, nint=nintx, phase=False, wrap=True)
circ.append(lab_gate, [*q_x, *q_ans[:nx+2], *q_lab]);
#y1in_gate = cin_gate(circ, q_y, q_lab, coeffs[1], nint=nintcs[0,1], phase=phase, wrap=True)
#circ.append(y1in_gate, [*q_y, *q_lab]);
#circ.append(QFT(circ, q_y, do_swaps=False, wrap=True), q_y);
for i in np.arange(1, Nord):
y0in_gate = cin_gate(circ, q_coff, q_lab, coeffs[i-1], nint=nintcs[i-1,0], phase=phase, wrap=True, comp2=comp2)
circ.append(y0in_gate, [*q_coff, *q_lab]);
mul_gate = QFTPosMultiplicand(circ, q_coff, q_x, q_y, wrap=True, nint1=nintcs[i-1,0], nint2=nintx, nint3=nint, iQFT_on=True, QFT_on=True, comp2=comp2)
circ.append(mul_gate, [*q_coff, *q_x, *q_y]);
if unfirst or True:
y0in_gate_inv = cin_gate(circ, q_coff, q_lab, coeffs[i-1], nint=nintcs[i-1,0], phase=phase, wrap=True, comp2=comp2, inverse=True)
circ.append(y0in_gate_inv, [*q_coff, *q_lab]);
y1in_gate = cin_gate(circ, q_coff, q_lab, coeffs[i], nint=nintcs[i-1,1], phase=phase, wrap=True)
circ.append(y1in_gate, [*q_coff, *q_lab]);
add_gate = QFTAddition(circ, q_coff, q_y, wrap=True, phase=phase, nint1=nintcs[i-1,1], nint2=nint, QFT_on=True, iQFT_on=True)
circ.append(add_gate, [*q_coff, *q_y]);
#circ.append(QFT(circ, q_y, do_swaps=False, wrap=True, inverse=True), q_y);
if unlabel:
lab_gate_inv = label_gate(circ, q_x, q_ans[0], q_ans[1:nx+2], q_lab, bounds=bounds, nint=nintx, phase=False, wrap=True, inverse=True)
circ.append(lab_gate_inv, [*q_x, *q_ans[:nx+2], *q_lab]);
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def SWAP_test(circ, q_1, q_2, q_a, wrap=False, inverse=False, label='SWAP'):
n = len(q_1)
if len(q_1)!=len(q_2):
raise ValueError('The two registers should be the same size!')
if inverse:
wrap = True
if wrap:
q_1 = QuantumRegister(n, 'q_1')
q_2 = QuantumRegister(n, 'q_2')
q_a = QuantumRegister(1, 'q_a')
circ = QuantumCircuit(q_1, q_2, q_a)
circ.h(q_a[0]);
for qubit in np.arange(n):
circ.cswap(q_a,q_1[qubit],q_2[qubit])
circ.h(q_a[0]);
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def gate_decompose(qc):
"""decompose circuit to evaluate cost"""
pass_ = Unroller(["u3", "cx"])
return PassManager(pass_).run(qc).count_ops()
def Grover_Rudolph_load(circ, qx, probs, wrap=False, inverse=False, nstart=0, nend=None, label='GR_load'):
nx = len(qx)
if nend==None:
nend=nx
if len(probs)!=2**nx:
raise ValueError('Probabilities must equal length of x register')
if inverse:
wrap = True
if wrap:
qx = QuantumRegister(nx, 'q_x')
circ = QuantumCircuit(qx)
for m in np.arange(nstart, nend):
def GR_func(j):
j = np.array(j).astype(int)
As = []
for i in np.arange(2**m):
As.append(np.sum(probs[i*2**(nx-m):(i+1)*2**(nx-m)]))
As1 = []
for i in np.arange(2**(m+1)):
As1.append(np.sum(probs[i*2**(nx-(m+1)):(i+1)*2**(nx-(m+1))]))
return np.arccos(np.sqrt(np.array(As1)[::2][j]/np.array(As)[j]))
if m==0:
coeffs = np.arccos(np.sqrt(np.sum(probs[:2**(nx-1)])))
circ.ry(2*coeffs, qx[nx-m-1]);
else:
js = np.arange(2**m)
coeffs = GR_func(js)
for i in np.arange(2**m):
control_bits = my_binary_repr(i, m, nint=None, phase=False)
if i>0:
control_bits_ = my_binary_repr(i-1, m, nint=None, phase=False)[::-1]
else:
control_bits_ = np.ones(m).astype(int).astype(str)
for j,control_bit in enumerate(control_bits[::-1]):
if control_bit=='0' and control_bits_[j]=='1':
circ.x(qx[nx-j-1]);
R_gate = RYGate(2*coeffs[i]).control(int(m))
circ.append(R_gate, [*qx[nx-m-1:][::-1]]);
if i<2**m-1:
control_bits_ = my_binary_repr(i+1, m, nint=None, phase=False)[::-1]
else:
control_bits_ = np.ones(m).astype(int).astype(str)
for j,control_bit in enumerate(control_bits[::-1]):
if control_bit=='0' and control_bits_[j]=='1':
circ.x(qx[nx-j-1]);
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def Grover_Rudolph_func(circ, qx, qanc, qlab, qcoff, probs, wrap=False, inverse=False, mtol=1, mmax=None, norder=1, label='GR_func'):
nx = len(qx)
n = len(qcoff)
nanc = len(qanc)
nlab = len(qlab)
if mmax==None:
mmax=nx
if n!=nanc:
raise ValueError('I think ancilla and coefficient reg should be the same size')
if len(probs)!=2**nx:
raise ValueError('Probabilities must equal length of x register')
if inverse:
wrap = True
if wrap:
qx = QuantumRegister(nx, 'q_x')
qanc = QuantumRegister(nanc, 'q_anc')
qlab = QuantumRegister(nlab, 'q_lab')
qcoff = QuantumRegister(nanc, 'q_coff')
circ = QuantumCircuit(qx, qanc, qlab, qcoff)
if mtol>nx:
GRL_gate = Grover_Rudolph_load(circ, qx, probs, wrap=True)
circ.append(GRL_gate, qx);
elif mtol!=0:
probs_ = []
for i in np.arange(2**mtol):
probs_.append(np.sum(probs[i*2**(nx-mtol):(i+1)*2**(nx-mtol)]))
probs_ = np.array(probs_)
GRL_gate = Grover_Rudolph_load(circ, qx[nx-mtol:], probs_, wrap=True)
circ.append(GRL_gate, qx[nx-mtol:]);
for m in np.arange(mtol,mmax):
def GR_func(j):
j = np.array(j).astype(int)
As = []
for i in np.arange(2**m):
As.append(np.sum(probs[i*2**(nx-m):(i+1)*2**(nx-m)]))
As1 = []
for i in np.arange(2**(m+1)):
As1.append(np.sum(probs[i*2**(nx-(m+1)):(i+1)*2**(nx-(m+1))]))
return np.arccos(np.sqrt(np.array(As1)[::2][j]/np.array(As)[j]))
js = np.arange(2**m)
coeffs = GR_func(js)
bounds_ = np.linspace(0,2**m,(2**nlab)+1).astype(int)
coeffs = get_bound_coeffs(GR_func, bounds_, norder, reterr=False).T#[::-1]
bounds = bounds_[1:]
max_list0 = np.array([coeffs[0], coeffs[1], coeffs[0]*2**nx, (coeffs[0]*2**nx)+coeffs[-1]])
max_list1 = max_list0
nintcs = []
nintcs.append(int(np.ceil(np.log2(np.max(np.abs(max_list0))))))
nintcs.append(int(np.ceil(np.log2(np.max(np.abs(max_list1))))))
nint = nintcs[-1]
nintcs = np.array([nintcs])
func_gate = piecewise_function_posmulti(circ, qx[nx-m:], qanc, qlab, qcoff, coeffs, bounds, nint=nint, nintx=nx, nintcs=nintcs, phase=False, wrap=True, unlabel=False, unfirst=False)
circ.append(func_gate, [*qx[nx-m:], *qanc, *qlab, *qcoff]);
rot_gate = CRotation(circ, qanc, qx[nx-m-1], nint=nint, wrap=True)
circ.append(rot_gate, [*qanc, qx[nx-m-1]])
func_gate_inv = piecewise_function_posmulti(circ, qx[nx-m:], qanc, qlab, qcoff, coeffs, bounds, nint=nint, nintx=nx, nintcs=nintcs, phase=False, wrap=True, inverse=True, unlabel=False, unfirst=False)
circ.append(func_gate_inv, [*qx[nx-m:], *qanc, *qlab, *qcoff]);
for m in np.arange(mmax,nx):
circ.h(qx[nx-m-1]);
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def lpf(circ, qx, qout, qlab, qcoff, coeffs, bounds, nintx=None, nintcs=None, nint=None, phasex=False, phase=True, wrap=False, inverse=False, label='f_x'):
nlab = int(np.ceil(np.log2(len(bounds))))
nx = len(qx)
n = len(qout)
nc = len(qcoff)
Nord, Ncoeffs = coeffs.shape
if Nord!=2:
raise ValueError('Currently only working for linear piecewise approximations.')
if nlab!=len(qlab):
raise ValueError('Size of label register is smaller than number of bounds.')
return 0
if nint==None:
nint=n
if np.any(nintcs==None):
nintcs = []
for coeffs_ in coeffs:
nintcs.append(int(np.ceil(np.log2(np.max(np.abs(coeffs_))))))
nintcs[-1] = nint
nintcs = np.array(nintcs).astype(int)
if nintx is None:
nintx = int(np.ceil(np.log2(np.max(np.abs(bounds)))))
if inverse:
wrap = True
if wrap:
qx = QuantumRegister(nx, 'x')
qout = QuantumRegister(n, 'out')
qlab = QuantumRegister(nlab, 'lab')
qcoff = QuantumRegister(nc, 'coff')
circ = QuantumCircuit(qx, qout, qlab, qcoff)
qans = [*qcoff[1:], *qout][:nx-1]
qtarg = qcoff[0]
# Label the data with the labelling operation
l_gate = label_gate(circ, qx, qtarg, qans, qlab, bounds=bounds, nint=nintx, phase=phase, wrap=True)
circ.append(l_gate, [*qx, qtarg, *qans, *qlab]);
# Load A1 into the coefficient register conditioned on the label register
X1_gate = cin_gate(circ, qcoff, qlab, coeffs[0], nint=nintcs[0,0], phase=phase, wrap=True)
circ.append(X1_gate, [*qcoff, *qlab]);
# Multiply the coefficient and x registers and save the output on the output register
mul_gate = QFTMultPhase(circ, qcoff, qx, qout, wrap=True, nint1=nintcs[0,0], nint2=nintx, nint3=nint)
circ.append(mul_gate, [*qcoff, *qx, *qout]);
# Unload A1 from the coefficient register with the inverse load operation
X1_gate_inv = cin_gate(circ, qcoff, qlab, coeffs[0], nint=nintcs[0,0], phase=phase, wrap=True, inverse=True)
circ.append(X1_gate_inv, [*qcoff, *qlab]);
# Load A0 into the coefficient register conditioned on the label register
X0_gate = cin_gate(circ, qcoff, qlab, coeffs[1], nint=nintcs[0,1], phase=phase, wrap=True)
circ.append(X0_gate, [*qcoff, *qlab]);
# Add the coefficient register to the output register
add_gate = QFTAddition(circ, qcoff, qout, nint1=nintcs[0,1], nint2=nint, wrap=True, phase=phase)
circ.append(add_gate, [*qcoff, *qout]);
# Unload A0 to clear the coefficient register
X0_gate_inv = cin_gate(circ, qcoff, qlab, coeffs[1], nint=nintcs[0,1], phase=phase, wrap=True, inverse=True)
circ.append(X0_gate_inv, [*qcoff, *qlab]);
# Unlabel the label register
l_gate_inv = label_gate(circ, qx, qtarg, qans, qlab, bounds=bounds, nint=nintx, phase=phase, wrap=True, inverse=True)
circ.append(l_gate_inv, [*qx, qtarg, *qans, *qlab]);
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def PQC_realamp(circ, qreg, weights, wrap=False, inverse=False, label='PQCrealamp'):
n = len(qreg)
reps = weights.shape[0] - 1
if weights.shape[1]!=n:
raise ValueError('Shape of weight array does not match the number of qubits of the target register.')
if inverse:
wrap = True
if wrap:
qreg = QuantumRegister(n, 'q_reg')
circ = QuantumCircuit(qreg)
circ.h(qreg);
for rep in np.arange(reps+1):
for i in np.arange(n):
circ.ry(weights[rep,i],qreg[i])
for i in np.arange(n):
if i!=n-1 and rep!=reps:
circ.cx(qreg[i], qreg[i+1])
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def round_sig(xs, sigfig=0):
if np.array(xs).ndim==0:
xs = np.array([xs])
rxs = []
for x in xs:
if x!=0.:
rxs.append(np.round(x, sigfig-int(np.floor(np.log10(np.abs(x))))))
else:
rxs.append(0.)
rxs = np.array(rxs)
return rxs
def optimize_coeffs_qubits(f_x, xs, m, n=None, npres0=None, npres1=None, norder=1, phase=True, label_swap=False):
if n==None and npres0==None and npres1==None:
raise ValueError('Must specify either the number of qubits of the output register or the precision qubits of sets of coefficients.')
if npres0==None and npres1!=None or npres0!=None and npres1==None:
raise ValueError('Must leave both precision qubit options as None.')
xmin = xs[0]
xmax = xs[-1]
nx = int(np.log2(len(xs)))
nintx = get_nint(xs)
npresx = int(-np.log2(xs[1]-xs[0]))
if xmin==0.:
xphase=False
else:
xphase=True
bounds_ = np.linspace(xs[1], xmax, (2**m))
bounds__ = []
for bound in bounds_:
bounds__.append(bin_to_dec(my_binary_repr(bound, n=nx, nint=nintx, phase=xphase), nint=nintx, phase=xphase))
bounds_ = bounds__
bounds_[0] = xs[1]
bounds_ = np.append(xmin, bounds_)
coeffs = get_bound_coeffs(f_x, bounds_, norder, reterr=False).T
#bounds = np.copy(np.array(bounds_[:-1]))
bounds = np.copy(np.array(bounds_))
# The number of integer bits of A1, A0 and the result
nint0 = get_nint(coeffs[0])
nint1 = get_nint(coeffs[1])
nint = nintx + nint0
nswitch = False
if n==None:
nswitch = True
# The number of precision bits of the result
npres = npresx + npres0
# The total number of bits of A1, A0 and the result
n0 = npres0 + nint0 + 1
n1 = npres1 + nint1 + 1
n = npres + nint + 1
else:
npres = n - nint - 1
npres0 = npres - npresx
n0 = npres0 + nint0 + 1
npres1 = n0 - nint1 - 1
n1 = npres1 + nint1 + 1
rcoeffs = []
for coeff in coeffs[0]:
# Convert coefficient to binary string of new length n0, then calculate the corresponding decimal value
rcoeff = bin_to_dec(my_binary_repr(coeff, n0, nint=nint0, phase=phase), nint=nint0, phase=phase)
rcoeffs.append(rcoeff)
coeffs[0] = np.array(rcoeffs)
# Calculate the differences between the f(x) and A1x over all x
fdifs = f_x(xs) - piecewise_poly(xs, np.array([coeffs[0],np.zeros(len(coeffs[1]))]).T, bounds)
coeffs_ = []
bounds__ = np.copy(bounds_)
bounds__[-1] = np.inf
for i in np.arange(len(bounds__))[:-1]:
# Calculate the mean differences in each domain to be the new bias A0
coeffs_.append(np.mean(fdifs[np.greater_equal(xs,bounds__[i])&np.greater(bounds__[i+1],xs)]))
coeffs[1] = np.array(coeffs_)
nint1 = get_nint(coeffs[1])
rcoeffs = []
for coeff in coeffs[1]:
# Convert coefficient to binary string of new length n1, then calculate the corresponding decimal value
rcoeff = bin_to_dec(my_binary_repr(coeff, n1, nint=nint1, phase=phase), nint=nint1, phase=phase)
rcoeffs.append(rcoeff)
coeffs[1] = np.array(rcoeffs)
coeffs[0,0] = 0.
coeffs[1,0] = bin_to_dec(my_binary_repr(f_x(bounds[0]), n1, nint=nint1, phase=phase), nint=nint1, phase=phase)
# The number of integer bits of A1, A0 and the result
nint0 = get_nint(coeffs[0])
nint1 = get_nint(coeffs[1])
nint = nintx + nint0
if nswitch:
# The number of precision bits of the result
npres = npresx + npres0
# The total number of bits of A1, A0 and the result
n0 = npres0 + nint0 + 1
n1 = npres1 + nint1 + 1
n = npres + nint + 1
else:
npres = n - nint - 1
npres0 = npres - npresx
n0 = npres0 + nint0 + 1
npres1 = n0 - nint1 - 1
n1 = npres1 + nint1 + 1
ys_rnd = piecewise_poly(xs, coeffs.T, bounds)
A1x = piecewise_poly(xs, np.array([coeffs[0],np.zeros(len(coeffs[1]))]).T, bounds)
nint = get_nint([A1x, ys_rnd])
if nswitch:
n = npres + nint + 1
nintcs = np.array([[nint0,nint1]])
if 16*(2**(n0+n+nx+m))/2**20>7568:
raise ValueError('Too many qubits!',n0+n+nx+m)
if label_swap:
coeffs[0] = np.array([coeffs[0,-1],*coeffs[0,:-1]])
coeffs[1] = np.array([coeffs[1,-1],*coeffs[1,:-1]])
return n, n0, nint, nintcs, coeffs, bounds[:-1], npres0, npres1
def get_bound_coeffs(func, bounds, norder, reterr=False):
if np.array(bounds).ndim==0:
print('Bounds must be a list of two entries!')
if len(bounds)==1:
print('Bounds must be a list of two entries!')
coeffs = []
errs = []
for i in np.arange(len(bounds))[:-1]:
coeffs_, err_ = run_remez(func, bounds[i], bounds[i+1], norder)
coeffs.append(np.array(coeffs_))
errs.append(err_)
if reterr:
return np.array(coeffs), np.array(errs)
else:
return np.array(coeffs)
def _get_chebyshev_nodes(n, a, b):
nodes = [.5 * (a + b) + .5 * (b - a) * np.cos((2 * k + 1) / (2. * n) * np.pi)
for k in range(n)]
return nodes
def _get_errors(exact_values, poly_coeff, nodes):
ys = np.polyval(poly_coeff, nodes)
for i in range(len(ys)):
ys[i] = abs(ys[i] - exact_values[i])
return ys
def run_remez(fun, a, b, d=5, odd=False, even=False, tol=1.e-13):
finished = False
# initial set of points for the interpolation
cn = _get_chebyshev_nodes(d + 2, a, b)
# mesh on which we'll evaluate the error
cn2 = _get_chebyshev_nodes(100 * d, a, b)
# do at most 50 iterations and cancel if we "lose" an interpolation
# point
it = 0
while not finished and len(cn) == d + 2 and it < 50:
it += 1
# set up the linear system of equations for Remez' algorithm
b = np.array([fun(c) for c in cn])
A = np.matrix(np.zeros([d + 2,d + 2]))
for i in range(d + 2):
x = 1.
if odd:
x *= cn[i]
for j in range(d + 2):
A[i, j] = x
x *= cn[i]
if odd or even:
x *= cn[i]
A[i, -1] = (-1)**(i + 1)
# this will give us a polynomial interpolation
res = np.linalg.solve(A, b)
# add padding for even/odd polynomials
revlist = reversed(res[0:-1])
sc_coeff = []
for c in revlist:
sc_coeff.append(c)
if odd or even:
sc_coeff.append(0)
if even:
sc_coeff = sc_coeff[0:-1]
# evaluate the approximation error
errs = _get_errors([fun(c) for c in cn2], sc_coeff, cn2)
maximum_indices = []
# determine points of locally maximal absolute error
if errs[0] > errs[1]:
maximum_indices.append(0)
for i in range(1, len(errs) - 1):
if errs[i] > errs[i-1] and errs[i] > errs[i+1]:
maximum_indices.append(i)
if errs[-1] > errs[-2]:
maximum_indices.append(-1)
# and choose those as new interpolation points
# if not converged already.
finished = True
for idx in maximum_indices[1:]:
if abs(errs[idx] - errs[maximum_indices[0]]) > tol:
finished = False
cn = [cn2[i] for i in maximum_indices]
return sc_coeff, max(abs(errs))
def PhaseEst(circ, qreg, qanc, A_gate, wrap=False, inverse=False, do_swaps=True, reverse_bits=False, label='QPE'):
n = len(qreg)
nanc = len(qanc)
if inverse:
wrap = True
if wrap:
qreg = QuantumRegister(n, 'q_reg')
qanc = QuantumRegister(nanc, 'q_anc')
circ = QuantumCircuit(qreg, qanc)
circ.h(qanc);
for i in np.arange(nanc):
A_gate_i = A_gate.power(-2.**(i)).control(1)
circ.append(A_gate_i, [qanc[i], *qreg]);
iqft_gate = QFT(circ, qanc, do_swaps=do_swaps, wrap=True, inverse=True)
if reverse_bits:
circ.append(iqft_gate, qanc[::-1]);
else:
circ.append(iqft_gate, qanc);
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def HHL(circ, qb, qanc, qtarg, A, t=2.*np.pi, scaling=None, wrap=False, inverse=False, phase=True, label='HHL'):
n = len(qb)
nanc = len(qanc)
if inverse:
wrap = True
if wrap:
qb = QuantumRegister(n, 'b')
qanc = QuantumRegister(nanc, 'anc')
qtarg = QuantumRegister(1, 'targ')
circ = QuantumCircuit(qb, qanc, qtarg)
# Define unitary operator given matrix A and evolution time t
A_gate = HamiltonianGate(A, t)
# Apply phase estimation
qe_gate = PhaseEst(circ, qb, qanc, A_gate, wrap=True, do_swaps=False, reverse_bits=True)
circ.append(qe_gate, [*qb, *qanc]);
# Apply ExactReciprocal to rotate the target qubit proportionally to the given scaling and the inverse of the
# values stored in the computational basis of the ancillary register
rec_gate = ExactReciprocal(nanc, scaling=scaling, neg_vals=phase).to_gate()
circ.append(rec_gate, [*qanc[::-1], qtarg]);
# Apply the inverse phase estimation
qe_gate_inv = PhaseEst(circ, qb, qanc, A_gate, wrap=True, inverse=True, do_swaps=False, reverse_bits=True)
circ.append(qe_gate_inv, [*qb, *qanc]);
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
def QGPR(circ, qreg, qanc, qtarg, qcont, v_gate, u_gate, A, t, scaling, wrap=False, inverse=False, neg_vals=True, label='QGPR'):
n = len(qreg)
nanc = len(qanc)
if inverse:
wrap = True
if wrap:
qcont = QuantumRegister(1, 'q_cont')
qtarg = QuantumRegister(1, 'q_targ')
qreg = QuantumRegister(n, 'q_reg')
qanc = QuantumRegister(nanc, 'anc')
circ = QuantumCircuit(qreg, qanc, qtarg, qcont)
circ.h(qcont);
circ.append(v_gate.control(1), [qcont, *qreg]);
circ.x(qcont);
circ.cx(qcont, qtarg);
circ.append(u_gate.control(1), [qcont, *qreg]);
circ.x(qcont);
hhl_gate = HHL(circ, qreg, qanc, qtarg, A, t=t, scaling=scaling, wrap=True).control(1)
circ.append(hhl_gate, [qcont, *qreg, *qanc, qtarg]);
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
# You can reverse the order of the qubits.
from qiskit.quantum_info import DensityMatrix
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.t(1)
qc.s(0)
qc.cx(0,1)
matrix = DensityMatrix(qc)
plot_bloch_multivector(matrix, title='My Bloch Spheres', reverse_bits=True)
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit.circuit import Parameter
from qiskit import pulse
from qiskit.test.mock.backends.almaden import *
phase = Parameter('phase')
with pulse.build(FakeAlmaden()) as phase_test_sched:
pulse.shift_phase(phase, pulse.drive_channel(0))
phase_test_sched.instructions # ()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.