repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw, IQXSimple
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial')
draw(qc, style=IQXSimple())
|
https://github.com/anish-ku/Deutsch-Jozsa-Algorithm-Qiskit
|
anish-ku
|
import numpy as np
from qiskit import QuantumCircuit as QC
from qiskit import execute
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit.tools.jupyter import *
provider = IBMQ.load_account()
from qiskit.visualization import plot_histogram
def oracle(case, n):
##creating an oracle
oracle_qc = QC(n+1)
if case=="balanced":
for i in range(n):
oracle_qc.cx(i,n)
if case=="constant":
pass
##converting circuit to a indivsual gate
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle"
return oracle_gate
def dj_algo(n, case="random"):
dj_crc = QC(n+1,n)
for i in range(n):
dj_crc.h(i)
dj_crc.x(n)
dj_crc.h(n)
if case=="random":
rnd = np.random.randint(2)
if rnd == 0:
case = "constant"
else:
case = "balanced"
dj_oracle = oracle(case, n)
dj_crc.append(dj_oracle, range(n+1))
for i in range(n):
dj_crc.h(i)
dj_crc.measure(i,i)
return dj_crc
n = 3
dj_crc = dj_algo(n)
dj_crc.draw('mpl')
#simulating
backend=BasicAer.get_backend('qasm_simulator')
shots = 1024
dj_circuit = dj_algo(n, "balanced")
results = execute(dj_circuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
#running on real quantum computer
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and
not x.configuration().simulator and x.status().operational == True))
print("Using least busy backend: ", backend)
%qiskit_job_watcher
dj_circuit = dj_algo(n, "balanced")
job = execute(dj_circuit, backend=backend, shots=shots, optimization_level=3)
result = job.result()
answer = result.get_counts()
plot_histogram(answer)
|
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!
plt.figure(figsize=(12, 5))
plt.plot(times, measurements, "--o", linewidth=3);
plt.xlabel("Time [microseconds]");
plt.ylabel("Probability of excited state");
plt.title("T1 measurement data")
plt.grid();
plt.show()
"""Do the data fitting."""
def fit(time: float, T1: float) -> float:
return np.exp(-time / T1) ### Your code here!
"""Use scipy.optimize.curve_fit to fit the data."""
### Your code here!
optimal_params, covariance = scp.optimize.curve_fit(fit, times, measurements)
print(f"Computed T1 value: {round(optimal_params[0], 3)} microseconds.")
"""Plot your fit over the raw data here."""
### Your code here!
# Compute the fit
fitvals = fit(times, *optimal_params)
# Plot the fit and data
plt.figure(figsize=(12, 5))
plt.plot(times, measurements, "-.", linewidth=2, label="Data");
plt.plot(times, fitvals, "-", linewidth=4, label="Fit");
plt.xlabel("Time [microseconds]");
plt.ylabel("Frequency of excited state");
plt.title("T1 measurement data");
plt.legend();
plt.grid();
plt.text(20, 0.8, rf"T1 = {round(optimal_params[0], 3)} $\mu$s")
plt.show()
"""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!
plt.figure(figsize=(12, 5))
plt.scatter(times, measurements);
plt.xlabel("Time [microseconds]");
plt.ylabel("Probability of ground state");
plt.title("Ramsey measurement data")
plt.grid();
plt.show()
"""Define the fit function."""
def ramsey_fit(time: float, domega: float, T2: float) -> float:
return 0.5 + 0.5 * np.cos(domega * times) * np.exp(- times / T2) ### Your code here!
"""Do the fitting."""
### Your code here!
optimal_params, covariance = scp.optimize.curve_fit(ramsey_fit, times, measurements)
"""Plot the fit and data."""
### Your code here!
# Compute the fit
fitvals = ramsey_fit(times, *optimal_params)
# Do the plotting
plt.figure(figsize=(12, 5))
plt.plot(times, fitvals, "-", linewidth=4, label="Fit", color="red");
plt.scatter(times, measurements, label="Data");
plt.xlabel("Time [microseconds]");
plt.ylabel("Probability of ground state");
plt.title("Ramsey measurement data")
plt.legend();
plt.grid();
plt.text(30, -0.1, rf"T2 = {round(optimal_params[1], 3)} $\mu$s")
plt.show()
"""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!
plt.figure(figsize=(12, 5))
plt.plot(times, measurements, "--o", linewidth=3);
plt.xlabel("Time [microseconds]");
plt.ylabel("Frequency of ground state");
plt.title("Hahn-echo measurement data");
plt.grid();
plt.show()
"""Define a fit function."""
def hahn_fit(time: float, T2: float) -> float:
return 0.5 * (1 + np.exp(-time / T2)) ### Your code here!
"""Do the fitting."""
### Your code here!
optimal_params, covariance = scp.optimize.curve_fit(hahn_fit, times, measurements)
print("T2 =", round(optimal_params[0], 2), "microseconds.")
"""Plot the fit function and data."""
### Your code here!
# Compute the fit
fitvals = hahn_fit(times, *optimal_params)
# Plot the fit and data
plt.figure(figsize=(12, 5))
plt.plot(times, measurements, "--o", linewidth=2, label="Data");
plt.plot(times, fitvals, "-", linewidth=4, label="Fit");
plt.xlabel("Time [microseconds]");
plt.ylabel("Frequency of ground state");
plt.title("Hahn-echo measurement data");
plt.legend();
plt.grid();
plt.text(25, 0.9, rf"T2 = {round(optimal_params[0], 3)} $\mu$s")
plt.show()
"""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/Keerthiraj-Nagaraj/IBM-quantum-challenge-2020
|
Keerthiraj-Nagaraj
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import json
from typing import Any, Callable, Optional, Tuple, Union
from urllib.parse import urljoin
from qiskit import QuantumCircuit, execute
from qiskit.providers import JobStatus
from qiskit.providers.ibmq.job import IBMQJob
from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint
from .exercises import get_question_id
from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate
def _circuit_criteria(
circuit: QuantumCircuit,
max_qubits: Optional[int] = None,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False
) -> Tuple[Optional[int], Optional[int]]:
if max_qubits is not None and circuit.num_qubits > max_qubits:
print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.')
print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.')
return None, None
try:
if check_gates and not uses_multiqubit_gate(circuit):
print('Your circuit appears to not use any multi-quibit gates.')
print('Please review your circuit and try again.')
return None, None
cost = compute_cost(circuit)
if min_cost is not None and cost < min_cost:
print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n'
'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.')
return None, None
return circuit.num_qubits, cost
except Exception as err:
print(f'Unable to compute cost: {err}')
return None, None
def _circuit_grading(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False,
max_qubits: Optional[int] = None,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
payload = None
server = None
if not isinstance(circuit, QuantumCircuit):
print(f'Expected a QuantumCircuit, but was given {type(circuit)}')
print(f'Please provide a circuit as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or '
'the grading servers are down right now.')
return None, None
else:
server = None
_, cost = _circuit_criteria(
circuit,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if cost is not None:
payload = {
'answer': circuit_to_json(circuit)
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def _job_grading(
job_or_id: Union[IBMQJob, str],
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str):
print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}')
print(f'Please submit a job as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or the grading '
'servers are down right now.')
return None, None
else:
server = None
job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id
if not job:
print('An invalid or non-existent job was specified.')
return None, None
job_status = job.status()
if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]:
print(f'Job did not successfully complete: {job_status.value}.')
return None, None
elif job_status is not JobStatus.DONE:
print(f'Job has not yet completed: {job_status.value}.')
print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.')
return None, None
header = job.result().header.to_dict()
if 'qc_cost' not in header:
if is_submit:
print('An unprepared answer was specified. '
'Please prepare() and grade() answer before submitting.')
else:
print('An unprepared answer was specified. Please prepare() answer before grading.')
return None, None
download_url, result_url = get_job_urls(job)
if not download_url or not result_url:
print('Unable to obtain job URLs')
return None, None
payload = {
'answer': json.dumps({
'download_url': download_url,
'result_url': result_url
})
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def _number_grading(
answer: int,
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
if not isinstance(answer, int):
print(f'Expected a integer, but was given {type(answer)}')
print(f'Please provide a number as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server '
'or the grading servers are down right now.')
return None, None
else:
server = None
payload = {
'answer': str(answer)
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def prepare_circuit(
circuit: QuantumCircuit,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False,
**kwargs
) -> Optional[IBMQJob]:
job = None
if not isinstance(circuit, QuantumCircuit):
print(f'Expected a QuantumCircuit, but was given {type(circuit)}')
print(f'Please provide a circuit.')
return None
_, cost = _circuit_criteria(
circuit,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if cost is not None:
if 'backend' not in kwargs:
kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator')
# execute experiments
print('Starting experiment. Please wait...')
job = execute(
circuit,
qobj_header={
'qc_cost': cost
},
**kwargs
)
print(f'You may monitor the job (id: {job.job_id()}) status '
'and proceed to grading when it successfully completes.')
return job
def prepare_solver(
solver_func: Callable,
lab_id: str,
ex_id: str,
problem_set: Optional[Any] = None,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False,
**kwargs
) -> Optional[IBMQJob]:
job = None
if not callable(solver_func):
print(f'Expected a function, but was given {type(solver_func)}')
print(f'Please provide a function that returns a QuantumCircuit.')
return None
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or the grading servers are down right now.')
return
endpoint = server + 'problem-set'
index, value = get_problem_set(lab_id, ex_id, endpoint)
print(f'Running {solver_func.__name__}...')
qc_1 = solver_func(problem_set)
_, cost = _circuit_criteria(
qc_1,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if value and index is not None and index >= 0 and cost is not None:
qc_2 = solver_func(value)
if 'backend' not in kwargs:
kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator')
# execute experiments
print('Starting experiments. Please wait...')
job = execute(
[qc_1, qc_2],
qobj_header={
'qc_index': [None, index],
'qc_cost': cost
},
**kwargs
)
print(f'You may monitor the job (id: {job.job_id()}) status '
'and proceed to grading when it successfully completes.')
return job
def grade_circuit(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None
) -> bool:
payload, server = _circuit_grading(
circuit,
lab_id,
ex_id,
is_submit=False,
max_qubits=max_qubits,
min_cost=min_cost
)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def grade_job(
job_or_id: Union[IBMQJob, str],
lab_id: str,
ex_id: str
) -> bool:
payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def grade_number(
answer: int,
lab_id: str,
ex_id: str
) -> bool:
payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def submit_circuit(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None
) -> bool:
payload, _ = _circuit_grading(
circuit,
lab_id,
ex_id,
is_submit=True,
max_qubits=max_qubits,
min_cost=min_cost
)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def submit_job(
job_or_id: IBMQJob,
lab_id: str,
ex_id: str,
) -> bool:
payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def submit_number(
answer: int,
lab_id: str,
ex_id: str
) -> bool:
payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def get_problem_set(
lab_id: str, ex_id: str, endpoint: str
) -> Tuple[Optional[int], Optional[Any]]:
problem_set_response = None
try:
payload = {'question_id': get_question_id(lab_id, ex_id)}
problem_set_response = send_request(endpoint, query=payload, method='GET')
except Exception as err:
print('Unable to obtain the problem set')
if problem_set_response:
status = problem_set_response.get('status')
if status == 'valid':
try:
index = problem_set_response.get('index')
value = json.loads(problem_set_response.get('value'))
return index, value
except Exception as err:
print(f'Problem set could not be processed: {err}')
else:
cause = problem_set_response.get('cause')
print(f'Problem set failed: {cause}')
return None, None
def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool:
try:
answer_response = send_request(endpoint, body=payload)
status = answer_response.get('status', None)
cause = answer_response.get('cause', None)
score = cost if cost else answer_response.get('score', None)
handle_grade_response(status, score=score, cause=cause)
return status == 'valid' or status is True
except Exception as err:
print(f'Failed: {err}')
return False
def submit_answer(payload: dict) -> bool:
try:
access_token = get_access_token()
baseurl = get_submission_endpoint()
endpoint = urljoin(baseurl, './challenges/answers')
submit_response = send_request(
endpoint,
body=payload,
query={'access_token': access_token}
)
status = submit_response.get('status', None)
if status is None:
status = submit_response.get('valid', None)
cause = submit_response.get('cause', None)
handle_submit_response(status, cause=cause)
return status == 'valid' or status is True
except Exception as err:
print(f'Failed: {err}')
return False
def handle_grade_response(
status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None
) -> None:
if status == 'valid':
print('\nCongratulations 🎉! Your answer is correct.')
if score is not None:
print(f'Your score is {score}.')
elif status == 'invalid':
print(f'\nOops 😕! {cause}')
print('Please review your answer and try again.')
elif status == 'notFinished':
print(f'Job has not finished: {cause}')
print(f'Please wait for the job to complete then try again.')
else:
print(f'Failed: {cause}')
print('Unable to grade your answer.')
def handle_submit_response(
status: Union[str, bool], cause: Optional[str] = None
) -> None:
if status == 'valid' or status is True:
print('\nSuccess 🎉! Your answer has been submitted.')
elif status == 'invalid' or status is False:
print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}')
print('Make sure your answer is correct and successfully graded before submitting.')
elif status == 'notFinished':
print(f'Job has not finished: {cause}')
print(f'Please wait for the job to complete, grade it, and then try to submit again.')
else:
print(f'Failed: {cause}')
print('Unable to submit your answer at this time.')
|
https://github.com/zapatacomputing/qe-qiskit
|
zapatacomputing
|
################################################################################
# © Copyright 2021-2022 Zapata Computing Inc.
################################################################################
############################################################################
# Copyright 2017 Rigetti Computing, Inc.
# Modified by Zapata Computing 2020 to work for qiskit's SummedOp.
#
# 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.
############################################################################
import numpy as np
import pytest
from qeqiskit.conversions import qiskitpauli_to_qubitop, qubitop_to_qiskitpauli
from qiskit.opflow import PauliOp, SummedOp
from qiskit.quantum_info import Pauli
from zquantum.core.openfermion.ops import (
FermionOperator,
InteractionOperator,
InteractionRDM,
QubitOperator,
)
from zquantum.core.openfermion.transforms import jordan_wigner
from zquantum.core.openfermion.utils import hermitian_conjugated
def test_translation_type_enforcement():
"""
Make sure type check works
"""
create_one = FermionOperator("1^")
empty_one_body = np.zeros((2, 2))
empty_two_body = np.zeros((2, 2, 2, 2))
interact_one = InteractionOperator(1, empty_one_body, empty_two_body)
interact_rdm = InteractionRDM(empty_one_body, empty_two_body)
with pytest.raises(TypeError):
qubitop_to_qiskitpauli(create_one)
with pytest.raises(TypeError):
qubitop_to_qiskitpauli(interact_one)
with pytest.raises(TypeError):
qubitop_to_qiskitpauli(interact_rdm)
def test_qubitop_to_qiskitpauli():
"""
Conversion of QubitOperator; accuracy test
"""
hop_term = FermionOperator(((2, 1), (0, 0)))
term = hop_term + hermitian_conjugated(hop_term)
pauli_term = jordan_wigner(term)
qiskit_op = qubitop_to_qiskitpauli(pauli_term)
ground_truth = (
PauliOp(Pauli.from_label("XZX"), 0.5) + PauliOp(Pauli.from_label("YZY"), 0.5)
).to_pauli_op()
assert ground_truth == qiskit_op
def test_qubitop_to_qiskitpauli_zero():
zero_term = QubitOperator()
qiskit_term = qubitop_to_qiskitpauli(zero_term)
ground_truth = SummedOp([])
assert ground_truth == qiskit_term
def test_qiskitpauli_to_qubitop():
qiskit_term = SummedOp([PauliOp(Pauli.from_label("XIIIIY"), coeff=1)])
op_fermion_term = QubitOperator(((0, "X"), (5, "Y")))
test_op_fermion_term = qiskitpauli_to_qubitop(qiskit_term)
assert test_op_fermion_term.isclose(op_fermion_term)
def test_qiskitpauli_to_qubitop_type_enforced():
"""Enforce the appropriate type"""
create_one = FermionOperator("1^")
empty_one_body = np.zeros((2, 2))
empty_two_body = np.zeros((2, 2, 2, 2))
interact_one = InteractionOperator(1, empty_one_body, empty_two_body)
interact_rdm = InteractionRDM(empty_one_body, empty_two_body)
with pytest.raises(TypeError):
qiskitpauli_to_qubitop(create_one)
with pytest.raises(TypeError):
qiskitpauli_to_qubitop(interact_one)
with pytest.raises(TypeError):
qiskitpauli_to_qubitop(interact_rdm)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.quantum_info import SparsePauliOp
H2_op = SparsePauliOp.from_list(
[
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
]
)
print(f"Number of qubits: {H2_op.num_qubits}")
from qiskit.algorithms import NumPyMinimumEigensolver
from qiskit.opflow import PauliSumOp
numpy_solver = NumPyMinimumEigensolver()
result = numpy_solver.compute_minimum_eigenvalue(operator=PauliSumOp(H2_op))
ref_value = result.eigenvalue.real
print(f"Reference value: {ref_value:.5f}")
# define ansatz and optimizer
from qiskit.circuit.library import TwoLocal
from qiskit.algorithms.optimizers import SPSA
iterations = 125
ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz")
spsa = SPSA(maxiter=iterations)
# define callback
# note: Re-run this cell to restart lists before training
counts = []
values = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
# define Aer Estimator for noiseless statevector simulation
from qiskit.utils import algorithm_globals
from qiskit_aer.primitives import Estimator as AerEstimator
seed = 170
algorithm_globals.random_seed = seed
noiseless_estimator = AerEstimator(
run_options={"seed": seed, "shots": 1024},
transpile_options={"seed_transpiler": seed},
)
# instantiate and run VQE
from qiskit.algorithms.minimum_eigensolvers import VQE
vqe = VQE(
noiseless_estimator, ansatz, optimizer=spsa, callback=store_intermediate_result
)
result = vqe.compute_minimum_eigenvalue(operator=H2_op)
print(f"VQE on Aer qasm simulator (no noise): {result.eigenvalue.real:.5f}")
print(
f"Delta from reference energy value is {(result.eigenvalue.real - ref_value):.5f}"
)
import pylab
pylab.rcParams["figure.figsize"] = (12, 4)
pylab.plot(counts, values)
pylab.xlabel("Eval count")
pylab.ylabel("Energy")
pylab.title("Convergence with no noise")
from qiskit_aer.noise import NoiseModel
from qiskit.providers.fake_provider import FakeVigo
# fake providers contain data from real IBM Quantum devices stored in Qiskit Terra,
# and are useful for extracting realistic noise models.
device = FakeVigo()
coupling_map = device.configuration().coupling_map
noise_model = NoiseModel.from_backend(device)
print(noise_model)
noisy_estimator = AerEstimator(
backend_options={
"method": "density_matrix",
"coupling_map": coupling_map,
"noise_model": noise_model,
},
run_options={"seed": seed, "shots": 1024},
transpile_options={"seed_transpiler": seed},
)
# re-start callback variables
counts = []
values = []
vqe.estimator = noisy_estimator
result1 = vqe.compute_minimum_eigenvalue(operator=H2_op)
print(f"VQE on Aer qasm simulator (with noise): {result1.eigenvalue.real:.5f}")
print(
f"Delta from reference energy value is {(result1.eigenvalue.real - ref_value):.5f}"
)
if counts or values:
pylab.rcParams["figure.figsize"] = (12, 4)
pylab.plot(counts, values)
pylab.xlabel("Eval count")
pylab.ylabel("Energy")
pylab.title("Convergence with noise")
print(f"Reference value: {ref_value:.5f}")
print(f"VQE on Aer qasm simulator (no noise): {result.eigenvalue.real:.5f}")
print(f"VQE on Aer qasm simulator (with noise): {result1.eigenvalue.real:.5f}")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
#!/usr/bin/env python3
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute
from qiskit.visualization import plot_bloch_multivector, plot_histogram
import numpy as np
import pylab as plt
import sys
sys.path.append("/Users/gshyam/projects/work_projects/machine_learning/QuantumComputing/quantum_computing/utils")
from utils import get_statevector
def get_state_bell_ckt(qc):
backend = Aer.get_backend('statevector_simulator')
res = execute(qc, backend=backend).result()
final_state = res.get_statevector()
counts = res.get_counts()
return (final_state, counts)
qc1 = QuantumCircuit(2)
qc1.h(0)
qc1.cx(0,1)
fig, ax = plt.subplots(1, 2, constrained_layout=True)
qc1.draw(output='mpl', ax=ax[0], scale=1.5)
sv, counts = get_state_bell_ckt(qc1)
plot_histogram(counts, ax=ax[1])
qc1 = QuantumCircuit(2)
qc1.h(0)
qc1.cx(0,1)
qc1.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
res = execute(qc1, backend=backend).result()
final_state = res.get_statevector()
counts = res.get_counts()
print (final_state, counts)
plot_histogram(counts)
qc2 = QuantumCircuit(2)
qc2.h(0)
qc2.cx(0,1)
qc2.x(0)
qc2.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
res = execute(qc2, backend=backend).result()
final_state = res.get_statevector()
counts = res.get_counts()
print (final_state, counts)
plot_histogram(counts)
qc3 = QuantumCircuit(2)
qc3.h(0)
qc3.cx(0,1)
qc3.x(1)
qc3.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
res = execute(qc3, backend=backend).result()
final_state = res.get_statevector()
counts = res.get_counts()
print (final_state, counts)
plot_histogram(counts)
qc4 = QuantumCircuit(2)
qc4.h(0)
qc4.cx(0,1)
qc4.x(1)
qc4.x(0)
qc4.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
res = execute(qc4, backend=backend).result()
final_state = res.get_statevector()
counts = res.get_counts()
print (final_state, counts)
plot_histogram(counts)
#!/usr/bin/env python3
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute
from qiskit.visualization import plot_histogram
# Define quantum circuit
N_qubits=2; N_bits=2;
bell= QuantumCircuit(N_qubits, N_bits);
bell.h(0) # Add a hadamard
bell.cx(0, 1) # add a Cnot gate # similar to Last week's discussion
# Measure the result : Syntax QuantumCircuit.measure(qubit, cbit)
#bell.measure([0,1],[0,1])
#bell.draw()
bell.draw(output='mpl')
for backend in Aer.backends():
print(backend.name() )
backend = Aer.get_backend('unitary_simulator')
job_uni = execute(bell, backend)
res_uni = job_uni.result()
print(res_uni.get_unitary(bell, decimals=1))
bell.measure([0,1],[0,1])
backend = Aer.get_backend('unitary_simulator')
N=2
q=QuantumRegister(N)
c=ClassicalRegister(N)
circ = QuantumCircuit(q,c)
circ.h(q[0])
circ.cx(q[0],q[1])
circ.h(q[1])
job = execute(circ, backend)
result = job.result()
print(result.get_unitary(circ, decimals=1))
sim_qsm = Aer.get_backend('qasm_simulator')
job_qsm = execute(bell, sim_qsm, shots=1024) # shots=1024 (default)
res_qsm = job_qsm.result()
print (res_qsm)
counts_qsm = res_qsm.get_counts(bell)
print (counts_qsm)
plot_histogram( counts_qsm, title='Bell-State counts')
# Define quantum circuit
N_qubits=2; N_bits=2;
ckt2= QuantumCircuit(N_qubits, N_bits);
ckt2.h(0)
ckt2.cx(0, 1)
ckt2.h(1) # this time on quibit 1
ckt2.cx(0, 1)
ckt2.measure([0,1],[0,1])
#ckt2.draw()
ckt2.draw(output='mpl', style = {'backgroundcolor':'lightblue'})
sim_qsm = Aer.get_backend('qasm_simulator')
job_qsm = execute(ckt2, sim_qsm, shots=2000)
res_qsm = job_qsm.result()
counts_qsm = res_qsm.get_counts(ckt2)
print (counts_qsm)
plot_histogram( counts_qsm, title='Bell-State counts')
# Define quantum circuit
import pylab as plt
%matplotlib inline
def ckt_(N, init_state, axis):
q=QuantumRegister(N)
c=ClassicalRegister(N)
ckt3= QuantumCircuit(q, c);
#print (q, c, q[0], c[0], q[1], q[2])
ckt3.h(q[init_state])
ckt3.cx(q[0], q[1])
ckt3.h(q[1]) # this time on quibit 1
ckt3.cx(q[1], q[2])
ckt3.h(q[2])
ckt3.cx(q[0], q[2])
ckt3.measure(q, c)
ckt3.draw(output='mpl', ax=axis)
fig, ax = plt.subplots(1, 2) #figsize=(7, 7)
ckt_(3, 0, axis=ax[0])
ckt_(3, 1, axis=ax[1])
N=3;
q=QuantumRegister(N)
c=ClassicalRegister(N)
ckt3= QuantumCircuit(q, c, name='ckt3');
ckt3.h(q[0])
ckt3.cx(q[0], q[1])
ckt3.h(q[1])
ckt3.cx(q[1], q[2])
ckt3.h(q[2])
ckt3.cx(q[0], q[2])
ckt3.measure(q, c)
ckt3.draw(output='mpl')
sim_uni = Aer.get_backend('unitary_simulator')
job_uni = execute(ckt3, sim_uni)
res_uni = job_uni.result()
print (res_uni)
#print (res_uni.get_unitary(ckt3,decimals=1))
sim_qsm = Aer.get_backend('qasm_simulator')
job_qsm = execute(ckt3, sim_qsm, shots=2000)
res_qsm = job_qsm.result()
counts_qsm = res_qsm.get_counts(ckt3)
print (counts_qsm, sum(counts_qsm.values()))
plot_histogram( counts_qsm, title='Bell-State counts')
#ckt3.to_matrix()
N=4;
q=QuantumRegister(N)
c=ClassicalRegister(N)
circ = QuantumCircuit(q, c);
for i in range(0, N-1):
circ.h(q[i])
circ.cx(q[i], q[i+1])
circ.measure(q, c)
sim_qsm = Aer.get_backend('qasm_simulator')
job_qsm = execute(circ, sim_qsm, shots=2000)
res_qsm = job_qsm.result()
counts_qsm = res_qsm.get_counts(circ)
print (len(counts_qsm.values()))
print("Time taken: {} sec".format(res_qsm.time_taken))
%matplotlib inline
plot_histogram( counts_qsm)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 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.
# pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module
# pylint: disable=attribute-defined-outside-init,unsubscriptable-object
import os
from qiskit import QuantumCircuit
from qiskit.compiler import transpile
from qiskit.test.mock import FakeToronto
class TranspilerQualitativeBench:
params = ([0, 1, 2, 3], ["stochastic", "sabre"], ["dense", "noise_adaptive", "sabre"])
param_names = ["optimization level", "routing method", "layout method"]
timeout = 600
# pylint: disable=unused-argument
def setup(self, optimization_level, routing_method, layout_method):
self.backend = FakeToronto()
self.qasm_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "qasm"))
self.depth_4gt10_v1_81 = QuantumCircuit.from_qasm_file(
os.path.join(self.qasm_path, "depth_4gt10-v1_81.qasm")
)
self.depth_4mod5_v0_19 = QuantumCircuit.from_qasm_file(
os.path.join(self.qasm_path, "depth_4mod5-v0_19.qasm")
)
self.depth_mod8_10_178 = QuantumCircuit.from_qasm_file(
os.path.join(self.qasm_path, "depth_mod8-10_178.qasm")
)
self.time_cnt3_5_179 = QuantumCircuit.from_qasm_file(
os.path.join(self.qasm_path, "time_cnt3-5_179.qasm")
)
self.time_cnt3_5_180 = QuantumCircuit.from_qasm_file(
os.path.join(self.qasm_path, "time_cnt3-5_180.qasm")
)
self.time_qft_16 = QuantumCircuit.from_qasm_file(
os.path.join(self.qasm_path, "time_qft_16.qasm")
)
def track_depth_transpile_4gt10_v1_81(self, optimization_level, routing_method, layout_method):
return transpile(
self.depth_4gt10_v1_81,
self.backend,
routing_method=routing_method,
layout_method=layout_method,
optimization_level=optimization_level,
seed_transpiler=0,
).depth()
def track_depth_transpile_4mod5_v0_19(self, optimization_level, routing_method, layout_method):
return transpile(
self.depth_4mod5_v0_19,
self.backend,
routing_method=routing_method,
layout_method=layout_method,
optimization_level=optimization_level,
seed_transpiler=0,
).depth()
def track_depth_transpile_mod8_10_178(self, optimization_level, routing_method, layout_method):
return transpile(
self.depth_mod8_10_178,
self.backend,
routing_method=routing_method,
layout_method=layout_method,
optimization_level=optimization_level,
seed_transpiler=0,
).depth()
def time_transpile_time_cnt3_5_179(self, optimization_level, routing_method, layout_method):
transpile(
self.time_cnt3_5_179,
self.backend,
routing_method=routing_method,
layout_method=layout_method,
optimization_level=optimization_level,
seed_transpiler=0,
)
def time_transpile_time_cnt3_5_180(self, optimization_level, routing_method, layout_method):
transpile(
self.time_cnt3_5_180,
self.backend,
routing_method=routing_method,
layout_method=layout_method,
optimization_level=optimization_level,
seed_transpiler=0,
)
def time_transpile_time_qft_16(self, optimization_level, routing_method, layout_method):
transpile(
self.time_qft_16,
self.backend,
routing_method=routing_method,
layout_method=layout_method,
optimization_level=optimization_level,
seed_transpiler=0,
)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 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.
"""Test calling passes (passmanager-less)"""
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import ZGate
from qiskit.transpiler.passes import Unroller
from qiskit.test import QiskitTestCase
from qiskit.exceptions import QiskitError
from qiskit.transpiler import PropertySet
from ._dummy_passes import PassD_TP_NR_NP, PassE_AP_NR_NP, PassN_AP_NR_NP
class TestPassCall(QiskitTestCase):
"""Test calling passes (passmanager-less)."""
def assertMessageLog(self, context, messages):
"""Checks the log messages"""
self.assertEqual([record.message for record in context.records], messages)
def test_transformation_pass(self):
"""Call a transformation pass without a scheduler"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
pass_d = PassD_TP_NR_NP(argument1=[1, 2])
with self.assertLogs("LocalLogger", level="INFO") as cm:
result = pass_d(circuit)
self.assertMessageLog(cm, ["run transformation pass PassD_TP_NR_NP", "argument [1, 2]"])
self.assertEqual(circuit, result)
def test_analysis_pass_dict(self):
"""Call an analysis pass without a scheduler (property_set dict)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
property_set = {"another_property": "another_value"}
pass_e = PassE_AP_NR_NP("value")
with self.assertLogs("LocalLogger", level="INFO") as cm:
result = pass_e(circuit, property_set)
self.assertMessageLog(cm, ["run analysis pass PassE_AP_NR_NP", "set property as value"])
self.assertEqual(property_set, {"another_property": "another_value", "property": "value"})
self.assertIsInstance(property_set, dict)
self.assertEqual(circuit, result)
def test_analysis_pass_property_set(self):
"""Call an analysis pass without a scheduler (PropertySet dict)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
property_set = PropertySet({"another_property": "another_value"})
pass_e = PassE_AP_NR_NP("value")
with self.assertLogs("LocalLogger", level="INFO") as cm:
result = pass_e(circuit, property_set)
self.assertMessageLog(cm, ["run analysis pass PassE_AP_NR_NP", "set property as value"])
self.assertEqual(
property_set, PropertySet({"another_property": "another_value", "property": "value"})
)
self.assertIsInstance(property_set, PropertySet)
self.assertEqual(circuit, result)
def test_analysis_pass_remove_property(self):
"""Call an analysis pass that removes a property without a scheduler"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
property_set = {"to remove": "value to remove", "to none": "value to none"}
pass_e = PassN_AP_NR_NP("to remove", "to none")
with self.assertLogs("LocalLogger", level="INFO") as cm:
result = pass_e(circuit, property_set)
self.assertMessageLog(
cm,
[
"run analysis pass PassN_AP_NR_NP",
"property to remove deleted",
"property to none noned",
],
)
self.assertEqual(property_set, PropertySet({"to none": None}))
self.assertIsInstance(property_set, dict)
self.assertEqual(circuit, result)
def test_error_unknown_defn_unroller_pass(self):
"""Check for proper error message when unroller cannot find the definition
of a gate."""
circuit = ZGate().control(2).definition
basis = ["u1", "u2", "u3", "cx"]
unroller = Unroller(basis)
with self.assertRaises(QiskitError) as cm:
unroller(circuit)
exp_msg = (
"Error decomposing node of instruction 'p': 'NoneType' object has no"
" attribute 'global_phase'. Unable to define instruction 'u' in the basis."
)
self.assertEqual(exp_msg, cm.exception.message)
|
https://github.com/RQC-QApp/Seminars
|
RQC-QApp
|
# Подключаем необходимые методы/классы/etc.
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
# Указываем необходимое число квантовых регистров (кубитов)
# и классических регистров.
#
# В обоих случаях указано 2. Помимо количества им присваиваются идентификаторы
# в рамках программы `qp`: "qr" и "cr" соответственно.
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
# Создаём квантовую цепь с квантовыми регистрами `qr`, классическими регистрами `cr` и называем её "Bell".
qc = QuantumCircuit(qr, cr, name="Bell")
# Начинаем добавлять различные гейты (операции над кубитами).
#
# Синтаксис следующий:
# "<квантовая_цепь>.<гейт>(<квантовый/классический регистр, параметры, etc. - в зависимости от гейта>)".
# Гейт Адамара на нулевой кубит.
qc.h(qr[0])
# Controlled NOT (CNOT) гейт, который использует `qr[0]` кубит как управляющий, а кубит `qr[1]` как таргет.
qc.cx(qr[0], qr[1])
# Измерить кубиты и записать измеренные значения в классические регистры.
qc.measure(qr, cr)
# Скомпилировать и запустить выполнение программы
# "Bell" на бэкэнде "local_qasm_simulator".
job_sim = execute(qc, "local_qasm_simulator")
result = job_sim.result()
# Посмотреть на результаты программы в виде "{'00': n1, '01': n2, ...}", где n1, n2, ... - число
# соответствующих исходов.
print(result.get_counts("Bell"))
from qiskit.tools.visualization import circuit_drawer
# Изобразим квантовую цепь, которая соответствует "Bell".
circuit_drawer(qc)
from qiskit.tools.visualization import plot_histogram
# Гистограмма распределения исходов.
plot_histogram(result.get_counts('Bell'))
# Посмотреть на программу в представлении OpenQASM - Open Quantum Assembly Language. Этот язык используется
# для описания инструкций к квантовой машине.
print(qc.qasm())
from qiskit import register
import Qconfig
# Указываем APItoken и ссылку на соответствующий API.
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']
}
print('Qconfig loaded from %s.' % Qconfig.__file__)
# Регистрируемся в системе IBM Q.
register(qx_config['APItoken'], qx_config['url'])
from qiskit import available_backends
# Список облачных устройств, которые подключены к сети.
available_backends({'local': False})
from qiskit import get_backend
# По названию устройства можно проверить его статус.
get_backend('ibmqx5').status
# Следующими строками можно найти доступный в настоящий момент времени квантовое устройство, которое имеет 16 кубит.
#
# Составляем список из всех облачных бэкэндов (симуляторы не рассматриваем, потому что у них нет параметра 'n_qubits').
backends = available_backends({'local': False})
real_device_backend = [backend for backend in backends if
get_backend(backend).configuration['n_qubits'] == 16 and
get_backend(backend).status['available'] == True]
real_device_backend
backend = real_device_backend[0]
# Список из квантовых схем, которые хочется запустить на квантовом устройстве. Здесь
# может быть перечислено несколько схем, это будет оптимальнее запускать на сервере
# в том плане, что на сервере есть очередь на запуск.
circuits = [qc]
# Количество "запусков" программы на бэкэнде. Максимальное число равно 8192.
shots = 1024
# Максимальное число кредитов, которые вы готовы потратить за запуск программы.
max_credits = 5
# Отпраляем программу в облако и ожидаем выполнения.
job = execute(circuits, backend=backend, shots=shots,
max_credits=max_credits)
result_real = job.result()
# Проверяем статус программы.
result_real.get_status()
%%time
# Гистограмма распределения исходов на настоящем квантовом устройстве.
plot_histogram(result_real.get_counts('Bell'))
qc_1 = qp.create_circuit('qc_1', [qr], [cr])
qc_1.measure(qr[0], cr[0])
# Теперь заметим, что квантовая цепь "qc_1" добавилась к остальным.
qp.get_circuit_names()
# Запустим на локальном симуляторе и построим гистограмму исходов.
result = qp.execute('qc_1')
plot_histogram(result.get_counts('qc_1'))
%%time
# Запустим ту же цепь на реальном устройстве.
result_real = qp.execute('qc_1', backend=backend,
shots=shots, max_credits=max_credits,
wait=wait_time, timeout=timeout)
plot_histogram(result_real.get_counts('qc_1'))
qc_2 = qp.create_circuit('qc_2', [qr], [cr])
# Добавляем NOT-гейт.
qc_2.x(qr[0])
qc_2.measure(qr[0], cr[0])
result = qp.execute('qc_2')
plot_histogram(result.get_counts('qc_2'))
qc_3 = qp.create_circuit('qc_3', [qr], [cr])
# Добавляем гейт Адамара.
qc_3.h(qr[0])
qc_3.measure(qr[0], cr[0])
result = qp.execute('qc_3')
plot_histogram(result.get_counts('qc_3'))
aux = qp.create_circuit('auxiliary', [qr], [cr])
aux.cx(qr[0], qr[1])
# Измерения.
aux.measure(qr[0], cr[0])
aux.measure(qr[1], cr[1])
utils.circuitImage(aux, utils.basis)
qc_4 = qp.create_circuit('qc_4_begin', [qr], [cr])
qc_4.x(qr[0])
qc_4.x(qr[1])
# Квантовые цепи можно "складывать" вместе, вернее, составлять.
qc_4 = qc_4 + aux
# Таким образом мы получаем четвертую квантовую цепь.
utils.circuitImage(qc_4, utils.basis)
# И записываем её в программу под соответствующим названием.
qp.add_circuit('qc_4', qc_4)
result = qp.execute('qc_4')
plot_histogram(result.get_counts('qc_4'))
qc_5 = qp.create_circuit('qc_5_begin', [qr], [cr])
qc_5.h(qr[0])
qc_5.x(qr[1])
qc_5 = qc_5 + aux
qp.add_circuit('qc_5', qc_5)
utils.circuitImage(qp.get_circuit('qc_5'), utils.basis)
result = qp.execute('qc_5')
plot_histogram(result.get_counts('qc_5'))
|
https://github.com/alejomonbar/Quantum-Supply-Chain-Manager
|
alejomonbar
|
%load_ext autoreload
%autoreload 2
#pip install pennyane
#improt pennylane dependnecies
import pennylane as qml
from pennylane import numpy as np
from pennylane.optimize import NesterovMomentumOptimizer
# load the csv files
import pandas as pd
# plot the historical acc and cost
import matplotlib.pyplot as plt
import seaborn as sns
from IPython.display import clear_output
clear_output(wait=False)
import os
data_train = pd.read_csv("dataset/fair_train.csv")
X_train,y_train = data_train[data_train.columns[:16]].values, data_train[data_train.columns[16]].values
data_test = pd.read_csv("dataset/classic_test.csv")
X_test,y_test = data_test[data_test.columns[:16]].values, data_test[data_test.columns[16]].values
(X_train.shape, y_train.shape),(X_test.shape, y_test.shape)
n_wires = 4
dev = qml.device("default.mixed", wires=n_wires)
def block(weights, wires):
qml.CNOT(wires=[wires[0],wires[1]])
qml.RY(weights[0], wires=wires[0])
qml.RY(weights[1], wires=wires[1])
n_block_wires = 2
n_params_block = 2
n_blocks = qml.MERA.get_n_blocks(range(n_wires),n_block_wires)
n_blocks
@qml.qnode(dev)
@qml.transforms.insert(qml.AmplitudeDamping, 0.2, position="end")
def circuit(weights, x):
qml.AmplitudeEmbedding(x, wires=[0,1,2,3],normalize=True,pad_with=True)
for w in weights:
qml.MERA(range(n_wires),n_block_wires,block, n_params_block, w)
#print(w)
#print(x)
return qml.expval(qml.PauliZ(1))
def variational_classifier(weights, bias, x):
return circuit(weights, x) + bias
def square_loss(labels, predictions):
loss = 0
for l, p in zip(labels, predictions):
loss = loss + (l - p) ** 2
loss = loss / len(labels)
return loss
def accuracy(labels, predictions):
loss = 0
for l, p in zip(labels, predictions):
if abs(l - p) < 1e-5:
loss = loss + 1
loss = loss / len(labels)
return loss
def cost(weights, bias, X, Y):
#print(1)
predictions = [variational_classifier(weights, bias, x) for x in X]
return square_loss(Y, predictions)
np.random.seed(0)
num_layers = 1
weights_init = 2*np.pi * np.random.randn(num_layers,n_blocks, n_params_block, requires_grad=True)
bias_init = np.array(0.0, requires_grad=True)
print(weights_init, bias_init)
print(qml.draw(circuit,expansion_strategy='device',wire_order=[0,1,2,3])(weights_init,np.asarray(X_train[0])))
for i in weights_init:
print(i[0])
y_train = np.where(y_train < 1, -1, y_train)
y_test = np.where(y_test < 1, -1, y_test)
from sklearn.utils import shuffle
X,y = shuffle(X_train, y_train, random_state=0)
from sklearn.model_selection import train_test_split
opt = NesterovMomentumOptimizer(0.4)
batch_size = 32
num_data = len(y_train)
num_train = 0.9
# train the variational classifier
weights = weights_init
bias = bias_init
print()
cost_g = []
acc_train = []
acc_test = []
plt.show()
for it in range(50):
X_train_70, X_test_30, y_train_70, y_test_30 =train_test_split(np.asarray(X), np.asarray(y), train_size=num_train, test_size=1.0-num_train, shuffle=True)
# Update the weights by one optimizer step
batch_index = np.random.randint(0, len(X_train_70), (batch_size,))
feats_train_batch = X_train_70[batch_index]
Y_train_batch = y_train_70[batch_index]
weights, bias, _, _ = opt.step(cost, weights, bias, feats_train_batch, Y_train_batch)
# Compute predictions on train and validation set
predictions_train = [np.sign(variational_classifier(weights, bias, f)) for f in X_train_70]
predictions_val = [np.sign(variational_classifier(weights, bias, f)) for f in X_test_30]
# Compute accuracy on train and validation set
acc_tra = accuracy(y_train_70, predictions_train)
acc_val = accuracy(y_test_30, predictions_val)
cost_train = cost(weights, bias,X_train, y_train)
cost_g.append(cost_train)
acc_train.append(acc_tra)
acc_test.append(acc_val)
clear_output(wait=True)
plt.plot(cost_g,label='cost')
plt.plot(acc_train,label='acc_train')
plt.plot(acc_test,label='acc_test')
plt.legend(['cost','acc_train','acc_test'])
plt.show()
print(
"Iter: {:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} "
"".format(it + 1, cost_train, acc_tra, acc_val)
)
print(weights)
x_test = []
for x in X_test.tolist():
if sum(x) == 0:
x[0]=1
x_test.append( x/ np.linalg.norm(x))
x_test[0]
y_test
y_pred = [np.sign(variational_classifier(weights, bias, f)) for f in x_test]
y_test_pred = []
for i in y_pred:
if i < 0:
y_test_pred.append(-1)
else:
y_test_pred.append(1)
from sklearn.metrics import confusion_matrix, roc_curve, auc
from sklearn.preprocessing import StandardScaler
# demonstration of calculating metrics for a neural network model using sklearn
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
from sklearn.metrics import cohen_kappa_score
from sklearn.metrics import roc_auc_score
accuracy = accuracy_score(y_test, y_test_pred)
print('Accuracy: %f' % accuracy)
# precision tp / (tp + fp)
precision = precision_score(y_test, y_test_pred)
print('Precision: %f' % precision)
# recall: tp / (tp + fn)
recall = recall_score(y_test, y_test_pred)
print('Recall: %f' % recall)
# f1: 2 tp / (2 tp + fp + fn)
f1 = f1_score(y_test, y_test_pred)
print('F1 score: %f' % f1)
# kappa
kappa = cohen_kappa_score(y_test, y_test_pred)
print('Cohens kappa: %f' % kappa)
# ROC AUC
auc = roc_auc_score(y_test, y_test_pred)
print('ROC AUC: %f' % auc)
# confusion matrix
test_matrix = confusion_matrix(y_test, y_test_pred)
print(test_matrix)
ax = sns.heatmap(test_matrix, annot=True, cmap='Blues', fmt='g')
ax.set_title('Seaborn Confusion Matrix with labels\n\n');
ax.set_xlabel('\nPredicted Values')
ax.set_ylabel('Actual Values ');
ax.xaxis.set_ticklabels(['0','1'])
ax.yaxis.set_ticklabels(['0','1'])
## Display the visualization of the Confusion Matrix.
plt.show()
y_pred_1 = [int(i) for i in y_test_pred ]
y_pred_1 = ["{}\n".format(i) for i in y_pred_1]
with open(r'mera_1_layers_noise.csv', 'w') as fp:
fp.writelines(y_pred_1)
|
https://github.com/qiskit-community/qgss-2023
|
qiskit-community
|
%set_env QC_GRADE_ONLY=true
from qiskit.circuit import QuantumCircuit
from qiskit.primitives import Estimator, Sampler
from qiskit.quantum_info import SparsePauliOp
from qiskit.visualization import plot_histogram
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('dark_background') # optional
# create excited |1> state
qc_1 = QuantumCircuit(1)
qc_1.x(0)
qc_1.draw('mpl')
# create superposition |+> state
qc_plus = QuantumCircuit(1)
qc_plus.h(0)
qc_plus.draw('mpl')
qc_1.measure_all()
qc_plus.measure_all()
sampler = Sampler()
job_1 = sampler.run(qc_1)
job_plus = sampler.run(qc_plus)
job_1.result().quasi_dists
job_plus.result().quasi_dists
legend = ["Excited State", "Plus State"] # TODO: Excited State does not appear
plot_histogram([job_1.result().quasi_dists[0], job_plus.result().quasi_dists[0]], legend=legend)
qc_1.remove_final_measurements()
qc_plus.remove_final_measurements()
# rotate into the X-basis
qc_1.h(0)
qc_plus.h(0)
qc_1.measure_all()
qc_plus.measure_all()
sampler = Sampler()
job_1 = sampler.run(qc_1)
job_plus = sampler.run(qc_plus)
plot_histogram([job_1.result().quasi_dists[0], job_plus.result().quasi_dists[0]], legend=legend)
qc2_1 = QuantumCircuit(1)
qc2_1.x(0)
qc2_plus = QuantumCircuit(1)
qc2_plus.h(0)
obsvs = list(SparsePauliOp(['Z', 'X']))
estimator = Estimator()
job2_1 = estimator.run([qc2_1]*len(obsvs), observables=obsvs)
job2_plus = estimator.run([qc2_plus]*len(obsvs), observables=obsvs)
job2_1.result()
# TODO: make this into module that outputs a nice table
print(f' | <Z> | <X> ')
print(f'----|------------------')
print(f'|1> | {job2_1.result().values[0]} | {job2_1.result().values[1]}')
print(f'|+> | {job2_plus.result().values[0]} | {job2_plus.result().values[1]}')
# this is a correct answer:
obsv = SparsePauliOp('X').tensor(SparsePauliOp(['X', 'Z'], coeffs=[1, -1])) + SparsePauliOp('Z').tensor(SparsePauliOp(['X', 'Z'], coeffs=[1, 1]))
from qc_grader.challenges.qgss_2023 import grade_lab2_ex1
grade_lab2_ex1(obsv)
from qiskit.circuit import Parameter
theta = Parameter('θ')
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.ry(theta, 0)
qc.draw('mpl')
# this is a correct answer
num_params = 21
angles=[[angle] for angle in np.linspace(-np.pi, np.pi, num_params)]
estimator = Estimator()
job = estimator.run([qc]*len(angles), observables=[obsv]*len(angles), parameter_values=angles)
exps = job.result().values
plt.plot(angles, exps, marker='x', ls='-', color='green')
plt.plot(angles, [2]*len(angles), ls='--', color='red', label='Classical Bound')
plt.plot(angles, [-2]*len(angles), ls='--', color='red')
plt.xlabel('angle (rad)')
plt.ylabel('CHSH Witness')
plt.legend(loc=4)
from qc_grader.challenges.qgss_2023 import grade_lab2_ex2
grade_lab2_ex2(obsv, angles)
from qiskit.circuit import ClassicalRegister, QuantumRegister
theta = Parameter('θ')
qr = QuantumRegister(1, 'q')
qc = QuantumCircuit(qr)
qc.ry(theta, 0)
qc.draw('mpl')
tele_qc = qc.copy()
bell = QuantumRegister(2, 'Bell')
alice = ClassicalRegister(2, 'Alice')
bob = ClassicalRegister(1, 'Bob')
tele_qc.add_register(bell, alice, bob)
tele_qc.draw('mpl')
# create Bell state with other two qubits
tele_qc.barrier()
tele_qc.h(1)
tele_qc.cx(1, 2)
tele_qc.barrier()
tele_qc.draw('mpl')
# alice operates on her qubits
tele_qc.cx(0, 1)
tele_qc.h(0)
tele_qc.barrier()
tele_qc.draw('mpl')
tele_qc.measure([qr[0], bell[0]], alice)
tele_qc.draw('mpl')
# either pairs are correct
# tele_qc.x(2).c_if(alice[1], 1)
# tele_qc.z(2).c_if(alice[0], 1)
with tele_qc.if_test((alice[1], 1)):
tele_qc.x(2)
with tele_qc.if_test((alice[0], 1)):
tele_qc.z(2)
tele_qc.draw('mpl')
tele_qc.barrier()
tele_qc.measure(bell[1], bob)
tele_qc.draw('mpl')
from qc_grader.challenges.qgss_2023 import grade_lab2_ex3
grade_lab2_ex3(tele_qc, theta, 5*np.pi/7)
from qiskit_aer.primitives import Sampler
angle = 5*np.pi/7
sampler = Sampler()
qc.measure_all()
job_static = sampler.run(qc.bind_parameters({theta: angle}))
job_dynamic = sampler.run(tele_qc.bind_parameters({theta: angle}))
print(f"Original Dists: {job_static.result().quasi_dists[0].binary_probabilities()}")
print(f"Teleported Dists: {job_dynamic.result().quasi_dists[0].binary_probabilities()}")
from qiskit.result import marginal_counts
# this is correct
tele_counts = marginal_counts(job_dynamic.result().quasi_dists[0].binary_probabilities(), indices=[2])
legend = ['Original State', 'Teleported State']
plot_histogram([job_static.result().quasi_dists[0].binary_probabilities(), tele_counts], legend=legend)
from qc_grader.challenges.qgss_2023 import grade_lab2_ex4
grade_lab2_ex4(tele_counts, job_dynamic.result().quasi_dists[0])
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw, IQXDebugging
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, style=IQXDebugging(), backend=FakeBoeblingen())
|
https://github.com/biswaroopmukherjee/Quantum-Waddle
|
biswaroopmukherjee
|
import qiskit
from qiskit import IBMQ
from qiskit.tools.monitor import job_monitor
IBMQ.load_account()
IBMQ.providers()
provider = IBMQ.get_provider(group='open') #check open servers
import numpy as np
import time
import networkx as nx
import matplotlib.pyplot as plt
import random
from qiskit import (QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer)
from matplotlib import cm
%matplotlib inline
def counts_to_prob_2d(counts):
states = list(counts.keys())
state_counts = list(counts.values())
nshots = sum(state_counts)
n = int(len(states[0])/2)
def sep_xy(states):
# Separate x and y coordinates in state vector
states_x = [s[:n] for s in states]
states_y = [s[n:] for s in states]
states_x = np.array([int(s[::-1],2) for s in states_x])
states_y = np.array([int(s[::-1],2) for s in states_y])
return states_x, states_y
x,y = sep_xy(states)
# Create array of probability values
probabilities = np.zeros((2**n,2**n))
probabilities[x,y] = state_counts
probabilities /= nshots
return probabilities
def increment_gate(circuit, qpos, qcoin):
n = len(qpos)
for i in range(n):
circuit.mct(qcoin[:]+qpos[i+1:], qpos[i], None, mode='noancilla')
def decrement_gate(circuit, qpos, qcoin):
n = len(qpos)
for i in range(n):
if i+1 < n: circuit.x(qpos[i+1:])
circuit.mct(qcoin[:]+qpos[i+1:], qpos[i], None, mode='noancilla')
if i+1 < n: circuit.x(qpos[i+1:])
def step(circuit, qpos, qcoin, cpos, simulatorType):
circuit.h(qcoin)
circuit.barrier()
# y operations
increment_gate(circuit, qpos[len(qpos)//2:], qcoin)
circuit.x(qcoin[0])
decrement_gate(circuit, qpos[len(qpos)//2:], qcoin)
# x operations
circuit.x(qcoin)
increment_gate(circuit, qpos[:len(qpos)//2], qcoin)
circuit.x(qcoin[0])
decrement_gate(circuit, qpos[:len(qpos)//2:], qcoin)
circuit.barrier()
if simulatorType == 'classical':
circuit.measure(qpos,cpos)
def initialize_2D(circuit, n, pos):
# convert position to binary
formatLabel = '{0:0'+str(n)+'b}'
x = formatLabel.format(pos[0])
y = formatLabel.format(pos[1])
for i in range(len(x)):
if x[i]=='1':
circuit.x((n-i)-1)
for j in range(len(y)):
if y[j]=='1':
circuit.x((2*n-j)-1)
return circuit
def run(steps,simulatorType):
# steps = number of quantum walks steps
# simulatorType = 'sim', 'quantum' or 'classical'
if simulatorType == 'sim':
simulator = Aer.get_backend('qasm_simulator')
elif simulatorType == 'quantum':
simulator = provider.get_backend('ibmq_16_melbourne')
elif simulatorType == 'classical':
simulator = Aer.get_backend('qasm_simulator')
else:
simulator = Aer.get_backend('qasm_simulator')
qpos = QuantumRegister(2*n,'qc')
qcoin = QuantumRegister(2,'qanc')
cpos = ClassicalRegister(2*n,'cr')
circuit = QuantumCircuit(qpos, qcoin, cpos)
circuit = initialize_2D(circuit, n, [round(n/2),round(n/2)])
for i in range(steps):
step(circuit, qpos, qcoin, cpos, simulatorType)
# # Map the quantum measurement to the classical bits
circuit.measure(qpos,cpos)
# # Execute the circuit on the qasm simulator
job = execute(circuit, simulator, shots=1000)
# monitor job
job_monitor(job)
# # Grab results from the job
result = job.result()
# # Returns counts
counts = result.get_counts(circuit)
return counts
n=2
steps = 3
for i in range(steps+1):
#run classical random walk
countsClassical = run(i,'classical')
propClassical = counts_to_prob_2d(countsClassical)
#run quantum simulation
countsSim = run(i,'sim')
propSim = counts_to_prob_2d(countsSim)
#run the real thing
countsQuantum = run(i,'quantum')
propQuantum = counts_to_prob_2d(countsQuantum)
#plotting
names = []
values = []
formatLabel = '{0:0'+str(n)+'b}'
for idx in range(2**n):
names.append('|' + formatLabel.format(idx) +'>')
values.append(idx)
f, axs = plt.subplots(1,3,figsize=(13,8))
margin=0.4
f.subplots_adjust(margin, margin, 1.-margin, 1.-margin)
axs[0].set_title('classical random walk')
plt.sca(axs[0])
plt.imshow(propClassical,cmap=plt.get_cmap('Reds'))
plt.xticks(rotation=45)
axs[0].set_xticks(values)
axs[0].set_xticklabels(names)
plt.xlim(-0.5,values[-1]+0.5)
axs[0].set_yticks(values)
axs[0].set_yticklabels(names)
plt.ylim(-0.5,values[-1]+0.5)
axs[1].set_title('simulated quantum walk')
plt.sca(axs[1])
plt.imshow(propSim,cmap=plt.get_cmap('Greens'))
plt.xticks(rotation=45)
axs[1].set_xticks(values)
axs[1].set_xticklabels(names)
plt.xlim(-0.5,values[-1]+0.5)
axs[1].set_yticks(values)
axs[1].set_yticklabels(names)
plt.ylim(-0.5,values[-1]+0.5)
axs[2].set_title('IBM quantum walk')
plt.sca(axs[2])
plt.imshow(propQuantum,cmap=plt.get_cmap('Blues'))
plt.xticks(rotation=45)
axs[2].set_xticks(values)
axs[2].set_xticklabels(names)
plt.xlim(-0.5,values[-1]+0.5)
axs[2].set_yticks(values)
axs[2].set_yticklabels(names)
plt.ylim(-0.5,values[-1]+0.5)
plt.tight_layout()
plt.show()
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
# vector v
v = [1,2,-3]
# vector u
u=[-2,3]
vu = []
for i in range(len(v)): # each element of v will be replaced
for j in range(len(u)): # the vector u will come here after multiplying with the entry there
vu.append( v[i] * u[j] )
print("v=",v)
print("u=",u)
print("vu=",vu)
#
# your solution is here
#
u = [-2,-1,0,1]
v = [1,2,3]
uv = []
vu = []
for i in range(len(u)): # one element of u is picked
for j in range(len(v)): # now we iteratively select every element of v
uv.append(u[i]*v[j]) # this one element of u is iteratively multiplied with every element of v
print("u-tensor-v is",uv)
for i in range(len(v)): # one element of v is picked
for j in range(len(u)): # now we iteratively select every element of u
vu.append(v[i]*u[j]) # this one element of v is iteratively multiplied with every element of u
print("v-tensor-u is",vu)
# matrix M
M = [
[-1,0,1],
[-2,-1,2],
[1,2,-2]
]
# matrix N
N = [
[0,2,1],
[3,-1,-2],
[-1,1,0]
]
# MN will be a (9x9)-dimensional matrix
# prepare it as a zero matrix
# this helps us to easily fill it
MN=[]
for i in range(9):
MN.append([])
for j in range(9):
MN[i].append(0)
for i in range(3): # row of M
for j in range(3): # column of M
for k in range(3): # row of N
for l in range(3): # column of N
MN[i*3+k][3*j+l] = M[i][j] * N[k][l]
print("M-tensor-N is")
for i in range(9):
print(MN[i])
# matrices M and N were defined above
# matrix NM will be prepared as a (9x9)-dimensional zero matrix
NM=[]
for i in range(9):
NM.append([])
for j in range(9):
NM[i].append(0)
for i in range(3): # row of N
for j in range(3): # column of N
for k in range(3): # row of M
for l in range(3): # column of M
NM[i*3+k][3*j+l] = N[i][j] * M[k][l]
print("N-tensor-M is")
for i in range(9):
print(NM[i])
#
# your solution is here
#
A = [
[-1,0,1],
[-2,-1,2]
]
B = [
[0,2],
[3,-1],
[-1,1]
]
print("A =")
for i in range(len(A)):
print(A[i])
print() # print a line
print("B =")
for i in range(len(B)):
print(B[i])
# let's define A-tensor-B as a (6x6)-dimensional zero matrix
AB = []
for i in range(6):
AB.append([])
for j in range(6):
AB[i].append(0)
# let's find A-tensor-B
for i in range(2):
for j in range(3):
# for each A(i,j) we execute the following codes
a = A[i][j]
# we access each element of B
for m in range(3):
for n in range(2):
b = B[m][n]
# now we put (a*b) in the appropriate index of AB
AB[3*i+m][2*j+n] = a * b
print() # print a line
print("A-tensor-B =")
print() # print a line
for i in range(6):
print(AB[i])
#
# your solution is here
#
A = [
[-1,0,1],
[-2,-1,2]
]
B = [
[0,2],
[3,-1],
[-1,1]
]
print() # print a line
print("B =")
for i in range(len(B)):
print(B[i])
print("A =")
for i in range(len(A)):
print(A[i])
# let's define B-tensor-A as a (6x6)-dimensional zero matrix
BA = []
for i in range(6):
BA.append([])
for j in range(6):
BA[i].append(0)
# let's find B-tensor-A
for i in range(3):
for j in range(2):
# for each B(i,j) we execute the following codes
b = B[i][j]
# we access each element of A
for m in range(2):
for n in range(3):
a = A[m][n]
# now we put (a*b) in the appropriate index of AB
BA[2*i+m][3*j+n] = b * a
print() # print a line
print("B-tensor-A =")
print() # print a line
for i in range(6):
print(BA[i])
|
https://github.com/derek-wang-ibm/coding-with-qiskit
|
derek-wang-ibm
|
from qiskit import QuantumCircuit, transpile
qc = QuantumCircuit(2)
qc.reset(0)
qc.x(0)
qc.cx(0, 1)
qc.reset(0)
qc.reset(0)
qc.h(0)
qc.draw(output='mpl')
qc_basic_transpile = transpile(qc, optimization_level=3)
qc_basic_transpile.draw(output='mpl', style='iqp')
from qiskit.transpiler.passes.optimization.remove_reset_in_zero_state import RemoveResetInZeroState
from qiskit.converters import circuit_to_dag, dag_to_circuit
remove_reset = RemoveResetInZeroState()
remove_reset(qc).draw('mpl')
from dynacir.dynacir_passes import CollectResets
collect_resets = CollectResets()
circuit_with_less_resets = collect_resets(qc)
circuit_with_less_resets.draw(output='mpl')
!pip install git+https://github.com/derek-wang-ibm/dynacir.git
from qiskit.transpiler.preset_passmanagers.plugin import list_stage_plugins
print(list_stage_plugins("optimization"))
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
pm = generate_preset_pass_manager(optimization_level=3, optimization_method="dynacir"
)
qc_dynacir = pm.run(qc)
qc_dynacir.draw(output='mpl', style='iqp')
|
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
!pip install amazon-braket-pennylane-plugin
my_bucket = "amazon-braket-Your-Bucket-Name" # the name of the bucket, keep the 'amazon-braket-' prefix and then include the bucket name
my_prefix = "Your-Folder-Name" # the name of the folder in the bucket
s3_folder = (my_bucket, my_prefix)
device_arn = "arn:aws:braket:::device/quantum-simulator/amazon/sv1"
import pennylane as qml
from pennylane import numpy as np
n_wires = 25
dev_remote = qml.device(
"braket.aws.qubit",
device_arn=device_arn,
wires=n_wires,
s3_destination_folder=s3_folder,
parallel=True,
)
dev_local = qml.device("default.qubit", wires=n_wires)
def circuit(params):
for i in range(n_wires):
qml.RX(params[i], wires=i)
for i in range(n_wires):
qml.CNOT(wires=[i, (i + 1) % n_wires])
# Measure all qubits to make sure all's good with Braket
observables = [qml.PauliZ(n_wires - 1)] + [qml.Identity(i) for i in range(n_wires - 1)]
return qml.expval(qml.operation.Tensor(*observables))
qnode_remote = qml.QNode(circuit, dev_remote)
qnode_local = qml.QNode(circuit, dev_local)
import time
params = np.random.random(n_wires)
t_0_remote = time.time()
qnode_remote(params)
t_1_remote = time.time()
t_0_local = time.time()
qnode_local(params)
t_1_local = time.time()
print("Execution time on remote device (seconds):", t_1_remote - t_0_remote)
print("Execution time on local device (seconds):", t_1_local - t_0_local)
d_qnode_remote = qml.grad(qnode_remote)
t_0_remote_grad = time.time()
d_qnode_remote(params)
t_1_remote_grad = time.time()
print("Gradient calculation time on remote device (seconds):", t_1_remote_grad - t_0_remote_grad)
d_qnode_local = qml.grad(qnode_local)
t_0_local_grad = time.time()
d_qnode_local(params)
t_1_local_grad = time.time()
print("Gradient calculation time on local device (seconds):", t_1_local_grad - t_0_local_grad)
import networkx as nx
nodes = n_wires = 20
edges = 60
seed = 1967
g = nx.gnm_random_graph(nodes, edges, seed=seed)
positions = nx.spring_layout(g, seed=seed)
nx.draw(g, with_labels=True, pos=positions)
dev = qml.device(
"braket.aws.qubit",
device_arn=device_arn,
wires=n_wires,
s3_destination_folder=s3_folder,
parallel=True,
max_parallel=20,
poll_timeout_seconds=30,
)
cost_h, mixer_h = qml.qaoa.maxcut(g)
n_layers = 2
def qaoa_layer(gamma, alpha):
qml.qaoa.cost_layer(gamma, cost_h)
qml.qaoa.mixer_layer(alpha, mixer_h)
def circuit(params, **kwargs):
for i in range(n_wires): # Prepare an equal superposition over all qubits
qml.Hadamard(wires=i)
qml.layer(qaoa_layer, n_layers, params[0], params[1])
return qml.expval(cost_h)
cost_function = qml.QNode(circuit, dev)
optimizer = qml.AdagradOptimizer(stepsize=0.1)
import time
np.random.seed(1967)
params = 0.01 * np.random.uniform(size=[2, n_layers], requires_grad=True)
iterations = 10
for i in range(iterations):
t0 = time.time()
params, cost_before = optimizer.step_and_cost(cost_function, params)
t1 = time.time()
if i == 0:
print("Initial cost:", cost_before)
else:
print(f"Cost at step {i}:", cost_before)
print(f"Completed iteration {i + 1}")
print(f"Time to complete iteration: {t1 - t0} seconds")
print(f"Cost at step {iterations}:", cost_function(params))
np.save("params.npy", params)
print("Parameters saved to params.npy")
|
https://github.com/qiskit-community/prototype-entanglement-forging
|
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.
"""Entanglement forged VQE."""
import datetime
import time
import warnings
from typing import Iterable, Tuple, Callable, Union
import numpy as np
from qiskit import transpile, QuantumCircuit
from qiskit.algorithms import VQE
from qiskit.utils.mitigation import complete_meas_cal
from qiskit.quantum_info import Pauli
from qiskit.utils import QuantumInstance
from qiskit.opflow import OperatorBase
from entanglement_forging.core.entanglement_forged_config import (
EntanglementForgedConfig,
)
from entanglement_forging.core.forged_operator import ForgedOperator
from entanglement_forging.core.classical_energies import ClassicalEnergies
from entanglement_forging.core.wrappers.entanglement_forged_vqe_result import (
DataResults,
Bootstrap,
AuxiliaryResults,
)
from entanglement_forging.utils.bootstrap_result import resample_result
from entanglement_forging.utils.copysample_circuits import (
copysample_circuits,
combine_copysampled_results,
)
from entanglement_forging.utils.forging_subroutines import (
prepare_circuits_to_execute,
make_stateprep_circuits,
eval_forged_op_with_result,
get_optimizer_instance,
)
from entanglement_forging.utils.generic_execution_subroutines import execute_with_retry
from entanglement_forging.utils.legacy.op_converter import (
to_tpb_grouped_weighted_pauli_operator,
)
from entanglement_forging.utils.legacy.tpb_grouped_weighted_pauli_operator import (
TPBGroupedWeightedPauliOperator,
)
from entanglement_forging.utils.legacy.weighted_pauli_operator import (
WeightedPauliOperator,
)
from entanglement_forging.utils.log import Log
from entanglement_forging.utils.meas_mit_fitters_faster import CompleteMeasFitter
from entanglement_forging.utils.pseudorichardson import make_pseudorichardson_circuits
# pylint: disable=too-many-branches,too-many-arguments,too-many-locals,too-many-instance-attributes,too-many-statements
class EntanglementForgedVQE(VQE):
"""A class for Entanglement Forged VQE <https://arxiv.org/abs/2104.10220>."""
def __init__(
self,
ansatz: QuantumCircuit,
bitstrings_u: Iterable[Iterable[int]],
config: EntanglementForgedConfig,
forged_operator: ForgedOperator,
classical_energies: ClassicalEnergies,
bitstrings_v: Iterable[Iterable[int]] = None,
):
"""Initialize the EntanglementForgedVQE class."""
if ansatz.num_qubits != len(bitstrings_u[0]):
raise ValueError(
"The number of qubits in ansatz does "
"not match the number of bits in reduced_bitstrings."
)
if any(len(bitstrings_u[0]) != len(bitstr) for bitstr in bitstrings_u):
raise ValueError("All U bitstrings must be the same length.")
if bitstrings_v:
if len(bitstrings_u) != len(bitstrings_v):
raise ValueError(
"The same number of bitstrings should be passed for U and V."
)
if len(bitstrings_u[0]) != len(bitstrings_v[0]):
raise ValueError("Bitstrings for U and V should be the same length.")
if any(len(bitstrings_v[0]) != len(bitstr) for bitstr in bitstrings_v):
raise ValueError("All V bitstrings must be the same length.")
super().__init__(
ansatz=ansatz,
optimizer=get_optimizer_instance(config),
initial_point=config.initial_params,
max_evals_grouped=config.max_evals_grouped,
callback=None,
)
# Prevent unnecessary duplication if subsystems are equivalent
if (bitstrings_v is None) or (bitstrings_u == bitstrings_v):
self.bitstrings_v = []
else:
self.bitstrings_v = bitstrings_v
self.ansatz = ansatz
self.config = config
self._energy_each_iteration_each_paramset = []
self._paramsets_each_iteration = []
self._schmidt_coeffs_each_iteration_each_paramset = []
self._zero_noise_extrap = config.zero_noise_extrap
self.bitstrings_u = bitstrings_u
self._bitstrings_s_u = np.asarray(bitstrings_u)
# Make circuits which prepare states U|b_n_u> and U|phi^p_nm_u>
(
self._tensor_prep_circuits_u,
self._superpos_prep_circuits_u,
hybrid_superpos_coeffs_u,
) = make_stateprep_circuits(
bitstrings_u, config.fix_first_bitstring, suffix="u"
)
self._tensor_prep_circuits_v = []
self._superpos_prep_circuits_v = []
hybrid_superpos_coeffs_v = []
self._bitstrings_s_v = np.array([])
if self.bitstrings_v:
# Make circuits which prepare states V|b_n_v> and V|phi^p_nm_v>
# Where U = V but bitstring |b_n_v> does not necessarily equal |b_n_u>
self._bitstrings_s_v = np.asarray(bitstrings_v)
(
self._tensor_prep_circuits_v,
self._superpos_prep_circuits_v,
hybrid_superpos_coeffs_v,
) = make_stateprep_circuits(
bitstrings_v, config.fix_first_bitstring, suffix="v"
)
hybrid_superpos_coeffs_u.update(hybrid_superpos_coeffs_v)
self._hybrid_superpos_coeffs = hybrid_superpos_coeffs_u
self._iteration_start_time = np.nan
self._running_estimate_of_schmidts = np.array(
[1.0] + [0.1] * (len(self._bitstrings_s_u) - 1)
)
self._running_estimate_of_schmidts /= np.linalg.norm(
self._running_estimate_of_schmidts
)
self.copysample_job_size = config.copysample_job_size
self._backend = config.backend
self.quantum_instance = QuantumInstance(backend=self._backend)
self._initial_layout = config.qubit_layout
self._shots = config.shots
self._meas_error_mit = config.meas_error_mit
self._meas_error_shots = config.meas_error_shots
self._meas_error_refresh_period_minutes = (
config.meas_error_refresh_period_minutes
)
self._meas_error_refresh_timestamp = None
self._coupling_map = self._backend.configuration().coupling_map
self._meas_fitter = None
self._bootstrap_trials = config.bootstrap_trials
self._no_bs0_circuits = config.fix_first_bitstring
self._rep_delay = config.rep_delay
self.forged_operator = forged_operator
self._add_this_to_energies_displayed = classical_energies.shift
self._hf_energy = classical_energies.HF
self.aux_results: Iterable[Tuple[str, AuxiliaryResults]] = []
self.parameter_sets = []
self.energy_mean_each_parameter_set = []
self.energy_std_each_parameter_set = []
# Paramters for get_energy_evaluation. Moved them here to match parent function signature
self._shots_multiplier = 1
self._bootstrap_trials = 0
statevector_sims = ["aer_simulator_statevector", "statevector_simulator"]
if self._backend.name() in statevector_sims:
self._is_sv_sim = True
else:
self._is_sv_sim = False
# Load the two circuit generation operations
self._pauli_names_for_tensor_states = None
self._pauli_names_for_superpos_states = None
self._w_ij_tensor_states = None
self._w_ab_superpos_states = None
self._op_for_generating_tensor_circuits = None
self._op_for_generating_superpos_circuits = None
self._load_ops()
@property
def shots_multiplier(self):
"""Return the shots multiplier."""
return self._shots_multiplier
@shots_multiplier.setter
def shots_multiplier(self, multiplier):
"""Set the shots multiplier."""
self._shots_multiplier = multiplier
@property
def bootstrap_trials(self):
"""Return the bootstrap trials."""
return self._bootstrap_trials
@bootstrap_trials.setter
def bootstrap_trials(self, trials):
"""Set the bootstrap trials."""
self._bootstrap_trials = trials
def _load_ops(self):
# Get the weighted Pauli deconstruction of the operator
(
pauli_names_for_tensor_states,
pauli_names_for_superpos_states,
w_ij_tensor_states,
w_ab_superpos_states,
) = self.forged_operator.construct()
self._pauli_names_for_tensor_states = pauli_names_for_tensor_states
self._pauli_names_for_superpos_states = pauli_names_for_superpos_states
self._w_ij_tensor_states = w_ij_tensor_states
self._w_ab_superpos_states = w_ab_superpos_states
op_for_generating_tensor_circuits = to_tpb_grouped_weighted_pauli_operator(
WeightedPauliOperator(
paulis=[
[1, Pauli(pname)] for pname in self._pauli_names_for_tensor_states
]
),
TPBGroupedWeightedPauliOperator.sorted_grouping,
)
if len(self._pauli_names_for_superpos_states) > 0:
op_for_generating_superpos_circuits = (
to_tpb_grouped_weighted_pauli_operator(
WeightedPauliOperator(
paulis=[
[1, Pauli(pname)]
for pname in self._pauli_names_for_superpos_states
]
),
TPBGroupedWeightedPauliOperator.sorted_grouping,
)
)
else:
op_for_generating_superpos_circuits = None
self._op_for_generating_tensor_circuits = op_for_generating_tensor_circuits
self._op_for_generating_superpos_circuits = op_for_generating_superpos_circuits
def get_energy_evaluation(
self, operator: OperatorBase, return_expectation: bool = False
) -> Callable[[np.ndarray], Union[float, Iterable[float]]]:
if self._is_sv_sim:
self._shots_multiplier = 1
ansatz_params = self.ansatz.parameters
_, expectation = self.construct_expectation(
ansatz_params, operator, return_expectation=True
)
def energy_evaluation(parameters):
Log.log("------ new iteration energy evaluation -----")
# num_parameter_sets = len(parameters) // self.ansatz.num_parameters
# parameter_sets = np.split(parameters, num_parameter_sets)
parameter_sets = np.reshape(parameters, (-1, self.ansatz.num_parameters))
new_iteration_start_time = time.time()
Log.log(
"duration of last iteration:",
new_iteration_start_time - self._iteration_start_time,
)
self._iteration_start_time = new_iteration_start_time
Log.log("Parameter sets:", parameter_sets)
# Compute the expectation value of the forged operator with respect
# to the ansatz at the given parameters
eval_forged_result = self._evaluate_forged_operator(
parameter_sets=parameter_sets,
hf_value=self._hf_energy,
add_this_to_mean_values_displayed=self._add_this_to_energies_displayed,
shots_multiplier=self._shots_multiplier,
bootstrap_trials=self._bootstrap_trials,
)
(
energy_mean_each_parameter_set,
bootstrap_means_each_parameter_set,
energy_mean_raw_each_parameter_set,
energy_mean_sv_each_parameter_set,
schmidt_coeffs_each_parameter_set,
schmidt_coeffs_raw_each_parameter_set,
schmidt_coeffs_sv_each_parameter_set,
) = eval_forged_result
self._schmidt_coeffs_each_iteration_each_paramset.append(
schmidt_coeffs_each_parameter_set
)
# TODO Not Implemented # pylint: disable=fixme
energy_std_each_parameter_set = [0] * len(energy_mean_each_parameter_set)
# TODO Not Implemented # pylint: disable=fixme
energy_std_raw_each_parameter_set = [0] * len(
energy_mean_each_parameter_set
)
energy_std_sv_each_parameter_set = [0] * len(energy_mean_each_parameter_set)
self._energy_each_iteration_each_paramset.append(
energy_mean_each_parameter_set
)
self._paramsets_each_iteration.append(parameter_sets)
timestamp_string = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")
# additional results
for params, bootstrap_means in zip(
parameter_sets, bootstrap_means_each_parameter_set
):
self.aux_results.append(
(
"bootstrap",
Bootstrap(
eval_count=self._eval_count,
eval_timestamp=timestamp_string,
parameters=params,
bootstrap_values=[
v + self._add_this_to_energies_displayed
for v in bootstrap_means
],
),
)
)
data_titles = ["data", "data_noextrapolation", "data_statevec"][:-1]
for (
filename,
energies_each_paramset,
stds_each_paramset,
schmidts_each_paramset,
) in zip(
data_titles,
[
energy_mean_each_parameter_set,
energy_mean_raw_each_parameter_set,
energy_mean_sv_each_parameter_set,
],
[
energy_std_each_parameter_set,
energy_std_raw_each_parameter_set,
energy_std_sv_each_parameter_set,
],
[
schmidt_coeffs_each_parameter_set,
schmidt_coeffs_raw_each_parameter_set,
schmidt_coeffs_sv_each_parameter_set,
],
):
for params, energy_mean, energy_std, schmidts in zip(
parameter_sets,
energies_each_paramset,
stds_each_paramset,
schmidts_each_paramset,
):
self.aux_results.append(
(
filename,
DataResults(
eval_count=self._eval_count,
eval_timestamp=timestamp_string,
energy_hartree=(
energy_mean + self._add_this_to_energies_displayed
),
energy_std=energy_std,
parameters=parameters,
schmidts=schmidts,
),
)
)
for params, energy_mean, energy_std in zip(
parameter_sets,
energy_mean_each_parameter_set,
energy_std_each_parameter_set,
):
self._eval_count += 1
if self._callback is not None:
self._callback(self._eval_count, params, energy_mean, energy_std)
self.parameter_sets = parameter_sets
self.energy_mean_each_parameter_set = energy_mean_each_parameter_set
self.energy_std_each_parameter_set = energy_std_each_parameter_set
return (
np.array(energy_mean_each_parameter_set)
if len(energy_mean_each_parameter_set) > 1
else energy_mean_each_parameter_set[0]
)
if return_expectation:
return energy_evaluation, expectation
return energy_evaluation
def _evaluate_forged_operator(
self,
parameter_sets,
hf_value=0,
add_this_to_mean_values_displayed=0,
shots_multiplier=1,
bootstrap_trials=0,
):
"""Computes the expectation value of the forged operator
with respect to the ansatz at the given parameters."""
# These calculations are parameter independent for
# a given operator so could be moved outside the optimization loop:
circuits_to_execute = []
for params_idx, params in enumerate(parameter_sets):
Log.log("Constructing the circuits for parameter set", params, "...")
# Get all the tensor circuits associated with ansatz U
tensor_circuits_to_execute_u = prepare_circuits_to_execute(
params,
self._tensor_prep_circuits_u,
self._op_for_generating_tensor_circuits,
self._ansatz,
self._is_sv_sim,
)
# Get all tensor circuits associated with ansatz V
tensor_circuits_to_execute_v = prepare_circuits_to_execute(
params,
self._tensor_prep_circuits_v,
self._op_for_generating_tensor_circuits,
self._ansatz,
self._is_sv_sim,
)
# Combine all tensor circuits into a single list
tensor_circuits_to_execute = (
tensor_circuits_to_execute_u + tensor_circuits_to_execute_v
)
if len(self._pauli_names_for_superpos_states) > 0:
# Get superposition circuits associated with ansatz U
superpos_circuits_to_execute_u = prepare_circuits_to_execute(
params,
self._superpos_prep_circuits_u,
self._op_for_generating_superpos_circuits,
self._ansatz,
self._is_sv_sim,
)
# Get superposition circuits associated with ansatz V
superpos_circuits_to_execute_v = prepare_circuits_to_execute(
params,
self._superpos_prep_circuits_v,
self._op_for_generating_superpos_circuits,
self._ansatz,
self._is_sv_sim,
)
# Combine all superposition circuits into a single list
superpos_circuits_to_execute = (
superpos_circuits_to_execute_u + superpos_circuits_to_execute_v
)
else:
superpos_circuits_to_execute_u = []
superpos_circuits_to_execute_v = []
superpos_circuits_to_execute = []
if params_idx == 0:
Log.log(
"inferred number of pauli groups for tensor statepreps:",
len(tensor_circuits_to_execute)
/ (
len(self._tensor_prep_circuits_u)
+ len(self._tensor_prep_circuits_v)
),
)
if self._superpos_prep_circuits_u:
Log.log(
"inferred number of pauli groups for superposition statepreps:",
len(superpos_circuits_to_execute)
/ (
len(self._superpos_prep_circuits_u)
+ len(self._superpos_prep_circuits_v)
),
)
circuits_to_execute += (
tensor_circuits_to_execute + superpos_circuits_to_execute
)
Log.log("Transpiling circuits...")
Log.log(self._initial_layout)
circuits_to_execute = transpile(
circuits_to_execute,
self._backend,
initial_layout=self._initial_layout,
coupling_map=self._coupling_map,
)
if not isinstance(circuits_to_execute, list):
circuits_to_execute = [circuits_to_execute]
Log.log("Building pseudo-richardson circuits...")
circuits_to_execute = make_pseudorichardson_circuits(
circuits_to_execute,
simple_richardson_orders=[
int(x) for x in (np.asarray(self._zero_noise_extrap) - 1) / 2
],
)
if self.copysample_job_size:
Log.log("Copysampling circuits...")
Log.log(
"num circuits to execute before copysampling:", len(circuits_to_execute)
)
weight_each_stateprep = np.abs(
np.array(self._running_estimate_of_schmidts)[:, np.newaxis]
* np.array(self._running_estimate_of_schmidts)[np.newaxis, :]
)
if self._no_bs0_circuits:
## IMPORTANT: assumes special-case of NOT executing HF bitstring state-prep
weight_each_stateprep[0, 0] = 0
weight_each_circuit = []
for qcirc in circuits_to_execute:
name_parts = qcirc.name.split("_")
stretch_factor = float(name_parts[-2].split("richardson")[1])
indices_of_involved_bitstrings = [
int("".join(c for c in x if c.isdigit()))
for x in name_parts[1].split("bs")[1:]
]
if len(indices_of_involved_bitstrings) == 1:
i, j = (
indices_of_involved_bitstrings[0],
indices_of_involved_bitstrings[0],
)
elif len(indices_of_involved_bitstrings) == 2:
i, j = indices_of_involved_bitstrings
else:
raise ValueError(
"Circuit name should be of form [params]_bs#_... "
"or [params]_bs#bs#_... indicating which 1 or 2 "
"bitstrings it involves, but instead name is:",
qcirc.name,
)
if len(self._zero_noise_extrap) <= 2:
weight_each_circuit.append(
weight_each_stateprep[i, j] / stretch_factor
)
else:
warnings.warn(
"Weighted sampling when more than 2 stretch factors are present "
"is not supported (may or may not just work, haven't "
"looked into it). Reverting to uniform sampling of stretch factors."
)
weight_each_circuit.append(weight_each_stateprep[i, j] / 1)
circuits_to_execute = copysample_circuits(
circuits_to_execute,
weights=weight_each_circuit,
new_job_size=self.copysample_job_size * len(parameter_sets),
)
Log.log(
"num circuits to execute after copysampling:", len(circuits_to_execute)
)
if self._meas_error_mit:
if (not self._meas_fitter) or (
(time.time() - self._meas_error_refresh_timestamp) / 60
> self._meas_error_refresh_period_minutes
):
Log.log("Generating measurement fitter...")
physical_qubits = np.asarray(self._initial_layout).tolist()
cal_circuits, state_labels = complete_meas_cal(
range(len(physical_qubits))
)
result = execute_with_retry(
cal_circuits, self._backend, self._meas_error_shots, self._rep_delay
)
self._meas_fitter = CompleteMeasFitter(result, state_labels)
self._meas_error_refresh_timestamp = time.time()
Log.log("Executing", len(circuits_to_execute), "circuits...")
result = execute_with_retry(
circuits_to_execute,
self._backend,
self._shots * shots_multiplier,
self._rep_delay,
)
if self._meas_error_mit:
Log.log("Applying meas fitter/filter...")
result = self._meas_fitter.filter.apply(result)
Log.log("Done executing. Analyzing results...")
op_mean_each_parameter_set = [None] * len(parameter_sets)
op_std_each_parameter_set = [None] * len(parameter_sets)
schmidt_coeffs_each_parameter_set = [None] * len(parameter_sets)
op_mean_raw_each_parameter_set = [None] * len(parameter_sets)
op_std_raw_each_parameter_set = [None] * len(parameter_sets)
schmidt_coeffs_raw_each_parameter_set = [None] * len(parameter_sets)
op_mean_sv_each_parameter_set = [None] * len(parameter_sets)
schmidt_coeffs_sv_each_parameter_set = [None] * len(parameter_sets)
if self.copysample_job_size:
result = combine_copysampled_results(result)
if bootstrap_trials:
Log.log(f"Bootstrap: resampling result {bootstrap_trials} times...")
bootstrap_results = [
resample_result(result) for _ in range(bootstrap_trials)
]
Log.log(
"Done bootstrapping new counts, starting analysis of bootstrapped data."
)
else:
bootstrap_results = []
bootstrap_means_each_parameter_set = []
for idx, params in enumerate(parameter_sets):
bootstrap_means = []
for is_bootstrap_index, res in enumerate([result] + bootstrap_results):
results_extrap, results_raw = eval_forged_op_with_result(
res,
self._w_ij_tensor_states,
self._w_ab_superpos_states,
params,
self._bitstrings_s_u,
self._op_for_generating_tensor_circuits,
self._op_for_generating_superpos_circuits,
self._zero_noise_extrap,
bitstrings_s_v=self._bitstrings_s_v,
hf_value=hf_value,
statevector_mode=self._is_sv_sim,
hybrid_superpos_coeffs=self._hybrid_superpos_coeffs,
add_this_to_mean_values_displayed=add_this_to_mean_values_displayed,
no_bs0_circuits=self._no_bs0_circuits,
)
op_mean, op_std, schmidts = results_extrap
op_mean_raw, op_std_raw, schmidts_raw = results_raw
if not is_bootstrap_index:
op_mean_each_parameter_set[idx] = op_mean
op_std_each_parameter_set[idx] = op_std
op_mean_raw_each_parameter_set[idx] = op_mean_raw
op_std_raw_each_parameter_set[idx] = op_std_raw
schmidt_coeffs_raw_each_parameter_set[idx] = schmidts_raw
Log.log("Optimal schmidt coeffs sqrt(p) =", schmidts)
schmidt_coeffs_each_parameter_set[idx] = schmidts
else:
bootstrap_means.append(op_mean)
bootstrap_means_each_parameter_set.append(bootstrap_means)
self._running_estimate_of_schmidts = np.mean(
schmidt_coeffs_each_parameter_set, axis=0
)
return (
op_mean_each_parameter_set,
bootstrap_means_each_parameter_set,
op_mean_raw_each_parameter_set,
op_mean_sv_each_parameter_set,
schmidt_coeffs_each_parameter_set,
schmidt_coeffs_raw_each_parameter_set,
schmidt_coeffs_sv_each_parameter_set,
)
def get_optimal_vector(self):
"""Prevents the VQE superclass version of this function from running."""
warnings.warn(
"get_optimal_vector not implemented for forged VQE. Returning None."
)
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
from qiskit_cold_atom.providers import ColdAtomProvider
provider = ColdAtomProvider()
backend = provider.get_backend("fermionic_tweezer_simulator")
# give initial occupations separated by spin species
qc = backend.initialize_circuit([[1, 0, 0, 1], [0, 0, 1, 1]])
qc.draw(output='mpl', style='clifford')
qc.measure_all()
print("measured counts: ", backend.run(qc, shots=10).result().get_counts())
print("measured counts: ", backend.run(qc, shots=10).result().get_memory())
from qiskit_cold_atom.fermions.fermion_gate_library import FermiHubbard
qc = backend.initialize_circuit([[1, 0, 0, 1], [0, 0, 1, 1]])
all_modes=range(8)
qc.append(FermiHubbard(num_modes=8, j=[0.5, 1., -1.], u=5., mu=[0., -1., 1., 0.]), qargs=all_modes)
# alternatively append the FH gate directly:
# qc.fhubbard(j=[0.5, 1., -1.], u=5., mu=[0., -1., 1., 0.], modes=all_modes)
qc.draw(output='mpl', style='clifford')
from qiskit_cold_atom.fermions.fermion_gate_library import Hop, Interaction, Phase
qc = backend.initialize_circuit([[0, 1, 1, 0], [0, 1, 0, 1]])
hop_gate = Hop(num_modes=4, j=[0.5])
interaction_gate = Interaction(num_modes=8, u=2.)
phase_gate = Phase(num_modes=2, mu=[1.])
qc.append(hop_gate, qargs=[0, 1, 4, 5])
qc.append(interaction_gate, qargs=all_modes)
qc.append(phase_gate, qargs=[2, 6])
# equivalently, we can build the same circuit with a shortcut notation:
# qc.fhop([0.5], [0, 1, 4, 5])
# qc.fint(2., all_modes)
# qc.fphase([1.], [2, 6])
qc.draw(output= "mpl", style='clifford')
print("hopping generator: \n", hop_gate.generator)
print("\n interaction generator: \n",interaction_gate.generator)
print("\n phase generator: \n", phase_gate.generator)
qc.measure_all()
job = backend.run(qc, shots=100)
print("counts: ", job.result().get_counts())
print("time taken: ", job.result().time_taken)
print(backend.get_basis(qc))
job_efficient = backend.run(qc, shots=100, num_species=2)
print("counts: ", job_efficient.result().get_counts())
print("time taken: ",job_efficient.result().time_taken)
print("basis: ", backend.get_basis(qc, num_species=2))
from qiskit_cold_atom.fermions.fermion_gate_library import FRXGate, FRYGate, FRZGate
import numpy as np
qc = backend.initialize_circuit([[0, 1, 1, 0], [0, 1, 0, 1]])
# flip the spin of the atom at site 3
qc.append(FRXGate(np.pi), [2, 6])
# equivalently use shortcut
# qc.frx(np.pi, [2, 6])
qc.measure_all()
print("counts: ", backend.run(qc, num_species=2).result().get_counts())
print("basis dimension :", backend.get_basis(qc).dimension)
from pprint import pprint
tweezer_configuration = backend.configuration().to_dict()
pprint(tweezer_configuration)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
from qiskit import *
p = 0.01
P = 3 * p**2 * (1-p) + p**3
print('Probability of a single reply being garbled:',p)
print('Probability of a the majority of three replies being garbled:',P)
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import pauli_error, depolarizing_error
def get_noise(p_meas,p_gate):
error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)])
error_gate1 = depolarizing_error(p_gate, 1)
error_gate2 = error_gate1.tensor(error_gate1)
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error_meas, "measure") # measurement error is applied to measurements
noise_model.add_all_qubit_quantum_error(error_gate1, ["x"]) # single qubit gate error is applied to x gates
noise_model.add_all_qubit_quantum_error(error_gate2, ["cx"]) # two qubit gate error is applied to cx gates
return noise_model
noise_model = get_noise(0.01,0.01)
qc0 = QuantumCircuit(3,3,name='0') # initialize circuit with three qubits in the 0 state
qc0.measure(qc0.qregs[0],qc0.cregs[0]) # measure the qubits
# run the circuit with th noise model and extract the counts
counts = execute( qc0, Aer.get_backend('qasm_simulator'),noise_model=noise_model,shots=10000).result().get_counts()
print(counts)
qc1 = QuantumCircuit(3,3,name='0') # initialize circuit with three qubits in the 0 state
qc1.x(qc1.qregs[0]) # flip each 0 to 1
qc1.measure(qc1.qregs[0],qc1.cregs[0]) # measure the qubits
# run the circuit with th noise model and extract the counts
counts = execute( qc1, Aer.get_backend('qasm_simulator'),noise_model=noise_model,shots=10000).result().get_counts()
print(counts)
noise_model = get_noise(0.5,0.0)
counts = execute( qc1, Aer.get_backend('qasm_simulator'),noise_model=noise_model,shots=10000).result().get_counts()
print(counts)
from qiskit import *
cq = QuantumRegister(2,'code_qubit')
lq = QuantumRegister(1,'ancilla_qubit')
sb = ClassicalRegister(1,'syndrome_bit')
qc = QuantumCircuit(cq,lq,sb)
qc.cx(cq[0],lq[0])
qc.cx(cq[1],lq[0])
qc.measure(lq,sb)
print(qc)
qc_init = QuantumCircuit(cq)
print(qc_init+qc)
counts = execute( qc_init+qc, Aer.get_backend('qasm_simulator'),shots=10000).result().get_counts()
print('\nResults:',counts)
qc_init = QuantumCircuit(cq)
qc_init.x(cq)
print(qc_init+qc)
counts = execute( qc_init+qc, Aer.get_backend('qasm_simulator'),shots=10000).result().get_counts()
print('\nResults:',counts)
qc_init = QuantumCircuit(cq)
qc_init.h(cq[0])
qc_init.cx(cq[0],cq[1])
print(qc_init+qc)
counts = execute( qc_init+qc, Aer.get_backend('qasm_simulator'),shots=10000).result().get_counts()
print('\nResults:',counts)
qc_init = QuantumCircuit(cq)
qc_init.h(cq[0])
qc_init.cx(cq[0],cq[1])
qc_init.x(cq[0])
print(qc_init+qc)
counts = execute( qc_init+qc, Aer.get_backend('qasm_simulator'),shots=10000).result().get_counts()
print('\nResults:',counts)
from qiskit.ignis.verification.topological_codes import RepetitionCode
from qiskit.ignis.verification.topological_codes import lookuptable_decoding
n = 3
T = 1
code = RepetitionCode(n,T)
code.qubit_registers
code.code_qubit
for log in ['0','1']:
print('\n========= logical',log,'=========\n')
print( code.circuit[log] )
circuits = code.get_circuit_list()
job = execute( circuits, Aer.get_backend('qasm_simulator') )
for log in ['0','1']:
print('\nLogical',log,':',job.result().get_counts(log))
code = RepetitionCode(n,4)
circuits = code.get_circuit_list()
job = execute( circuits, Aer.get_backend('qasm_simulator') )
for log in ['0','1']:
print('\nLogical',log,':',job.result().get_counts(log))
code = RepetitionCode(5,4)
circuits = code.get_circuit_list()
job = execute( circuits, Aer.get_backend('qasm_simulator') )
for log in ['0','1']:
print('\nLogical',log,':',job.result().get_counts(log))
code = RepetitionCode(n,4)
circuits = code.get_circuit_list()
job = execute( circuits, Aer.get_backend('qasm_simulator') )
for log in ['0','1']:
print('\nLogical',log,':',job.result().get_counts(log))
code = RepetitionCode(3,1)
noise_model = get_noise(0.2,0.2)
circuits = code.get_circuit_list()
job = execute( circuits, Aer.get_backend('qasm_simulator'), noise_model=noise_model )
raw_results = {}
for log in ['0','1']:
raw_results[log] = job.result().get_counts(log)
print('\n========= logical',log,'=========\n')
print(raw_results[log])
job = execute( circuits, Aer.get_backend('qasm_simulator'), noise_model=noise_model, shots=10000 )
table_results = {}
for log in ['0','1']:
table_results[log] = job.result().get_counts(log)
P = lookuptable_decoding(raw_results,table_results)
print('P =',P)
code = RepetitionCode(3,1)
noise_model = get_noise(0.1,0.1)
circuits = code.get_circuit_list()
job = execute( circuits, Aer.get_backend('qasm_simulator'), noise_model=noise_model )
raw_results = {}
for log in ['0','1']:
raw_results[log] = job.result().get_counts(log)
job = execute( circuits, Aer.get_backend('qasm_simulator'), noise_model=noise_model, shots=10000 )
table_results = {}
for log in ['0','1']:
table_results[log] = job.result().get_counts(log)
P = lookuptable_decoding(raw_results,table_results)
print('P =',P)
|
https://github.com/nahumsa/volta
|
nahumsa
|
import sys
sys.path.append('../../')
# Python imports
import numpy as np
import matplotlib.pyplot as plt
# Qiskit
from qiskit import BasicAer
from qiskit.aqua.components.optimizers import COBYLA, SPSA
from qiskit.circuit.library import TwoLocal
# VOLTA
from volta.vqd import VQD
from volta.utils import classical_solver
from volta.hamiltonians import BCS_hamiltonian
%load_ext autoreload
%autoreload 2
EPSILONS = [3., 3., 3., 4., 3.]
V = -2
hamiltonian = BCS_hamiltonian(EPSILONS, V)
print(hamiltonian)
eigenvalues, eigenvectors = classical_solver(hamiltonian)
print(f"Eigenvalues: {eigenvalues}")
from tqdm import tqdm
from qiskit.utils import QuantumInstance
# Parameters Variables
n_trials = 50
max_depth = 7
# Auxiliary Variables
solution_dict = {}
# Define Optimizer
# optimizer = COBYLA()
optimizer = SPSA(maxiter=250, c1=.7, last_avg=25)
# Define Backend
backend = QuantumInstance(backend=BasicAer.get_backend('qasm_simulator'),
shots=10000)
for depth in range(1,max_depth):
# Ansatz with diferent depth
ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=depth)
es_1 = []
es_2 = []
for _ in tqdm(range(n_trials), desc=f"Depth {depth}"):
# Run algorithm
Algo = VQD(hamiltonian=hamiltonian,
ansatz=ansatz,
n_excited_states=1,
beta=10.,
optimizer=optimizer,
backend=backend,
overlap_method="amplitude",
)
Algo.run(0)
vqd_energies = Algo.energies
es_1.append(vqd_energies[0])
es_2.append(vqd_energies[1])
es_1 = np.array(es_1)
es_2 = np.array(es_2)
# Maybe use a pd.dataframe
solution_dict[depth] = {'mean':np.mean(es_2 - es_1), 'std':np.std(es_2 - es_1)}
mean = []
std = []
for i in range(1,max_depth):
mean.append(solution_dict[i]['mean'])
std.append(solution_dict[i]['std'])
solution_dict
ed_eig= (eigenvalues[1] - eigenvalues[0])/2
import seaborn as sns
sns.set()
from matplotlib.ticker import MaxNLocator
x_axis = [i for i in range(1,max_depth)]
plt.errorbar(x_axis,
np.array(mean)/2,
yerr=np.array(std)/2,
fmt='ro', ecolor='green')
plt.hlines(y=ed_eig, xmin=0.5, xmax=6.5,
label='Expected value',color='b')
plt.title('Varying Depth SPSA', size=18)
plt.xlabel('Depth', size= 14)
plt.ylabel('Gap', size=14)
plt.xticks(x_axis)
plt.legend()
plt.show()
from matplotlib.ticker import MaxNLocator
x_axis = [i for i in range(1,max_depth)]
plt.errorbar(x_axis,
np.array(mean)/2,
yerr=np.array(std)/2,
fmt='ro', ecolor='green')
plt.hlines(y=ed_eig, xmin=0.5, xmax=6.5,
label='Expected value',color='b')
plt.title('Varying Depth', size=18)
plt.xlabel('Depth', size= 14)
plt.ylabel('Gap', size=14)
plt.xticks(x_axis)
plt.legend()
plt.show()
max_depth = 7
spsa_dict = {1: {'mean': 7.63536, 'std': 2.024100436737268},
2: {'mean': 6.421452, 'std': 3.009174019443874},
3: {'mean': 5.842042, 'std': 3.040774217602484},
4: {'mean': 5.632112000000001, 'std': 3.7485136763063838},
5: {'mean': 5.302354, 'std': 4.1340626645086065},
6: {'mean': 4.079198, 'std': 3.6543650323135477}}
spsa_dict = {1: {'mean': 5.335038, 'std': 1.708178187062462},
2: {'mean': 4.527469999999999, 'std': 1.756017706431231},
3: {'mean': 3.160082, 'std': 1.587476022331046},
4: {'mean': 2.16104, 'std': 1.5474551641970113},
5: {'mean': 1.3676439999999996, 'std': 1.5716504103852103},
6: {'mean': 0.19817400000000002, 'std': 1.071217238623427}}
cobyla_dict = {1: {'mean': 3.1321660000000002, 'std': 0.24530721278429674},
2: {'mean': 2.94829, 'std': 1.0438090011587366},
3: {'mean': 2.912668, 'std': 0.9325122996379187},
4: {'mean': 3.16006, 'std': 0.38378217728289615},
5: {'mean': 3.048998, 'std': 0.8419937475991135},
6: {'mean': 2.630514, 'std': 1.029439954734612}}
mean_spsa = []
std_spsa = []
mean_cobyla = []
std_cobyla = []
for i in range(1,max_depth):
mean_spsa.append(spsa_dict[i]['mean'])
std_spsa.append(spsa_dict[i]['std'])
mean_cobyla.append(cobyla_dict[i]['mean'])
std_cobyla.append(cobyla_dict[i]['std'])
from matplotlib.ticker import MaxNLocator
x_axis = [i for i in range(1,max_depth)]
plt.errorbar(x_axis,
np.array(mean_spsa)/2,
yerr=np.array(std_spsa)/2,
fmt='o', color='black',
ecolor='gray', elinewidth=2,
label='SPSA')
plt.errorbar(x_axis,
np.array(mean_cobyla)/2,
yerr=np.array(std_cobyla)/2,
fmt='o', color='red',
ecolor='green', elinewidth=2,
label='COBYLA')
plt.hlines(y=ed_eig, xmin=0.5, xmax=6.5,
label='Expected value',color='b')
plt.title('Varying Depth', size=18)
plt.xlabel('Depth', size= 14)
plt.ylabel('Gap', size=14)
plt.ylim(0., 4.1)
plt.xticks(x_axis)
plt.legend(loc="upper left")
plt.savefig('Depth.png')
plt.show()
plt.plot(x_axis, np.array(mean_spsa)/2, 'or')
plt.fill_between(x_axis, np.array(mean_spsa)/2 - np.array(std_spsa)/2 , np.array(mean_spsa)/2 + np.array(std_spsa)/2,
color='gray', alpha=0.2)
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
# Virtual -> physical
# 0 -> 3
# 1 -> 4
# 2 -> 2
my_ghz = transpile(ghz, backend, initial_layout=[3, 4, 2])
plot_circuit_layout(my_ghz, backend)
|
https://github.com/daimurat/qiskit-implementation
|
daimurat
|
!pip install qulacs
from qulacs import QuantumState,QuantumCircuit, Observable, PauliOperator
from qulacs.gate import X,Z,RX,RY,RZ,CNOT,merge,DenseMatrix,add
from qulacs.state import inner_product
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
# 量子ビットの数
nqubits = 4
# ダイナミクスをシミュレーションする時間
t = 10
# トロッター分解の分割数
M = 1000
# 時間の刻み幅
delta = t/M
## 横磁場の強さ
h = 1000
## 初期状態(nquibitsに合わせて変更)
state = QuantumState(nqubits)
initial_states = [0b0000, 0b1101, 0b1010]
## 全磁化に対応するオブザーバブルを準備しておく
magnetization_obs = Observable(nqubits)
for i in range(nqubits):
magnetization_obs.add_operator(PauliOperator("Z "+str(i), 1.0/nqubits))
## 時間と磁化を記録するリスト
x = [i*delta for i in range(M+1)]
ylist = []
# トロッター分解の1回分、
# e^{iZ_1Z_2*delta}*e^{iZ_2Z_3*delta}*...e^{iZ_nZ_1*delta} * e^{i X_1*delta}*...*e^{i X_n*delta} を量子ゲートに変換
circuit_trotter_transIsing = QuantumCircuit(nqubits)
for i in range(nqubits):
circuit_trotter_transIsing.add_CNOT_gate(i,(i+1)%(nqubits))
circuit_trotter_transIsing.add_RZ_gate((i+1)%nqubits,-2*delta)
circuit_trotter_transIsing.add_CNOT_gate(i,(i+1)%(nqubits))
circuit_trotter_transIsing.add_RX_gate(i, -2*delta*h)
for i in range(len(initial_states)):
y = []
state.set_computational_basis(initial_states[i])
#t=0の時の全磁化のみ先に計算
y.append( magnetization_obs.get_expectation_value(state) )
#t=0以降の全磁化を計算
for i in range(M):
# delta=t/Mだけ時間発展
circuit_trotter_transIsing.update_quantum_state(state)
# 磁化を計算して記録
y.append(magnetization_obs.get_expectation_value(state))
ylist.append(y)
#グラフの描画
plt.xlabel("time")
plt.ylabel("Value of magnetization")
plt.title("Dynamics of Ising model")
plt.ylim(-1.1, 1.1)
for i in range(len(initial_states)):
plt.plot(x, ylist[i], "-",label=bin(initial_states[i])[2:].ljust(nqubits, '0'))
plt.legend()
plt.show()
## 初期状態
state_trotter = QuantumState(nqubits)
state_trotter.set_computational_basis(initial_states[0])
state_exact = QuantumState(nqubits)
state_exact.set_computational_basis(initial_states[0])
# トロッター分解の1回分、
# e^{iZ_1Z_2*delta}*e^{iZ_2Z_3*delta}*...e^{iZ_nZ_1*delta} * e^{i X_1*delta}*...*e^{i X_n*delta} を量子ゲートに変換
circuit_trotter_transIsing = QuantumCircuit(nqubits)
for i in range(nqubits):
circuit_trotter_transIsing.add_CNOT_gate(i,(i+1)%(nqubits))
circuit_trotter_transIsing.add_RZ_gate((i+1)%nqubits,-2*delta) ## RZ(a)=exp(i*a/2*Z)に注意
circuit_trotter_transIsing.add_CNOT_gate(i,(i+1)%(nqubits))
circuit_trotter_transIsing.add_RX_gate(i, -2*delta*h) ## RX(a)=exp(i*a/2*X)に注意
# e^{-iHt}を直接対角化する。Hの行列表現を得るために、gateを生成してそのmatrixを取得する
zz_matrix = -np.array([[1,0,0,0],[0,-1,0,0],[0,0,-1,0],[0,0,0,1]]) ## Z_i*Z_{i+1}の行列表示
hx_matrix = -h*np.array( [ [0,1], [1,0] ] )
zz = DenseMatrix([0,1], zz_matrix) ## 0~1間の相互作用
hx = DenseMatrix(0, hx_matrix) ## 0サイトへの横磁場
## qulacs.gate.addを用いて、1以降のサイトの相互作用と横磁場を足していく
for i in range(1, nqubits):
zz = add(zz, DenseMatrix([i,(i+1)%nqubits], zz_matrix))
hx = add(hx, DenseMatrix(i, hx_matrix) )
## 最終的なハミルトニアン
ham = add(zz, hx)
matrix = ham.get_matrix() #行列の取得
eigenvalue, P = np.linalg.eigh(np.array(matrix)) #取得した行列の固有値、固有ベクトルを取得
## e^{-i*H*delta}を行列として作る
e_iHdelta = np.diag(np.exp(-1.0j*eigenvalue*delta))
e_iHdelta = np.dot(P, np.dot(e_iHdelta, P.T))
## 回路に変換
circuit_exact_transIsing = QuantumCircuit(nqubits)
circuit_exact_transIsing.add_dense_matrix_gate( np.arange(nqubits), e_iHdelta)
## 時間と磁化を記録するリスト
x = [i*delta for i in range(M+1)]
y_trotter = []
y_exact = []
#t=0の時の全磁化のみ先に計算
y_trotter.append( magnetization_obs.get_expectation_value(state_trotter) )
y_exact.append( magnetization_obs.get_expectation_value(state_exact) )
#t=0以降の全磁化を計算
for i in range(M):
# delta=t/Mだけ時間発展
circuit_trotter_transIsing.update_quantum_state(state_trotter)
circuit_exact_transIsing.update_quantum_state(state_exact)
# 磁化を計算して記録
y_trotter.append( magnetization_obs.get_expectation_value(state_trotter) )
y_exact.append( magnetization_obs.get_expectation_value(state_exact) )
#グラフの描画
plt.xlabel("time")
plt.ylabel("Value of magnetization")
plt.title("Dynamics of transverse Ising model")
plt.plot(x, y_trotter, "-", label="Trotter")
plt.plot(x, y_exact, "-", label="exact")
plt.ylim(-1.1, 1.1)
plt.legend()
plt.show()
#エラーの描画
plt.xlabel("time")
plt.ylabel("Value of magnetization")
plt.title("Error")
plt.plot(x, np.abs(np.array(y_trotter) - np.array(y_exact)), "-", label="Trotter")
plt.legend()
plt.show()
|
https://github.com/kerenavnery/qmail
|
kerenavnery
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
from qiskit import *
from qiskit.quantum_info import Statevector
#From Marc
from parser import QSerializer
#From Luca
import socket
from SocketChannel import SocketChannel
# In[33]:
class Channel:
def __init__(self,slave_offset=0):
self._state_vector = None
self._arr_qubits = None
self._basis_gates = ['u1', 'u2', 'u3', 'cx','x','y','H','z']
self._master = True
self._offset = 0
self._slave_offset = slave_offset
def send(self,circuit,arr_qubits):
self._state_vector = Statevector.from_instruction(circuit)
self._arr_qubits = arr_qubits
#From Marc
ser = parser.QSerializer()
ser.add_element('channel_class', self)
str_to_send = ser.encode()
#From Luca
message = str_to_send
TCP_IP = '127.0.0.1'
channel = SocketChannel()
channel.connect(TCP_IP, 5005)
channel.send(message)
#channel.close()
## TODO: TCP THINGS
return self
def receive(self,circuit)#,recieve_channel): ## TODO: remove recieve as an input
#TODO: TCP things
#recieve_channel = TCP_STUFF
#From Luca
channel = SocketChannel(port=5005, listen=True)
data = channel.receive()
print("received data:", data)
#channel.close()
#From Marc
ser2 = parser.QSerializer()
ser2.decode(data)
recieve_channel = ser2.get_element('channel_class')
self._slave_offset = recieve_channel._slave_offset
if(recieve_channel._master):
self._master = False
self._offset = self._slave_offset
new_circuit = QuantumCircuit(len(recieve_channel._state_vector.dims()))
new_circuit.initialize(recieve_channel._state_vector.data, range(len(recieve_channel._state_vector.dims())))
new_circuit = transpile(new_circuit, basis_gates=self._basis_gates)
return new_circuit, self._offset
# In[34]:
n_master = 2
n_slave = 1
master_offset = 0
slave_offset = n_master
circ = QuantumCircuit(n_master + n_slave)
channel = Channel(slave_offset)
## Master
circ.h(0 + channel._offset)
#circ.cx(0 + channel._offset, 1 + channel._offset)
#irc.h(1 + channel._offset)
to_tpc = channel.send(circ,[1]) ## TODO: remove
circ.draw()
# In[35]:
#Bob Part
circ_bob = QuantumCircuit(3)
bob_channel = Channel()
circ_bob, offset = bob_channel.receive(circ_bob)#,to_tpc)
circ_bob.draw()
# In[11]:
# Initialize circ-2 in state psi (using transpile to remove reset)
#circ2 = QuantumCircuit(2)
#circ2.initialize(psi1.data, [0, 1])
#circ2 = transpile(circ2, basis_gates=basis_gates)
#circ2.draw()
# In[6]:
# Add new gates to circ2
circ_bob.h(0+offset)
#circ_bob.cx(0+offset, 1+offset)
#psi2 = Statevector.from_instruction(circ_bob)
to_tpc = bob_channel.send(circ_bob,[1])
circ_bob.draw()
# In[7]:
#Alice Part
circ_alice = QuantumCircuit(3)
alice_channel = Channel()
circ_alice , offset = alice_channel.receive(circ_alice,to_tpc)
circ_alice.draw()
# In[8]:
_
|
https://github.com/omarcostahamido/qiskit_app_carbon_design
|
omarcostahamido
|
# Copyright 2015 IBM Corp. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import flask
import flask_login
import json
import requests
# New QISKit libraries
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit import execute
from qiskit import IBMQ
#from qiskit.backends.ibmq import least_busy
# Visualization libraries
import numpy as np
from spheres import applyOperators
# Custom libraries
from emoticons import generateCircuit, executeCircuit
# Read config.json file
with open('config.json') as f:
credentials_file = json.load(f)
# QISKit authentication
print('loading credentials')
# IBMQ.load_accounts()
IBMQ.enable_account(credentials_file['IBMQ']['apikey'])
print('printing backends')
backends = IBMQ.backends()
print("========")
print(backends)
print('finished printing')
app = flask.Flask(__name__)
jsonify = flask.jsonify
# # === Start Login ====
# app.secret_key = 'italy ibm q application pythonQ'
# login_manager = flask_login.LoginManager()
# login_manager.init_app(app)
# # Mock database
# users = {credentials_file['user']['mail']: {'password': credentials_file['user']['password']}}
# class User(flask_login.UserMixin):
# pass
#
# @login_manager.user_loader
# def user_loader(email):
# if email not in users:
# return
#
# user = User()
# user.id = email
# return user
#
# @login_manager.request_loader
# def request_loader(request):
# email = request.form.get('email')
# if email not in users:
# return
#
# user = User()
# user.id = email
#
# # DO NOT ever store passwords in plaintext and always compare password
# # hashes using constant-time comparison!
# user.is_authenticated = request.form['password'] == users[email]['password']
#
# return user
#
# @app.route('/login', methods=['GET', 'POST'])
# def login():
# if flask.request.method == 'GET':
# return app.send_static_file('login.html')
#
# email = flask.request.form['email']
# if email in users.keys():
# if flask.request.form['password'] == users[email]['password']:
# user = User()
# user.id = email
# flask_login.login_user(user)
# return app.send_static_file('dashboard.html') # Redirect to landing page
#
# return '''<p>Invalid login, try again</p>'''
#
# @login_manager.unauthorized_handler
# def unauthorized_handler():
# return app.send_static_file('login.html')
#
# # === End Login ===
# @app.route('/', methods=['GET', 'POST'])
# @flask_login.login_required
# def Welcome():
# return app.send_static_file('login.html')
@app.route('/', methods=['GET', 'POST'])
# @flask_login.login_required
def Welcome():
return app.send_static_file('dashboard.html')
@app.route('/dashboard',methods=['GET', 'POST'])
# @flask_login.login_required
def Dashboard():
return app.send_static_file('dashboard.html')
@app.route('/spheres', methods=['GET', 'POST'])
# @flask_login.login_required
def Spheres():
return app.send_static_file('spheres.html')
@app.route('/docs', methods=['GET', 'POST'])
# @flask_login.login_required
def Docs():
return app.send_static_file('docs.html')
@app.route('/team', methods=['GET', 'POST'])
# @flask_login.login_required
def Team():
return app.send_static_file('team.html')
@app.route('/publications', methods=['GET', 'POST'])
# @flask_login.login_required
def Publications():
return app.send_static_file('publications.html')
@app.route('/emoticons', methods=['GET', 'POST'])
# @flask_login.login_required
def Emoticons():
return app.send_static_file('emoticons.html')
@app.route('/generateCircuit', methods=['POST'])
def genCirc():
return jsonify(generateCircuit())
#@app.route('/executeCircuit', methods=['POST'])
#def exeCirc():
@app.route('/applyOperators', methods=["POST"])
def appOper():
print('received POST applyOp')
res = applyOperators()
return jsonify(res)
@app.route('/visualize3d', methods=['GET','POST'])
def sphere():
return app.send_static_file('visualize3d.html')
port = os.getenv('PORT', '5000')
if __name__ == "__main__":
# app.debug = True
app.run(host='0.0.0.0', port=int(port),threaded=True)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.circuit.library import UCCSD
ansatz = UCCSD()
ansatz.num_spin_orbitals = 10
from qiskit_nature.second_q.circuit.library import UCCSD
ansatz = UCCSD()
ansatz.num_spatial_orbitals = 5
from qiskit_nature.circuit.library import UCC, UVCC
ucc = UCC(qubit_converter=None, num_particles=None, num_spin_orbitals=None, excitations=None)
uvcc = UVCC(qubit_converter=None, num_modals=None, excitations=None)
from qiskit_nature.second_q.circuit.library import UCC, UVCC
ucc = UCC(num_spatial_orbitals=None, num_particles=None, excitations=None, qubit_converter=None)
uvcc = UVCC(num_modals=None, excitations=None, qubit_converter=None)
from qiskit_nature.circuit.library import HartreeFock, VSCF
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import DirectMapper, JordanWignerMapper
hf = HartreeFock(
num_spin_orbitals=4, num_particles=(1, 1), qubit_converter=QubitConverter(JordanWignerMapper())
)
vscf = VSCF(num_modals=[2, 2])
from qiskit_nature.second_q.circuit.library import HartreeFock, VSCF
from qiskit_nature.second_q.mappers import DirectMapper, JordanWignerMapper, QubitConverter
hf = HartreeFock()
hf.num_spatial_orbitals = 2
hf.num_particles = (1, 1)
hf.qubit_converter = QubitConverter(JordanWignerMapper())
vscf = VSCF()
vscf.num_modals = [2, 2]
from qiskit.providers.basicaer import BasicAer
from qiskit.utils import QuantumInstance
from qiskit_nature.algorithms.ground_state_solvers import VQEUCCFactory
quantum_instance = QuantumInstance(BasicAer.get_backend("statevector_simulator"))
vqe_factory = VQEUCCFactory(quantum_instance=quantum_instance)
from qiskit.algorithms.optimizers import SLSQP
from qiskit.primitives import Estimator
from qiskit_nature.second_q.circuit.library import UCCSD
from qiskit_nature.second_q.algorithms.ground_state_solvers import VQEUCCFactory
estimator = Estimator()
ansatz = UCCSD()
optimizer = SLSQP()
vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer)
from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver, VQEUCCFactory
from qiskit_nature.algorithms.excited_states_solvers import QEOM
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
vqe_factory = VQEUCCFactory()
converter = QubitConverter(JordanWignerMapper())
ground_state_solver = GroundStateEigensolver(converter, vqe_factory)
qeom = QEOM(ground_state_solver)
from qiskit.algorithms.optimizers import SLSQP
from qiskit.primitives import Estimator
from qiskit_nature.second_q.circuit.library import UCCSD
from qiskit_nature.second_q.algorithms.ground_state_solvers import (
GroundStateEigensolver,
VQEUCCFactory,
)
from qiskit_nature.second_q.algorithms.excited_states_solvers import QEOM
from qiskit_nature.second_q.mappers import JordanWignerMapper, QubitConverter
estimator = Estimator()
ansatz = UCCSD()
optimizer = SLSQP()
vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer)
converter = QubitConverter(JordanWignerMapper())
ground_state_solver = GroundStateEigensolver(converter, vqe_factory)
qeom = QEOM(ground_state_solver, estimator)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/kazawai/shor_qiskit
|
kazawai
|
"""The following is python code utilizing the qiskit library that can be run on extant quantum
hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding,
for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find
r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1,
results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>).
To find the factor, use the equivalence a^r mod 15. From this:
(a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r
values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15
Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients,
gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15,
so the result of running shors algorithm to find the prime factors of an integer using quantum
hardware are demonstrated. Note, this is not the same as the technical implementation of shor's
algorithm described in this section for breaking the discrete log hardness assumption,
though the proof of concept remains."""
# Import libraries
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from numpy import pi
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.visualization import plot_histogram
# Initialize qubit registers
qreg_q = QuantumRegister(5, 'q')
creg_c = ClassicalRegister(5, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
circuit.reset(qreg_q[0])
circuit.reset(qreg_q[1])
circuit.reset(qreg_q[2])
circuit.reset(qreg_q[3])
circuit.reset(qreg_q[4])
# Apply Hadamard transformations to qubit registers
circuit.h(qreg_q[0])
circuit.h(qreg_q[1])
circuit.h(qreg_q[2])
# Apply first QFT, modular exponentiation, and another QFT
circuit.h(qreg_q[1])
circuit.cx(qreg_q[2], qreg_q[3])
circuit.crx(pi/2, qreg_q[0], qreg_q[1])
circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4])
circuit.h(qreg_q[0])
circuit.rx(pi/2, qreg_q[2])
circuit.crx(pi/2, qreg_q[1], qreg_q[2])
circuit.crx(pi/2, qreg_q[1], qreg_q[2])
circuit.cx(qreg_q[0], qreg_q[1])
# Measure the qubit registers 0-2
circuit.measure(qreg_q[2], creg_c[2])
circuit.measure(qreg_q[1], creg_c[1])
circuit.measure(qreg_q[0], creg_c[0])
# Get least busy quantum hardware backend to run on
provider = IBMQ.load_account()
device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and
not x.configuration().simulator and x.status().operational==True))
print("Running on current least busy device: ", device)
# Run the circuit on available quantum hardware and plot histogram
from qiskit.tools.monitor import job_monitor
job = execute(circuit, backend=device, shots=1024, optimization_level=3)
job_monitor(job, interval = 2)
results = job.result()
answer = results.get_counts(circuit)
plot_histogram(answer)
#largest amplitude results correspond with r values used to find the prime factor of N.
|
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
|
Qiskit-Extensions
|
# This code is a Qiskit project.
# (C) Copyright IBM 2024.
# 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.
"""Helper functions that are used in the code."""
from __future__ import annotations
from qiskit import QuantumCircuit
from qiskit.circuit import Instruction, Gate
from .optimization_settings import OptimizationSettings
from typing import TYPE_CHECKING, cast, Callable
if TYPE_CHECKING:
from .cut_optimization import CutOptimizationFuncArgs # pragma: no cover
from .disjoint_subcircuits_state import DisjointSubcircuitsState
from .search_space_generator import SearchFunctions
from .best_first_search import BestFirstSearch
from .circuit_interface import CircuitElement, SimpleGateList
from ..qpd import QPDBasis
def qc_to_cco_circuit(circuit: QuantumCircuit) -> list[str | CircuitElement]:
"""Convert a :class:`qiskit.QuantumCircuit` instance into a circuit list that is compatible with the :class:`SimpleGateList`.
To conform with the uniformity of the design, single qubit gates are assigned :math:`gamma=None`.
In the converted list, a barrier across the entire circuit is represented by the string "barrier."
Everything else is represented by an instance of :class:`CircuitElement`.
Args:
circuit: an instance of :class:`qiskit.QuantumCircuit` .
Returns:
circuit_list_rep: list of circuit instructions represented in a form that is compatible with
:class:`SimpleGateList` and can therefore be ingested by the cut finder.
TODO: Extend this function to allow for circuits with (mid-circuit or other)
measurements, as needed.
"""
circuit_list_rep = []
for inst in circuit.data:
if inst.operation.name == "barrier" and len(inst.qubits) == circuit.num_qubits:
circuit_element: CircuitElement | str = "barrier"
else:
gamma = None
if isinstance(inst.operation, Gate) and len(inst.qubits) == 2:
gamma = QPDBasis.from_instruction(inst.operation).kappa
name = inst.operation.name
params = inst.operation.params
circuit_element = CircuitElement(
name=name,
params=params,
qubits=list(circuit.find_bit(q).index for q in inst.qubits),
gamma=gamma,
)
circuit_list_rep.append(circuit_element)
return circuit_list_rep
# currently not in use, written up for future use.
def cco_to_qc_circuit(interface: SimpleGateList) -> QuantumCircuit:
"""Convert the cut circuit outputted by the cut finder into a :class:`qiskit.QuantumCircuit` instance.
Args:
interface: An instance of :class:`SimpleGateList` whose attributes carry information about the cut circuit.
Returns:
qc_cut: The SimpleGateList converted into a :class:`qiskit.QuantumCircuit` instance.
TODO: This function only works for instances of LO gate cutting.
Expand to cover the wire cutting case if or when needed.
"""
cut_circuit_list = interface.export_cut_circuit(name_mapping=None)
num_qubits = interface.get_num_wires()
cut_types = interface.cut_type
qc_cut = QuantumCircuit(num_qubits)
for k, op in enumerate([cut_circuit for cut_circuit in cut_circuit_list]):
if cut_types[k] is None: # only append gates that are not cut.
op_name = op.name
op_qubits = op.qubits
op_params = op.params
inst = Instruction(op_name, len(op_qubits), 0, op_params)
qc_cut.append(inst, op_qubits)
return qc_cut
def select_search_engine(
stage_of_optimization: str,
optimization_settings: OptimizationSettings,
search_space_funcs: SearchFunctions,
stop_at_first_min: bool = False,
) -> BestFirstSearch:
"""Select the search algorithm to use.
In this release, the main search engine is always Dijkstra's
best first search algorithm. Note however that there is also
:func:``greedy_best_first_search``, which is used to warm start
the search algorithm. It can also provide a solution should the
main search engine fail to find a solution given the constraints
on the computation it is allowed to perform.
"""
engine = optimization_settings.get_engine_selection(stage_of_optimization)
if engine == "BestFirst":
return BestFirstSearch(
optimization_settings,
search_space_funcs,
stop_at_first_min=stop_at_first_min,
)
else:
raise ValueError(f"Search engine {engine} is not supported.")
def greedy_best_first_search(
state: DisjointSubcircuitsState,
search_space_funcs: SearchFunctions,
*args: CutOptimizationFuncArgs,
) -> None | DisjointSubcircuitsState:
"""Perform greedy best-first search using the input starting state and the input search-space functions.
The resulting goal state is returned, or None if a deadend is reached. Any additional input argumnets
are passed as additional arguments to the search-space functions.
"""
search_space_funcs.goal_state_func = cast(
Callable, search_space_funcs.goal_state_func
)
search_space_funcs.cost_func = cast(Callable, search_space_funcs.cost_func)
search_space_funcs.next_state_func = cast(
Callable, search_space_funcs.next_state_func
)
while not search_space_funcs.goal_state_func(state, *args):
best = min(
[
(search_space_funcs.cost_func(next_state, *args), k, next_state)
for k, next_state in enumerate(
search_space_funcs.next_state_func(state, *args)
)
],
default=(None, None, None),
)
if best[-1] is None: # pragma: no cover
# This covers a rare edge case.
# We have so far found no circuit that triggers it.
# Excluding from test coverage for now.
return None
state = best[-1]
return state
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
from random import randrange
dimension = 7
# create u and v as empty list
u = []
v = []
for i in range(dimension):
u.append(randrange(-10,11)) # add a randomly picked number to the list u
v.append(randrange(-10,11)) # add a randomly picked number to the list v
# print both lists
print("u is",u)
print("v is",v)
# please execute the cell for Task 1 to define u and v
# let's create a result list
# the first method
result=[]
# fill it with zeros
for i in range(dimension):
result.append(0)
print("by using the first method, result is initialized to",result)
# the second method
# alternative and shorter solution for creating a list with zeros
result = [0] * 7
print("by using the second method, result is initialized to",result)
# let's calculate 3u-2v
for i in range(dimension):
result[i] = 3 * u[i] - 2 * v[i]
# print all lists
print("u is",u)
print("v is",v)
print("3u-2v is",result)
u = [1,-2,-4,2]
fouru=[4,-8,-16,8]
len_u = 0
len_fouru = 0
for i in range(len(u)):
len_u = len_u + u[i]**2 # adding square of each value
len_fouru = len_fouru + fouru[i]**2 # adding square of each value
len_u = len_u ** 0.5 # taking square root of the summation
len_fouru = len_fouru ** 0.5 # taking square root of the summation
# print the lengths
print("length of u is",len_u)
print("4 * length of u is",4 * len_u)
print("length of 4u is",len_fouru)
from random import randrange
u = [1,-2,-4,2]
print("u is",u)
r = randrange(9) # r is a number in {0,...,8}
r = r + 1 # r is a number in {1,...,9}
r = r/10 # r is a number in {1/10,...,9/10}
print()
print("r is",r)
newu=[]
for i in range(len(u)):
newu.append(-1*r*u[i])
print()
print("-ru is",newu)
print()
length = 0
for i in range(len(newu)):
length = length + newu[i]**2 # adding square of each number
print(newu[i],"->[square]->",newu[i]**2)
print()
print("the summation of squares is",length)
length = length**0.5 # taking square root
print("the length of",newu,"is",length)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
This module contains the definition of a base class for quantum fourier transforms.
"""
from abc import abstractmethod
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.aqua import Pluggable, AquaError
class QFT(Pluggable):
"""Base class for QFT.
This method should initialize the module and its configuration, and
use an exception if a component of the module is
available.
Args:
configuration (dict): configuration dictionary
"""
@abstractmethod
def __init__(self, *args, **kwargs):
super().__init__()
@classmethod
def init_params(cls, params):
qft_params = params.get(Pluggable.SECTION_KEY_QFT)
kwargs = {k: v for k, v in qft_params.items() if k != 'name'}
return cls(**kwargs)
@abstractmethod
def _build_matrix(self):
raise NotImplementedError
@abstractmethod
def _build_circuit(self, qubits=None, circuit=None, do_swaps=True):
raise NotImplementedError
def construct_circuit(self, mode='circuit', qubits=None, circuit=None, do_swaps=True):
"""Construct the circuit.
Args:
mode (str): 'matrix' or 'circuit'
qubits (QuantumRegister or qubits): register or qubits to build the circuit on.
circuit (QuantumCircuit): circuit for construction.
do_swaps (bool): include the swaps.
Returns:
The matrix or circuit depending on the specified mode.
"""
if mode == 'circuit':
return self._build_circuit(qubits=qubits, circuit=circuit, do_swaps=do_swaps)
elif mode == 'matrix':
return self._build_matrix()
else:
raise AquaError('Unrecognized mode: {}.'.format(mode))
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
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/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.
"""Test registerless QuantumCircuit and Gates on wires"""
import numpy
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Qubit, Clbit, AncillaQubit
from qiskit.circuit.exceptions import CircuitError
from qiskit.test import QiskitTestCase
class TestRegisterlessCircuit(QiskitTestCase):
"""Test registerless QuantumCircuit."""
def test_circuit_constructor_qwires(self):
"""Create a QuantumCircuit directly with quantum wires"""
circuit = QuantumCircuit(2)
expected = QuantumCircuit(QuantumRegister(2, "q"))
self.assertEqual(circuit, expected)
def test_circuit_constructor_wires_wrong(self):
"""Create a registerless QuantumCircuit wrongly"""
self.assertRaises(CircuitError, QuantumCircuit, 1, 2, 3) # QuantumCircuit(1, 2, 3)
def test_circuit_constructor_wires_wrong_mix(self):
"""Create an almost-registerless QuantumCircuit"""
# QuantumCircuit(1, ClassicalRegister(2))
self.assertRaises(CircuitError, QuantumCircuit, 1, ClassicalRegister(2))
class TestAddingBitsWithoutRegisters(QiskitTestCase):
"""Test adding Bit instances outside of Registers."""
def test_circuit_constructor_on_bits(self):
"""Verify we can add bits directly to a circuit."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit()]
ancillas = [AncillaQubit(), AncillaQubit()]
qc = QuantumCircuit(qubits, clbits, ancillas)
self.assertEqual(qc.qubits, qubits + ancillas)
self.assertEqual(qc.clbits, clbits)
self.assertEqual(qc.ancillas, ancillas)
self.assertEqual(qc.qregs, [])
self.assertEqual(qc.cregs, [])
def test_circuit_constructor_on_invalid_bits(self):
"""Verify we raise if passed not a Bit."""
with self.assertRaisesRegex(CircuitError, "Expected an instance of"):
_ = QuantumCircuit([3.14])
def test_raise_if_bits_already_present(self):
"""Verify we raise when attempting to add a Bit already in the circuit."""
qubits = [Qubit()]
with self.assertRaisesRegex(CircuitError, "bits found already"):
_ = QuantumCircuit(qubits, qubits)
qc = QuantumCircuit(qubits)
with self.assertRaisesRegex(CircuitError, "bits found already"):
qc.add_bits(qubits)
qr = QuantumRegister(1, "qr")
qc = QuantumCircuit(qr)
with self.assertRaisesRegex(CircuitError, "bits found already"):
qc.add_bits(qr[:])
def test_addding_individual_bit(self):
"""Verify we can add a single bit to a circuit."""
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
new_bit = Qubit()
qc.add_bits([new_bit])
self.assertEqual(qc.qubits, list(qr) + [new_bit])
self.assertEqual(qc.qregs, [qr])
def test_inserted_ancilla_bits_are_added_to_qubits(self):
"""Verify AncillaQubits added via .add_bits are added to .qubits."""
anc = AncillaQubit()
qb = Qubit()
qc = QuantumCircuit()
qc.add_bits([anc, qb])
self.assertEqual(qc.qubits, [anc, qb])
class TestGatesOnWires(QiskitTestCase):
"""Test gates on wires."""
def test_circuit_single_wire_h(self):
"""Test circuit on wire (H gate)."""
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
circuit.h(1)
expected = QuantumCircuit(qreg)
expected.h(qreg[1])
self.assertEqual(circuit, expected)
def test_circuit_two_wire_cx(self):
"""Test circuit two wires (CX gate)."""
qreg = QuantumRegister(2)
expected = QuantumCircuit(qreg)
expected.cx(qreg[0], qreg[1])
circuit = QuantumCircuit(qreg)
circuit.cx(0, 1)
self.assertEqual(circuit, expected)
def test_circuit_single_wire_measure(self):
"""Test circuit on wire (measure gate)."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg, creg)
circuit.measure(1, 1)
expected = QuantumCircuit(qreg, creg)
expected.measure(qreg[1], creg[1])
self.assertEqual(circuit, expected)
def test_circuit_multi_qregs_h(self):
"""Test circuit multi qregs and wires (H gate)."""
qreg0 = QuantumRegister(2)
qreg1 = QuantumRegister(2)
circuit = QuantumCircuit(qreg0, qreg1)
circuit.h(0)
circuit.h(2)
expected = QuantumCircuit(qreg0, qreg1)
expected.h(qreg0[0])
expected.h(qreg1[0])
self.assertEqual(circuit, expected)
def test_circuit_multi_qreg_cregs_measure(self):
"""Test circuit multi qregs/cregs and wires (measure)."""
qreg0 = QuantumRegister(2)
creg0 = ClassicalRegister(2)
qreg1 = QuantumRegister(2)
creg1 = ClassicalRegister(2)
circuit = QuantumCircuit(qreg0, qreg1, creg0, creg1)
circuit.measure(0, 2)
circuit.measure(2, 1)
expected = QuantumCircuit(qreg0, qreg1, creg0, creg1)
expected.measure(qreg0[0], creg1[0])
expected.measure(qreg1[0], creg0[1])
self.assertEqual(circuit, expected)
def test_circuit_barrier(self):
"""Test barrier on wires."""
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.barrier(0)
circuit.barrier(2)
expected = QuantumCircuit(qreg01, qreg23)
expected.barrier(qreg01[0])
expected.barrier(qreg23[0])
self.assertEqual(circuit, expected)
def test_circuit_conditional(self):
"""Test conditional on wires."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(4)
circuit = QuantumCircuit(qreg, creg)
circuit.h(0).c_if(creg, 3)
expected = QuantumCircuit(qreg, creg)
expected.h(qreg[0]).c_if(creg, 3)
self.assertEqual(circuit, expected)
def test_circuit_qwire_out_of_range(self):
"""Fail if quantum wire is out of range."""
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
self.assertRaises(CircuitError, circuit.h, 99) # circuit.h(99)
def test_circuit_cwire_out_of_range(self):
"""Fail if classical wire is out of range."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg, creg)
self.assertRaises(CircuitError, circuit.measure, 1, 99) # circuit.measure(1, 99)
def test_circuit_initialize(self):
"""Test initialize on wires."""
init_vector = [0.5, 0.5, 0.5, 0.5]
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.initialize(init_vector, [0, 2])
expected = QuantumCircuit(qreg01, qreg23)
expected.initialize(init_vector, [qreg01[0], qreg23[0]])
self.assertEqual(circuit, expected)
def test_circuit_initialize_single_qubit(self):
"""Test initialize on single qubit."""
init_vector = [numpy.sqrt(0.5), numpy.sqrt(0.5)]
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
circuit.initialize(init_vector, qreg[0])
expected = QuantumCircuit(qreg)
expected.initialize(init_vector, [qreg[0]])
self.assertEqual(circuit, expected)
def test_mixed_register_and_registerless_indexing(self):
"""Test indexing if circuit contains bits in and out of registers."""
bits = [Qubit(), Qubit()]
qreg = QuantumRegister(3, "q")
circuit = QuantumCircuit(bits, qreg)
for i in range(len(circuit.qubits)):
circuit.rz(i, i)
expected_qubit_order = bits + qreg[:]
expected_circuit = QuantumCircuit(bits, qreg)
for i in range(len(expected_circuit.qubits)):
expected_circuit.rz(i, expected_qubit_order[i])
self.assertEqual(circuit.data, expected_circuit.data)
class TestGatesOnWireRange(QiskitTestCase):
"""Test gates on wire range."""
def test_wire_range(self):
"""Test gate wire range"""
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
circuit.h(range(0, 2))
expected = QuantumCircuit(qreg)
expected.h(qreg[0:2])
self.assertEqual(circuit, expected)
def test_circuit_multi_qregs_h(self):
"""Test circuit multi qregs in range of wires (H gate)."""
qreg0 = QuantumRegister(2)
qreg1 = QuantumRegister(2)
circuit = QuantumCircuit(qreg0, qreg1)
circuit.h(range(0, 3))
expected = QuantumCircuit(qreg0, qreg1)
expected.h(qreg0[0])
expected.h(qreg0[1])
expected.h(qreg1[0])
self.assertEqual(circuit, expected)
def test_circuit_multi_qreg_cregs_measure(self):
"""Test circuit multi qregs in range of wires (measure)."""
qreg0 = QuantumRegister(2)
creg0 = ClassicalRegister(2)
qreg1 = QuantumRegister(2)
creg1 = ClassicalRegister(2)
circuit = QuantumCircuit(qreg0, qreg1, creg0, creg1)
circuit.measure(range(1, 3), range(0, 4, 2))
expected = QuantumCircuit(qreg0, qreg1, creg0, creg1)
expected.measure(qreg0[1], creg0[0])
expected.measure(qreg1[0], creg1[0])
self.assertEqual(circuit, expected)
def test_circuit_barrier(self):
"""Test barrier on range of wires with multi regs."""
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.barrier(range(0, 3))
expected = QuantumCircuit(qreg01, qreg23)
expected.barrier(qreg01[0], qreg01[1], qreg23[0])
self.assertEqual(circuit, expected)
def test_circuit_initialize(self):
"""Test initialize on wires."""
init_vector = [0.5, 0.5, 0.5, 0.5]
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.initialize(init_vector, range(1, 3))
expected = QuantumCircuit(qreg01, qreg23)
expected.initialize(init_vector, [qreg01[1], qreg23[0]])
self.assertEqual(circuit, expected)
def test_circuit_conditional(self):
"""Test conditional on wires."""
qreg0 = QuantumRegister(2)
qreg1 = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg0, qreg1, creg)
circuit.h(range(1, 3)).c_if(creg, 3)
expected = QuantumCircuit(qreg0, qreg1, creg)
expected.h(qreg0[1]).c_if(creg, 3)
expected.h(qreg1[0]).c_if(creg, 3)
self.assertEqual(circuit, expected)
def test_circuit_qwire_out_of_range(self):
"""Fail if quantum wire is out of range."""
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
self.assertRaises(CircuitError, circuit.h, range(9, 99)) # circuit.h(range(9,99))
def test_circuit_cwire_out_of_range(self):
"""Fail if classical wire is out of range."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg, creg)
# circuit.measure(1, range(9,99))
self.assertRaises(CircuitError, circuit.measure, 1, range(9, 99))
class TestGatesOnWireSlice(QiskitTestCase):
"""Test gates on wire slice."""
def test_wire_slice(self):
"""Test gate wire slice"""
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
circuit.h(slice(0, 2))
expected = QuantumCircuit(qreg)
expected.h(qreg[0:2])
self.assertEqual(circuit, expected)
def test_wire_list(self):
"""Test gate wire list of integers"""
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
circuit.h([0, 1])
expected = QuantumCircuit(qreg)
expected.h(qreg[0:2])
self.assertEqual(circuit, expected)
def test_wire_np_int(self):
"""Test gate wire with numpy int"""
numpy_int = numpy.dtype("int").type(2)
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
circuit.h(numpy_int)
expected = QuantumCircuit(qreg)
expected.h(qreg[2])
self.assertEqual(circuit, expected)
def test_wire_np_1d_array(self):
"""Test gate wire with numpy array (one-dimensional)"""
numpy_arr = numpy.array([0, 1])
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
circuit.h(numpy_arr)
expected = QuantumCircuit(qreg)
expected.h(qreg[0])
expected.h(qreg[1])
self.assertEqual(circuit, expected)
def test_circuit_multi_qregs_h(self):
"""Test circuit multi qregs in slices of wires (H gate)."""
qreg0 = QuantumRegister(2)
qreg1 = QuantumRegister(2)
circuit = QuantumCircuit(qreg0, qreg1)
circuit.h(slice(0, 3))
expected = QuantumCircuit(qreg0, qreg1)
expected.h(qreg0[0])
expected.h(qreg0[1])
expected.h(qreg1[0])
self.assertEqual(circuit, expected)
def test_circuit_multi_qreg_cregs_measure(self):
"""Test circuit multi qregs in slices of wires (measure)."""
qreg0 = QuantumRegister(2)
creg0 = ClassicalRegister(2)
qreg1 = QuantumRegister(2)
creg1 = ClassicalRegister(2)
circuit = QuantumCircuit(qreg0, qreg1, creg0, creg1)
circuit.measure(slice(1, 3), slice(0, 4, 2))
expected = QuantumCircuit(qreg0, qreg1, creg0, creg1)
expected.measure(qreg0[1], creg0[0])
expected.measure(qreg1[0], creg1[0])
self.assertEqual(circuit, expected)
def test_circuit_barrier(self):
"""Test barrier on slice of wires with multi regs."""
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.barrier(slice(0, 3))
expected = QuantumCircuit(qreg01, qreg23)
expected.barrier([qreg01[0], qreg01[1], qreg23[0]])
self.assertEqual(circuit, expected)
def test_circuit_initialize(self):
"""Test initialize on wires."""
init_vector = [0.5, 0.5, 0.5, 0.5]
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.initialize(init_vector, slice(1, 3))
expected = QuantumCircuit(qreg01, qreg23)
expected.initialize(init_vector, [qreg01[1], qreg23[0]])
self.assertEqual(circuit, expected)
def test_circuit_conditional(self):
"""Test conditional on wires."""
qreg0 = QuantumRegister(2)
qreg1 = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg0, qreg1, creg)
circuit.h(slice(1, 3)).c_if(creg, 3)
expected = QuantumCircuit(qreg0, qreg1, creg)
expected.h(qreg0[1]).c_if(creg, 3)
expected.h(qreg1[0]).c_if(creg, 3)
self.assertEqual(circuit, expected)
def test_circuit_qwire_out_of_range(self):
"""Fail if quantum wire is out of range."""
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
self.assertRaises(CircuitError, circuit.h, slice(9, 99)) # circuit.h(slice(9,99))
def test_circuit_cwire_out_of_range(self):
"""Fail if classical wire is out of range."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg, creg)
# circuit.measure(1, slice(9,99))
self.assertRaises(CircuitError, circuit.measure, 1, slice(9, 99))
def test_wire_np_2d_array(self):
"""Test gate wire with numpy array (two-dimensional). Raises."""
numpy_arr = numpy.array([[0, 1], [2, 3]])
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
self.assertRaises(CircuitError, circuit.h, numpy_arr) # circuit.h(numpy_arr)
class TestBitConditional(QiskitTestCase):
"""Test gates with single bit conditionals."""
def test_bit_conditional_single_gate(self):
"""Test circuit with a single gate conditioned on a bit."""
qreg = QuantumRegister(1)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg, creg)
circuit.h(0).c_if(0, True)
expected = QuantumCircuit(qreg, creg)
expected.h(qreg[0]).c_if(creg[0], True)
self.assertEqual(circuit, expected)
def test_bit_conditional_multiple_gates(self):
"""Test circuit with multiple gates conditioned on individual bits."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
creg1 = ClassicalRegister(1)
circuit = QuantumCircuit(qreg, creg, creg1)
circuit.h(0).c_if(0, True)
circuit.h(1).c_if(1, False)
circuit.cx(1, 0).c_if(2, True)
expected = QuantumCircuit(qreg, creg, creg1)
expected.h(qreg[0]).c_if(creg[0], True)
expected.h(qreg[1]).c_if(creg[1], False)
expected.cx(qreg[1], qreg[0]).c_if(creg1[0], True)
self.assertEqual(circuit, expected)
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
from qiskit import *
print(qiskit.__version__)
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
def find_secret_number(secter_number):
# Using Bernstein Vazirani Algorithm
secret_number = str(secter_number)
circuit = QuantumCircuit(len(secret_number)+1, len(secret_number))
circuit.h(range(len(secret_number)))
circuit.x(len(secret_number))
circuit.h(len(secret_number))
circuit.barrier()
for position,value in enumerate(reversed(secret_number)):
if value == '1':
circuit.cx(position, len(secret_number))
circuit.barrier()
circuit.h(range(len(secret_number)))
circuit.barrier()
circuit.measure(range(len(secret_number)), range(len(secret_number)))
circuit.barrier()
# circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, backend=simulator, shots=1)
result = job.result()
counts = result.get_counts()
# print(counts)
return circuit, counts
secret_number = int(input("enter number: "))
circuit, number = find_secret_number(secret_number)
print('required number: ', number)
circuit.draw(output='mpl')
|
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
from qiskit.visualization import *
from qiskit import QuantumCircuit,transpile
from qiskit import IBMQ
provider=IBMQ.load_account()
provider
provider.backends()
backend=provider.get_backend("ibmq_lima")
backend
plot_gate_map(backend)
plot_error_map(backend)
qc=QuantumCircuit(3)
qc.h(0)
qc.cx(0,1)
qc.z(1)
qc.draw(output="mpl")
qc_transpile=transpile(qc,backend)
qc_transpile.draw(output="mpl")
plot_circuit_layout(qc_transpile,backend)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- 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.
# pylint: disable=cell-var-from-loop
"""
Measurement correction filters.
"""
from copy import deepcopy
from scipy.optimize import minimize
import scipy.linalg as la
import numpy as np
import qiskit
from qiskit.validation.base import Obj
from qiskit import QiskitError
from ...verification.tomography import count_keys
class MeasurementFilter():
"""
Measurement error mitigation filter
Produced from a measurement calibration fitter and can be applied
to data
"""
def __init__(self, cal_matrix, state_labels):
"""
Initialize a measurement error mitigation filter using the cal_matrix
from a measurement calibration fitter
Args:
cal_matrix: the calibration matrix for applying the correction
state_labels: the states for the ordering of the cal matrix
"""
self._cal_matrix = cal_matrix
self._state_labels = state_labels
@property
def cal_matrix(self):
"""Return cal_matrix."""
return self._cal_matrix
@property
def state_labels(self):
"""return the state label ordering of the cal matrix"""
return self._state_labels
@state_labels.setter
def state_labels(self, new_state_labels):
"""set the state label ordering of the cal matrix"""
self._state_labels = new_state_labels
@cal_matrix.setter
def cal_matrix(self, new_cal_matrix):
"""Set cal_matrix."""
self._cal_matrix = new_cal_matrix
def apply(self, raw_data, method='least_squares'):
"""
Apply the calibration matrix to results
Args:
raw_data: The data to be corrected. Can be in a number of forms.
Form1: a counts dictionary from results.get_counts
Form2: a list of counts of length==len(state_labels)
Form3: a list of counts of length==M*len(state_labels) where M
is an integer (e.g. for use with the tomography data)
Form4: a qiskit Result
method (str): fitting method. If None, then least_squares is used.
'pseudo_inverse': direct inversion of the A matrix
'least_squares': constrained to have physical probabilities
Returns:
The corrected data in the same form as raw_data
Additional Information:
e.g.
calcircuits, state_labels = complete_measurement_calibration(
qiskit.QuantumRegister(5))
job = qiskit.execute(calcircuits)
meas_fitter = CompleteMeasFitter(job.results(),
state_labels)
meas_filter = MeasurementFilter(meas_fitter.cal_matrix)
job2 = qiskit.execute(my_circuits)
result2 = job2.results()
error_mitigated_counts = meas_filter.apply(
result2.get_counts('circ1'))
"""
# check forms of raw_data
if isinstance(raw_data, dict):
# counts dictionary
data_format = 0
# convert to form2
raw_data2 = [np.zeros(len(self._state_labels), dtype=float)]
for stateidx, state in enumerate(self._state_labels):
raw_data2[0][stateidx] = raw_data.get(state, 0)
elif isinstance(raw_data, list):
size_ratio = len(raw_data)/len(self._state_labels)
if len(raw_data) == len(self._state_labels):
data_format = 1
raw_data2 = [raw_data]
elif int(size_ratio) == size_ratio:
data_format = 2
size_ratio = int(size_ratio)
# make the list into chunks the size of state_labels for easier
# processing
raw_data2 = np.zeros([size_ratio, len(self._state_labels)])
for i in range(size_ratio):
raw_data2[i][:] = raw_data[
i * len(self._state_labels):(i + 1)*len(
self._state_labels)]
else:
raise QiskitError("Data list is not an integer multiple "
"of the number of calibrated states")
elif isinstance(raw_data, qiskit.result.result.Result):
# extract out all the counts, re-call the function with the
# counts and push back into the new result
new_result = deepcopy(raw_data)
for resultidx, _ in enumerate(raw_data.results):
new_counts = self.apply(
raw_data.get_counts(resultidx), method=method)
new_result.results[resultidx].data.counts = \
new_result.results[resultidx]. \
data.counts.from_dict(new_counts)
return new_result
else:
raise QiskitError("Unrecognized type for raw_data.")
if method == 'pseudo_inverse':
pinv_cal_mat = la.pinv(self._cal_matrix)
# Apply the correction
for data_idx, _ in enumerate(raw_data2):
if method == 'pseudo_inverse':
raw_data2[data_idx] = np.dot(
pinv_cal_mat, raw_data2[data_idx])
elif method == 'least_squares':
nshots = sum(raw_data2[data_idx])
def fun(x):
return sum(
(raw_data2[data_idx] - np.dot(self._cal_matrix, x))**2)
x0 = np.random.rand(len(self._state_labels))
x0 = x0 / sum(x0)
cons = ({'type': 'eq', 'fun': lambda x: nshots - sum(x)})
bnds = tuple((0, nshots) for x in x0)
res = minimize(fun, x0, method='SLSQP',
constraints=cons, bounds=bnds, tol=1e-6)
raw_data2[data_idx] = res.x
else:
raise QiskitError("Unrecognized method.")
if data_format == 2:
# flatten back out the list
raw_data2 = raw_data2.flatten()
elif data_format == 0:
# convert back into a counts dictionary
new_count_dict = {}
for stateidx, state in enumerate(self._state_labels):
if raw_data2[0][stateidx] != 0:
new_count_dict[state] = raw_data2[0][stateidx]
raw_data2 = new_count_dict
else:
# TODO: should probably change to:
# raw_data2 = raw_data2[0].tolist()
raw_data2 = raw_data2[0]
return raw_data2
class TensoredFilter():
"""
Tensored measurement error mitigation filter
Produced from a tensored measurement calibration fitter and can be applied
to data
"""
def __init__(self, cal_matrices, substate_labels_list):
"""
Initialize a tensored measurement error mitigation filter using
the cal_matrices from a tensored measurement calibration fitter
Args:
cal_matrices: the calibration matrices for applying the correction
qubit_list_sizes: the lengths of the lists in mit_pattern
(see tensored_meas_cal in circuits.py for mit_pattern)
substate_labels_list (list of lists): for each calibration matrix
a list of the states (as strings, states in the subspace)
"""
self._cal_matrices = cal_matrices
self._qubit_list_sizes = []
self._indices_list = []
self._substate_labels_list = []
self.substate_labels_list = substate_labels_list
@property
def cal_matrices(self):
"""Return cal_matrices."""
return self._cal_matrices
@cal_matrices.setter
def cal_matrices(self, new_cal_matrices):
"""Set cal_matrices."""
self._cal_matrices = deepcopy(new_cal_matrices)
@property
def substate_labels_list(self):
"""Return _substate_labels_list"""
return self._substate_labels_list
@substate_labels_list.setter
def substate_labels_list(self, new_substate_labels_list):
"""Return _substate_labels_list"""
self._substate_labels_list = new_substate_labels_list
# get the number of qubits in each subspace
self._qubit_list_sizes = []
for _, substate_label_list in enumerate(self._substate_labels_list):
self._qubit_list_sizes.append(
int(np.log2(len(substate_label_list))))
# get the indices in the calibration matrix
self._indices_list = []
for _, sub_labels in enumerate(self._substate_labels_list):
self._indices_list.append(
{lab: ind for ind, lab in enumerate(sub_labels)})
@property
def qubit_list_sizes(self):
"""Return _qubit_list_sizes"""
return self._qubit_list_sizes
@property
def nqubits(self):
"""Return the number of qubits"""
return sum(self._qubit_list_sizes)
def apply(self, raw_data, method='least_squares'):
"""
Apply the calibration matrices to results
Args:
raw_data: The data to be corrected. Can be in a number of forms.
a counts dictionary from results.get_countsphy data);
or a qiskit Result
method (str): fitting method. If None, then least_squares is used.
'pseudo_inverse': direct inversion of the cal matrices
'least_squares': constrained to have physical probabilities
Returns:
The corrected data in the same form as raw_data
"""
all_states = count_keys(self.nqubits)
num_of_states = 2**self.nqubits
# check forms of raw_data
if isinstance(raw_data, dict):
# counts dictionary
# convert to list
raw_data2 = [np.zeros(num_of_states, dtype=float)]
for state, count in raw_data.items():
stateidx = int(state, 2)
raw_data2[0][stateidx] = count
elif isinstance(raw_data, qiskit.result.result.Result):
# extract out all the counts, re-call the function with the
# counts and push back into the new result
new_result = deepcopy(raw_data)
for resultidx, _ in enumerate(raw_data.results):
new_counts = self.apply(
raw_data.get_counts(resultidx), method=method)
new_result.results[resultidx].data.counts = \
Obj(**new_counts)
return new_result
else:
raise QiskitError("Unrecognized type for raw_data.")
if method == 'pseudo_inverse':
pinv_cal_matrices = []
for cal_mat in self._cal_matrices:
pinv_cal_matrices.append(la.pinv(cal_mat))
# Apply the correction
for data_idx, _ in enumerate(raw_data2):
if method == 'pseudo_inverse':
inv_mat_dot_raw = np.zeros([num_of_states], dtype=float)
for state1_idx, state1 in enumerate(all_states):
for state2_idx, state2 in enumerate(all_states):
if raw_data2[data_idx][state2_idx] == 0:
continue
product = 1.
end_index = self.nqubits
for p_ind, pinv_mat in enumerate(pinv_cal_matrices):
start_index = end_index - \
self._qubit_list_sizes[p_ind]
state1_as_int = \
self._indices_list[p_ind][
state1[start_index:end_index]]
state2_as_int = \
self._indices_list[p_ind][
state2[start_index:end_index]]
end_index = start_index
product *= \
pinv_mat[state1_as_int][state2_as_int]
if product == 0:
break
inv_mat_dot_raw[state1_idx] += \
(product * raw_data2[data_idx][state2_idx])
raw_data2[data_idx] = inv_mat_dot_raw
elif method == 'least_squares':
def fun(x):
mat_dot_x = np.zeros([num_of_states], dtype=float)
for state1_idx, state1 in enumerate(all_states):
mat_dot_x[state1_idx] = 0.
for state2_idx, state2 in enumerate(all_states):
if x[state2_idx] != 0:
product = 1.
end_index = self.nqubits
for c_ind, cal_mat in \
enumerate(self._cal_matrices):
start_index = end_index - \
self._qubit_list_sizes[c_ind]
state1_as_int = \
self._indices_list[c_ind][
state1[start_index:end_index]]
state2_as_int = \
self._indices_list[c_ind][
state2[start_index:end_index]]
end_index = start_index
product *= \
cal_mat[state1_as_int][state2_as_int]
if product == 0:
break
mat_dot_x[state1_idx] += \
(product * x[state2_idx])
return sum(
(raw_data2[data_idx] - mat_dot_x)**2)
x0 = np.random.rand(num_of_states)
x0 = x0 / sum(x0)
nshots = sum(raw_data2[data_idx])
cons = ({'type': 'eq', 'fun': lambda x: nshots - sum(x)})
bnds = tuple((0, nshots) for x in x0)
res = minimize(fun, x0, method='SLSQP',
constraints=cons, bounds=bnds, tol=1e-6)
raw_data2[data_idx] = res.x
else:
raise QiskitError("Unrecognized method.")
# convert back into a counts dictionary
new_count_dict = {}
for state_idx, state in enumerate(all_states):
if raw_data2[0][state_idx] != 0:
new_count_dict[state] = raw_data2[0][state_idx]
return new_count_dict
|
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)
state = Statevector(qc)
plot_bloch_multivector(state)
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
1 + cos(2*pi/3) + 1j*sin(2*pi/3) + cos(4*pi/3) + 1j*sin(4*pi/3)
1 + cos(4*pi/3) + 1j*sin(4*pi/3) + cos(8*pi/3) + 1j*sin(8*pi/3)
cos(2*pi/3), cos(4*pi/3)
|
https://github.com/DRA-chaos/Quantum-Classical-Hyrid-Neural-Network-for-binary-image-classification-using-PyTorch-Qiskit-pipeline
|
DRA-chaos
|
!pip install qiskit
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch.autograd import Function
from torchvision import datasets, transforms
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import qiskit
from qiskit import transpile, assemble
from qiskit.visualization import *
def to_numbers(tensor_list):
num_list = []
for tensor in tensor_list:
num_list += [tensor.item()]
return num_list
import numpy as np
import torch
from torch.autograd import Function
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import datasets, transforms
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, execute
from qiskit.circuit import Parameter
from qiskit import Aer
from tqdm import tqdm
from matplotlib import pyplot as plt
%matplotlib inline
class QuantumCircuit:
"""
This class provides a simple interface for interaction
with the quantum circuit
"""
def __init__(self, n_qubits, backend, shots):
# --- Circuit definition ---
self._circuit = qiskit.QuantumCircuit(n_qubits)
all_qubits = [i for i in range(n_qubits)]
self.theta = qiskit.circuit.Parameter('theta')
self._circuit.h(all_qubits)
self._circuit.barrier()
self._circuit.ry(self.theta, all_qubits)
self._circuit.measure_all()
# ---------------------------
self.backend = backend
self.shots = shots
def run(self, thetas):
t_qc = transpile(self._circuit,
self.backend)
qobj = assemble(t_qc,
shots=self.shots,
parameter_binds = [{self.theta: theta} for theta in thetas])
job = self.backend.run(qobj)
result = job.result().get_counts()
counts = np.array(list(result.values()))
states = np.array(list(result.keys())).astype(float)
# Compute probabilities for each state
probabilities = counts / self.shots
# Get state expectation
expectation = np.sum(states * probabilities)
return np.array([expectation])
simulator = qiskit.Aer.get_backend('qasm_simulator')
circuit = QuantumCircuit(1, simulator, 100)
print('Expected value for rotation pi {}'.format(circuit.run([np.pi])[0]))
circuit._circuit.draw()
class HybridFunction(Function):
""" Hybrid quantum - classical function definition """
@staticmethod
def forward(ctx, input, quantum_circuit, shift):
""" Forward pass computation """
ctx.shift = shift
ctx.quantum_circuit = quantum_circuit
expectation_z = ctx.quantum_circuit.run(input[0].tolist())
result = torch.tensor([expectation_z])
ctx.save_for_backward(input, result)
return result
@staticmethod
def backward(ctx, grad_output):
""" Backward pass computation """
input, expectation_z = ctx.saved_tensors
input_list = np.array(input.tolist())
shift_right = input_list + np.ones(input_list.shape) * ctx.shift
shift_left = input_list - np.ones(input_list.shape) * ctx.shift
gradients = []
for i in range(len(input_list)):
expectation_right = ctx.quantum_circuit.run(shift_right[i])
expectation_left = ctx.quantum_circuit.run(shift_left[i])
gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left])
gradients.append(gradient)
gradients = np.array([gradients]).T
return torch.tensor([gradients]).float() * grad_output.float(), None, None
class Hybrid(nn.Module):
""" Hybrid quantum - classical layer definition """
def __init__(self, backend, shots, shift):
super(Hybrid, self).__init__()
self.quantum_circuit = QuantumCircuit(1, backend, shots)
self.shift = shift
def forward(self, input):
return HybridFunction.apply(input, self.quantum_circuit, self.shift)
import torchvision
transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors
cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform)
labels = cifar_trainset.targets # get the labels for the data
labels = np.array(labels)
idx1 = np.where(labels == 0) # filter on aeroplanes
idx2 = np.where(labels == 1) # filter on automobiles
# Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set)
n=100
# concatenate the data indices
idx = np.concatenate((idx1[0][0:n],idx2[0][0:n]))
# create the filtered dataset for our training set
cifar_trainset.targets = labels[idx]
cifar_trainset.data = cifar_trainset.data[idx]
train_loader = torch.utils.data.DataLoader(cifar_trainset, batch_size=1, shuffle=True)
import numpy as np
import matplotlib.pyplot as plt
n_samples_show = 8
data_iter = iter(train_loader)
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 2))
while n_samples_show > 0:
images, targets = data_iter.__next__()
images=images.squeeze()
#axes[n_samples_show - 1].imshow( tf.shape( tf.squeeze(images[0]) ),cmap='gray' )
#plt.imshow((tf.squeeze(images[0])))
#plt.imshow( tf.shape( tf.squeeze(x_train) ) )
#axes[n_samples_show - 1].imshow(images[0].numpy().squeeze(), cmap='gray')
axes[n_samples_show - 1].imshow(images[0].numpy(), cmap='gray')
axes[n_samples_show - 1].set_xticks([])
axes[n_samples_show - 1].set_yticks([])
axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item()))
n_samples_show -= 1
import torchvision
transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors
cifar_testset = datasets.CIFAR10(root='./data1', train=False, download=True, transform=transform)
labels = cifar_testset.targets # get the labels for the data
labels = np.array(labels)
idx1 = np.where(labels == 0) # filter on aeroplanes
idx2 = np.where(labels == 1) # filter on automobiles
# Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set)
n=100
# concatenate the data indices
idx = np.concatenate((idx1[0][0:n],idx2[0][0:n]))
# create the filtered dataset for our training set
cifar_testset.targets = labels[idx]
cifar_testset.data = cifar_testset.data[idx]
test_loader = torch.utils.data.DataLoader(cifar_testset, batch_size=1, shuffle=True)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(500, 500)
self.fc2 = nn.Linear(500, 1)
self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(1, -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.hybrid(x)
return torch.cat((x, 1 - x), -1)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 5
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Now plotting the training graph
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 10
loss_listA = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_listA.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listA[-1]))
#Now plotting the training graph
plt.plot(loss_listA)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 15
loss_listb = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_listb.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listb[-1]))
#Now plotting the training graph
plt.plot(loss_listb)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.01)
loss_func = nn.NLLLoss()
epochs = 5
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Now plotting the training graph
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.01)
loss_func = nn.NLLLoss()
epochs = 10
loss_listc = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_listc.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listc[-1]))
#Now plotting the training graph
plt.plot(loss_listc)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.01)
loss_func = nn.NLLLoss()
epochs = 15
loss_listd = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_listd.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listd[-1]))
#Now plotting the training graph
plt.plot(loss_listd)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.0001)
loss_func = nn.NLLLoss()
epochs = 5
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Now plotting the training graph
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.SGD(model.parameters(), lr=0.0001)
loss_func = nn.NLLLoss()
epochs = 5
loss_listF = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_listF.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listF[-1]))
#Now plotting the training graph
plt.plot(loss_listF)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.SGD(model.parameters(), lr=0.0001)
loss_func = nn.NLLLoss()
epochs = 15
loss_listF = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_listF.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listF[-1]))
#Now plotting the training graph
plt.plot(loss_listF)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adadelta(model.parameters(), lr=0.0001)
loss_func = nn.NLLLoss()
epochs = 10
loss_listF = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_listF.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listF[-1]))
#Now plotting the training graph
plt.plot(loss_listF)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adadelta(model.parameters(), lr=0.0001)
loss_func = nn.NLLLoss()
epochs = 15
loss_listF = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_listF.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listF[-1]))
#Now plotting the training graph
plt.plot(loss_listF)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
##Adagrad
model = Net()
optimizer = optim.Adagrad(model.parameters(), lr=0.0001)
loss_func = nn.NLLLoss()
epochs = 5
loss_listG = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_listG.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listG[-1]))
#Now plotting the training graph
plt.plot(loss_listG)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100))
#RMSprop
model = Net()
optimizer = optim.RMSprop(model.parameters(), lr=0.0001)
loss_func = nn.NLLLoss()
epochs = 5
loss_listG = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_listG.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listG[-1]))
#Now plotting the training graph
plt.plot(loss_listG)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model = Net()
optimizer = optim.RMSprop(model.parameters(), lr=0.0001)
loss_func = nn.NLLLoss()
epochs = 10
loss_listH = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_listH.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listH[-1]))
#Now plotting the training graph
plt.plot(loss_listH)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100))
model = Net()
optimizer = optim.RMSprop(model.parameters(), lr=0.0001)
loss_func = nn.NLLLoss()
epochs = 15
loss_listH = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_listH.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listH[-1]))
#Now plotting the training graph
plt.plot(loss_listH)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100))
model = Net()
optimizer = optim.RMSprop(model.parameters(), lr=0.0001)
loss_func = nn.NLLLoss()
epochs = 20
loss_listH = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_listH.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listH[-1]))
#Now plotting the training graph
plt.plot(loss_listH)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100))
#ADAM 20 epochs
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.0001)
loss_func = nn.NLLLoss()
epochs = 20
loss_listH = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_listH.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listH[-1]))
#Now plotting the training graph
plt.plot(loss_listH)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100))
loss.item()
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100))
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100))
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.RMSprop(model.parameters(), lr=0.0001)
loss_func = nn.NLLLoss()
epochs = 10
loss_listD = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_listD.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listD[-1]))
#Now plotting the training graph
plt.plot(loss_listD)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.0001)
loss_func = nn.NLLLoss()
epochs = 10
loss_listD = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_listD.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listD[-1]))
#Now plotting the training graph
plt.plot(loss_listD)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.0001)
loss_func = nn.NLLLoss()
epochs = 15
loss_listE = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_listE.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listE[-1]))
#Now plotting the training graph
plt.plot(loss_listE)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 10
loss_list1 = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list1.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list1[-1]))
#Alongside, let's also plot the data
plt.plot(loss_list1)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 15
loss_list2 = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list2.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list2[-1]))
#Alongside, let's also plot the data
plt.plot(loss_list2)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 20
loss_list3 = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list3.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list3[-1]))
#Alongside, let's also plot the data
plt.plot(loss_list3)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 30
loss_list4 = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list4.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list4[-1]))
#Alongside, let's also plot the data
plt.plot(loss_list4)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adamax(model.parameters(), lr=0.0001)
loss_func = nn.NLLLoss()
epochs = 5
loss_list4 = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list4.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list4[-1]))
#Alongside, let's also plot the data
plt.plot(loss_list4)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.CrossEntropyLoss()
epochs = 5
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Now plotting the training graph
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Cross Entropy loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.CrossEntropyLoss()
epochs = 10
loss_listK = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_listK.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listK[-1]))
#Now plotting the training graph
plt.plot(loss_listK)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Cross Entropy loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.CrossEntropyLoss()
epochs = 15
loss_listL = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_listL.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listL[-1]))
#Now plotting the training graph
plt.plot(loss_listL)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Cross Entropy loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.PoissonNLLLoss()
epochs = 5
loss_listK = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_listK.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listK[-1]))
#Now plotting the training graph
plt.plot(loss_listK)
plt.title('Negative log likelihood with Poisson')
plt.xlabel('Training Iterations')
plt.ylabel('NLL with Poisson distribution.')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2022-2023 Qiskit on IQM developers
#
# 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.
"""
Error profile and fake backend base class for simulating IQM quantum computers.
"""
from __future__ import annotations
from copy import deepcopy
from dataclasses import dataclass
from itertools import permutations
from typing import Any, Optional, Union
from qiskit import QuantumCircuit
from qiskit.providers import JobV1, Options
from qiskit_aer import AerSimulator
from qiskit_aer.noise import NoiseModel
from qiskit_aer.noise.errors import depolarizing_error, thermal_relaxation_error
from iqm.iqm_client import QuantumArchitectureSpecification
from iqm.qiskit_iqm.iqm_backend import IQM_TO_QISKIT_GATE_NAME, IQMBackendBase
# pylint: disable=too-many-instance-attributes
@dataclass
class IQMErrorProfile:
r"""Properties of an IQM QPU specimen, used for constructing an error model.
All the attributes of this class refer to the qubits of the QPU using their physical names.
Args:
t1s: maps qubits to their :math:`T_1` times (in ns)
t2s: maps qubits to the :math:`T_2` times (in ns)
single_qubit_gate_depolarizing_error_parameters: Depolarizing error parameters for single-qubit gates.
Maps single-qubit gate names to a mapping of qubits (on which the gate acts) to a depolarizing error.
The error, used in a one-qubit depolarizing channel, concatenated with a thermal relaxation channel,
leads to average gate fidelities that would be determined by benchmarking.
two_qubit_gate_depolarizing_error_parameters: Depolarizing error parameters for two-qubit gates.
Maps two-qubit gate names to a mapping of pairs of qubits (on which the gate acts) to a depolarizing error.
The error, used in a two-qubit depolarizing channel, concatenated with thermal relaxation channels for the
qubits, leads to average gate fidelities that would be determined by benchmarking.
single_qubit_gate_durations: Gate duration (in ns) for each single-qubit gate
two_qubit_gate_durations: Gate duration (in ns) for each two-qubit gate.
readout_errors: Maps physical qubit names to dicts that describe their single-qubit readout errors.
For each qubit, the inner dict maps the state labels "0" and "1" to the probability :math:`P(\neg x|x)`
of observing the state :math:`\ket{\neg x}` given the true state is :math:`\ket{x}`.
name: Identifier of the QPU specimen.
Example:
.. code-block::
IQMErrorProfile(
t1s={"QB1": 10000.0, "QB2": 12000.0, "QB3": 14000.0},
t2s={"QB1": 10000.0, "QB2": 12000.0, "QB3": 13000.0},
single_qubit_gate_depolarizing_error_parameters={"r": {"QB1": 0.0005, "QB2": 0.0004, "QB3": 0.0010}},
two_qubit_gate_depolarizing_error_parameters={"cz": {("QB1", "QB2"): 0.08, ("QB2", "QB3"): 0.03}},
single_qubit_gate_durations={"r": 50.},
two_qubit_gate_durations={"cz": 100.},
readout_errors={"QB1": {"0": 0.02, "1": 0.03},
"QB2": {"0": 0.02, "1": 0.03},
"QB3": {"0": 0.02, "1": 0.03}},
name="threequbit-example_sample"
)
"""
t1s: dict[str, float]
t2s: dict[str, float]
single_qubit_gate_depolarizing_error_parameters: dict[str, dict[str, float]]
two_qubit_gate_depolarizing_error_parameters: dict[str, dict[tuple[str, str], float]]
single_qubit_gate_durations: dict[str, float]
two_qubit_gate_durations: dict[str, float]
readout_errors: dict[str, dict[str, float]]
name: Optional[str] = None
class IQMFakeBackend(IQMBackendBase):
"""Simulated backend that mimics the behaviour of IQM quantum computers.
Can be used to perform noisy gate-level simulations of quantum circuit execution on IQM hardware.
A fake backend contains information about a specific IQM system, such as the quantum architecture (number of qubits,
connectivity), the native gate set, and a noise model based on system parameters such as relaxation (:math:`T_1`)
and dephasing (:math:`T_2`) times, gate infidelities, and readout errors.
Args:
architecture: Quantum architecture associated with the backend instance.
error_profile: Characteristics of a particular QPU specimen.
"""
def __init__(
self,
architecture: QuantumArchitectureSpecification,
error_profile: IQMErrorProfile,
name: str = "IQMFakeBackend",
**kwargs,
):
super().__init__(architecture, **kwargs)
self._validate_architecture_and_error_profile(architecture, error_profile)
self.__architecture, self.__error_profile = architecture, error_profile
self.noise_model = self._create_noise_model(architecture, error_profile)
self.name = name
@property
def error_profile(self) -> IQMErrorProfile:
"""Error profile of this instance of IQM fake backend"""
return deepcopy(self.__error_profile)
@error_profile.setter
def error_profile(self, value: IQMErrorProfile) -> None:
""""""
raise NotImplementedError(
"Setting error profile of existing fake backend is not allowed. "
"You may consider using the method .copy_with_error_profile."
)
def copy_with_error_profile(self, new_error_profile: IQMErrorProfile) -> IQMFakeBackend:
"""Return another instance of IQMFakeBackend, which has the same quantum architecture but a different error
profile."""
return self.__class__(self.__architecture, new_error_profile)
@staticmethod
def _validate_architecture_and_error_profile(
architecture: QuantumArchitectureSpecification, error_profile: IQMErrorProfile
) -> None:
"""Verifies that the parameters of the QPU error profile match the constraints of its quantum architecture.
Raises:
ValueError: when length of `t1s` and number of qubits do not match.
ValueError: when length of `t2s` and number of qubits do not match.
ValueError: when length of `one_qubit_gate` parameter lists and number of qubits do not match.
ValueError: when length of `two_qubit_gate` parameter lists and number of couplings do not match.
ValueError: when gates in gate parameter lists are not supported by the quantum architecture.
"""
num_qubits = len(architecture.qubits)
# Check that T1 list has one element for each qubit
if len(error_profile.t1s) != num_qubits:
raise ValueError(
f"Length of t1s ({len(error_profile.t1s)}) and number of qubits ({num_qubits}) should match."
)
# Check that T2 list has one element for each qubit
if len(error_profile.t2s) != num_qubits:
raise ValueError(
f"Length of t2s ({len(error_profile.t2s)}) and number of qubits ({num_qubits}) should match."
)
property_dict: dict[str, dict[Any, float]]
# Check that one-qubit gate parameter qubits match those of the architecture
for property_name, property_dict in [
("depolarizing rates", error_profile.single_qubit_gate_depolarizing_error_parameters),
]:
gate_dict: dict[Any, float]
for gate, gate_dict in property_dict.items():
if set(gate_dict.keys()) != set(architecture.qubits):
raise ValueError(
(
f"The qubits specified for one-qubit gate {property_name} ({set(gate_dict.keys())}) "
f"don't match the qubits of the quantum architecture "
f"`{architecture.name}` ({architecture.qubits})."
)
)
# Check that two-qubit gate parameter couplings match those of the architecture
for property_name, property_dict in [
("depolarizing error parameters", error_profile.two_qubit_gate_depolarizing_error_parameters),
]:
for gate, gate_dict in property_dict.items():
if set(gate_dict.keys()) != set(tuple(item) for item in architecture.qubit_connectivity):
raise ValueError(
(
f"The couplings specified for two-qubit gate {property_name} ({set(gate_dict.keys())}) "
f"don't match the couplings of the quantum architecture "
f"`{architecture.name}` ({architecture.qubit_connectivity})."
)
)
# Check that the basis gates of the chip sample match the quantum architecture's
for property_name, specified_gates in [
(
"single_qubit_gate_depolarizing_error_parameters",
error_profile.single_qubit_gate_depolarizing_error_parameters.keys(),
),
(
"two_qubit_gate_depolarizing_error_parameters",
error_profile.two_qubit_gate_depolarizing_error_parameters.keys(),
),
("durations", (error_profile.single_qubit_gate_durations | error_profile.two_qubit_gate_durations).keys()),
]:
for gate in specified_gates:
if gate not in architecture.operations:
raise ValueError(
(
f"Gate `{gate}` in `{property_name}` "
f"is not supported by quantum architecture `{architecture.name}`. "
f"Valid gates: {architecture.operations}"
)
)
if set(error_profile.readout_errors.keys()) != set(architecture.qubits):
raise ValueError(
f"The qubits specified in readout errors ({set(error_profile.readout_errors.keys())}) "
f"don't match the qubits of the quantum architecture "
f"`{architecture.name}` ({architecture.qubits})."
)
def _create_noise_model(
self, architecture: QuantumArchitectureSpecification, error_profile: IQMErrorProfile
) -> NoiseModel:
"""
Builds a noise model from the attributes.
"""
noise_model = NoiseModel(basis_gates=["r", "cz"])
# Add single-qubit gate errors to noise model
for gate in error_profile.single_qubit_gate_depolarizing_error_parameters.keys():
for qb in architecture.qubits:
thermal_relaxation_channel = thermal_relaxation_error(
error_profile.t1s[qb], error_profile.t2s[qb], error_profile.single_qubit_gate_durations[gate]
)
depolarizing_channel = depolarizing_error(
error_profile.single_qubit_gate_depolarizing_error_parameters[gate][qb], 1
)
full_error_channel = thermal_relaxation_channel.compose(depolarizing_channel)
noise_model.add_quantum_error(
full_error_channel, IQM_TO_QISKIT_GATE_NAME[gate], [self.qubit_name_to_index(qb)]
)
# Add two-qubit gate errors to noise model
for gate, rates in error_profile.two_qubit_gate_depolarizing_error_parameters.items():
for (qb1, qb2), rate in rates.items():
for qb_order in permutations((qb1, qb2)):
thermal_relaxation_channel = thermal_relaxation_error(
error_profile.t1s[qb_order[0]],
error_profile.t2s[qb_order[0]],
error_profile.two_qubit_gate_durations[gate],
).tensor(
thermal_relaxation_error(
error_profile.t1s[qb_order[1]],
error_profile.t2s[qb_order[1]],
error_profile.two_qubit_gate_durations[gate],
)
)
depolarizing_channel = depolarizing_error(rate, 2)
full_error_channel = thermal_relaxation_channel.compose(depolarizing_channel)
noise_model.add_quantum_error(
full_error_channel,
IQM_TO_QISKIT_GATE_NAME[gate],
[self.qubit_name_to_index(qb_order[0]), self.qubit_name_to_index(qb_order[1])],
)
# Add readout errors
for qb, readout_error in error_profile.readout_errors.items():
probabilities = [[1 - readout_error["0"], readout_error["0"]], [readout_error["1"], 1 - readout_error["1"]]]
noise_model.add_readout_error(probabilities, [self.qubit_name_to_index(qb)])
return noise_model
@classmethod
def _default_options(cls) -> Options:
return Options(shots=1024, calibration_set_id=None)
@property
def max_circuits(self) -> Optional[int]:
return None
def run(self, run_input: Union[QuantumCircuit, list[QuantumCircuit]], **options) -> JobV1:
"""
Run `run_input` on the fake backend using a simulator.
This method runs circuit jobs (an individual or a list of QuantumCircuit
) and returns a :class:`~qiskit.providers.JobV1` object.
It will run the simulation with a noise model of the fake backend (e.g. Adonis).
Args:
run_input: One or more quantum circuits to simulate on the backend.
options: Any kwarg options to pass to the backend.
Returns:
The job object representing the run.
Raises:
ValueError: If empty list of circuits is provided.
"""
circuits = [run_input] if isinstance(run_input, QuantumCircuit) else run_input
if len(circuits) == 0:
raise ValueError("Empty list of circuits submitted for execution.")
shots = options.get("shots", self.options.shots)
# Create noisy simulator backend and run circuits
sim_noise = AerSimulator(noise_model=self.noise_model)
job = sim_noise.run(circuits, shots=shots)
return job
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from sympy import *
init_printing(use_unicode=True)
r1,r2,r3,s1,s2,s3 = symbols('r_1 r_2 r_3 s_1 s_2 s_3')
I = Matrix([[1,0],[0,1]]); X = Matrix([[0,1],[1,0]]); Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]])
rho = (1/2)*(I+r1*X+r2*Y+r3*Z); sigma = (1/2)*(I+s1*X+s2*Y+s3*Z)
#rho, sigma
def frho(r1,r2,r3):
return (1/2)*(I+r1*X+r2*Y+r3*Z)
def fsigma(s1,s2,s3):
return (1/2)*(I+s1*X+s2*Y+s3*Z)
A = frho(r1,0,r2)*fsigma(0,s2,0)
simplify(A.eigenvals())
A = frho(0,0,r3); B = fsigma(s1,s2,0)
simplify(A*(B**2)*A - B*(A**2)*B)
M = A*B; simplify(M)
simplify(M.eigenvals()) # parecem ser positivos o que esta na raiz e o autovalores
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
# let's randomly pick a number between 0 and 9, and print its value if it is greater than 5
from random import randrange
r = randrange(10)
if r > 5: print(r) # when the condition (r > 5) is valid/true, the code (print(r)) will be executed
# you may need to execute your code more than once to see an outcome
# repeat the same task four times, and also print the value of iteration variable (i)
for i in range(4):
r = randrange(10) # this code belongs to for-loop, and so it is indented
if r > 5: # this code also belongs to for-loop, and so it is indented as well
print("i =",i,"r =",r) # this code belongs to if-statement, and so it is indented with respect to if-statement
# if you are unlucky (with probabability less than 13/100), you may not see any outcome after a single run
# do the same task 100 times, and find the percentage of successful iterations (attempts)
# an iteration (attempt) is successful if the randomly picked number is greater than 5
# the expected percentage is 40, because, out of 10 numbers, there are 4 numbers greater than 5
# but the experimental results differ
success = 0
for i in range(100):
r = randrange(10)
if r > 5:
success = success + 1
print(success,"%")
# each experiment most probably will give different percentage value
# let's randomly pick a number between 0 and 9, and print whether it is less than 6 or not
# we use two conditionals here
r = randrange(10)
print("the picked number is ",r)
if r < 6:
print("it is less than 6")
if r >= 6:
print("it is greater than or equal to 6")
# let's write the same algorithm by using if-else structure
r = randrange(10)
print("the picked number is ",r)
if r < 6:
print("it is less than 6")
else: # if the above condition (r<6) is False
print("it is greater than or equal to 6")
#
# your solution is here
#
from random import randrange
r = randrange(10,51)
if r % 2 ==0: print(r,"is even")
else: print(r,"is odd")
#
# when there are many related conditionals, we can use if-elif-else structure
#
# let's randomly pick an even number between 1 and 99
# then determine whether it is less than 25, between 25 and 50, between 51 and 75, or greater than 75.
r = randrange(2,100,2) # randonmly pick a number in range {2,4,6,...,98}, which satisfies our condition
# let's print this range to verify our claim
print(list(range(2,100,2)))
print() # print an empty line
print("the picked number is",r)
if r < 25:
print("it is less than 25")
elif r<=50: # if the above condition is False and the condition here is True
print("it is between 25 and 50")
elif r<=75: # if both conditions above are False and the condition here is True
print("it is between 51 and 75")
else: # if none of the above conditions is True
print("it is greater than 75")
#
# your solution is here
#
from random import randrange
for N in [100,1000,10000,100000]:
first_half=second_half=0
for i in range(N):
r = randrange(100)
if r<50:
first_half = first_half + 1
else:
second_half=second_half + 1
print(N,"->",first_half/N,second_half/N)
# let's determine whether a randomly picked number between -10 and 100 is prime or not.
# this is a good example for using more than one conditional in different parts of the program
# this is also an example for "break" command, which terminates any loop immediately
r = randrange(-10,101) # pick a number between -10 and 100
print(r) # print is value
if r < 2: print("it is NOT a prime number") # this is by definition
elif r == 2: print("it is a PRIME number") # we already know this
else:
prime=True # we assume that r is prime, and try to falsify this assumption by looking for a divisor in the following loop
for i in range(2,r): # check all integers between 2 and r-1
if r % i ==0: # if i divides r without any reminder (or reminder is zero), then r is not a prime number
print("it is NOT a prime number")
prime=False # our assumption is falsifed
break # TERMINATE the iteration immediately
# we are out of if-scope
# we are out of for-loop-scope
if prime == True: # if our assumption is still True (if it was not falsified inside for-loop)
print("it is a PRIME number")
# this is an example to write a function
# our function will return a Boolean value True or False
def prime(number): # our function takes one parameter (has one argument)
if number < 2: return False # once return command is executed, we exit the function
if number == 2: return True # because of return command, we can use "if" instead of "elif"
if number % 2 == 0: return False # any even number greater than 2 is not prime, because it is divisible by 2
for i in range(3,number,2): # we can skip even integers
if number % i == 0: return False # once we find a divisor of the number, we return False and exit the function
return True # the number has passed all checks until now
# by using "return" command appropriately, the programs can be shortened
# remark that this might not be a good choice everytime for readibility of codes
# let's test our program by printing all prime numbers between -10 and 30
for i in range(-10,30):
# we pass i to the function prime
if prime(i): # the function prime(i) returns True or False
print(i) # this code will be executed if i is prime, i.e., prime(i) returns True
|
https://github.com/victor-onofre/Tutorial_QAOA_maxcut_Qiskit_FallFest
|
victor-onofre
|
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from scipy.optimize import minimize
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
style = {'backgroundcolor': 'lightyellow'} # Style of the drawing of the quantum circuit
Graph_Example_1 = nx.Graph()
Graph_Example_1.add_edges_from([[1,2],[2,3],[1,3]])
nx.draw(Graph_Example_1,with_labels=True,font_weight='bold')
nx.draw(Graph_Example_1,node_color = ['b','b','r'])
Graph_Example_2 = nx.Graph()
Graph_Example_2.add_edges_from([[1,2],[1,3],[4,2],[4,3]])
nx.draw(Graph_Example_2,with_labels=True,font_weight='bold')
nx.draw(Graph_Example_2,node_color = ['r','b','b','r'])
Graph_Example_3 = nx.Graph()
Graph_Example_3.add_edges_from([[1,4],[1,2],[2,5],[4,5],[5,3],[2,3]])
nx.draw(Graph_Example_3,with_labels=True,font_weight='bold')
nx.draw(Graph_Example_3,node_color = ['r','b','b','r','b'])
Graph = nx.Graph()
Graph.add_edges_from([[0,1],[0,3],[3,4],[1,4],[1,2],[4,2]])
nx.draw(Graph,with_labels=True)
Graph.edges()
N = Graph.number_of_nodes() # The number of nodes in the graph
qc = QuantumCircuit(N,N) # Quantum circuit with N qubits and N classical register
gamma = np.pi/8 # parameter gamma for the cost function (maxcut hamiltonian)
#Apply the operator to each edge
for i, j in Graph.edges():
qc.cx(i,j)
qc.rz(2*gamma, j)
qc.cx(i,j)
qc.barrier()
qc.draw(output='mpl', style=style) # Draw the quantum circuit
beta = np.pi/8 # parameter for the mixer hamiltonian
for n in Graph.nodes():
qc.rx(2*beta, n)
# measure the result
qc.barrier(range(N))
qc.measure(range(N), range(N))
qc.draw(output='mpl', style=style,fold= 35)
def qaoa_circuit(G, theta,p):
r"""
############################################
# Compute the QAOA circuit for the graph G
#
# |psi(theta) > = |psi(beta,gamma) > = e^{-i*beta_p*B} e^{-i*gamma_p*C}... e^{-i*beta_1*B} e^{-i*gamma_1*C} H^{otimes n}|0>
#
# where C is the Maxcut hamiltonian, B is the mixer hamiltonian.
#
# G: graph
# theta: parameters,first half is betas, second half is gammas
# p: number of QAOA steps
# return: The QAOA circuit
###########################################
"""
beta = theta[:p] #Parameters beta for the mixer hamiltonian
gamma = theta[p:]#Parameters gamma for the maxcut hamiltonian
N = G.number_of_nodes()#Number of nodes of the graph G
qc = QuantumCircuit(N,N)# Quantum circuit wiht N qubits and N classical register
qc.h(range(N))# Apply the Hadamard gate to all the qubits
# Apply p operators
for k in range(p):
for i, j in G.edges(): #Representation of the maxcut hamiltonian
qc.cx(i,j)
qc.rz(2*gamma[k], j)
qc.cx(i,j)
qc.barrier()
for n in G.nodes(): # Representation of the mixer hamiltonian
qc.rx(2*beta[k], n)
# Measurement in all the qubits
qc.barrier(range(N))
qc.measure(range(N), range(N))
return qc #Returns the quantum circuit
# p is the number of QAOA alternating operators
p = 1
theta = np.array([np.pi/8,np.pi/8])
circuit = qaoa_circuit(Graph, theta,p)
circuit.draw(output='mpl', style=style,fold= 35) # Draw the quantum circuit
#Qiskit uses the least significant bit in the bistring, we need to invert this string
def invert_counts(counts):
r"""
############################################
# Inverted the binary string
#
# counts: The result of running the quantum circuit
# return: The results with binary string inverted
###########################################
"""
inv_counts = {}
for k, v in counts.items():
inv_counts[k[::-1]] = v
return inv_counts
def maxcut_objective_function(x,G):
r"""
############################################
# Compute the maxcut objective function for the binary string x and graph G
#
# G: graph
# x: binary string
# return: The cost of the binary string x
###########################################
"""
cut = 0
for i, j in G.edges():
if x[i] != x[j]:
cut -= 1# the edge is cut
return cut # Sum of all the edges that are cut
def function_to_minimize(G,p):
r"""
############################################
# Define the function to minimize given the graph G and the number of parameters
#
# G: graph
# p: number of parameters
# return: The function to minimize
###########################################
"""
backend = Aer.get_backend('qasm_simulator')
def f(theta):
r"""
############################################
# Function that gives the energy for parameters theta
#
# theta: parameters
# return: Energy
###########################################
"""
qc = qaoa_circuit(G,theta,p) # Gives the circuit of QAOA fot a graph G, parameters theta and p operators
counts = execute(qc, backend, seed_simulator=10).result().get_counts()# Run the circuit and get the results using the backedn "qasm_simulator"
E = 0 # Initial energy
total_counts = 0 # Initial counts
#Qiskit uses the least significant bit in the bistring, we need to invert this string
InvertedCounts = invert_counts(counts) #Inverted the binary string
# meas is the binary string measure
# meas_count is the number of times that the binary string has been measure
for meas, meas_count in InvertedCounts.items():
objective_function = maxcut_objective_function(meas, G)#Compute the maxcut objetive function fot the binary string meas
E += objective_function*meas_count # Define the energy as the value of the objective functions times the counts of that measure
total_counts += meas_count # The total number of measures in the system
return E/total_counts # Returns the energy given the parameters theta
return f
p = 5 # p is the number of QAOA alternating operators
objective_function = function_to_minimize(Graph, p)
x0=np.random.randn(10)#Initial parameters
minim_solution = minimize(objective_function, x0) # Minimization of scalar function of one or more variable from scipy
minim_solution
optimal_theta = minim_solution['x'] # The optimal parameters to use
optimal_theta
backend = Aer.get_backend('qasm_simulator')
qc = qaoa_circuit(Graph, optimal_theta,p) # Define the quantum circuit with the optimal parameters
counts = invert_counts(execute(qc, backend).result().get_counts()) # Get the results
#energies = {bs: maxcut_objective_function(bs, Graph) for bs, _ in counts.items()}
#energies_sorted = {bs: en for bs, en in sorted(energies.items(), key=lambda item: item[1])}
#print(energies_sorted)
#print({bs: counts[bs] for bs, energy in energies_sorted.items()})
# Compute the maxcut objective function for the optimal parameters
results = []
for x in counts.keys():
results.append([maxcut_objective_function(x,Graph),x])
# Get the best solution given the results of the maxcut objective function
best_cut, best_solution = min(results)
print(f"Best string: {best_solution} with cut: {-best_cut}")
# Define the colors of the nodes for the best solution
colors = ['r' if best_solution[node] == '0' else 'b' for node in Graph]
nx.draw(Graph,node_color = colors)
def solution_max_cut(G):
r"""
############################################
# Compute the solution for the maxcut problem given a graph G
#
# G: graph
# return:The draw of the best solution with two colors. Print the solution in the binary string form and the number of cuts
###############
"""
p = 5 # p is the number of QAOA alternating operators
objective_function = function_to_minimize(G, p)
x0=np.random.randn(10)#Initial parameters
new_parameters = minimize(objective_function, x0) # Minimization of scalar function of one or more variable from scipy
optimal_theta = new_parameters['x']# The optimal parameters to use
qc = qaoa_circuit(G, optimal_theta,p) # Define the quantum circuit with the optimal parameters
counts = invert_counts(execute(qc, backend).result().get_counts()) # Get the results
# Compute the maxcut objective function for the optimal parameters
results = []
for x in counts.keys():
results.append([maxcut_objective_function(x,G),x])
best_cut, best_solution = min(results) # Get the best solution given the results of the maxcut objective function
colors = ['r' if best_solution[node] == '0' else 'b' for node in G] # Define the colors of the nodes for the best solution
return nx.draw(G,node_color = colors),print(f"Best string: {best_solution} with cut: {-best_cut}")
Graph1 = nx.Graph()
Graph1.add_edges_from([[0,1],[0,2],[2,1]])
nx.draw(Graph1,with_labels=True)
solution_max_cut(Graph1)
graph2 = nx.random_regular_graph(3, 4, seed=1234)
nx.draw(graph2) #drawing the graph
plt.show() #plotting the graph
solution_max_cut(graph2)
graph3 = nx.random_regular_graph(3, 12, seed=1234)
nx.draw(graph3) #drawing the graph
plt.show() #plotting the graph
solution_max_cut(graph3)
|
https://github.com/apcarrik/qiskit-dev
|
apcarrik
|
import numpy as np
from pprint import pprint
# import Qiskit
from qiskit import QuantumCircuit
from qiskit import Aer, transpile
from qiskit.tools.visualization import plot_histogram, plot_state_city
import qiskit.quantum_info as qi
# show all possible backends
pprint(Aer.backends())
# use AerSimulator backend
sumulator = Aer.get_backend('aer_simulator')
## Simulating a quantum circuit
# create circuit consisting of a 2-qubit bell state |phi> = 1/2*(|00> + |11>)
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0,1)
circ.measure_all()
# transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ,simulator)
# run simulation and get counts
result = simulator.run(circ).result()
counts = result.get_counts(circ)
plot_histogram(counts, title="Bell-State counts").show()
# save measurment outcomes
result = simulator.run(circ, shots=10, memory=True).result()
memory = result.get_memory(circ)
print(memory)
### Aer Simulation Options
## Simulation Method
# increase shots to reduce sampling variance
shots = 1000
# Stabilizer simulation method
sim_stabilizer = Aer.get_backend('aer_simulator_stabilizer')
job_stabilizer = sim_stabilizer.run(circ, shots=shots)
counts_stabilizer = job_stabilizer.result().get_counts(0)
# Statevector simulation method
sim_statevector = Aer.get_backend('aer_simulator_statevector')
job_statevector = sim_statevector.run(circ, shots=shots)
counts_statevector = job_statevector.result().get_counts(0)
# Density Matrix simulation method
sim_density = Aer.get_backend('aer_simulator_density_matrix')
job_density = sim_density.run(circ, shots=shots)
counts_density = job_density.result().get_counts(0)
# Matrix Product State simulation method
sim_mps = Aer.get_backend('aer_simulator_matrix_product_state')
job_mps = sim_mps.run(circ, shots=shots)
counts_mps = job_mps.result().get_counts(0)
# plot results
plot_histogram([counts_stabilizer,
counts_statevector,
counts_density,
counts_mps],
title="Counts for different simulation methods",
legend=['stabilizer', 'statevector', 'density_matrix',
'matrix_product_state']).show()
## GPU Simulation
from qiskit.providers.aer import AerError
# initialize a GPU backend - note that if the target machine does not have a GPU,
# this will raise an exception.
try:
simulator_gpu = Aer.get_backend('aer_simulator')
simulator_gpu.set_options(device='GPU')
except AerError as e:
print(e)
# the Aer provider will also contain preconfigured GPU simulator backends if Qiskit Aer was
# installed with GPU support on a compatible system:
# - aer_simulator_statevector_gpu
# - aer_simulator_density_matrix_gpu
# - aer_simulator_unitary_gpu
# Note: the GPU version of Aer can be installed using `pip install qiskit-aer-gpu`
## Simulation Precision
# configure a single-precision statevector simulator backend
simulator = Aer.get_backend('aer_simulator_statevector')
simulator.set_options(precision='single')
# run simulation and get counts
result = simulator.run(circ).result()
counts = result.get_counts(circ)
print(counts)
### Custom Simulator Instructions
## Saving the Simulator State
# see https://qiskit.org/documentation/tutorials/simulators/1_aer_provider.html#Saving-the-simulator-state
## Saving the Final Statevector
# construct quantum circuit wihtout measure
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc.save_statevector()
# transpile for simulator
simulator = Aer.get_backend('aer_simulator')
qc = transpile(qc,simulator)
# run simulation and get statevector
result = simulator.run(qc).result()
statevector = result.get_statevector(qc)
plot_state_city(statevector, title='Bell state').show()
## Saving the Circuit Unitary
# construct quantum circuit without measure
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc.save_unitary()
# transpile for simulator
simulator = Aer.get_backend('aer_simulator')
qc = transpile(qc, simulator)
# run simulation and get unitary
result = simulator.run(qc).result()
unitary = result.get_unitary(qc)
print("Circuit unitary:\n", unitary.round(5))
## Saving Multiple States
# construct quantum circuit without measure
steps = 5
qc = QuantumCircuit(1)
for i in range(steps):
qc.save_statevector(label=f'psi_{i}')
qc.rx(i * np.pi / steps, 0)
qc.save_statevector(label=f'psi_{steps}')
# transpile for simulator
simulator = Aer.get_backend('aer_simulator')
qc = transpile(qc, simulator)
# run simulation and get saved data
result = simulator.run(qc).result()
data = result.data(0)
pprint(data)
### Setting the Simulator to a Custom State
# see https://qiskit.org/documentation/tutorials/simulators/1_aer_provider.html#Setting-the-simulator-to-a-custom-state
## Setting a Custom Statevector
# generate a random statevector
num_qubits = 2
psi = qi.random_statevector(2 ** num_qubits, seed =100)
# set initial state to generated statevector
circ = QuantumCircuit(num_qubits)
circ.set_statevector(psi)
circ.save_state()
# transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# run simulation and get saved data
result = simulator.run(circ).result()
pprint(result.data(0))
## Use Initialize Instruction
# use intialize instruction to set initial state
circ = QuantumCircuit(num_qubits)
circ.initialize(psi, range(num_qubits))
circ.save_state()
# transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# run simulation and get results
result = simulator.run(circ).result()
pprint(result.data(0))
## Set Custom Density Matrix
num_qubits = 2
rho = qi.random_density_matrix(2 ** num_qubits, seed = 100)
circ = QuantumCircuit(num_qubits)
circ.set_density_matrix(rho)
circ.save_state()
# transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# run simulation and get saved data
result = simulator.run(circ).result()
pprint(result.data(0))
## Set Custom Unitary
# generates a random unitary
num_qubits = 2
unitary = qi.random_unitary(2** num_qubits, seed =100)
# set initial state to unitary
circ = QuantumCircuit(num_qubits)
circ.set_unitary(unitary)
circ.save_state()
# transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# run simulation and get saved data
result = simulator.run(circ).result()
pprint(result.data(0))
|
https://github.com/UST-QuAntiL/nisq-analyzer-content
|
UST-QuAntiL
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
# https://github.com/Qiskit/qiskit-community-tutorials/blob/master/algorithms/bernstein_vazirani.ipynb
# https://doi.org/10.1073/pnas.1618020114
def get_circuit(**kwargs):
number_of_qubits = kwargs["number_of_qubits"]
s = kwargs["s"]
s = s % 2 ** (number_of_qubits) # a = a mod 2^(number_of_qubits)
print(s)
qr = QuantumRegister(number_of_qubits + 1)
cr = ClassicalRegister(number_of_qubits)
qc = QuantumCircuit(qr, cr)
# hadamard gates
for i in range(number_of_qubits + 1):
qc.h(qr[i])
qc.z(qr[number_of_qubits])
# inner product oracle
for i in range(number_of_qubits):
if (s & (1 << i)): # if bin(s)[i] = 1 then use cnot with ancilla
qc.cx(qr[i], qr[number_of_qubits])
# hadamard gates
for i in range(number_of_qubits):
qc.h(qr[i])
# measurement
for i in range(number_of_qubits):
qc.measure(qr[i], cr[i])
return qc
|
https://github.com/Qottmann/Quantum-anomaly-detection
|
Qottmann
|
import time
import itertools
import numpy as np
from scipy.optimize import minimize, basinhopping
from qiskit import *
from qiskit.quantum_info import Statevector
from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from matplotlib.colors import BoundaryNorm
from modules.utils import Mag
%matplotlib inline
cmap = plt.get_cmap("plasma") #'viridis'
plt.rc('font', family='serif')#, serif='Times')
plt.rc('text', usetex=True)
plt.rc('xtick', labelsize=14)
plt.rc('ytick', labelsize=14)
plt.rc('axes', labelsize=16)
plt.rc('legend', fontsize=14)
plt.rc('legend', handlelength=2)
plt.rc('axes', titlesize=20)
# from: https://tenpy.readthedocs.io/en/latest/toycodes/tfi_exact.html
import numpy as np
import scipy.sparse as sparse
import scipy.sparse.linalg.eigen.arpack as arp
import warnings
import scipy.integrate
def ising_groundstate(L, J, gx, gz=0): # gx is transverse field, gz the longitudinal
"""For comparison: obtain ground state energy from exact diagonalization.
Exponentially expensive in L, only works for small enough `L` <~ 20.
"""
if L >= 20:
warnings.warn("Large L: Exact diagonalization might take a long time!")
# get single site operaors
sx = sparse.csr_matrix(np.array([[0., 1.], [1., 0.]]))
sz = sparse.csr_matrix(np.array([[1., 0.], [0., -1.]]))
id = sparse.csr_matrix(np.eye(2))
sx_list = [] # sx_list[i] = kron([id, id, ..., id, sx, id, .... id])
sz_list = []
for i_site in range(L):
x_ops = [id] * L
z_ops = [id] * L
x_ops[i_site] = sx
z_ops[i_site] = sz
X = x_ops[0]
Z = z_ops[0]
for j in range(1, L):
X = sparse.kron(X, x_ops[j], 'csr')
Z = sparse.kron(Z, z_ops[j], 'csr')
sx_list.append(X)
sz_list.append(Z)
H_zz = sparse.csr_matrix((2**L, 2**L))
H_z = sparse.csr_matrix((2**L, 2**L))
H_x = sparse.csr_matrix((2**L, 2**L))
for i in range(L - 1):
H_zz = H_zz + sz_list[i] * sz_list[(i + 1) % L]
for i in range(L):
H_z = H_z + sz_list[i]
H_x = H_x + sx_list[i]
H = -J * H_zz - gx * H_x - gz * H_z
E, V = arp.eigsh(H, k=1, which='SA', return_eigenvectors=True, ncv=20)
return V[:,0], E[0]
init_state, E = ising_groundstate(6, 1., 1., 1.)
def sort_vals(vals):
""" vals is (unsorted) dictionary of parameters from VQE ansatz circuit, this returns sorted values as list """
indices = np.array([_.index for _ in vals]) # unordered list of indices from the ParameterVectorElement(Theta(INDEX))
vals_sorted = np.array([vals[_] for _ in vals]) # unordered list of values (but same ordering as indices)
return vals_sorted[np.argsort(indices)]
def init_vqe(vals, L):
#return qiskit.circuit.library.EfficientSU2(L, reps=3).assign_parameters(sort_vals(vals))
return qiskit.circuit.library.EfficientSU2(L, reps=3).assign_parameters(vals)
L = 5
anti = -1
#filename = f'data/params_VQE_Ising_L{L}_anti_{anti}.npz' # name of the data file that is used
filename = f'data/params_VQE_Ising_L{L}_anti_{anti}_50x50.npz'
VQE_vals = np.load(filename, allow_pickle=True)
gxs = VQE_vals['gx_list']
gzs = VQE_vals['gz_list']
phis = VQE_vals['opt_params']
N = int(np.sqrt(gxs.size))
gxs = np.logspace(-2, 2, N)#gxs.reshape(N,N)
gzs = np.logspace(-2, 2, N)#gzs.reshape(N,N)
phis = phis.reshape(N,N,-1) #(gx, gz)
# Use Aer's qasm_simulator
backend_sim = Aer.get_backend('qasm_simulator')
L = 5 # system size
num_trash = 2
thetas = np.random.uniform(0, 2*np.pi, num_trash*L+num_trash) # initial parameters without feature encoding
# thetas = np.random.uniform(0, 2*np.pi, (2*L+2, 2)) # initial parameters with feature encoding
def prepare_circuit(init_state=None, measurement=True):
qreg = QuantumRegister(L, 'q')
creg = ClassicalRegister(2, 'c')
circ = QuantumCircuit(qreg, creg)
entangler_map1 = [(5, 4), (5, 3), (5, 1), (4, 2), (4, 0)]
entangler_map2 = [(5, 4), (5, 2), (4, 3), (5, 0), (4, 1)]
circ += circuit.library.TwoLocal(L, 'ry', 'cz', entanglement = [entangler_map1, entangler_map2], reps=2, insert_barriers=True, skip_final_rotation_layer=True)
circ.ry(circuit.Parameter('θ1'), 4)
circ.ry(circuit.Parameter('θ2'), 5)
if measurement:
circ.measure(qreg[4], creg[0])
circ.measure(qreg[5], creg[1])
if init_state is not None:
circ = init_vqe(init_state) + circ
return circ
# same circuit as above (more explicit)
def prepare_circuit2(thetas, init_state=None, measurement=True):
qreg = QuantumRegister(L, 'q')
creg = ClassicalRegister(2, 'c')
circ = QuantumCircuit(qreg, creg)
#if init_state is not None: circ.initialize(init_state, qreg)
for i,t in enumerate(thetas[:L]):
circ.ry(t, i)
circ.cz(5,4)
circ.cz(5,3)
circ.cz(5,1)
circ.cz(4,2)
circ.cz(4,0)
for i,t in enumerate(thetas[L:2*L]):
circ.ry(t, i)
circ.cz(5,4)
circ.cz(5,2)
circ.cz(4,3)
circ.cz(5,0)
circ.cz(4,1)
circ.ry(thetas[2*L], 4)
circ.ry(thetas[2*L+1], 5)
if measurement:
circ.measure(qreg[4], creg[0])
circ.measure(qreg[5], creg[1])
if init_state is not None:
circ = init_vqe(init_state) + circ
return circ
# linear entangler (as in scales linearly with trash qubits)
def get_entangler_map(L, num_trash, i_permut=1):
result = []
nums = list(range(L)) # here was the problem, it doesnt like when list elements are taken from numpy
nums_compressed = nums.copy()[:L-num_trash]
nums_trash = nums.copy()[-num_trash:]
#print(nums, nums_compressed, nums_trash)
# combine all trash qubits with themselves
for trash_q in nums_trash[:-1]:
result.append((trash_q+1,trash_q))
# combine each of the trash qubits with every n-th
repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly
for i in range(L-num_trash):
result.append((repeated[i_permut + i], nums_compressed[i]))
return result
def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz"):
entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)]
circ = qiskit.circuit.library.TwoLocal(L,
parametrized_gate,
entangling_gate,
entanglement,
reps=num_trash,
insert_barriers=insert_barriers,
skip_final_rotation_layer=True
).assign_parameters(thetas[:-num_trash])
if insert_barriers: circ.barrier()
for i in range(num_trash):
circ.ry(thetas[L-i-1], L-i-1)
#circ.ry(circuit.Parameter(f'θ{i}'), L-i-1)
return circ
def prepare_circuit3(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True):
qreg = QuantumRegister(L, 'q')
creg = ClassicalRegister(num_trash)#?, 'c')
circ = QuantumCircuit(qreg, creg)
print(circ.cregs)
if init_state is not None:
if not vqe:
circ.initialize(init_state, qreg)
circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=True)#.assign_parameters(thetas) # difference to bind?
if measurement:
for i in range(num_trash):
circ.measure(qreg[L-i-1], creg[i])
if init_state is not None:
if vqe:
circ = init_vqe(init_state, L) + circ
#else:
# circ.initialize(init_state, qreg)
return circ
def feature_encoding(thetas, x):
""" thetas: parameters to be optimized, x: Ising model parameter (eg. field) """
new_thetas = []
thetas = thetas.reshape((-1,2))
for theta in thetas:
new_thetas.append(theta[0] * x + theta[1])
return new_thetas
idx = 30
J, gx, gz = -1., gxs[idx], gzs[idx]
phi = phis[idx, idx]
def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100):
circ = prepare_circuit3(thetas, L, num_trash, init_state, vqe=vqe)
# Execute the circuit on the qasm simulator.
job_sim = execute(circ, backend_sim, shots=shots)#, memory=True)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(circ)
# print(counts)
# mems = result_sim.get_memory(circ)
# print(mems)
return counts
run_circuit(thetas, L, num_trash, phi)
#reset random seed
np.random.seed(123)
def hamming_distance(out):
return sum(key.count('1') * value for key, value in out.items())
def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0, model="bh"):
""" Optimizes circuit """
if vqe:
init_state = phis[p]
else:
if model=="ising":
J, gx, gz = p
init_state, _ = ising_groundstate(L, J, gx, gz)
elif model=="bh":
init_state = p#init_states[p]
if param_encoding: thetas = feature_encoding(thetas, x)
out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots)
cost = hamming_distance(out)
return cost/shots
def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0):
""" Optimizes circuit """
cost = 0.
n_samples = len(ising_params)
for i, p in enumerate(ising_params):
if param_encoding:
cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i])
else:
cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding)
return cost/n_samples
def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=500, lr=None, perturbation=None, vqe=True, param_encoding=False, x=0):
if thetas is None:
n_params = (num_trash*L+num_trash)*2 if param_encoding else (num_trash*L+num_trash)
thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding
print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x)))
counts, values, accepted = [], [], []
def store_intermediate_result(eval_count, parameters, mean, std, ac):
# counts.append(eval_count)
values.append(mean)
accepted.append(ac)
# Initialize optimizer
# optimizer = COBYLA(maxiter=max_iter, tol=0.0001)
# optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08)
optimizer = SPSA(maxiter=max_iter,
#blocking=True,
# callback=store_intermediate_result,
learning_rate=lr,
perturbation=perturbation
) # recommended from qiskit (first iteraction takes quite long)
# to reduce time figure out optimal learning rate and perturbation in advance
start_time = time.time()
ret = optimizer.optimize(
num_vars=len(thetas),
objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x)),
initial_point=thetas
)
print("Time: {:.5f} sec".format(time.time()-start_time))
print(ret)
return ret[0], values, accepted
thetas, loss, accepted = optimize(params, L, 2, max_iter=itera)
fig = plt.figure(figsize=(12,4))
plt.subplot(1, 2, 1)
plt.plot(losses[2,1,:], "x--") #2,2 1,2
plt.yscale("log")
plt.xlabel("step")
plt.ylabel("Loss");
for i,lr in enumerate(lrs):
for j,p in enumerate(perturbations):
fig = plt.figure(figsize=(12,4))
plt.subplot(1, 2, 1)
plt.plot(losses[i,j,:], "x--")
plt.yscale("log")
plt.xlabel("step")
plt.ylabel("Loss");
for i,lr in enumerate(lrs):
for j,p in enumerate(perturbations):
fig = plt.figure(figsize=(12,4))
plt.subplot(1, 2, 1)
plt.plot(losses[i,j,:], "x--")
plt.yscale("log")
plt.xlabel("step")
plt.ylabel("Loss");
params = [(13,13)]
num_trash = 2
print(gxs[params[0][0]], gzs[params[0][1]])
thetas, loss, accepted = optimize(params, L, 2, max_iter=40)
thetas_normal_phase_2 = thetas
len(loss)
params = [(13,13)]
num_trash = 2
print(gxs[params[0][0]], gzs[params[0][1]])
thetas, loss, accepted = optimize(params, L, 2, max_iter=40)
thetas_normal_phase_2 = thetas
params = [(18,38)]
thetas_test, loss, accepted = optimize(params, L, max_iter=40)
params = [(13,13)]
thetas_test, loss, accepted = optimize(params, 5, 2, max_iter=40, vqe=False)
L = 5
anti = -1
# filename = f'data/params_VQE_Ising_L{L}_anti_{anti}.npz' # name of the data file that is used
filename = f'data/params_VQE_Ising_L{L}_anti_{anti}_50x50.npz'
VQE_vals = np.load(filename, allow_pickle=True)
gxs = VQE_vals['gx_list']
gzs = VQE_vals['gz_list']
phis = VQE_vals['opt_params']
N = int(np.sqrt(gxs.size))
gxs = np.logspace(-2, 2, N)#gxs.reshape(N,N)
gzs = np.logspace(-2, 2, N)#gzs.reshape(N,N)
phis = phis.reshape(N,N,-1) #(gx, gz)
params = [(16,37),(37,16)]
num_trash = 2
print(gxs[params[0][0]], gzs[params[0][1]])
thetas, loss, accepted = optimize(params, L, num_trash)
thetas_normal_phase_2 = thetas
seeds = np.arange(20) + 10
for seed in seeds:
cost = np.load(f'data_rike/cost_bh_L12_trash2_d48_v5_seed{seed}.npy', allow_pickle=True) # 7, 10
params = [[48,5]]
# cost = np.load(f'data_rike/cost_bh_L12_trash2_d2_v5_seed{seed}.npy', allow_pickle=True) # -2
# cost = np.load(f'data_rike/cost_bh_L12_trash4_d2_v5_seed{seed}.npy', allow_pickle=True)
# params = [[2,5]]
# cost = np.load(f'data_rike/cost_bh_L12_trash2_d10_v10_seed{seed}.npy', allow_pickle=True) # 3, 6
# cost = np.load(f'data_rike/cost_bh_L12_trash4_d10_v10_seed{seed}.npy', allow_pickle=True)
# params = [[10,10]]
fig,axs = plt.subplots(figsize=(8,5),squeeze=False)
nbins=100
ax = axs[0,0]
levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max())
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
im = ax.pcolormesh(y, x, cost.T, cmap=cmap, norm=norm)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
# plt.yscale("log")
ax.set_title("Loss",fontsize=20)
ax.set_xlabel(r"$V$",fontsize=24)
ax.set_ylabel(r"$\delta t$",fontsize=24)
ax.tick_params(labelsize=20)
for p in params:
d = deltas[p[0]]
V = Vs[p[1]]
ax.plot(V,d,"o",label="training",color="cyan")
plt.show()
fig = plt.figure(figsize=(12,4))
plt.subplot(1, 2, 1)
plt.plot(loss, "x--")
plt.yscale("log")
plt.xlabel("step")
plt.ylabel("Loss");
points = 50
J = -1.0
x,y = np.meshgrid(gxs,gzs)
cost = np.zeros((points,points))
#Smags = np.zeros((points,points))
shots = 1000
for i,gx in enumerate(gxs):
for j,gz in enumerate(gzs):
cost[i,j] = cost_function_single(thetas, L, num_trash, (i,j), shots=shots)
#init_state, _ = ising_groundstate(5, J, gx, gz)
#Smags[i,j] = np.real(init_state.T.conj()@Mag(5,-1)@init_state)
fig,axs = plt.subplots(figsize=(8,5),squeeze=False)
nbins=100
ax = axs[0,0]
levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max())
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
im = ax.pcolormesh(x, y, cost, cmap=cmap, norm=norm)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
plt.yscale("log")
ax.set_title("Loss",fontsize=20)
ax.set_xlabel(r"$g_z$",fontsize=24)
ax.set_ylabel(r"$g_x$",fontsize=24)
ax.tick_params(labelsize=20)
fig,axs = plt.subplots(figsize=(8,5),squeeze=False)
nbins=100
ax = axs[0,0]
levels = MaxNLocator(nbins=nbins).tick_values(Smags.min(),Smags.max())
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
im = ax.pcolormesh(x, y, Smags, cmap=cmap, norm=norm)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
plt.yscale("log")
ax.set_title("Staggered magnetization",fontsize=20)
ax.set_xlabel(r"$g_z$",fontsize=24)
ax.set_ylabel(r"$g_x$",fontsize=24)
ax.tick_params(labelsize=20)
fig,axs = plt.subplots(figsize=(8,5),squeeze=False)
nbins=100
ax = axs[0,0]
levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max())
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
im = ax.pcolormesh(x, y, cost, cmap=cmap, norm=norm)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
plt.yscale("log")
ax.set_title("Loss",fontsize=20)
ax.set_xlabel(r"$g_z$",fontsize=24)
ax.set_ylabel(r"$g_x$",fontsize=24)
ax.tick_params(labelsize=20)
fig,axs = plt.subplots(figsize=(8,5),squeeze=False)
nbins=100
ax = axs[0,0]
levels = MaxNLocator(nbins=nbins).tick_values(Smags.min(),Smags.max())
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
im = ax.pcolormesh(x, y, Smags, cmap=cmap, norm=norm)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
plt.yscale("log")
ax.set_title("Staggered magnetization",fontsize=20)
ax.set_xlabel(r"$g_z$",fontsize=24)
ax.set_ylabel(r"$g_x$",fontsize=24)
ax.tick_params(labelsize=20)
J = -1
gz = gzs[0]
cost1, Smags1, Smags12 = [], [], []
shots = 10000
Ll = 5
for i,gx in enumerate(gxs):
cost1.append(cost_function_single(thetas, L, num_trash, (i, 0), shots=shots))
init_state, _ = ising_groundstate(Ll, J, gx, gz)
Smags1.append(np.real(init_state.T.conj()@Mag(Ll,-1)@init_state))
#init_state, _ = ising_groundstate(Ll+2, J, gx, gz)
#Smags12.append(np.real(init_state.T.conj()@Mag(Ll+2,-1)@init_state))
gx = gxs[0]
cost2, Smags2, Smags22 = [], [], []
for i,gz in enumerate(gzs):
cost2.append(cost_function_single(thetas, L, num_trash, (0, i), shots=shots))
init_state, _ = ising_groundstate(Ll, J, gx, gz)
Smags2.append(np.real(init_state.T.conj()@Mag(Ll,-1)@init_state))
#init_state, _ = ising_groundstate(Ll+2, J, gx, gz)
#Smags22.append(np.real(init_state.T.conj()@Mag(Ll+2,-1)@init_state))
fig = plt.figure(figsize=(12,4))
ax1 = plt.subplot(121)
ax2 = ax1.twinx()
ax3 = plt.subplot(122)
ax4 = ax3.twinx()
ax1.set_xlabel(r"$g_z$")
ax1.set_ylabel("Cost")
ax1.plot(gzs, cost1, "x--")
ax2.plot(gzs, Smags1, "g-.")
#ax2.plot(gzs, Smags12, "r--")
ax2.set_ylabel("Staggered mag.")
ax2.set_xscale("log")
ax3.set_xlabel(r"$g_x$")
ax3.set_ylabel("Cost")
ax3.plot(gzs, cost2, "x--")
ax4.plot(gzs, Smags2, "g-.")
#ax4.plot(gzs, Smags22, "r--")
ax4.set_xscale("log")
ax4.set_ylabel("Staggered mag.")
fig.tight_layout()
params = [(13,13)]
num_trash = 4
print(gxs[params[0][0]], gzs[params[0][1]])
thetas, loss, accepted = optimize(params, L, num_trash)
thetas_ordered_phase_4 = thetas
fig = plt.figure(figsize=(12,4))
plt.subplot(1, 2, 1)
plt.plot(loss, "x--")
plt.yscale("log")
plt.xlabel("step")
plt.ylabel("Loss");
thetas = thetas_ordered_phase_2
num_trash = 2
points = 50
J = -1.0
x,y = np.meshgrid(gxs,gzs)
cost = np.zeros((points,points))
#Smags = np.zeros((points,points))
shots = 1000
for i,gx in enumerate(gxs):
for j,gz in enumerate(gzs):
cost[i,j] = cost_function_single(thetas, L, num_trash, (i,j), shots=shots)
#init_state, _ = ising_groundstate(5, J, gx, gz)
#Smags[i,j] = np.real(init_state.T.conj()@Mag(5,-1)@init_state)
fig,axs = plt.subplots(figsize=(8,5),squeeze=False)
nbins=100
ax = axs[0,0]
levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max())
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
im = ax.pcolormesh(x, y, cost, cmap=cmap, norm=norm)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
plt.yscale("log")
ax.set_title("Loss",fontsize=20)
ax.set_xlabel(r"$g_z$",fontsize=24)
ax.set_ylabel(r"$g_x$",fontsize=24)
ax.tick_params(labelsize=20)
fig,axs = plt.subplots(figsize=(8,5),squeeze=False)
nbins=100
ax = axs[0,0]
levels = MaxNLocator(nbins=nbins).tick_values(Smags.min(),Smags.max())
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
im = ax.pcolormesh(x, y, Smags, cmap=cmap, norm=norm)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
plt.yscale("log")
ax.set_title("Staggered magnetization",fontsize=20)
ax.set_xlabel(r"$g_z$",fontsize=24)
ax.set_ylabel(r"$g_x$",fontsize=24)
ax.tick_params(labelsize=20)
# 3 trash qubits
fig,axs = plt.subplots(figsize=(8,5),squeeze=False)
nbins=100
ax = axs[0,0]
levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max())
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
im = ax.pcolormesh(x, y, cost, cmap=cmap, norm=norm)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
plt.yscale("log")
ax.set_title("Loss",fontsize=20)
ax.set_xlabel(r"$g_z$",fontsize=24)
ax.set_ylabel(r"$g_x$",fontsize=24)
ax.tick_params(labelsize=20)
fig,axs = plt.subplots(figsize=(8,5),squeeze=False)
nbins=100
ax = axs[0,0]
levels = MaxNLocator(nbins=nbins).tick_values(Smags.min(),Smags.max())
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
im = ax.pcolormesh(x, y, Smags, cmap=cmap, norm=norm)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
plt.yscale("log")
ax.set_title("Staggered magnetization",fontsize=20)
ax.set_xlabel(r"$g_z$",fontsize=24)
ax.set_ylabel(r"$g_x$",fontsize=24)
ax.tick_params(labelsize=20)
# 2 trash qubits
fig,axs = plt.subplots(figsize=(8,5),squeeze=False)
cost_shift = np.abs(1-cost)
nbins=100
ax = axs[0,0]
levels = MaxNLocator(nbins=nbins).tick_values(cost_shift.min(),cost_shift.max())
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
im = ax.pcolormesh(x, y, cost_shift, cmap=cmap, norm=norm)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
plt.yscale("log")
ax.set_title("Loss",fontsize=20)
ax.set_xlabel(r"$g_z$",fontsize=24)
ax.set_ylabel(r"$g_x$",fontsize=24)
ax.tick_params(labelsize=20)
fig,axs = plt.subplots(figsize=(8,5),squeeze=False)
nbins=100
ax = axs[0,0]
levels = MaxNLocator(nbins=nbins).tick_values(Smags.min(),Smags.max())
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
im = ax.pcolormesh(x, y, Smags, cmap=cmap, norm=norm)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
plt.yscale("log")
ax.set_title("Staggered magnetization",fontsize=20)
ax.set_xlabel(r"$g_z$",fontsize=24)
ax.set_ylabel(r"$g_x$",fontsize=24)
ax.tick_params(labelsize=20)
# 2 trash qubits
cmap = plt.get_cmap("plasma")
def plot_result(cost, params):
fig,axs = plt.subplots(figsize=(8,5),squeeze=False)
nbins=100
ax = axs[0,0]
im = ax.pcolormesh(x, y, cost.T, cmap=cmap, shading="auto")
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
ax.set_yscale("log")
# plt.xscale("log")
ax.set_title("Loss",fontsize=20)
ax.set_ylabel(r"$V$",fontsize=24)
ax.set_xlabel(r"$\delta t$",fontsize=24)
ax.tick_params(labelsize=20)
for p in params:
d = deltas[p[0]]
V = Vs[p[1]]
ax.plot(d,V,"o",label="training",color="cyan")
L = 12
N = 50
#filename = f'data/wf_BH_L{L}.npz'
#filename = '../wf_BH_L20.npz'
#filename = 'data/wf_BH_L10_logV.npz'
filename = 'data/wf_BH_L12_logV_50x50.npz'
VQE_vals = np.load(filename, allow_pickle=True)
deltas = VQE_vals['deltat_array']
Vs = VQE_vals['V_array']
init_states = VQE_vals['wf_array']
# Vs = np.linspace(2,8,10)
# Vs = np.linspace(0,1,10)
Vs = np.logspace(-2,2,N)
# deltas = np.linspace(-1,1,10)
# deltas = np.linspace(-2,2,10)
deltas = np.linspace(-0.95,0.95,N)
init_states = init_states.reshape(N,N,-1) #(delta, V)
dd_vals = np.load('data/BH_dd_L12.npz', allow_pickle=True)
# deltas = dd_vals['deltat_array']
dd = dd_vals['dd_array'].reshape(N,N)
# init_states = VQE_vals['wf_array']
es_vals = np.load('data/BH_ES_L12.npz', allow_pickle=True)
es = es_vals['ES_array'].reshape(N,N)
print(deltas[48], Vs[1])
num_trash = 2
thetas, loss, accepted = optimize([init_states[-2,1]], L, num_trash, max_iter=1500, vqe=False)
thetas_bh12_10_2 = thetas
fig = plt.figure(figsize=(12,4))
plt.subplot(1, 2, 1)
plt.plot(loss, "x--")
#plt.yscale("log")
plt.xlabel("step")
plt.ylabel("Loss");
thetas = thetas_bh__1_2
points = 50
x,y = np.meshgrid(deltas,Vs)
# cost = np.zeros((points,points))
# Smags = np.zeros((points,points))
# shots = 1000
# for i,d in enumerate(deltas):
# print(i)
# for j,v in enumerate(Vs):
# cost[i,j] = cost_function_single(thetas, L, num_trash, init_states[i,j], shots=shots, vqe=False)
#cost_bh12_10_2 = cost
np.save(f'data_rike/cost_bh_L{L}_trash{num_trash}_d5_v50.npy', cost_bh12__1_2)
dd.shape
np.save('../data_rike/es.npy', es)
x,y = np.meshgrid(deltas,Vs)
np.save('../data_rike/x.npy', y)
x
params = [[-2,1]]
cost = dd
fig,axs = plt.subplots(figsize=(8,5),squeeze=False)
nbins=100
ax = axs[0,0]
levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max())
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
im = ax.pcolormesh(y, x, cost.T, cmap=cmap, norm=norm)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
# plt.yscale("log")
ax.set_title("Loss",fontsize=20)
ax.set_xlabel(r"$V$",fontsize=24)
ax.set_ylabel(r"$\delta t$",fontsize=24)
ax.tick_params(labelsize=20)
for p in params:
d = deltas[p[0]]
V = Vs[p[1]]
ax.plot(V,d,"o",label="training",color="cyan")
#2 trash qubit
params = [[0,0]]
fig,axs = plt.subplots(figsize=(8,5),squeeze=False)
nbins=100
ax = axs[0,0]
levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max())
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
im = ax.pcolormesh(y, x, cost.T, cmap=cmap, norm=norm)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
# plt.yscale("log")
ax.set_title("Loss",fontsize=20)
ax.set_xlabel(r"$V$",fontsize=24)
ax.set_ylabel(r"$\delta t$",fontsize=24)
ax.tick_params(labelsize=20)
for p in params:
d = deltas[p[0]]
V = Vs[p[1]]
ax.plot(V,d,"o",label="training",color="cyan")
#2 trash qubit
params = [[5,-1]]
fig,axs = plt.subplots(figsize=(8,5),squeeze=False)
nbins=100
ax = axs[0,0]
levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max())
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
im = ax.pcolormesh(y, x, cost.T, cmap=cmap, norm=norm)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
# plt.yscale("log")
ax.set_title("Loss",fontsize=20)
ax.set_xlabel(r"$V$",fontsize=24)
ax.set_ylabel(r"$\delta t$",fontsize=24)
ax.tick_params(labelsize=20)
for p in params:
d = deltas[p[0]]
V = Vs[p[1]]
ax.plot(V,d,"o",label="training",color="cyan")
#2 trash qubit
params = [[0,0]]
fig,axs = plt.subplots(figsize=(8,5),squeeze=False)
nbins=100
ax = axs[0,0]
levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max())
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
im = ax.pcolormesh(y, x, cost.T, cmap=cmap, norm=norm)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
# plt.yscale("log")
ax.set_title("Loss",fontsize=20)
ax.set_xlabel(r"$V$",fontsize=24)
ax.set_ylabel(r"$\delta t$",fontsize=24)
ax.tick_params(labelsize=20)
for p in params:
d = deltas[p[0]]
V = Vs[p[1]]
ax.plot(V,d,"o",label="training",color="cyan")
#2 trash qubit
params = [[-1,0]]
fig,axs = plt.subplots(figsize=(8,5),squeeze=False)
nbins=100
ax = axs[0,0]
levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max())
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
im = ax.pcolormesh(y, x, cost.T, cmap=cmap, norm=norm)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
# plt.yscale("log")
ax.set_title("Loss",fontsize=20)
ax.set_xlabel(r"$V$",fontsize=24)
ax.set_ylabel(r"$\delta t$",fontsize=24)
ax.tick_params(labelsize=20)
for p in params:
d = deltas[p[0]]
V = Vs[p[1]]
ax.plot(V,d,"o",label="training",color="cyan")
#2 trash qubit
params = [[5,-1]]
fig,axs = plt.subplots(figsize=(8,5),squeeze=False)
nbins=100
ax = axs[0,0]
levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max())
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
im = ax.pcolormesh(y, x, cost.T, cmap=cmap, norm=norm)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
# plt.yscale("log")
ax.set_title("Loss",fontsize=20)
ax.set_xlabel(r"$V$",fontsize=24)
ax.set_ylabel(r"$\delta t$",fontsize=24)
ax.tick_params(labelsize=20)
for p in params:
d = deltas[p[0]]
V = Vs[p[1]]
ax.plot(V,d,"o",label="training",color="cyan")
#2 trash qubit
cost = np.load('data_rike/cost_bh_L12_trash2_d48_v5_seed10.npy', allow_pickle=True)
# cost = np.load('data_rike/cost_bh_L12_trash6_d25_v47_seed29.npy', allow_pickle=True)
params = [[25,47]]
cost = es
fig,axs = plt.subplots(figsize=(8,5),squeeze=False)
nbins=100
ax = axs[0,0]
levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max())
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
im = ax.pcolormesh(y, x, cost.T, cmap=cmap, norm=norm)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
# plt.yscale("log")
# ax.set_title("Density-density correlation",fontsize=22)
# ax.set_title("Loss",fontsize=22)
ax.set_title("Degeneracy entanglement spectrum",fontsize=22)
ax.set_xlabel(r"$V$",fontsize=24)
ax.set_ylabel(r"$\delta t$",fontsize=24)
ax.tick_params(labelsize=20)
# for p in params:
# d = deltas[p[0]]
# V = Vs[p[1]]
# ax.plot(V,d,"o",label="training",color="cyan")
fig.tight_layout()
# plt.savefig('plots_rike/cost_bh_L12_trash6_d25_v47_seed29.png', dpi=300)
plt.savefig('plots_rike/es_bh_L12.pdf', dpi=300)
seeds = np.arange(20) + 10
for seed in seeds:
# cost = np.load(f'data_rike/cost_bh_L12_trash2_d48_v5_seed{seed}.npy', allow_pickle=True) # 7, 10
# cost = np.load(f'data_rike/cost_bh_L12_trash4_d48_v5_seed{seed}.npy', allow_pickle=True) # 3
# cost = np.load(f'data_rike/cost_bh_L12_trash6_d48_v5_seed{seed}.npy', allow_pickle=True) # 0
# params = [[48,5]]
# cost = np.load(f'data_rike/cost_bh_L12_trash2_d2_v5_seed{seed}.npy', allow_pickle=True) # -2
# cost = np.load(f'data_rike/cost_bh_L12_trash4_d2_v5_seed{seed}.npy', allow_pickle=True) # 0
# cost = np.load(f'data_rike/cost_bh_L12_trash6_d2_v5_seed{seed}.npy', allow_pickle=True) # 2, 10
# params = [[2,5]]
# cost = np.load(f'data_rike/cost_bh_L12_trash2_d10_v10_seed{seed}.npy', allow_pickle=True) # 3, 6
# cost = np.load(f'data_rike/cost_bh_L12_trash4_d10_v10_seed{seed}.npy', allow_pickle=True) # -8
# cost = np.load(f'data_rike/cost_bh_L12_trash6_d10_v10_seed{seed}.npy', allow_pickle=True) # 6, 12
# params = [[10,10]]
# cost = np.load(f'data_rike/cost_bh_L12_trash2_d25_v47_seed{seed}.npy', allow_pickle=True) # 1
# cost = np.load(f'data_rike/cost_bh_L12_trash4_d25_v47_seed{seed}.npy', allow_pickle=True) # 6
cost = np.load(f'data_rike/cost_bh_L12_trash6_d25_v47_seed{seed}.npy', allow_pickle=True) # 1, 12, 19
params = [[25,47]]
fig,axs = plt.subplots(figsize=(8,5),squeeze=False)
nbins=100
ax = axs[0,0]
levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max())
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
im = ax.pcolormesh(y, x, cost.T, cmap=cmap, norm=norm)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
# plt.yscale("log")
ax.set_title("Loss",fontsize=20)
ax.set_xlabel(r"$V$",fontsize=24)
ax.set_ylabel(r"$\delta t$",fontsize=24)
ax.tick_params(labelsize=20)
for p in params:
d = deltas[p[0]]
V = Vs[p[1]]
ax.plot(V,d,"o",label="training",color="cyan")
seeds = np.arange(20) + 10
for seed in seeds:
cost = np.load(f'data_rike/cost_bh_L12_trash2_d48_v5_seed{seed}.npy', allow_pickle=True) # 7, 10
params = [[48,5]]
# cost = np.load(f'data_rike/cost_bh_L12_trash2_d2_v5_seed{seed}.npy', allow_pickle=True) # -2
# cost = np.load(f'data_rike/cost_bh_L12_trash4_d2_v5_seed{seed}.npy', allow_pickle=True)
# params = [[2,5]]
# cost = np.load(f'data_rike/cost_bh_L12_trash2_d10_v10_seed{seed}.npy', allow_pickle=True) # 3, 6
# cost = np.load(f'data_rike/cost_bh_L12_trash4_d10_v10_seed{seed}.npy', allow_pickle=True)
# params = [[10,10]]
fig,axs = plt.subplots(figsize=(8,5),squeeze=False)
nbins=100
ax = axs[0,0]
levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max())
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
im = ax.pcolormesh(y, x, cost.T, cmap=cmap, norm=norm)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
# plt.yscale("log")
ax.set_title("Loss",fontsize=20)
ax.set_xlabel(r"$V$",fontsize=24)
ax.set_ylabel(r"$\delta t$",fontsize=24)
ax.tick_params(labelsize=20)
for p in params:
d = deltas[p[0]]
V = Vs[p[1]]
ax.plot(V,d,"o",label="training",color="cyan")
plt.show()
seeds = np.arange(20) + 10
for seed in seeds:
# loss = np.load(f'data_rike/cost_bh_L12_trash2_d48_v5_seed{seed}.npy', allow_pickle=True)
# params = [[48,5]]
# loss = np.load(f'data_rike/cost_bh_L12_trash2_d2_v5_seed{seed}.npy', allow_pickle=True)
# loss = np.load(f'data_rike/cost_bh_L12_trash4_d2_v5_seed{seed}.npy', allow_pickle=True)
# params = [[2,5]]
# loss = np.load(f'data_rike/loss_bh_L12_trash2_d10_v10_seed{seed}.npy', allow_pickle=True)
# loss = np.load(f'data_rike/loss_bh_L12_trash4_d10_v10_seed{seed}.npy', allow_pickle=True)
loss = np.load(f'data_rike/loss_bh_L12_trash2_d25_v47_seed{seed}.npy', allow_pickle=True)
# loss = np.load(f'data_rike/loss_bh_L12_trash4_d25_v47_seed{seed}.npy', allow_pickle=True)
fig = plt.figure(figsize=(12,4))
plt.subplot(1, 2, 1)
plt.plot(loss, "x--")
plt.yscale("log")
plt.xlabel("step")
plt.ylabel("Loss")
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the decompose pass"""
from numpy import pi
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.transpiler.passes import Decompose
from qiskit.converters import circuit_to_dag
from qiskit.circuit.library import HGate, CCXGate, U2Gate
from qiskit.quantum_info.operators import Operator
from qiskit.test import QiskitTestCase
class TestDecompose(QiskitTestCase):
"""Tests the decompose pass."""
def setUp(self):
super().setUp()
# example complex circuit
# ┌────────┐ ┌───┐┌─────────────┐
# q2_0: ┤0 ├────────────■──┤ H ├┤0 ├
# │ │ │ └───┘│ circuit-57 │
# q2_1: ┤1 gate1 ├────────────■───────┤1 ├
# │ │┌────────┐ │ └─────────────┘
# q2_2: ┤2 ├┤0 ├──■──────────────────────
# └────────┘│ │ │
# q2_3: ──────────┤1 gate2 ├──■──────────────────────
# │ │┌─┴─┐
# q2_4: ──────────┤2 ├┤ X ├────────────────────
# └────────┘└───┘
circ1 = QuantumCircuit(3)
circ1.h(0)
circ1.t(1)
circ1.x(2)
my_gate = circ1.to_gate(label="gate1")
circ2 = QuantumCircuit(3)
circ2.h(0)
circ2.cx(0, 1)
circ2.x(2)
my_gate2 = circ2.to_gate(label="gate2")
circ3 = QuantumCircuit(2)
circ3.x(0)
q_bits = QuantumRegister(5)
qc = QuantumCircuit(q_bits)
qc.append(my_gate, q_bits[:3])
qc.append(my_gate2, q_bits[2:])
qc.mct(q_bits[:4], q_bits[4])
qc.h(0)
qc.append(circ3, [0, 1])
self.complex_circuit = qc
def test_basic(self):
"""Test decompose a single H into u2."""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
pass_ = Decompose(HGate)
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 1)
self.assertEqual(op_nodes[0].name, "u2")
def test_decompose_none(self):
"""Test decompose a single H into u2."""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
pass_ = Decompose()
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 1)
self.assertEqual(op_nodes[0].name, "u2")
def test_decompose_only_h(self):
"""Test to decompose a single H, without the rest"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
pass_ = Decompose(HGate)
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 2)
for node in op_nodes:
self.assertIn(node.name, ["cx", "u2"])
def test_decompose_toffoli(self):
"""Test decompose CCX."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(1, "qr2")
circuit = QuantumCircuit(qr1, qr2)
circuit.ccx(qr1[0], qr1[1], qr2[0])
dag = circuit_to_dag(circuit)
pass_ = Decompose(CCXGate)
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 15)
for node in op_nodes:
self.assertIn(node.name, ["h", "t", "tdg", "cx"])
def test_decompose_conditional(self):
"""Test decompose a 1-qubit gates with a conditional."""
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr).c_if(cr, 1)
circuit.x(qr).c_if(cr, 1)
dag = circuit_to_dag(circuit)
pass_ = Decompose(HGate)
after_dag = pass_.run(dag)
ref_circuit = QuantumCircuit(qr, cr)
ref_circuit.append(U2Gate(0, pi), [qr[0]]).c_if(cr, 1)
ref_circuit.x(qr).c_if(cr, 1)
ref_dag = circuit_to_dag(ref_circuit)
self.assertEqual(after_dag, ref_dag)
def test_decompose_oversized_instruction(self):
"""Test decompose on a single-op gate that doesn't use all qubits."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/3440
qc1 = QuantumCircuit(2)
qc1.x(0)
gate = qc1.to_gate()
qc2 = QuantumCircuit(2)
qc2.append(gate, [0, 1])
output = qc2.decompose()
self.assertEqual(qc1, output)
def test_decomposition_preserves_qregs_order(self):
"""Test decomposing a gate preserves it's definition registers order"""
qr = QuantumRegister(2, "qr1")
qc1 = QuantumCircuit(qr)
qc1.cx(1, 0)
gate = qc1.to_gate()
qr2 = QuantumRegister(2, "qr2")
qc2 = QuantumCircuit(qr2)
qc2.append(gate, qr2)
expected = QuantumCircuit(qr2)
expected.cx(1, 0)
self.assertEqual(qc2.decompose(), expected)
def test_decompose_global_phase_1q(self):
"""Test decomposition of circuit with global phase"""
qc1 = QuantumCircuit(1)
qc1.rz(0.1, 0)
qc1.ry(0.5, 0)
qc1.global_phase += pi / 4
qcd = qc1.decompose()
self.assertEqual(Operator(qc1), Operator(qcd))
def test_decompose_global_phase_2q(self):
"""Test decomposition of circuit with global phase"""
qc1 = QuantumCircuit(2, global_phase=pi / 4)
qc1.rz(0.1, 0)
qc1.rxx(0.2, 0, 1)
qcd = qc1.decompose()
self.assertEqual(Operator(qc1), Operator(qcd))
def test_decompose_global_phase_1q_composite(self):
"""Test decomposition of circuit with global phase in a composite gate."""
circ = QuantumCircuit(1, global_phase=pi / 2)
circ.x(0)
circ.h(0)
v = circ.to_gate()
qc1 = QuantumCircuit(1)
qc1.append(v, [0])
qcd = qc1.decompose()
self.assertEqual(Operator(qc1), Operator(qcd))
def test_decompose_only_h_gate(self):
"""Test decomposition parameters so that only a certain gate is decomposed."""
circ = QuantumCircuit(2, 1)
circ.h(0)
circ.cz(0, 1)
decom_circ = circ.decompose(["h"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 2)
self.assertEqual(dag.op_nodes()[0].name, "u2")
self.assertEqual(dag.op_nodes()[1].name, "cz")
def test_decompose_only_given_label(self):
"""Test decomposition parameters so that only a given label is decomposed."""
decom_circ = self.complex_circuit.decompose(["gate2"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 7)
self.assertEqual(dag.op_nodes()[0].op.label, "gate1")
self.assertEqual(dag.op_nodes()[1].name, "h")
self.assertEqual(dag.op_nodes()[2].name, "cx")
self.assertEqual(dag.op_nodes()[3].name, "x")
self.assertEqual(dag.op_nodes()[4].name, "mcx")
self.assertEqual(dag.op_nodes()[5].name, "h")
self.assertRegex(dag.op_nodes()[6].name, "circuit-")
def test_decompose_only_given_name(self):
"""Test decomposition parameters so that only given name is decomposed."""
decom_circ = self.complex_circuit.decompose(["mcx"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 13)
self.assertEqual(dag.op_nodes()[0].op.label, "gate1")
self.assertEqual(dag.op_nodes()[1].op.label, "gate2")
self.assertEqual(dag.op_nodes()[2].name, "h")
self.assertEqual(dag.op_nodes()[3].name, "cu1")
self.assertEqual(dag.op_nodes()[4].name, "rcccx")
self.assertEqual(dag.op_nodes()[5].name, "h")
self.assertEqual(dag.op_nodes()[6].name, "h")
self.assertEqual(dag.op_nodes()[7].name, "cu1")
self.assertEqual(dag.op_nodes()[8].name, "rcccx_dg")
self.assertEqual(dag.op_nodes()[9].name, "h")
self.assertEqual(dag.op_nodes()[10].name, "c3sx")
self.assertEqual(dag.op_nodes()[11].name, "h")
self.assertRegex(dag.op_nodes()[12].name, "circuit-")
def test_decompose_mixture_of_names_and_labels(self):
"""Test decomposition parameters so that mixture of names and labels is decomposed"""
decom_circ = self.complex_circuit.decompose(["mcx", "gate2"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 15)
self.assertEqual(dag.op_nodes()[0].op.label, "gate1")
self.assertEqual(dag.op_nodes()[1].name, "h")
self.assertEqual(dag.op_nodes()[2].name, "cx")
self.assertEqual(dag.op_nodes()[3].name, "x")
self.assertEqual(dag.op_nodes()[4].name, "h")
self.assertEqual(dag.op_nodes()[5].name, "cu1")
self.assertEqual(dag.op_nodes()[6].name, "rcccx")
self.assertEqual(dag.op_nodes()[7].name, "h")
self.assertEqual(dag.op_nodes()[8].name, "h")
self.assertEqual(dag.op_nodes()[9].name, "cu1")
self.assertEqual(dag.op_nodes()[10].name, "rcccx_dg")
self.assertEqual(dag.op_nodes()[11].name, "h")
self.assertEqual(dag.op_nodes()[12].name, "c3sx")
self.assertEqual(dag.op_nodes()[13].name, "h")
self.assertRegex(dag.op_nodes()[14].name, "circuit-")
def test_decompose_name_wildcards(self):
"""Test decomposition parameters so that name wildcards is decomposed"""
decom_circ = self.complex_circuit.decompose(["circuit-*"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 9)
self.assertEqual(dag.op_nodes()[0].name, "h")
self.assertEqual(dag.op_nodes()[1].name, "t")
self.assertEqual(dag.op_nodes()[2].name, "x")
self.assertEqual(dag.op_nodes()[3].name, "h")
self.assertRegex(dag.op_nodes()[4].name, "cx")
self.assertEqual(dag.op_nodes()[5].name, "x")
self.assertEqual(dag.op_nodes()[6].name, "mcx")
self.assertEqual(dag.op_nodes()[7].name, "h")
self.assertEqual(dag.op_nodes()[8].name, "x")
def test_decompose_label_wildcards(self):
"""Test decomposition parameters so that label wildcards is decomposed"""
decom_circ = self.complex_circuit.decompose(["gate*"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 9)
self.assertEqual(dag.op_nodes()[0].name, "h")
self.assertEqual(dag.op_nodes()[1].name, "t")
self.assertEqual(dag.op_nodes()[2].name, "x")
self.assertEqual(dag.op_nodes()[3].name, "h")
self.assertEqual(dag.op_nodes()[4].name, "cx")
self.assertEqual(dag.op_nodes()[5].name, "x")
self.assertEqual(dag.op_nodes()[6].name, "mcx")
self.assertEqual(dag.op_nodes()[7].name, "h")
self.assertRegex(dag.op_nodes()[8].name, "circuit-")
def test_decompose_empty_gate(self):
"""Test a gate where the definition is an empty circuit is decomposed."""
empty = QuantumCircuit(1)
circuit = QuantumCircuit(1)
circuit.append(empty.to_gate(), [0])
decomposed = circuit.decompose()
self.assertEqual(len(decomposed.data), 0)
def test_decompose_reps(self):
"""Test decompose reps function is decomposed correctly"""
decom_circ = self.complex_circuit.decompose(reps=2)
decomposed = self.complex_circuit.decompose().decompose()
self.assertEqual(decom_circ, decomposed)
def test_decompose_single_qubit_clbit(self):
"""Test the decomposition of a block with a single qubit and clbit works.
Regression test of Qiskit/qiskit-terra#8591.
"""
block = QuantumCircuit(1, 1)
block.h(0)
circuit = QuantumCircuit(1, 1)
circuit.append(block, [0], [0])
decomposed = circuit.decompose()
self.assertEqual(decomposed, block)
|
https://github.com/sebasmos/QuantumVE
|
sebasmos
|
import os
MODEL_METADATA = "RF"
model_name = "efficientnet_v2_m"#"efficientnet_b7"## "mobilenet_v3_large"#"convnext_base"
EXPERIMENT_NAME = f"{model_name}_embeddings"
results_path = f"{EXPERIMENT_NAME}/{MODEL_METADATA}"
os.makedirs(results_path, exist_ok = True)
os.makedirs(EXPERIMENT_NAME, exist_ok = True)
train_path = f"{EXPERIMENT_NAME}/train"
val_path = f"{EXPERIMENT_NAME}/val"
os.makedirs(train_path, exist_ok = True)
os.makedirs(val_path, exist_ok=True)
import sys
sys.path.insert(0,'../')
# from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
from torch.utils.data import random_split
from torch.utils.data import Subset, DataLoader, random_split
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import confusion_matrix, classification_report
import pandas as pd
import argparse
import argparse
import datetime
import json
import numpy as np
import os
import time
from pathlib import Path
import torch
import torch.backends.cudnn as cudnn
from torch.utils.tensorboard import SummaryWriter
# import models_vit
import sys
import os
import torch
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
# import models_mae
import torch; print(f'numpy version: {np.__version__}\nCUDA version: {torch.version.cuda} - Torch versteion: {torch.__version__} - device count: {torch.cuda.device_count()}')
from sklearn.metrics import confusion_matrix, classification_report
import seaborn as sns
from sklearn.preprocessing import LabelBinarizer
from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt
from itertools import cycle
import numpy as np
from sklearn.metrics import precision_score, recall_score, f1_score
import torch.optim as optim
import torch.nn as nn
import torch
import PIL
import pandas as pd
import torch
import numpy as np
import pandas as pd
from tqdm import tqdm
import os
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, fbeta_score
from sklearn.metrics import precision_score, recall_score, f1_score, fbeta_score
import numpy as np
from torchvision import datasets, transforms
from timm.data import create_transform
# from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
IMAGENET_DEFAULT_MEAN = np.array([0.485, 0.456, 0.406])
IMAGENET_DEFAULT_STD = np.array([0.229, 0.224, 0.225])
def show_image(image, title=''):
# image is [H, W, 3]
assert image.shape[2] == 3
plt.imshow(torch.clip((image * IMAGENET_DEFAULT_STD + IMAGENET_DEFAULT_MEAN) * 255, 0, 255).int())
plt.title(title, fontsize=16)
plt.axis('off')
return
def plot_multiclass_roc_curve(all_labels, all_predictions, results_path="."):
# Step 1: Label Binarization
label_binarizer = LabelBinarizer()
y_onehot = label_binarizer.fit_transform(all_labels)
all_predictions_hot = label_binarizer.transform(all_predictions)
# Step 2: Calculate ROC curves
fpr = dict()
tpr = dict()
roc_auc = dict()
unique_classes = range(y_onehot.shape[1])
for i in unique_classes:
fpr[i], tpr[i], _ = roc_curve(y_onehot[:, i], all_predictions_hot[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
# Step 3: Plot ROC curves
fig, ax = plt.subplots(figsize=(8, 8))
# Micro-average ROC curve
fpr_micro, tpr_micro, _ = roc_curve(y_onehot.ravel(), all_predictions_hot.ravel())
roc_auc_micro = auc(fpr_micro, tpr_micro)
plt.plot(
fpr_micro,
tpr_micro,
label=f"micro-average ROC curve (AUC = {roc_auc_micro:.2f})",
color="deeppink",
linestyle=":",
linewidth=4,
)
# Macro-average ROC curve
all_fpr = np.unique(np.concatenate([fpr[i] for i in unique_classes]))
mean_tpr = np.zeros_like(all_fpr)
for i in unique_classes:
mean_tpr += np.interp(all_fpr, fpr[i], tpr[i])
mean_tpr /= len(unique_classes)
fpr_macro = all_fpr
tpr_macro = mean_tpr
roc_auc_macro = auc(fpr_macro, tpr_macro)
plt.plot(
fpr_macro,
tpr_macro,
label=f"macro-average ROC curve (AUC = {roc_auc_macro:.2f})",
color="navy",
linestyle=":",
linewidth=4,
)
# Individual class ROC curves with unique colors
colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_classes)))
for class_id, color in zip(unique_classes, colors):
plt.plot(
fpr[class_id],
tpr[class_id],
color=color,
label=f"ROC curve for Class {class_id} (AUC = {roc_auc[class_id]:.2f})",
linewidth=2,
)
plt.plot([0, 1], [0, 1], color='gray', linestyle='--', linewidth=2) # Add diagonal line for reference
plt.axis("equal")
plt.xlabel("False Positive Rate")
plt.ylabel("True Positive Rate")
plt.title("Extension of Receiver Operating Characteristic\n to One-vs-Rest multiclass")
plt.legend()
plt.savefig(f'{results_path}/roc_curve.png')
plt.show()
def build_dataset(is_train, args):
transform = build_transform(is_train, args)
root = os.path.join(args.data_path, 'train' if is_train else 'val')
dataset = datasets.ImageFolder(root, transform=transform)
print(dataset)
return dataset
def build_transform(is_train, args):
mean = IMAGENET_DEFAULT_MEAN
std = IMAGENET_DEFAULT_STD
# train transform
if is_train:
# this should always dispatch to transforms_imagenet_train
transform = create_transform(
input_size=args.input_size,
is_training=True,
color_jitter=args.color_jitter,
auto_augment=args.aa,
interpolation='bicubic',
re_prob=args.reprob,
re_mode=args.remode,
re_count=args.recount,
mean=mean,
std=std,
)
return transform
# eval transform
t = []
if args.input_size <= 224:
crop_pct = 224 / 256
else:
crop_pct = 1.0
size = int(args.input_size / crop_pct)
t.append(
transforms.Resize(size, interpolation=PIL.Image.BICUBIC), # to maintain same ratio w.r.t. 224 images
)
t.append(transforms.CenterCrop(args.input_size))
t.append(transforms.ToTensor())
t.append(transforms.Normalize(mean, std))
return transforms.Compose(t)
# Set the seed for PyTorch
torch.manual_seed(42)
# Read embeddings CSV files
train_embeddings = pd.read_csv(f'{train_path}/train_embeddings.csv')
val_embeddings = pd.read_csv(f'{val_path}/val_embeddings.csv')
print(f"Reading embeddings from: ", train_path)
# Prepare data for training
X_train = train_embeddings.iloc[:, :-1].values # Features
y_train = train_embeddings.iloc[:, -1].values # Labels
X_val = val_embeddings.iloc[:, :-1].values # Features
y_val = val_embeddings.iloc[:, -1].values # Labels
# Train a Random Forest Classifier
# Use los mejores parámetros encontrados
# best_params = {'max_depth': 80, 'min_samples_leaf': 4, 'min_samples_split': 10, 'n_estimators': 150}
# Inicializa el clasificador SVM con los mejores parámetros
rf_classifier = RandomForestClassifier(random_state=42)
rf_classifier.fit(X_train, y_train)
# Predict on validation data
y_pred = rf_classifier.predict(X_val)
# Calculate accuracy
accuracy = accuracy_score(y_val, y_pred)
# Calculate precision
precision = precision_score(y_val, y_pred, average='weighted')
# Calculate recall
recall = recall_score(y_val, y_pred, average='weighted')
# Calculate F1 score
f1 = f1_score(y_val, y_pred, average='weighted')
# Calculate F0.75 score
fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted')
print("Validation Accuracy:", accuracy)
print("Precision:", precision)
print("Recall:", recall)
print("F1 Score:", f1)
print("F0.75 Score:", fbeta_75)
unique_classes = np.unique(np.concatenate(((y_pred, y_val))))
confusion_mat = confusion_matrix(y_pred, y_val, labels=unique_classes)
conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes)
# Plot the confusion matrix using seaborn
plt.figure(figsize=(5, 4))
ax = sns.heatmap(conf_matrix, annot=True, fmt='.1f', cmap=sns.cubehelix_palette(as_cmap=True), linewidths=0.1, cbar=True)
# Set labels and ticks
ax.set_xlabel('Predicted Labels')
ax.set_ylabel('True Labels')
# Set x and y ticks using the unique classes
ax.set_xticks(range(len(unique_classes)))
ax.set_yticks(range(len(unique_classes)))
# Set x and y ticks at the center of the cells
ax.set_xticks([i + 0.5 for i in range(len(unique_classes))])
ax.set_yticks([i + 0.5 for i in range(len(unique_classes))])
plt.show()
plot_multiclass_roc_curve(y_pred, y_val, results_path)
report = classification_report(y_val,y_pred, target_names=unique_classes,output_dict=True)# Mostrar el informe de
df = pd.DataFrame(report).transpose()
df.to_csv(os.path.join(results_path, f"confusion_matrix_{MODEL_METADATA}.csv"))
print(df)
# Calculate precision, recall, and specificity (micro-averaged)
precision = precision_score(y_val, y_pred, average='micro')
recall = recall_score(y_val, y_pred, average='micro')
# Calculate true negatives, false positives, and specificity (micro-averaged)
tn = np.sum((y_val != 1) & (y_pred != 1))
fp = np.sum((y_val != 1) & (y_pred == 1))
specificity = tn / (tn + fp)
# Calculate F1 score (weighted average)
f1 = f1_score(y_val, y_pred, average='weighted')
fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted')
evaluation_metrics = {
"Accuracy": accuracy,
"F1 Score": f1,
"F0.75 Score": fbeta_75,
"Precision": precision,
"Recall": recall,
"Specificity": specificity
}
print("Evaluation Metrics:")
# for metric, value in evaluation_metrics.items():
# print(f"{metric}: {value}")
# Create a DataFrame from the dictionary
df = pd.DataFrame(evaluation_metrics, index=[0])
# # Save the DataFrame to a CSV file
df.to_csv(f'{results_path}/evaluation_metrics_for_table_{MODEL_METADATA}.csv', index=False)
df
results_path
# from sklearn.model_selection import GridSearchCV
# from sklearn.ensemble import RandomForestClassifier
# from sklearn.preprocessing import StandardScaler
# from sklearn.pipeline import Pipeline
# from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, fbeta_score
# # Define the parameter grid to search
# param_grid = {
# 'classifier__n_estimators': [50, 100, 150],
# 'classifier__max_depth': [None, 10, 20],
# 'classifier__min_samples_split': [2, 5, 10],
# 'classifier__min_samples_leaf': [1, 2, 4]
# }
# # Create a pipeline with normalization and RandomForestClassifier
# rf_pipeline = Pipeline([
# ('scaler', StandardScaler()),
# ('classifier', RandomForestClassifier(random_state=42))
# ])
# # Create GridSearchCV
# grid_search = GridSearchCV(estimator=rf_pipeline, param_grid=param_grid, cv=3, scoring='accuracy')
# # Fit the grid search to the data
# grid_search.fit(X_train, y_train)
# # Get the best parameters and best score
# best_params = grid_search.best_params_
# best_score = grid_search.best_score_
# print("Best Parameters:", best_params)
# print("Best Score:", best_score)
# # Use the best estimator found by GridSearchCV
# best_rf_classifier = grid_search.best_estimator_
# # Predict on validation data using the best model
# y_pred = best_rf_classifier.predict(X_val)
# # Calculate metrics
# accuracy = accuracy_score(y_val, y_pred)
# precision = precision_score(y_val, y_pred, average='weighted')
# recall = recall_score(y_val, y_pred, average='weighted')
# f1 = f1_score(y_val, y_pred, average='weighted')
# fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted')
# print("Validation Accuracy:", accuracy)
# print("Precision:", precision)
# print("Recall:", recall)
# print("F1 Score:", f1)
# print("F0.75 Score:", fbeta_75)
|
https://github.com/anpaschool/quantum-computing
|
anpaschool
|
from qiskit import *
from math import pi
import numpy as np
from qiskit.visualization import *
import matplotlib.pyplot as plt
from qutip import *
qc = QuantumCircuit(2)
qc.barrier()
qc.h(0)
qc.cx(0, 1)
qc.barrier()
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
out = execute(qc,backend).result().get_statevector()
print(out)
I = np.eye(2,2)
H = 1/np.sqrt(2)*np.array([[1,1],[1,-1]])
CNOT = np.array([[1,0,0,0],[0,0,0,1],[0,0,1,0],[0,1,0,0]])
IKH = np.kron(I,H)
U = np.dot(CNOT,IKH)
print(U)
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
print(result.get_unitary(qc, decimals=3))
ket_00 = np.array([1,0,0,0])
np.dot(U,ket_00)
qc = QuantumCircuit(2)
qc.x(1)
qc.barrier()
qc.h(0)
qc.cx(0, 1)
qc.barrier()
qc.draw('mpl')
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
out = execute(qc,backend).result().get_statevector()
print(out)
qc = QuantumCircuit(2)
qc.x(0)
qc.barrier()
qc.h(0)
qc.cx(0, 1)
qc.barrier()
qc.draw('mpl')
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
out = execute(qc,backend).result().get_statevector()
print(out)
qc = QuantumCircuit(2)
qc.x(0)
qc.x(1)
qc.barrier()
qc.h(0)
qc.cx(0, 1)
qc.barrier()
qc.draw('mpl')
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
out = execute(qc,backend).result().get_statevector()
print(out)
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
import os, shutil, time
from random_qubo.random_qubo import RandomQubo
DIR = 'TEST_DATA' + "/" + time.strftime("%d_%m_%Y")
def getPath(filename = "", directory = ""):
return DIR + "/" + directory + "/" + filename
bounds = {"matrix_q_lb": -5, "matrix_q_ub": 5, "c_lb": -5, "c_ub": 5}
DIR
shutil.rmtree(DIR, ignore_errors=True)
os.makedirs(getPath(directory = "SPARSE"))
os.makedirs(getPath(directory = "DENSE"))
os.makedirs(getPath(directory = "MULTIPLE"))
os.makedirs(getPath(directory = "CPLEX"))
# create sparse random qubos
# 3 variables connected
# start with 3x1 qubits
qaoa_max_qubits = 27 # number of qubits in Falcon r5.1 processors
var = 3
multiple = 1
while True:
qp = RandomQubo.create_random_qubo("test_" + str(multiple), var, multiple=multiple, **bounds)
qp.write_to_lp_file(getPath(qp.name, directory = "SPARSE"))
if qp.get_num_vars() > qaoa_max_qubits :
print(multiple)
break
multiple = multiple + 1
# create dense random qubos
# start with 3 variables
while True:
qp = RandomQubo.create_random_qubo("test_" + str(var), var, **bounds)
qp.write_to_lp_file(getPath(qp.name, directory = "DENSE"))
if qp.get_num_vars() > qaoa_max_qubits :
print(var)
break
var = var + 3
# create more test data for pegasus
# instances with several times the last instance which Mumbai is able to solve
# 27 variables each
# start with 27x2 qubits
var = qaoa_max_qubits
multiples = [2, 5, 10, 20]
for multiple in multiples:
qp = RandomQubo.create_random_qubo("test_" + str(multiple), var, multiple=multiple, **bounds)
qp.write_to_lp_file(getPath(qp.name, directory = "MULTIPLE"))
qp = RandomQubo.create_random_qubo("test_cplex", 100, **bounds) # used 10 for test data
qp.write_to_lp_file(getPath(qp.name, directory = "CPLEX"))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate
from qiskit.converters import dag_to_circuit
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)
dag = circuit_to_dag(circ)
circuit = dag_to_circuit(dag)
circuit.draw('mpl')
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import qiskit
from qiskit import *
from qiskit import Aer
import pandas as pd
from qiskit.providers.aer.noise.noise_model import NoiseModel
from qiskit.test.mock import *
from qiskit.providers.aer import AerSimulator, QasmSimulator
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
import itertools
import mitiq
import argparse
import cma
import os
import sys
from qiskit import IBMQ
import pickle
import random
import re
from pprint import pprint
#! ここからmainの実行処理
IBMQ.load_account()
# provider = IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
print("provider:", provider)
L = 3
p = 2
dt = 1.0
tf = 20
shots = 8192
#TODO 外部実装
def TwirlCircuit(circ: str) -> QuantumCircuit:
#! qasm ベタ書き
def apply_pauli(num: int, qb: int) -> str:
if (num == 0):
return f'id q[{qb}];\n'
elif (num == 1):
return f'x q[{qb}];\n'
elif (num == 2):
return f'y q[{qb}];\n'
else:
return f'z q[{qb}];\n'
paulis = [(i,j) for i in range(0,4) for j in range(0,4)]
paulis.remove((0,0))
paulis_map = [(0, 1), (3, 2), (3, 3), (1, 1), (1, 0), (2, 3), (2, 2), (2, 1), (2, 0), (1, 3), (1, 2), (3, 0), (3, 1), (0, 2), (0, 3)]
new_circ = ''
ops = circ.qasm().splitlines(True) #! 生のqasmコードを持ってきてる: オペレータに分解
for op in ops:
if (op[:2] == 'cx'): # can add for cz, etc.
num = random.randrange(len(paulis))
qbs = re.findall('q\[(.)\]', op)
new_circ += apply_pauli(paulis[num][0], qbs[0])
new_circ += apply_pauli(paulis[num][1], qbs[1])
new_circ += op
new_circ += apply_pauli(paulis_map[num][0], qbs[0])
new_circ += apply_pauli(paulis_map[num][1], qbs[1])
else:
new_circ += op
return qiskit.circuit.QuantumCircuit.from_qasm_str(new_circ)
#! convert 完了
def TrotterEvolveCircuit(dt, nt, init):
"""
Implements trotter evolution of the Heisenberg hamiltonian using the circuit from https://arxiv.org/pdf/1906.06343.pdf #! 要チェック
:param tf: time to evolve to #! dt * nt = tf ???
:param nt: number of trotter steps to use
:param init: initial state for the trotter evolution. Should be another Qiskit circuit
外部変数: L
"""
# def get_angles(a, b, c):
# return (np.pi/2 - 2*c, 2*a - np.pi/2, np.pi/2 - 2*b)
def get_angles(a):
#! 角度計算, aはalpha, return値タプルの0はtheta, 1はphi, 2はlambd = theta
return (np.pi/2 - 2*a, 2*a - np.pi/2, np.pi/2 - 2*a)
def N(cir, qb0, qb1):
#! fig 4を実装: thetaとphiとlambdはglobal変数
#! cnotのdepthは3
cir.rz(-np.pi/2, qb1)
cir.cnot(qb1, qb0)
cir.rz(theta, qb0)
cir.ry(phi, qb1)
cir.cnot(qb0, qb1)
cir.ry(lambd, qb1)
cir.cnot(qb1, qb0)
cir.rz(np.pi/2, qb0)
return cir
#! dtはtrotter step size ← step sizeとは??? (default: 0.25)
theta, phi, lambd = get_angles(-dt/4) #! why divided by 4??? 少なくとも時間間隔ではある
circ = init
for i in range(nt): #! ntはTrotterステップ数 (ここではcnotが深さnt * 3かかる)
# even (odd indices)
if (L % 2 == 0): #! Lはsystem size
# UEven
for i in range(1, L-1, 2): # L for periodic bdy conditions
circ = N(circ, i, (i+1)%L)
# UOdd
for i in range(0, L-1, 2):
circ = N(circ, i, (i+1)%L)
else:
# UEven
for i in range(1, L, 2):
circ = N(circ, i, (i+1)%L)
# UOdd
for i in range(0, L-1, 2):
circ = N(circ, i, (i+1)%L)
# UBdy
# circ = N(circ, L-1, 0)
return circ
#! convert完了
def AnsatzCircuit(params: list, p: int) -> QuantumCircuit:
"""
Implements HVA ansatz using circuits from https://arxiv.org/pdf/1906.06343.pdf #! 要チェック
#! HVA := Hamiltonian Variational Ansatz
:param params: parameters to parameterize circuit
:param p: depth of the ansatz
外部変数: L, p
"""
circ = QuantumCircuit(L) #! L = system size
def get_angles(a): #! 回転角度の計算 (肩に乗せるやつ)
return (np.pi/2 - 2*a, 2*a - np.pi/2, np.pi/2 - 2*a)
def N(cir, angles, qb0, qb1):
#! angles = (theta, phi, lambd)
cir.rz(-np.pi/2, qb1)
cir.cnot(qb1, qb0)
cir.rz(angles[0], qb0)
cir.ry(angles[1], qb1)
cir.cnot(qb0, qb1)
cir.ry(angles[2], qb1)
cir.cnot(qb1, qb0)
cir.rz(np.pi/2, qb0)
return cir
for i in range(p):
if (L % 2 == 0):
for j in range(1, L-1, 2): # L for periodic bdy conditions #! periodicなので、Lで割って、0とn-1にまたがる回路が存在する
circ = N(circ, get_angles(-params[((L-1)*i)+j]/4), j, (j+1)%L)
for j in range(0, L-1, 2):
circ = N(circ, get_angles(-params[((L-1)*i)+j]/4), j, (j+1)%L)
else:
for j in range(1, L, 2):
circ = N(circ, get_angles(-params[((L-1)*i)+j]/4), j, (j+1)%L)
for j in range(0, L-1, 2):
circ = N(circ, get_angles(-params[((L-1)*i)+j]/4), j, (j+1)%L)
# circ = N(circ, get_angles(-params[(L*i)+L-1]/4), L-1, 0) # boundary
return circ
#TODO reverse_bitを適宜挟む
def ReorderBasis(circ):
"""
#! changing the big endian to little endian
#! unnecessary function: equal to reverse_bit() method
Reorders basis so that 0th qubit is on the left side of the tensor product
:param circ: circuit to reorder, can also be a vector
"""
if (isinstance(circ, qiskit.circuit.quantumcircuit.QuantumCircuit)):
for i in range(L//2):
circ.swap(i, L-i-1)
return circ
else:
perm = np.eye(2**L)
for i in range(1, 2**L//2):
perm[:, [i, 2**L-i-1]] = perm[:, [2**L-i-1, i]]
return perm @ circ
#TODO VTCとは別実装?→ no, 同じ実装に。
def SimulateAndReorder(circ):
"""
#! execution wrapper
Executes a circuit using the statevector simulator and reorders basis to match with standard
"""
circ = ReorderBasis(circ)
backend = Aer.get_backend('statevector_simulator')
return execute(circ, backend).result().get_statevector()
#TODO
def Simulate(circ):
"""
#! execution wrapper
Executes a circuit using the statevector simulator. Doesn't reorder -- which is needed for intermediate steps in the VTC
"""
backend = Aer.get_backend('statevector_simulator')
return execute(circ, backend).result().get_statevector()
#TODO
def LoschmidtEchoExecutor(circuits, backend, shots, filter):
"""
#! 回路を実行
Returns the expectation value to be mitigated.
:param circuit: Circuit to run. #! ここでのcircuitsは
:param backend: backend to run the circuit on
:param shots: Number of times to execute the circuit to compute the expectation value.
:param fitter: measurement error mitigator
"""
# circuits = [TwirlCircuit(circ) for circ in circuits]
scale_factors = [1.0, 2.0, 3.0] #! ZNEのノイズスケーリングパラメタ
folded_circuits = [] #! ZNE用の回路
for circuit in circuits:
folded_circuits.append([mitiq.zne.scaling.fold_gates_at_random(circuit, scale) for scale in scale_factors]) #! ここでmitiqを使用
folded_circuits = list(itertools.chain(*folded_circuits)) #! folded_circuitsを平坦化
folded_circuits = [TwirlCircuit(circ) for circ in folded_circuits] #! 後からPauli Twirlingを施す!
print("length of circuit in job", len(folded_circuits))
#! jobを投げる
job = qiskit.execute(
experiments=folded_circuits,
backend=backend,
optimization_level=0,
shots=shots
)
print("casted job")
c = ['1','1','0'] #! これをpermutationする
# c = [str((1 + (-1)**(i+1)) // 2) for i in range(L)]
c = ''.join(c)[::-1] #! endianを反転 (big endianへ)
res = job.result()
if (filter is not None): #! QREM
res = filter.apply(res)
print("retrieved job")
all_counts = [job.result().get_counts(i) for i in range(len(folded_circuits))]
expectation_values = []
for counts in all_counts:
total_allowed_shots = [counts.get(''.join(p)) for p in set(itertools.permutations(c))] #! ここでcをpermutationしている
total_allowed_shots = sum([0 if x is None else x for x in total_allowed_shots])
if counts.get(c) is None:
expectation_values.append(0)
else:
expectation_values.append(counts.get(c)/total_allowed_shots)
# expectation_values = [counts.get(c) / shots for counts in all_counts]
zero_noise_values = []
if isinstance(backend, qiskit.providers.aer.backends.qasm_simulator.QasmSimulator): # exact_sim
for i in range(len(circuits)):
zero_noise_values.append(np.mean(expectation_values[i*len(scale_factors):(i+1)*len(scale_factors)]))
else: #device_sim, real_device
fac = mitiq.zne.inference.LinearFactory(scale_factors)
for i in range(len(circuits)):
zero_noise_values.append(fac.extrapolate(scale_factors,
expectation_values[i*len(scale_factors):(i+1)*len(scale_factors)]))
print("zero_noise_values")
pprint(zero_noise_values)
print()
return zero_noise_values
#TODO
def LoschmidtEchoCircuit(params, U_v, U_trot, init, p):
"""
#! 回路を作成
Cost function using the Loschmidt Echo. Just using statevectors currently -- can rewrite using shots
:param params: parameters new variational circuit that represents U_trot U_v | init >. Need dagger for cost function
:param U_v: variational circuit that stores the state before the trotter step
:param U_trot: trotter step
:param init: initial state
:param p: number of ansatz steps
"""
U_v_prime = AnsatzCircuit(params, p)
circ = init + U_v + U_trot + U_v_prime.inverse()
circ.measure_all()
return circ
def LoschmidtEcho(params, U_v, U_trot, init, p, backend, shots, filter):
"""
#! 実行パート
"""
circs = []
for param in params:
circs.append(LoschmidtEchoCircuit(param, U_v, U_trot, init, p)) #! 回路を作成
print("length of circuits without zne:", len(circs))
res = LoschmidtEchoExecutor(circs, backend, shots, filter) #! 回路を実行
return abs(1 - np.array(res))
def LoschmidtEchoExact(params, U_v, U_trot, init, p):
"""
#! unused function
"""
U_v_prime = AnsatzCircuit(params, p)
circ = init + U_v + U_trot + U_v_prime.inverse()
circ_vec = Simulate(circ)
init_vec = Simulate(init)
return 1 - abs(np.conj(circ_vec) @ init_vec)**2
def CMAES(U_v, U_trot, init, p, backend, shots, filter):
"""
#! 実行 + 最適化パート
"""
init_params = np.random.uniform(0, 2*np.pi, (L-1)*p)
es = cma.CMAEvolutionStrategy(init_params, np.pi/2)
es.opts.set({'ftarget':5e-3, 'maxiter':1000})
# es = pickle.load(open(f'./results_{L}/optimizer_dump', 'rb'))
while not es.stop(): #! 最適化パート
# solutions = es.ask(25) # ! 25 = number of returned solutions
solutions = es.ask(10)
print("solutions")
pprint(solutions)
es.tell(solutions, LoschmidtEcho(solutions, U_v, U_trot, init, p, backend, shots, filter)) #! 実行パート
# es.tell(solutions, LoschmidtEchoExact(solutions, U_v, U_trot, init, p)) #! 実行パート
es.disp()
open(f'./results_{L}/optimizer_dump', 'wb').write(es.pickle_dumps())
return es.result_pretty()
def VTC(tf, dt, p, init, backend, shots, filter):
"""
#! tf: 総経過時間
#! dt: trotter step size: 時間間隔
#! p: ansatzのステップ数
"""
VTCParamList = [np.zeros((L-1)*p)] #! デフォルトのパラメタ(初期値)
VTCStepList = [SimulateAndReorder(init.copy())] #! type: List[Statevector]
# TrotterFixStepList = [init]
TimeStep = [0]
if (os.path.exists(f'./results_{L}/VTD_params_{tf}_{L}_{p}_{dt}_{shots}.csv')): #! 2巡目からこっち
VTCParamList = pd.read_csv(f'./results_{L}/VTD_params_{tf}_{L}_{p}_{dt}_{shots}.csv', index_col=0)
VTCStepList = pd.read_csv(f'./results_{L}/VTD_results_{tf}_{L}_{p}_{dt}_{shots}.csv', index_col=0)
temp = VTCParamList.iloc[-1]
print(temp, "th time interval")
U_v = AnsatzCircuit(temp, p)
else: #! 最初はこっちに入る
VTCParamList = pd.DataFrame(np.array(VTCParamList), index=np.array(TimeStep))
VTCStepList = pd.DataFrame(np.array(VTCStepList), index=np.array(TimeStep))
print("0 th time interval")
print()
U_v = QuantumCircuit(L)
ts = VTCParamList.index
#! 時間間隔
U_trot = TrotterEvolveCircuit(dt, p, QuantumCircuit(L)) #! Trotter分解のunitaryを作る
print()
print("start CMAES")
print()
res = CMAES(U_v, U_trot, init, p, backend, shots, filter) #! ここでプロセスを実行!!!!
print()
print("res")
pprint(res)
#! 新しいループ結果を追加し、tsを更新
res = res.xbest # ! best solution evaluated
print("res.xbest")
pprint(res)
VTCParamList.loc[ts[-1]+(dt*p)] = np.array(res)
VTCStepList.loc[ts[-1]+(dt*p)] = np.array(SimulateAndReorder(init + AnsatzCircuit(res, p)))
ts = VTCParamList.index
# VTCParamList = pd.DataFrame(np.array(VTCParamList), index=np.array(TimeStep))
# VTCStepList = pd.DataFrame(np.array(VTCStepList), index=np.array(TimeStep))
#! csvファイルを更新
VTCParamList.to_csv(f'./results_{L}/VTD_params_{tf}_{L}_{p}_{dt}_{shots}.csv')
VTCStepList.to_csv(f'./results_{L}/VTD_results_{tf}_{L}_{p}_{dt}_{shots}.csv')
if (ts[-1] >= tf):
return
else:
print("next step")
VTC(tf, dt, p, init, backend, shots, filter)
#! ここからQREM回路
qr = QuantumRegister(L)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# device_backend = FakeJakarta()
# device_sim = AerSimulator.from_backend(device_backend)
real_device = provider.get_backend('ibmq_jakarta')
noise_model = NoiseModel.from_backend(real_device)
device_sim = QasmSimulator(method='statevector', noise_model=noise_model)
exact_sim = Aer.get_backend('qasm_simulator') # QasmSimulator(method='statevector')
t_qc = transpile(meas_calibs)
qobj = assemble(t_qc, shots=8192)
# cal_results = real_device.run(qobj, shots=8192).result()
cal_results = device_sim.run(qobj, shots=8192).result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
print("qrem done")
# np.around(meas_fitter.cal_matrix, decimals=2)
init = QuantumCircuit(L)
# c = [str((1 + (-1)**(i+1)) // 2) for i in range(L)]
c = ['1','1','0'] #! なぜinitial stateが110なの??????? もしかしてopen science prizeを意識???
#! けどループでこのプログラムが実行されるたびにここが|110>だとおかしくないか?
for q in range(len(c)):
if (c[q] == '1'):
init.x(q)
#! ここまでQREM回路
nt = int(np.ceil(tf / (dt * p)))
# f = open(f'./results_{L}/logging.txt', 'a')
# sys.stdout = f
#! tf: シミュレーションの(経過)時間
#! dt: trotter分解のステップ数
#! p: ansatzのステップ数 (論文中のL)
# VTC(tf, dt, p, init, real_device, shots, meas_fitter.filter) #! mainの処理
print("vtc start!!!! \n\n\n")
VTC(tf, dt, p, init, device_sim, shots, meas_fitter.filter) #! mainの処理
# f.close()
|
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_state_qsphere
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_qsphere(state)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.problems import BaseProblem
dummy_hamiltonian = None
base_problem = BaseProblem(dummy_hamiltonian)
print(base_problem.properties)
from qiskit_nature.second_q.properties import AngularMomentum
print("AngularMomentum is in problem.properties:", AngularMomentum in base_problem.properties)
print("Adding AngularMomentum to problem.properties...")
base_problem.properties.add(AngularMomentum(2))
print("AngularMomentum is in problem.properties:", AngularMomentum in base_problem.properties)
print("Discarding AngularMomentum from problem.properties...")
base_problem.properties.discard(AngularMomentum)
print("AngularMomentum is in problem.properties:", AngularMomentum in base_problem.properties)
from qiskit_nature.second_q.drivers import PySCFDriver
es_problem = PySCFDriver().run()
print(es_problem.properties.particle_number)
print(es_problem.properties.angular_momentum)
print(es_problem.properties.magnetization)
print(es_problem.properties.electronic_dipole_moment)
print(es_problem.properties.electronic_density)
from qiskit_nature.second_q.properties import ElectronicDensity
density = ElectronicDensity.from_orbital_occupation(
es_problem.orbital_occupations,
es_problem.orbital_occupations_b,
)
es_problem.properties.electronic_density = density
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2024 Qiskit on IQM developers
#
# 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.
"""A layout algorithm that generates an initial layout for a quantum circuit that is
valid on the quantum architecture specification of the given IQM backend."""
from qiskit import QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.transpiler import PassManager, TranspilerError
from qiskit.transpiler.passes import TrivialLayout
from iqm.qiskit_iqm.iqm_provider import IQMBackend
class IQMMoveLayout(TrivialLayout):
r"""Creates a qubit layout that is valid on the quantum architecture specification of the
given IQM backend with regard to the move gate. In more detail, assumes that the move
operations in the quantum architecture define which physical qubit is the resonator and
which is a move qubit, and shuffles the logical indices of the circuit so that they match
the requirements.
This is required because Qiskit's basic layout algorithm assumes each connection between
two qubits has the same gates defined.
Note: This simple version of the mapper only works reliably with a single move qubit
and resonator, and only if the circuit contains at least one move gate."""
def __init__(self, backend: IQMBackend):
super().__init__(backend.target)
self._backend = backend
def run(self, dag):
"""Creates the qubit layout for the given quantum circuit.
Args:
dag (DAGCircuit): DAG to find layout for.
Raises:
TranspilerError: if dag wider than the target backend or if a valid mapping could not be found
"""
# Run TrivialLayout to get the initial 1-to-1 mapping
super().run(dag)
changes = self._determine_required_changes(dag)
if len(changes) < 1:
# No need to shuffle any qubits
return
layout = self.get_initial_layout()
for src, dst in changes:
layout.swap(src, dst)
self.property_set['layout'] = layout
def get_initial_layout(self):
"""Returns the initial layout generated by the algorithm.
Returns:
the initial layout
"""
return self.property_set['layout']
def _determine_required_changes(self, dag: DAGCircuit) -> list[tuple[int, int]]:
"""Scans the operations in the given circuit and determines what qubits
need to be switched so that the operations are valid for the specified quantum architecture.
Args:
dag - the circuit to check
Returns:
the list of required changes as tuples of logical indices that should be switched;
empty list if no changes are required.
"""
reqs = self._calculate_requirements(dag)
types = self._get_qubit_types()
changes: list[tuple[int, int]] = []
for index, qubit_type in reqs.items():
if index not in types or qubit_type != types[index]:
# Need to change qubit at index to qubit_type
matching_qubit = next((i for i, t in types.items() if t == qubit_type), None)
if matching_qubit is None:
raise TranspilerError(f"Cannot find a '{qubit_type}' from the quantum architecture.")
changes.append((index, matching_qubit))
return changes
def _get_qubit_types(self) -> dict[int, str]:
"""Determines the types of qubits in the quantum architecture.
Returns:
a dictionary mapping logical indices to qubit types for those
qubits where the type is relevant.
"""
backend = self._backend
qubit_types: dict[int, str] = {}
for instruction_name, loci in backend.architecture.operations.items():
if instruction_name == 'move':
for locus in loci:
[qubit, resonator] = [backend.qubit_name_to_index(q) for q in locus]
if qubit is not None:
qubit_types[qubit] = 'move_qubit'
if resonator is not None:
qubit_types[resonator] = 'resonator'
return qubit_types
@staticmethod
def _calculate_requirements(dag: DAGCircuit) -> dict[int, str]:
"""Calculates the requirements for each logical qubit in the circuit.
Args:
dag - the circuit to check
Returns:
A mapping of the logical qubit indices to the required type for that qubit.
"""
required_types: dict[int, str] = {}
def _require_type(qubit_index: int, required_type: str, instruction_name: str):
if qubit_index in required_types and required_types[qubit_index] != required_type:
raise TranspilerError(
f"""Invalid target '{qubit_index}' for the '{instruction_name}' operation,
qubit {qubit_index} would need to be {required_type} but it is already required to be
'{required_types[qubit_index]}'."""
)
required_types[qubit_index] = required_type
for node in dag.topological_op_nodes():
if node.name == 'move':
# The move operation requires that the first operand is the move qubit,
# and the second must be the resonator
(qubit, resonator) = node.qargs
_require_type(qubit.index, 'move_qubit', 'move')
_require_type(resonator.index, 'resonator', 'move')
return required_types
def generate_initial_layout(backend: IQMBackend, circuit: QuantumCircuit):
"""Generates the initial layout for the given circuit, when run against the given backend.
Args:
backend - the IQM backend to run against
circuit - the circuit for which a layout is to be generated
Returns:
a layout that remaps the qubits so that the move qubit and the resonator are using the correct
indices.
"""
layout_gen = IQMMoveLayout(backend)
pm = PassManager(layout_gen)
pm.run(circuit)
return layout_gen.get_initial_layout()
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test Variational Quantum Imaginary Time Evolution algorithm."""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from ddt import ddt
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
from qiskit_algorithms.gradients import LinCombQGT, LinCombEstimatorGradient
from qiskit.primitives import Estimator
from qiskit.quantum_info import SparsePauliOp, Pauli
from qiskit.utils import algorithm_globals
from qiskit_algorithms import TimeEvolutionProblem, VarQITE
from qiskit_algorithms.time_evolvers.variational import (
ImaginaryMcLachlanPrinciple,
)
from qiskit.circuit.library import EfficientSU2
from qiskit.quantum_info import Statevector
@ddt
class TestVarQITE(QiskitAlgorithmsTestCase):
"""Test Variational Quantum Imaginary Time Evolution algorithm."""
def setUp(self):
super().setUp()
self.seed = 11
np.random.seed(self.seed)
def test_run_d_1_with_aux_ops(self):
"""Test VarQITE for d = 1 and t = 1 with evaluating auxiliary operator and the Forward
Euler solver.."""
observable = SparsePauliOp.from_list(
[
("II", 0.2252),
("ZZ", 0.5716),
("IZ", 0.3435),
("ZI", -0.4347),
("YY", 0.091),
("XX", 0.091),
]
)
aux_ops = [Pauli("XX"), Pauli("YZ")]
d = 1
ansatz = EfficientSU2(observable.num_qubits, reps=d)
parameters = list(ansatz.parameters)
init_param_values = np.zeros(len(parameters))
for i in range(len(parameters)):
init_param_values[i] = np.pi / 2
init_param_values[0] = 1
time = 1
evolution_problem = TimeEvolutionProblem(observable, time, aux_operators=aux_ops)
thetas_expected = [
0.87984606025879,
2.04681975664763,
2.68980594039104,
2.75915988512186,
2.38796546567171,
1.78144857115127,
2.13109162826101,
1.9259609596416,
]
thetas_expected_shots = [
0.9392668013702317,
1.8756706968454864,
2.6915067128662398,
2.655420131540562,
2.174687086978046,
1.6997059390911056,
1.8056912289547045,
1.939353810908912,
]
with self.subTest(msg="Test exact backend."):
algorithm_globals.random_seed = self.seed
estimator = Estimator()
qgt = LinCombQGT(estimator)
gradient = LinCombEstimatorGradient(estimator)
var_principle = ImaginaryMcLachlanPrinciple(qgt, gradient)
var_qite = VarQITE(
ansatz, init_param_values, var_principle, estimator, num_timesteps=25
)
evolution_result = var_qite.evolve(evolution_problem)
aux_ops = evolution_result.aux_ops_evaluated
parameter_values = evolution_result.parameter_values[-1]
expected_aux_ops = (-0.2177982985749799, 0.2556790598588627)
for i, parameter_value in enumerate(parameter_values):
np.testing.assert_almost_equal(
float(parameter_value), thetas_expected[i], decimal=2
)
np.testing.assert_array_almost_equal(
[result[0] for result in aux_ops], expected_aux_ops
)
with self.subTest(msg="Test shot-based backend."):
algorithm_globals.random_seed = self.seed
estimator = Estimator(options={"shots": 4096, "seed": self.seed})
qgt = LinCombQGT(estimator)
gradient = LinCombEstimatorGradient(estimator)
var_principle = ImaginaryMcLachlanPrinciple(qgt, gradient)
var_qite = VarQITE(
ansatz, init_param_values, var_principle, estimator, num_timesteps=25
)
evolution_result = var_qite.evolve(evolution_problem)
aux_ops = evolution_result.aux_ops_evaluated
parameter_values = evolution_result.parameter_values[-1]
expected_aux_ops = (-0.24629853310903974, 0.2518122871921184)
for i, parameter_value in enumerate(parameter_values):
np.testing.assert_almost_equal(
float(parameter_value), thetas_expected_shots[i], decimal=2
)
np.testing.assert_array_almost_equal(
[result[0] for result in aux_ops], expected_aux_ops
)
def test_run_d_1_t_7(self):
"""Test VarQITE for d = 1 and t = 7 with RK45 ODE solver."""
observable = SparsePauliOp.from_list(
[
("II", 0.2252),
("ZZ", 0.5716),
("IZ", 0.3435),
("ZI", -0.4347),
("YY", 0.091),
("XX", 0.091),
]
)
d = 1
ansatz = EfficientSU2(observable.num_qubits, reps=d)
parameters = list(ansatz.parameters)
init_param_values = np.zeros(len(parameters))
for i in range(len(parameters)):
init_param_values[i] = np.pi / 2
init_param_values[0] = 1
var_principle = ImaginaryMcLachlanPrinciple()
time = 7
var_qite = VarQITE(
ansatz, init_param_values, var_principle, ode_solver="RK45", num_timesteps=25
)
thetas_expected = [
0.828917365718767,
1.88481074798033,
3.14111335991238,
3.14125849601269,
2.33768562678401,
1.78670990729437,
2.04214275514208,
2.04009918594422,
]
self._test_helper(observable, thetas_expected, time, var_qite, 2)
def test_run_d_2(self):
"""Test VarQITE for d = 2 and t = 1 with RK45 ODE solver."""
observable = SparsePauliOp.from_list(
[
("II", 0.2252),
("ZZ", 0.5716),
("IZ", 0.3435),
("ZI", -0.4347),
("YY", 0.091),
("XX", 0.091),
]
)
d = 2
ansatz = EfficientSU2(observable.num_qubits, reps=d)
parameters = list(ansatz.parameters)
init_param_values = np.zeros(len(parameters))
for i in range(len(parameters)):
init_param_values[i] = np.pi / 4
var_principle = ImaginaryMcLachlanPrinciple()
time = 1
var_qite = VarQITE(
ansatz, init_param_values, var_principle, ode_solver="RK45", num_timesteps=25
)
thetas_expected = [
1.29495364023786,
1.08970061333559,
0.667488228710748,
0.500122687902944,
1.4377736672043,
1.22881086103085,
0.729773048146251,
1.01698854755226,
0.050807780587492,
0.294828474947149,
0.839305697704923,
0.663689581255428,
]
self._test_helper(observable, thetas_expected, time, var_qite, 4)
def test_run_d_1_time_dependent(self):
"""Test VarQITE for d = 1 and a time-dependent Hamiltonian with the Forward Euler solver."""
t_param = Parameter("t")
time = 1
observable = SparsePauliOp(["I", "Z"], np.array([0, t_param]))
x, y, z = [Parameter(s) for s in "xyz"]
ansatz = QuantumCircuit(1)
ansatz.rz(x, 0)
ansatz.ry(y, 0)
ansatz.rz(z, 0)
parameters = list(ansatz.parameters)
init_param_values = np.zeros(len(parameters))
x_val = 0
y_val = np.pi / 2
z_val = 0
init_param_values[0] = x_val
init_param_values[1] = y_val
init_param_values[2] = z_val
evolution_problem = TimeEvolutionProblem(observable, time, t_param=t_param)
thetas_expected = [1.83881002737137e-18, 2.43224994794434, -3.05311331771918e-18]
thetas_expected_shots = [1.83881002737137e-18, 2.43224994794434, -3.05311331771918e-18]
state_expected = Statevector([0.34849948 + 0.0j, 0.93730897 + 0.0j]).to_dict()
# the expected final state is Statevector([0.34849948+0.j, 0.93730897+0.j])
with self.subTest(msg="Test exact backend."):
algorithm_globals.random_seed = self.seed
estimator = Estimator()
var_principle = ImaginaryMcLachlanPrinciple()
var_qite = VarQITE(
ansatz, init_param_values, var_principle, estimator, num_timesteps=100
)
evolution_result = var_qite.evolve(evolution_problem)
evolved_state = evolution_result.evolved_state
parameter_values = evolution_result.parameter_values[-1]
for key, evolved_value in Statevector(evolved_state).to_dict().items():
# np.allclose works with complex numbers
self.assertTrue(np.allclose(evolved_value, state_expected[key], 1e-02))
for i, parameter_value in enumerate(parameter_values):
np.testing.assert_almost_equal(
float(parameter_value), thetas_expected[i], decimal=2
)
with self.subTest(msg="Test shot-based backend."):
algorithm_globals.random_seed = self.seed
estimator = Estimator(options={"shots": 4 * 4096, "seed": self.seed})
var_principle = ImaginaryMcLachlanPrinciple()
var_qite = VarQITE(
ansatz, init_param_values, var_principle, estimator, num_timesteps=100
)
evolution_result = var_qite.evolve(evolution_problem)
evolved_state = evolution_result.evolved_state
parameter_values = evolution_result.parameter_values[-1]
for key, evolved_value in Statevector(evolved_state).to_dict().items():
# np.allclose works with complex numbers
self.assertTrue(np.allclose(evolved_value, state_expected[key], 1e-02))
for i, parameter_value in enumerate(parameter_values):
np.testing.assert_almost_equal(
float(parameter_value), thetas_expected_shots[i], decimal=2
)
def _test_helper(self, observable, thetas_expected, time, var_qite, decimal):
evolution_problem = TimeEvolutionProblem(observable, time)
evolution_result = var_qite.evolve(evolution_problem)
parameter_values = evolution_result.parameter_values[-1]
for i, parameter_value in enumerate(parameter_values):
np.testing.assert_almost_equal(
float(parameter_value), thetas_expected[i], decimal=decimal
)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import pulse
d0 = pulse.DriveChannel(0)
x90 = pulse.Gaussian(10, 0.1, 3)
x180 = pulse.Gaussian(10, 0.2, 3)
def udd10_pos(j):
return np.sin(np.pi*j/(2*10 + 2))**2
with pulse.build() as udd_sched:
pulse.play(x90, d0)
with pulse.align_func(duration=300, func=udd10_pos):
for _ in range(10):
pulse.play(x180, d0)
pulse.play(x90, d0)
udd_sched.draw()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# useful additional packages
import random
import math
from sympy.ntheory import isprime
# importing QISKit
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import Aer, IBMQ, execute
from qiskit.tools.monitor import job_monitor
from qiskit.providers.ibmq import least_busy
from qiskit.tools.visualization import plot_histogram
IBMQ.load_accounts()
sim_backend = Aer.get_backend('qasm_simulator')
device_backend = least_busy(IBMQ.backends(operational=True, simulator=False))
#Function that takes in a prime number and a string of letters and returns a quantum circuit
def qfa_algorithm(string, prime):
if isprime(prime) == False:
raise ValueError("This number is not a prime") #Raises a ValueError if the input prime number is not prime
else:
n = math.ceil((math.log(prime))) #Rounds up to the next integer of the log(prime)
qr = QuantumRegister(n) #Creates a quantum register of length log(prime) for log(prime) qubits
cr = ClassicalRegister(n) #Creates a classical register for measurement
qfaCircuit = QuantumCircuit(qr, cr) #Defining the circuit to take in the values of qr and cr
for x in range(n): #For each qubit, we want to apply a series of unitary operations with a random int
random_value = random.randint(1,prime - 1) #Generates the random int for each qubit from {1, prime -1}
for letter in string: #For each letter in the string, we want to apply the same unitary operation to each qubit
qfaCircuit.ry((2*math.pi*random_value) / prime, qr[x]) #Applies the Y-Rotation to each qubit
qfaCircuit.measure(qr[x], cr[x]) #Measures each qubit
return qfaCircuit #Returns the created quantum circuit
#A function that returns a string saying if the string is accepted into the language or rejected
def accept(parameter):
states = list(result.get_counts(parameter))
for s in states:
for integer in s:
if integer == "1":
return "Reject: the string is not accepted into the language"
return "Accept: the string is accepted into the language"
range_lower = 0
range_higher = 36
prime_number = 11
for length in range(range_lower,range_higher):
params = qfa_algorithm("a"* length, prime_number)
job = execute(params, sim_backend, shots=1000)
result = job.result()
print(accept(params), "\n", "Length:",length," " ,result.get_counts(params))
qfa_algorithm("a"* 3, prime_number).draw(output='mpl')
#Function that takes in a prime number and a string of letters and returns a quantum circuit
def qfa_controlled_algorithm(string, prime):
if isprime(prime) == False:
raise ValueError("This number is not a prime") #Raises a ValueError if the input prime number is not prime
else:
n = math.ceil((math.log(math.log(prime,2),2))) #Represents log(log(p)) control qubits
states = 2 ** (n) #Number of states that the qubits can represent/Number of QFA's to be performed
qr = QuantumRegister(n+1) #Creates a quantum register of log(log(prime)) control qubits + 1 target qubit
cr = ClassicalRegister(1) #Creates a classical register of log(log(prime)) control qubits + 1 target qubit
control_qfaCircuit = QuantumCircuit(qr, cr) #Defining the circuit to take in the values of qr and cr
for q in range(n): #We want to take each control qubit and put them in a superposition by applying a Hadamard Gate
control_qfaCircuit.h(qr[q])
for letter in string: #For each letter in the string, we want to apply a series of Controlled Y-rotations
for q in range(n):
control_qfaCircuit.cu3(2*math.pi*(2**q)/prime, 0, 0, qr[q], qr[n]) #Controlled Y on Target qubit
control_qfaCircuit.measure(qr[n], cr[0]) #Measure the target qubit
return control_qfaCircuit #Returns the created quantum circuit
for length in range(range_lower,range_higher):
params = qfa_controlled_algorithm("a"* length, prime_number)
job = execute(params, sim_backend, shots=1000)
result = job.result()
print(accept(params), "\n", "Length:",length," " ,result.get_counts(params))
qfa_controlled_algorithm("a"* 3, prime_number).draw(output='mpl')
prime_number = 3
length = 2 # set the length so that it is not divisible by the prime_number
print("The length of a is", length, " while the prime number is", prime_number)
qfa1 = qfa_controlled_algorithm("a"* length, prime_number)
job = execute(qfa1, backend=device_backend, shots=100)
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts())
qfa1.draw(output='mpl')
print_number = length = 3 # set the length so that it is divisible by the prime_number
print("The length of a is", length, " while the prime number is", prime_number)
qfa2 = qfa_controlled_algorithm("a"* length, prime_number)
job = execute(qfa2, backend=device_backend, shots=100)
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts())
qfa2.draw(output='mpl')
|
https://github.com/khaledalam/QuantumComputingAndPrimesAndOthers
|
khaledalam
|
# Author: Khaled Alam(khaledalam.net@gmail.com)
'''
Guess binary string (secret) of length N in 1 shot only using quantum computing circuit!
~ by using clasical computers we need at least N shots to guess string (secret) of length N
~ by using quantum computer we need 1 shot to guess string (secret) of ANY length ( cool isn't it! ^^ )
'''
secret = '01000001' # `01000001` = `A`
from qiskit import *
n = len(secret)
qCircuit = QuantumCircuit(n+1, n) # n+1 qubits and n classical bits
qCircuit.x(n)
qCircuit.barrier()
qCircuit.h(range(n+1))
qCircuit.barrier()
for ii, OZ in enumerate(reversed(secret)):
if OZ == '1':
qCircuit.cx(ii, n)
qCircuit.barrier()
qCircuit.h(range(n+1))
qCircuit.barrier()
qCircuit.measure(range(n), range(n))
%matplotlib inline
qCircuit.draw(output='mpl')
# run on simulator
simulator = Aer.get_backend('qasm_simulator')
result = execute(qCircuit, backend=simulator, shots=1).result() # only 1 shot
from qiskit.visualization import plot_histogram
plot_histogram(
result.get_counts(qCircuit)
)
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit_nature.drivers import Molecule
from qiskit_nature.drivers.second_quantization import ElectronicStructureDriverType, ElectronicStructureMoleculeDriver
# PSPCz molecule
geometry = [['C', [ -0.2316640, 1.1348450, 0.6956120]],
['C', [ -0.8886300, 0.3253780, -0.2344140]],
['C', [ -0.1842470, -0.1935670, -1.3239330]],
['C', [ 1.1662930, 0.0801450, -1.4737160]],
['C', [ 1.8089230, 0.8832220, -0.5383540]],
['C', [ 1.1155860, 1.4218050, 0.5392780]],
['S', [ 3.5450920, 1.2449890, -0.7349240]],
['O', [ 3.8606900, 1.0881590, -2.1541690]],
['C', [ 4.3889120, -0.0620730, 0.1436780]],
['O', [ 3.8088290, 2.4916780, -0.0174650]],
['C', [ 4.6830900, 0.1064460, 1.4918230]],
['C', [ 5.3364470, -0.9144080, 2.1705280]],
['C', [ 5.6895490, -2.0818670, 1.5007820]],
['C', [ 5.4000540, -2.2323130, 0.1481350]],
['C', [ 4.7467230, -1.2180160, -0.5404770]],
['N', [ -2.2589180, 0.0399120, -0.0793330]],
['C', [ -2.8394600, -1.2343990, -0.1494160]],
['C', [ -4.2635450, -1.0769890, 0.0660760]],
['C', [ -4.5212550, 0.2638010, 0.2662190]],
['C', [ -3.2669630, 0.9823890, 0.1722720]],
['C', [ -2.2678900, -2.4598950, -0.3287380]],
['C', [ -3.1299420, -3.6058560, -0.3236210]],
['C', [ -4.5179520, -3.4797390, -0.1395160]],
['C', [ -5.1056310, -2.2512990, 0.0536940]],
['C', [ -5.7352450, 1.0074800, 0.5140960]],
['C', [ -5.6563790, 2.3761270, 0.6274610]],
['C', [ -4.4287740, 3.0501460, 0.5083650]],
['C', [ -3.2040560, 2.3409470, 0.2746950]],
['H', [ -0.7813570, 1.5286610, 1.5426490]],
['H', [ -0.7079140, -0.7911480, -2.0611600]],
['H', [ 1.7161320, -0.2933710, -2.3302930]],
['H', [ 1.6308220, 2.0660550, 1.2427990]],
['H', [ 4.4214900, 1.0345500, 1.9875450]],
['H', [ 5.5773000, -0.7951290, 3.2218590]],
['H', [ 6.2017810, -2.8762260, 2.0345740]],
['H', [ 5.6906680, -3.1381740, -0.3739110]],
['H', [ 4.5337010, -1.3031330, -1.6001680]],
['H', [ -1.1998460, -2.5827750, -0.4596910]],
['H', [ -2.6937370, -4.5881470, -0.4657540]],
['H', [ -5.1332290, -4.3740010, -0.1501080]],
['H', [ -6.1752900, -2.1516170, 0.1987120]],
['H', [ -6.6812260, 0.4853900, 0.6017680]],
['H', [ -6.5574610, 2.9529350, 0.8109620]],
['H', [ -4.3980410, 4.1305040, 0.5929440]],
['H', [ -2.2726630, 2.8838620, 0.1712760]]]
molecule = Molecule(geometry=geometry, charge=0, multiplicity=1)
driver = ElectronicStructureMoleculeDriver(molecule=molecule,
basis='631g*',
driver_type=ElectronicStructureDriverType.PYSCF)
num_ao = {
'C': 14,
'H': 2,
'N': 14,
'O': 14,
'S': 18,
}
##############################
# Provide your code here
num_C_atom =
num_H_atom =
num_N_atom =
num_O_atom =
num_S_atom =
num_atoms_total =
num_AO_total =
num_MO_total =
##############################
answer_ex2a ={
'C': num_C_atom,
'H': num_H_atom,
'N': num_N_atom,
'O': num_O_atom,
'S': num_S_atom,
'atoms': num_atoms_total,
'AOs': num_AO_total,
'MOs': num_MO_total
}
print(answer_ex2a)
# Check your answer and submit using the following code
from qc_grader.challenges.unimelb_2022 import grade_ex2a
grade_ex2a(answer_ex2a)
from qiskit_nature.drivers.second_quantization import HDF5Driver
driver_reduced = HDF5Driver("resources/PSPCz_reduced.hdf5")
properties = driver_reduced.run()
from qiskit_nature.properties.second_quantization.electronic import ElectronicEnergy
electronic_energy = properties.get_property(ElectronicEnergy)
print(electronic_energy)
from qiskit_nature.properties.second_quantization.electronic import ParticleNumber
##############################
# Provide your code here
particle_number =
num_electron =
num_MO =
num_SO =
num_qubits =
##############################
answer_ex2b = {
'electrons': num_electron,
'MOs': num_MO,
'SOs': num_SO,
'qubits': num_qubits
}
print(answer_ex2b)
# Check your answer and submit using the following code
from qc_grader.challenges.unimelb_2022 import grade_ex2b
grade_ex2b(answer_ex2b)
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
##############################
# Provide your code here
es_problem =
##############################
second_q_op = es_problem.second_q_ops()
print(second_q_op[0])
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper, ParityMapper, BravyiKitaevMapper
##############################
# Provide your code here
qubit_converter =
##############################
qubit_op = qubit_converter.convert(second_q_op[0])
print(qubit_op)
from qiskit_nature.circuit.library import HartreeFock
##############################
# Provide your code here
init_state =
##############################
init_state.draw()
from qiskit.circuit.library import EfficientSU2, TwoLocal, NLocal, PauliTwoDesign
from qiskit_nature.circuit.library import UCCSD, PUCCD, SUCCD
##############################
# Provide your code here
ansatz =
##############################
ansatz.decompose().draw()
from qiskit.algorithms import NumPyMinimumEigensolver
from qiskit_nature.algorithms import GroundStateEigensolver
##############################
# Provide your code here
numpy_solver =
numpy_ground_state_solver =
numpy_results =
##############################
exact_energy = numpy_results.computed_energies[0]
print(f"Exact electronic energy: {exact_energy:.6f} Hartree\n")
print(numpy_results)
# Check your answer and submit using the following code
from qc_grader.challenges.unimelb_2022 import grade_ex2c
grade_ex2c(numpy_results)
from qiskit.providers.aer import StatevectorSimulator, QasmSimulator
from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA, SLSQP
##############################
# Provide your code here
backend =
optimizer =
##############################
from qiskit.algorithms import VQE
from qiskit_nature.algorithms import VQEUCCFactory, GroundStateEigensolver
from jupyterplot import ProgressPlot
import numpy as np
error_threshold = 10 # mHartree
np.random.seed(5) # fix seed for reproducibility
initial_point = np.random.random(ansatz.num_parameters)
# for live plotting
pp = ProgressPlot(plot_names=['Energy'],
line_names=['Runtime VQE', f'Target + {error_threshold}mH', 'Target'])
intermediate_info = {
'nfev': [],
'parameters': [],
'energy': [],
'stddev': []
}
def callback(nfev, parameters, energy, stddev):
intermediate_info['nfev'].append(nfev)
intermediate_info['parameters'].append(parameters)
intermediate_info['energy'].append(energy)
intermediate_info['stddev'].append(stddev)
pp.update([[energy, exact_energy+error_threshold/1000, exact_energy]])
##############################
# Provide your code here
vqe =
vqe_ground_state_solver =
vqe_results =
##############################
print(vqe_results)
error = (vqe_results.computed_energies[0] - exact_energy) * 1000 # mHartree
print(f'Error is: {error:.3f} mHartree')
# Check your answer and submit using the following code
from qc_grader.challenges.unimelb_2022 import grade_ex2d
grade_ex2d(vqe_results)
from qiskit_nature.algorithms import QEOM
##############################
# Provide your code here
qeom_excited_state_solver =
qeom_results =
##############################
print(qeom_results)
# Check your answer and submit using the following code
from qc_grader.challenges.unimelb_2022 import grade_ex2e
grade_ex2e(qeom_results)
bandgap = qeom_results.computed_energies[1] - qeom_results.computed_energies[0]
bandgap # in Hartree
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-education', group='ibm-4', project='qiskit-hackathon')
backend = provider.get_backend('ibmq_qasm_simulator')
backend
from qiskit_nature.runtime import VQEProgram
error_threshold = 10 # mHartree
# for live plotting
pp = ProgressPlot(plot_names=['Energy'],
line_names=['Runtime VQE', f'Target + {error_threshold}mH', 'Target'])
intermediate_info = {
'nfev': [],
'parameters': [],
'energy': [],
'stddev': []
}
def callback(nfev, parameters, energy, stddev):
intermediate_info['nfev'].append(nfev)
intermediate_info['parameters'].append(parameters)
intermediate_info['energy'].append(energy)
intermediate_info['stddev'].append(stddev)
pp.update([[energy,exact_energy+error_threshold/1000, exact_energy]])
##############################
# Provide your code here
optimizer = {
'name': 'QN-SPSA', # leverage the Quantum Natural SPSA
# 'name': 'SPSA', # set to ordinary SPSA
'maxiter': 100,
}
runtime_vqe =
##############################
# Submit a runtime job using the following code
from qc_grader.challenges.unimelb_2022 import prepare_ex2f
runtime_job = prepare_ex2f(runtime_vqe, qubit_converter, es_problem)
# Check your answer and submit using the following code
from qc_grader.challenges.unimelb_2022 import grade_ex2f
grade_ex2f(runtime_job)
print(runtime_job.result().get("eigenvalue"))
# Please change backend before running the following code
runtime_job_real_device = prepare_ex2f(runtime_vqe, qubit_converter, es_problem, real_device=True)
print(runtime_job_real_device.result().get("eigenvalue"))
|
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
|
MonitSharma
|
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, IBMQ
from qiskit.compiler import transpile
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator
from qiskit.visualization import *
from qiskit.quantum_info import *
qc1 = QuantumCircuit(1)
qc1.x(0)
qc1.measure_all()
qc1.draw(output='mpl')
job1 = execute(qc1, backend=QasmSimulator(), shots=1024)
plot_histogram(job1.result().get_counts())
qc2 = QuantumCircuit(2)
# State Preparation
qc2.x(0)
qc2.barrier()
# Perform q_0 XOR 0
qc2.cx(0,1)
qc2.measure_all()
qc2.draw(output='mpl')
job2 = execute(qc2.reverse_bits(), backend=QasmSimulator(), shots=1024)
plot_histogram(job2.result().get_counts())
qc3 = QuantumCircuit(3)
# State Preparation
qc3.x(0)
qc3.x(1)
qc3.barrier()
# Perform q_0 XOR 0
qc3.ccx(0,1,2)
qc3.measure_all()
qc3.draw(output='mpl')
job3 = execute(qc3.reverse_bits(), backend=QasmSimulator(), shots=1024)
plot_histogram(job3.result().get_counts())
qc4 = QuantumCircuit(3)
# State Preparation
qc4.h(range(3))
qc4.measure_all()
qc4.draw(output='mpl')
job4 = execute(qc4.reverse_bits(), backend=QasmSimulator(), shots=8192)
plot_histogram(job4.result().get_counts())
from qiskit.providers.aer.noise import NoiseModel
from qiskit.test.mock import FakeMelbourne
device_backend = FakeMelbourne()
coupling_map = device_backend.configuration().coupling_map
noise_model = NoiseModel.from_backend(device_backend)
basis_gates = noise_model.basis_gates
result_noise = execute(qc4, QasmSimulator(),
shots=8192,
noise_model=noise_model,
coupling_map=coupling_map,
basis_gates=basis_gates).result()
plot_histogram(result_noise.get_counts())
qc3_t = transpile(qc3, basis_gates=basis_gates)
qc3_t.draw(output='mpl')
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
provider.backends()
ibmq_backend = provider.get_backend('ibmq_16_melbourne')
result_device = execute(qc4, backend=ibmq_backend, shots=8192).result()
plot_histogram(result_device.get_counts())
|
https://github.com/lynnlangit/learning-quantum
|
lynnlangit
|
#!/usr/bin/env python
# coding: utf-8
# # Solving linear systems of equations using HHL and its Qiskit implementation
# In this tutorial, we introduce the HHL algorithm, derive the circuit, and implement it using Qiskit. We show how to run the HHL on a simulator and on a five qubit device.
# ## Contents
# 1. [Introduction](#introduction)
# 2. [The HHL algorithm](#hhlalg)
# 1. [Some mathematical background](#mathbackground)
# 2. [Description of the HHL](#hhldescription)
# 3. [Quantum Phase Estimation (QPE) within HHL](#qpe)
# 4. [Non-exact QPE](#qpe2)
# 3. [Example 1: 4-qubit HHL](#example1)
# 4. [Qiskit Implementation](#implementation)
# 1. [Running HHL on a simulator: general method](#implementationsim)
# 2. [Running HHL on a real quantum device: optimised example](#implementationdev)
# 5. [Problems](#problems)
# 6. [References](#references)
# ## 1. Introduction <a id='introduction'></a>
#
# Systems of linear equations arise naturally in many real-life applications in a wide range of areas, such as in the solution of Partial Differential Equations, the calibration of financial models, fluid simulation or numerical field calculation. The problem can be defined as, given a matrix $A\in\mathbb{C}^{N\times N}$ and a vector $\vec{b}\in\mathbb{C}^{N}$, find $\vec{x}\in\mathbb{C}^{N}$ satisfying $A\vec{x}=\vec{b}$
#
# For example, take $N=2$,
#
# $$A = \begin{pmatrix}1 & -1/3\\-1/3 & 1 \end{pmatrix},\quad \vec{x}=\begin{pmatrix} x_{1}\\ x_{2}\end{pmatrix}\quad \text{and} \quad \vec{b}=\begin{pmatrix}1 \\ 0\end{pmatrix}$$
#
# Then the problem can also be written as find $x_{1}, x_{2}\in\mathbb{C}$ such that
# $$\begin{cases}x_{1} - \frac{x_{2}}{3} = 1 \\ -\frac{x_{1}}{3} + x_{2} = 0\end{cases} $$
#
# A system of linear equations is called $s$-sparse if $A$ has at most $s$ non-zero entries per row or column. Solving an $s$-sparse system of size $N$ with a classical computer requires $\mathcal{ O }(Ns\kappa\log(1/\epsilon))$ running time using the conjugate gradient method <sup>[1](#conjgrad)</sup>. Here $\kappa$ denotes the condition number of the system and $\epsilon$ the accuracy of the approximation.
#
# The HHL is a quantum algorithm to estimate a function of the solution with running time complexity of $\mathcal{ O }(\log(N)s^{2}\kappa^{2}/\epsilon)$<sup>[2](#hhl)</sup> when $A$ is a Hermitian matrix under the assumptions of efficient oracles for loading the data, Hamiltonian simulation and computing a function of the solution. This is an exponential speed up in the size of the system, however one crucial remark to keep in mind is that the classical algorithm returns the full solution, while the HHL can only approximate functions of the solution vector.
# ## 2. The HHL algorithm<a id='hhlalg'></a>
#
# ### A. Some mathematical background<a id='mathbackground'></a>
# The first step towards solving a system of linear equations with a quantum computer is to encode the problem in the quantum language. By rescaling the system, we can assume $\vec{b}$ and $\vec{x}$ to be normalised and map them to the respective quantum states $|b\rangle$ and $|x\rangle$. Usually the mapping used is such that $i^{th}$ component of $\vec{b}$ (resp. $\vec{x}$) corresponds to the amplitude of the $i^{th}$ basis state of the quantum state $|b\rangle$ (resp. $|x\rangle$). From now on, we will focus on the rescaled problem
#
# $$ A|x\rangle=|b\rangle$$
#
# Since $A$ is Hermitian, it has a spectral decomposition
# $$
# A=\sum_{j=0}^{N-1}\lambda_{j}|u_{j}\rangle\langle u_{j}|,\quad \lambda_{j}\in\mathbb{ R }
# $$
# where $|u_{j}\rangle$ is the $j^{th}$ eigenvector of $A$ with respective eigenvalue $\lambda_{j}$. Then,
# $$
# A^{-1}=\sum_{j=0}^{N-1}\lambda_{j}^{-1}|u_{j}\rangle\langle u_{j}|
# $$
# and the right hand side of the system can be written in the eigenbasis of $A$ as
# $$
# |b\rangle=\sum_{j=0}^{N-1}b_{j}|u_{j}\rangle,\quad b_{j}\in\mathbb{ C }
# $$
# It is useful to keep in mind that the goal of the HHL is to exit the algorithm with the readout register in the state
# $$
# |x\rangle=A^{-1}|b\rangle=\sum_{j=0}^{N-1}\lambda_{j}^{-1}b_{j}|u_{j}\rangle
# $$
# Note that here we already have an implicit normalisation constant since we are talking about a quantum state.
# ### B. Description of the HHL algorithm <a id='hhldescription'></a>
#
# The algorithm uses three quantum registers, all of them set to $|0\rangle $ at the beginning of the algorithm. One register, which we will denote with the subindex $n_{l}$, is used to store a binary representation of the eigenvalues of $A$. A second register, denoted by $n_{b}$, contains the vector solution, and from now on $N=2^{n_{b}}$. There is an extra register, for the auxiliary qubits. These are qubits used as intermediate steps in the individual computations but will be ignored in the following description since they are set to $|0\rangle $ at the beginning of each computation and restored back to the $|0\rangle $ state at the end of the individual operation.
#
# The following is an outline of the HHL algorithm with a high-level drawing of the corresponding circuit. For simplicity all computations are assumed to be exact in the ensuing description, and a more detailed explanation of the non-exact case is given in Section [2.D.](#qpe2).
#
# <img src="images/hhlcircuit.png" width = "75%" height = "75%">
#
# 1. Load the data $|b\rangle\in\mathbb{ C }^{N}$. That is, perform the transformation
# $$ |0\rangle _{n_{b}} \mapsto |b\rangle _{n_{b}} $$
# 2. Apply Quantum Phase Estimation (QPE) with
# $$
# U = e ^ { i A t } := \sum _{j=0}^{N-1}e ^ { i \lambda _ { j } t } |u_{j}\rangle\langle u_{j}|
# $$
# The quantum state of the register expressed in the eigenbasis of $A$ is now
# $$
# \sum_{j=0}^{N-1} b _ { j } |\lambda _ {j }\rangle_{n_{l}} |u_{j}\rangle_{n_{b}}
# $$
# where $|\lambda _ {j }\rangle_{n_{l}}$ is the $n_{l}$-bit binary representation of $\lambda _ {j }$.
#
# 3. Add an auxiliary qubit and apply a rotation conditioned on $|\lambda_{ j }\rangle$,
# $$
# \sum_{j=0}^{N-1} b _ { j } |\lambda _ { j }\rangle_{n_{l}}|u_{j}\rangle_{n_{b}} \left( \sqrt { 1 - \frac { C^{2} } { \lambda _ { j } ^ { 2 } } } |0\rangle + \frac { C } { \lambda _ { j } } |1\rangle \right)
# $$
# where $C$ is a normalisation constant, and, as expressed in the current form above, should be less than the smallest eigenvalue $\lambda_{min}$ in magnitude, i.e., $|C| < \lambda_{min}$.
#
# 4. Apply QPE$^{\dagger}$. Ignoring possible errors from QPE, this results in
# $$
# \sum_{j=0}^{N-1} b _ { j } |0\rangle_{n_{l}}|u_{j}\rangle_{n_{b}} \left( \sqrt { 1 - \frac {C^{2} } { \lambda _ { j } ^ { 2 } } } |0\rangle + \frac { C } { \lambda _ { j } } |1\rangle \right)
# $$
#
# 5. Measure the auxiliary qubit in the computational basis. If the outcome is $1$, the register is in the post-measurement state
# $$
# \left( \sqrt { \frac { 1 } { \sum_{j=0}^{N-1} \left| b _ { j } \right| ^ { 2 } / \left| \lambda _ { j } \right| ^ { 2 } } } \right) \sum _{j=0}^{N-1} \frac{b _ { j }}{\lambda _ { j }} |0\rangle_{n_{l}}|u_{j}\rangle_{n_{b}}
# $$
# which up to a normalisation factor corresponds to the solution.
#
# 6. Apply an observable $M$ to calculate $F(x):=\langle x|M|x\rangle$.
# ### C. Quantum Phase Estimation (QPE) within HHL <a id='qpe'></a>
#
# Quantum Phase Estimation is described in more detail in Chapter 3. However, since this quantum procedure is at the core of the HHL algorithm, we recall here the definition. Roughly speaking, it is a quantum algorithm which, given a unitary $U$ with eigenvector $|\psi\rangle_{m}$ and eigenvalue $e^{2\pi i\theta}$, finds $\theta$. We can formally define this as follows.
#
# **Definition:** Let $U\in\mathbb{ C }^{2^{m}\times 2^{m}}$ be unitary and let $|\psi\rangle_{m}\in\mathbb{ C }^{2^{m}}$ be one of its eigenvectors with respective eigenvalue $e^{2\pi i\theta}$. The **Quantum Phase Estimation** algorithm, abbreviated **QPE**, takes as inputs the unitary gate for $U$ and the state $|0\rangle_{n}|\psi\rangle_{m}$ and returns the state $|\tilde{\theta}\rangle_{n}|\psi\rangle_{m}$. Here $\tilde{\theta}$ denotes a binary approximation to $2^{n}\theta$ and the $n$ subscript denotes it has been truncated to $n$ digits.
# $$
# \operatorname { QPE } ( U , |0\rangle_{n}|\psi\rangle_{m} ) = |\tilde{\theta}\rangle_{n}|\psi\rangle_{m}
# $$
#
# For the HHL we will use QPE with $U = e ^ { i A t }$, where $A$ is the matrix associated to the system we want to solve. In this case,
# $$
# e ^ { i A t } = \sum_{j=0}^{N-1}e^{i\lambda_{j}t}|u_{j}\rangle\langle u_{j}|
# $$
# Then, for the eigenvector $|u_{j}\rangle_{n_{b}}$, which has eigenvalue $e ^ { i \lambda _ { j } t }$, QPE will output $|\tilde{\lambda }_ { j }\rangle_{n_{l}}|u_{j}\rangle_{n_{b}}$. Where $\tilde{\lambda }_ { j }$ represents an $n_{l}$-bit binary approximation to $2^{n_l}\frac{\lambda_ { j }t}{2\pi}$. Therefore, if each $\lambda_{j}$ can be exactly represented with $n_{l}$ bits,
# $$
# \operatorname { QPE } ( e ^ { i A t } , \sum_{j=0}^{N-1}b_{j}|0\rangle_{n_{l}}|u_{j}\rangle_{n_{b}} ) = \sum_{j=0}^{N-1}b_{j}|\lambda_{j}\rangle_{n_{l}}|u_{j}\rangle_{n_{b}}
# $$
# ### D. Non-exact QPE <a id='qpe2'></a>
#
# In reality, the quantum state of the register after applying QPE to the initial state is
# $$
# \sum _ { j=0 }^{N-1} b _ { j } \left( \sum _ { l = 0 } ^ { 2 ^ { n_{l} } - 1 } \alpha _ { l | j } |l\rangle_{n_{l}} \right)|u_{j}\rangle_{n_{b}}
# $$
# where
# $$
# \alpha _ { l | j } = \frac { 1 } { 2 ^ { n_{l} } } \sum _ { k = 0 } ^ { 2^{n_{l}}- 1 } \left( e ^ { 2 \pi i \left( \frac { \lambda _ { j } t } { 2 \pi } - \frac { l } { 2 ^ { n_{l} } } \right) } \right) ^ { k }
# $$
#
# Denote by $\tilde{\lambda_{j}}$ the best $n_{l}$-bit approximation to $\lambda_{j}$, $1\leq j\leq N$. Then we can relabel the $n_{l}$-register so that $\alpha _ { l | j }$ denotes the amplitude of $|l + \tilde { \lambda } _ { j } \rangle_{n_{l}}$. So now,
# $$
# \alpha _ { l | j } : = \frac { 1 } { 2 ^ { n_{l}} } \sum _ { k = 0 } ^ { 2 ^ { n_{l} } - 1 } \left( e ^ { 2 \pi i \left( \frac { \lambda _ { j } t } { 2 \pi } - \frac { l + \tilde { \lambda } _ { j } } { 2 ^ { n_{l} } } \right) } \right) ^ { k }
# $$
# If each $\frac { \lambda _ { j } t } { 2 \pi }$ can be represented exactly with $n_{l}$ binary bits, then $\frac { \lambda _ { j } t } { 2 \pi }=\frac { \tilde { \lambda } _ { j } } { 2 ^ { n_{l} } }$ $\forall j$. Therefore in this case $\forall j$, $1\leq j \leq N$, it holds that $\alpha _ { 0 | j } = 1$ and $\alpha _ { l | j } = 0 \quad \forall l \neq 0$. Only in this case we can write that the state of the register after QPE is
# $$
# \sum_{j=0}^{N-1} b _ { j } |\lambda _ {j }\rangle_{n_{l}} |u_{j}\rangle_{n_{b}}
# $$
# Otherwise, $|\alpha _ { l | j }|$ is large if and only if $\frac { \lambda _ { j } t } { 2 \pi } \approx \frac { l + \tilde { \lambda } _ { j } } { 2 ^ { n_{l} } }$ and the state of the register is
# $$
# \sum _ { j=0 }^{N-1} \sum _ { l = 0 } ^ { 2 ^ { n_{l} } - 1 } \alpha _ { l | j } b _ { j }|l\rangle_{n_{l}} |u_{j}\rangle_{n_{b}}
# $$
# ## 3. Example: 4-qubit HHL<a id='example1'></a>
#
# Let's take the small example from the introduction to illustrate the algorithm. That is,
# $$A = \begin{pmatrix}1 & -1/3\\-1/3 & 1 \end{pmatrix}\quad \text{and} \quad |b\rangle=\begin{pmatrix}1 \\ 0\end{pmatrix}$$
#
# We will use $n_{b}=1$ qubit to represent $|b\rangle$, and later the solution $|x\rangle$, $n_{l}=2$ qubits to store the binary representation of the eigenvalues and $1$ auxiliary qubit to store whether the conditioned rotation, hence the algorithm, was successful.
#
# For the purpose of illustrating the algorithm, we will cheat a bit and calculate the eigenvalues of $A$ to be able to choose $t$ to obtain an exact binary representation of the rescaled eigenvalues in the $n_{l}$-register. However, keep in mind that for the HHL algorithm implementation one does not need previous knowledge of the eigenvalues. Having said that, a short calculation will give
# $$\lambda_{1} = 2/3\quad\text{and}\quad\lambda_{2}=4/3$$
#
# Recall from the previous section that the QPE will output an $n_{l}$-bit ($2$-bit in this case) binary approximation to $\frac{\lambda_ { j }t}{2\pi}$. Therefore, if we set
# $$t=2\pi\cdot \frac{3}{8}$$
# the QPE will give a $2$-bit binary approximation to
# $$\frac{\lambda_ { 1 }t}{2\pi} = 1/4\quad\text{and}\quad\frac{\lambda_ { 2 }t}{2\pi}=1/2$$
# which is, respectively,
# $$|01\rangle_{n_{l}}\quad\text{and}\quad|10\rangle_{n_{l}}$$
#
# The eigenvectors are, respectively,
# $$|u_{1}\rangle=\begin{pmatrix}1 \\ -1\end{pmatrix}\quad\text{and}\quad|u_{2}\rangle=\begin{pmatrix}1 \\ 1\end{pmatrix}$$
# Again, keep in mind that one does not need to compute the eigenvectors for the HHL implementation. In fact, a general Hermitian matrix $A$ of dimension $N$ can have up to $N$ different eigenvalues, therefore calculating them would take $\mathcal{O}(N)$ time and the quantum advantage would be lost.
#
# We can then write $|b\rangle$ in the eigenbasis of $A$ as
# $$|b\rangle _{n_{b}}=\sum_{j=1}^{2}\frac{1}{\sqrt{2}}|u_{j}\rangle _{n_{b}}$$
#
# Now we are ready to go through the different steps of the HHL algorithm.
#
# 1. State preparation in this example is trivial since $|b\rangle=|0\rangle$.
# 2. Applying QPE will yield
# $$
# \frac{1}{\sqrt{2}}|01\rangle|u_{1}\rangle + \frac{1}{\sqrt{2}}|10\rangle|u_{2}\rangle
# $$
# 3. Conditioned rotation with $C=1/8$ that is less than the smallest (rescaled) eigenvalue of $\frac {1} {4}$. Note, the contant $C$ here needs to be chosen such that it is less than the smallest (rescaled) eigenvalue of $\frac {1} {4}$ but as large as possible so that when the auxiliary qubit is measured, the probabilit of it being in the state $|1>$ is large.
# $$\frac{1}{\sqrt{2}}|01\rangle|u_{1}\rangle\left( \sqrt { 1 - \frac { (1/8)^{2} } {(1/4)^{2} } } |0\rangle + \frac { 1/8 } { 1/4 } |1\rangle \right) + \frac{1}{\sqrt{2}}|10\rangle|u_{2}\rangle\left( \sqrt { 1 - \frac { (1/8)^{2} } {(1/2)^{2} } } |0\rangle + \frac { 1/8 } { 1/2 } |1\rangle \right)
# $$
# $$
# =\frac{1}{\sqrt{2}}|01\rangle|u_{1}\rangle\left( \sqrt { 1 - \frac { 1 } {4 } } |0\rangle + \frac { 1 } { 2 } |1\rangle \right) + \frac{1}{\sqrt{2}}|10\rangle|u_{2}\rangle\left( \sqrt { 1 - \frac { 1 } {16 } } |0\rangle + \frac { 1 } { 4 } |1\rangle \right)
# $$
# 4. After applying QPE$^{\dagger}$ the quantum computer is in the state
# $$
# \frac{1}{\sqrt{2}}|00\rangle|u_{1}\rangle\left( \sqrt { 1 - \frac { 1 } {4 } } |0\rangle + \frac { 1 } { 2 } |1\rangle \right) + \frac{1}{\sqrt{2}}|00\rangle|u_{2}\rangle\left( \sqrt { 1 - \frac { 1 } {16 } } |0\rangle + \frac { 1 } { 4 } |1\rangle \right)
# $$
# 5. On outcome $1$ when measuring the auxiliary qubit, the state is
# $$
# \frac{\frac{1}{\sqrt{2}}|00\rangle|u_{1}\rangle\frac { 1 } { 2 } |1\rangle + \frac{1}{\sqrt{2}}|00\rangle|u_{2}\rangle\frac { 1 } { 4 } |1\rangle}{\sqrt{5/32}}
# $$
# A quick calculation shows that
# $$
# \frac{\frac{1}{2\sqrt{2}}|u_{1}\rangle+ \frac{1}{4\sqrt{2}}|u_{2}\rangle}{\sqrt{5/32}} = \frac{|x\rangle}{||x||}
# $$
# 6. Without using extra gates, we can compute the norm of $|x\rangle$: it is the probability of measuring $1$ in the auxiliary qubit from the previous step.
# $$
# P(|1\rangle) = \left(\frac{1}{2\sqrt{2}}\right)^{2} + \left(\frac{1}{4\sqrt{2}}\right)^{2} = \frac{5}{32} = ||x||^{2}
# $$
#
#
# ## 4. Qiskit Implementation<a id='implementation'></a>
# Now that we have analytically solved the problem from the example we are going to use it to illustrate how to run the HHL on a quantum simulator and on the real hardware. For the quantum simulator, Qiskit already provides an implementation of the HHL algorithm requiring only the matrix $A$ and $|b\rangle$ as inputs in the simplest example. Although we can give the algorithm a general Hermitian matrix and an arbitrary initial state as NumPy arrays, in these cases the quantum algorithm will not achieve an exponential speedup. This is because the default implementation is exact and therefore exponential in the number of qubits (there is no algorithm that can prepare exactly an arbitrary quantum state using polynomial resources in the number of qubits or that can perform exactly the operation $e^{iAt}$ for some general Hermitian matrix $A$ using polynomial resources in the number of qubits). If we know an efficient implementation for a particular problem, the matrix and/or the vector can be given as `QuantumCircuit` objects. Alternatively, there's already an efficient implementation for tridiagonal Toeplitz matrices and in the future there might be more.
#
# However,at the time of writing the existing quantum computers are noisy and can only run small circuits. Therefore, in Section [4.B.](#implementationdev) we will see an optimised circuit that can be used for a class of problems to which our example belongs and mention the existing procedures to deal with noise in quantum computers.
# ## A. Running HHL on a simulator: general method<a id='implementationsim'></a>
# The interface for all algorithms to solve the linear system problem is `LinearSolver`. The problem to be solved is only specified when the `solve()` method is called:
# ```python
# LinearSolver(...).solve(matrix, vector)
# ```
#
# The simplest implementation takes the matrix and the vector as NumPy arrays. Below we also create a `NumPyLinearSolver` (the classical algorithm) to validate our solutions.
# In[1]:
###### see this link to setup Qiskit --> https://qiskit.org/textbook/ch-prerequisites/setting-the-environment.html #####
import numpy as np
from qiskit.algorithms.linear_solvers.numpy_linear_solver import NumPyLinearSolver
from qiskit.algorithms.linear_solvers.hhl import HHL
matrix = np.array([[1, -1/3], [-1/3, 1]])
vector = np.array([1, 0])
naive_hhl_solution = HHL().solve(matrix, vector)
# For the classical solver we need to rescale the right hand side (i.e. `vector / np.linalg.norm(vector)`) to take into account the renormalisation that occurs once `vector` is encoded in a quantum state within HHL.
# In[2]:
classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector))
# The `linear_solvers` package contains a folder called `matrices` intended to be a placeholder for efficient implementations of particular types of matrices. At the time of writing the only truly efficient implementation it contains (i.e. complexity scaling polynomially in the number of qubits) is the `TridiagonalToeplitz` class. Tridiagonal Toeplitz symmetric real matrices are of the following form
# $$A = \begin{pmatrix}a & b & 0 & 0\\b & a & b & 0 \\ 0 & b & a & b \\ 0 & 0 & b & a \end{pmatrix}, a,b\in\mathbb{R}$$
# (note that in this setting we do not consider non symmetric matrices since the HHL algorithm assumes that the input matrix is Hermitian).
#
# Since the matrix $A$ from our example is of this form we can create an instance of `TridiagonalToeplitz(num_qubits, a, b)` and compare the results to solving the system with an array as input.
# In[3]:
from qiskit.algorithms.linear_solvers.matrices.tridiagonal_toeplitz import TridiagonalToeplitz
tridi_matrix = TridiagonalToeplitz(1, 1, -1 / 3)
tridi_solution = HHL().solve(tridi_matrix, vector)
# Recall that the HHL algorithm can find a solution exponentially faster in the size of the system than their classical counterparts (i.e. logarithmic complexity instead of polynomial). However the cost for this exponential speedup is that we do not obtain the full solution vector.
# Instead, we obtain a quantum state representing the vector $x$ and learning all the components of this vector would take a linear time in its dimension, diminishing any speedup obtained by the quantum algorithm.
#
# Therefore, we can only compute functions from $x$ (the so called observables) to learn information about the solution.
# This is reflected in the `LinearSolverResult` object returned by `solve()`, which contains the following properties
# - `state`: either the circuit that prepares the solution or the solution as a vector
# - `euclidean_norm`: the euclidean norm if the algorithm knows how to calculate it
# - `observable`: the (list of) calculated observable(s)
# - `circuit_results`: the observable results from the (list of) circuit(s)
#
# Let's ignore `observable` and `circuit_results` for the time being and check the solutions we obtained before.
#
# First, `classical_solution` was the result from a classical algorithm, so if we call `.state` it will return an array:
# In[4]:
print('classical state:', classical_solution.state)
# Our other two examples were quantum algorithms, hence we can only access to the quantum state. This is achieved by returning the quantum circuit that prepares the solution state:
# In[5]:
print('naive state:')
print(naive_hhl_solution.state)
print('tridiagonal state:')
print(tridi_solution.state)
# Recall that the Euclidean norm for a vector $\mathbf{x}=(x_1,\dots,x_N)$ is defined as $||\mathbf{x}||=\sqrt{\sum_{i=1}^N x_i^2}$. Therefore, the probability of measuring $1$ in the auxiliary qubit from Step $5$ in Section B is the squared norm of $\mathbf{x}$. This means that the HHL algorithm can always calculate the euclidean norm of the solution and we can compare the accuracy of the results:
# In[6]:
print('classical Euclidean norm:', classical_solution.euclidean_norm)
print('naive Euclidean norm:', naive_hhl_solution.euclidean_norm)
print('tridiagonal Euclidean norm:', tridi_solution.euclidean_norm)
# Comparing the solution vectors componentwise is more tricky, reflecting again the idea that we cannot obtain the full solution vector from the quantum algorithm. However, for educational purposes we can check that indeed the different solution vectors obtained are a good approximation at the vector component level as well.
#
# To do so first we need to use `Statevector` from the `quantum_info` package and extract the right vector components, i.e. those corresponding to the ancillary qubit (bottom in the circuits) being $1$ and the work qubits (the two middle in the circuits) being $0$. Thus, we are interested in the states `1000` and `1001`, corresponding to the first and second components of the solution vector respectively.
# In[7]:
from qiskit.quantum_info import Statevector
naive_sv = Statevector(naive_hhl_solution.state).data
tridi_sv = Statevector(tridi_solution.state).data
# Extract the right vector components. 1000 corresponds to the index 8 and 1001 corresponds to the index 9
naive_full_vector = np.array([naive_sv[8], naive_sv[9]])
tridi_full_vector = np.array([tridi_sv[8], tridi_sv[9]])
print('naive raw solution vector:', naive_full_vector)
print('tridi raw solution vector:', tridi_full_vector)
# At a first glance it might seem that this is wrong because the components are complex numbers instead of reals. However note that the imaginary part is very small, most likely due to computer accuracy, and can be disregarded in this case.
# In[8]:
naive_full_vector = np.real(naive_full_vector)
tridi_full_vector = np.real(tridi_full_vector)
# Next, we will divide the vectors by their respective norms to suppress any constants coming from the different parts of the circuits. The full solution vector can then be recovered by multiplying these normalised vectors by the respective Euclidean norms calculated above:
# In[9]:
print('full naive solution vector:', naive_hhl_solution.euclidean_norm*naive_full_vector/np.linalg.norm(naive_full_vector))
print('full tridi solution vector:', tridi_solution.euclidean_norm*tridi_full_vector/np.linalg.norm(tridi_full_vector))
print('classical state:', classical_solution.state)
# It should not come as a surprise that `naive_hhl_solution` is exact because all the default methods used are exact. However, `tridi_solution` is exact only in the $2\times 2$ system size case. For larger matrices it will be an approximation, as shown in the slightly larger example below.
# In[10]:
from scipy.sparse import diags
num_qubits = 2
matrix_size = 2 ** num_qubits
# entries of the tridiagonal Toeplitz symmetric matrix
a = 1
b = -1/3
matrix = diags([b, a, b], [-1, 0, 1], shape=(matrix_size, matrix_size)).toarray()
vector = np.array([1] + [0]*(matrix_size - 1))
# run the algorithms
classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector))
naive_hhl_solution = HHL().solve(matrix, vector)
tridi_matrix = TridiagonalToeplitz(num_qubits, a, b)
tridi_solution = HHL().solve(tridi_matrix, vector)
print('classical euclidean norm:', classical_solution.euclidean_norm)
print('naive euclidean norm:', naive_hhl_solution.euclidean_norm)
print('tridiagonal euclidean norm:', tridi_solution.euclidean_norm)
# We can also compare the difference in resources from the exact method and the efficient implementation. The $2\times 2$ system size is again special in that the exact algorithm requires less resources, but as we increase the system size, we can see that indeed the exact method scales exponentially in the number of qubits while `TridiagonalToeplitz` is polynomial.
# In[11]:
from qiskit import transpile
num_qubits = list(range(1,5))
a = 1
b = -1/3
i=1
# calculate the circuit depths for different number of qubits to compare the use of resources
naive_depths = []
tridi_depths = []
for nb in num_qubits:
matrix = diags([b, a, b], [-1, 0, 1], shape=(2**nb, 2**nb)).toarray()
vector = np.array([1] + [0]*(2**nb -1))
naive_hhl_solution = HHL().solve(matrix, vector)
tridi_matrix = TridiagonalToeplitz(nb, a, b)
tridi_solution = HHL().solve(tridi_matrix, vector)
naive_qc = transpile(naive_hhl_solution.state,basis_gates=['id', 'rz', 'sx', 'x', 'cx'])
tridi_qc = transpile(tridi_solution.state,basis_gates=['id', 'rz', 'sx', 'x', 'cx'])
naive_depths.append(naive_qc.depth())
tridi_depths.append(tridi_qc.depth())
i +=1
# In[ ]:
sizes = [str(2**nb)+"x"+str(2**nb) for nb in num_qubits]
columns = ['size of the system', 'quantum_solution depth', 'tridi_solution depth']
data = np.array([sizes, naive_depths, tridi_depths])
row_format ="{:>23}" * (len(columns) + 2)
for team, row in zip(columns, data):
print(row_format.format(team, *row))
# The reason the implementation still seems to need exponential resources is because the current conditioned rotation implementation (step 3 from Section 2.B) is exact (i.e. needs exponential resources in $n_l$). Instead we can calculate how many more resources the default implementation needs compared to Tridiagonal - since they only differ in how they implement $e^{iAt}$:
# In[13]:
print('excess:', [naive_depths[i] - tridi_depths[i] for i in range(0, len(naive_depths))])
# In the near future the plan is to integrate `qiskit.circuit.library.arithmetics.PiecewiseChebyshev` to obtain a polynomial implementation of the conditioned rotation as well.
#
# Now we can return to the topic of observables and find out what the `observable` and `circuit_results` properties contain.
#
# The way to compute functions of the solution vector $\mathbf{x}$ is through giving the `.solve()` method a `LinearSystemObservable` as input. There are are two types of available `LinearSystemObservable` which can be given as input:
# In[12]:
from qiskit.algorithms.linear_solvers.observables import AbsoluteAverage, MatrixFunctional
# For a vector $\mathbf{x}=(x_1,...,x_N)$, the `AbsoluteAverage` observable computes $|\frac{1}{N}\sum_{i=1}^{N}x_i|$.
# In[13]:
num_qubits = 1
matrix_size = 2 ** num_qubits
# entries of the tridiagonal Toeplitz symmetric matrix
a = 1
b = -1/3
matrix = diags([b, a, b], [-1, 0, 1], shape=(matrix_size, matrix_size)).toarray()
vector = np.array([1] + [0]*(matrix_size - 1))
tridi_matrix = TridiagonalToeplitz(1, a, b)
average_solution = HHL().solve(tridi_matrix, vector, AbsoluteAverage())
classical_average = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector), AbsoluteAverage())
print('quantum average:', average_solution.observable)
print('classical average:', classical_average.observable)
print('quantum circuit results:', average_solution.circuit_results)
# The `MatrixFunctional` observable computes $\mathbf{x}^T B \mathbf{x}$ for a vector $\mathbf{x}$ and a tridiagonal symmetric Toeplitz matrix $B$. The class takes the main and off diagonal values of the matrix for its constuctor method.
# In[14]:
observable = MatrixFunctional(1, 1 / 2)
functional_solution = HHL().solve(tridi_matrix, vector, observable)
classical_functional = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector), observable)
print('quantum functional:', functional_solution.observable)
print('classical functional:', classical_functional.observable)
print('quantum circuit results:', functional_solution.circuit_results)
# Therefore, `observable` contains the final value of the function on $\mathbf{x}$, while `circuit_results` contains the raw values obtained from the circuit and used to process the result of `observable`.
#
# This 'how to process the result' is better explained by looking at what arguments `.solve()` takes. The `solve()` method accepts up to five arguments:
# ```python
# def solve(self, matrix: Union[np.ndarray, QuantumCircuit],
# vector: Union[np.ndarray, QuantumCircuit],
# observable: Optional[Union[LinearSystemObservable, BaseOperator,
# List[BaseOperator]]] = None,
# post_rotation: Optional[Union[QuantumCircuit, List[QuantumCircuit]]] = None,
# post_processing: Optional[Callable[[Union[float, List[float]]],
# Union[float, List[float]]]] = None) \
# -> LinearSolverResult:
# ```
# The first two are the matrix defining the linear system and the vector right hand side of the equation, which we have already covered. The remaining parameters concern the (list of) observable(s) to be computed out of the solution vector $x$, and can be specified in two different ways. One option is to give as the third and last parameter a (list of) `LinearSystemObservable`(s). Alternatively, we can give our own implementations of the `observable`, `post_rotation` and `post_processing`, where
# - `observable` is the operator to compute the expected value of the observable and can be e.g. a `PauliSumOp`
# - `post_rotation` is the circuit to be applied to the solution to extract information if additional gates are needed.
# - `post_processing` is the function to compute the value of the observable from the calculated probabilities.
#
# In other words, there will be as many `circuit_results` as `post_rotation` circuits, and `post_processing` is telling the algorithm how to use the values we see when we print `circuit_results` to obtain the value we see when we print `observable`.
#
# Finally, the `HHL` class accepts the following parameters in its constructor method:
# - error tolerance : the accuracy of the approximation of the solution, the default is `1e-2`
# - expectation : how the expectation values are evaluated, the default is `PauliExpectation`
# - quantum instance: the `QuantumInstance` or backend, the default is a `Statevector` simulation
# In[15]:
from qiskit import BasicAer
backend = BasicAer.get_backend('qasm_simulator')
hhl = HHL(1e-3, quantum_instance=backend)
accurate_solution = hhl.solve(matrix, vector)
classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector))
print(accurate_solution.euclidean_norm)
print(classical_solution.euclidean_norm)
# ## B. Running HHL on a real quantum device: optimised example<a id='implementationdev'></a>
# In the previous section we ran the standard algorithm provided in Qiskit and saw that it uses $7$ qubits, has a depth of ~$100$ gates and requires a total of $54$ CNOT gates. These numbers are not feasible for the current available hardware, therefore we need to decrease these quantities. In particular, the goal will be to reduce the number of CNOTs by a factor of $5$ since they have worse fidelity than single-qubit gates. Furthermore, we can reduce the number of qubits to $4$ as was the original statement of the problem: the Qiskit method was written for a general problem and that is why it requires $3$ additional auxiliary qubits.
#
# However, solely decreasing the number of gates and qubits will not give a good approximation to the solution on real hardware. This is because there are two sources of errors: those that occur during the run of the circuit and readout errors.
#
# Qiskit provides a module to mitigate the readout errors by individually preparing and measuring all basis states, a detailed treatment on the topic can be found in the paper by Dewes et al.<sup>[3](#readouterr)</sup> To deal with the errors occurring during the run of the circuit, Richardson extrapolation can be used to calculate the error to the zero limit by running the circuit three times, each replacing each CNOT gate by $1$, $3$ and $5$ CNOTs respectively<sup>[4](#richardson)</sup>. The idea is that theoretically the three circuits should produce the same result, but in real hardware adding CNOTs means amplifying the error. Since we know that we have obtained results with an amplified error, and we can estimate by how much the error was amplified in each case, we can recombine the quantities to obtain a new result that is a closer approximation to the analytic solution than any of the previous obtained values.
#
# Below we give the optimised circuit that can be used for any problem of the form
# $$A = \begin{pmatrix}a & b\\b & a \end{pmatrix}\quad \text{and} \quad |b\rangle=\begin{pmatrix}\cos(\theta) \\ \sin(\theta)\end{pmatrix},\quad a,b,\theta\in\mathbb{R}$$
#
# The following optimisation was extracted from a work on the HHL for tridiagonal symmetric matrices<sup>[[5]](#tridi)</sup>, this particular circuit was derived with the aid of the UniversalQCompiler software<sup>[[6]](#qcompiler)</sup>.
#
# In[16]:
from qiskit import QuantumRegister, QuantumCircuit
import numpy as np
t = 2 # This is not optimal; As an exercise, set this to the
# value that will get the best results. See section 8 for solution.
nqubits = 4 # Total number of qubits
nb = 1 # Number of qubits representing the solution
nl = 2 # Number of qubits representing the eigenvalues
theta = 0 # Angle defining |b>
a = 1 # Matrix diagonal
b = -1/3 # Matrix off-diagonal
# Initialize the quantum and classical registers
qr = QuantumRegister(nqubits)
# Create a Quantum Circuit
qc = QuantumCircuit(qr)
qrb = qr[0:nb]
qrl = qr[nb:nb+nl]
qra = qr[nb+nl:nb+nl+1]
# State preparation.
qc.ry(2*theta, qrb[0])
# QPE with e^{iAt}
for qu in qrl:
qc.h(qu)
qc.p(a*t, qrl[0])
qc.p(a*t*2, qrl[1])
qc.u(b*t, -np.pi/2, np.pi/2, qrb[0])
# Controlled e^{iAt} on \lambda_{1}:
params=b*t
qc.p(np.pi/2,qrb[0])
qc.cx(qrl[0],qrb[0])
qc.ry(params,qrb[0])
qc.cx(qrl[0],qrb[0])
qc.ry(-params,qrb[0])
qc.p(3*np.pi/2,qrb[0])
# Controlled e^{2iAt} on \lambda_{2}:
params = b*t*2
qc.p(np.pi/2,qrb[0])
qc.cx(qrl[1],qrb[0])
qc.ry(params,qrb[0])
qc.cx(qrl[1],qrb[0])
qc.ry(-params,qrb[0])
qc.p(3*np.pi/2,qrb[0])
# Inverse QFT
qc.h(qrl[1])
qc.rz(-np.pi/4,qrl[1])
qc.cx(qrl[0],qrl[1])
qc.rz(np.pi/4,qrl[1])
qc.cx(qrl[0],qrl[1])
qc.rz(-np.pi/4,qrl[0])
qc.h(qrl[0])
# Eigenvalue rotation
t1=(-np.pi +np.pi/3 - 2*np.arcsin(1/3))/4
t2=(-np.pi -np.pi/3 + 2*np.arcsin(1/3))/4
t3=(np.pi -np.pi/3 - 2*np.arcsin(1/3))/4
t4=(np.pi +np.pi/3 + 2*np.arcsin(1/3))/4
qc.cx(qrl[1],qra[0])
qc.ry(t1,qra[0])
qc.cx(qrl[0],qra[0])
qc.ry(t2,qra[0])
qc.cx(qrl[1],qra[0])
qc.ry(t3,qra[0])
qc.cx(qrl[0],qra[0])
qc.ry(t4,qra[0])
qc.measure_all()
print("Depth: %i" % qc.depth())
print("CNOTS: %i" % qc.count_ops()['cx'])
qc.draw(fold=-1)
# The code below takes as inputs our circuit, the real hardware backend and the set of qubits we want to use, and returns and instance that can be run on the specified device. Creating the circuits with $3$ and $5$ CNOTs is the same but calling the transpile method with the right quantum circuit.
#
# Real hardware devices need to be recalibrated regularly, and the fidelity of a specific qubit or gate can change over time. Furthermore, different chips have different connectivities. If we try to run a circuit that performs a two-qubit gate between two qubits that are not connected on the specified device, the transpiler will add SWAP gates. Therefore it is good practice to check with the IBM Quantum Experience webpage<sup>[[7]](#qexperience)</sup> before running the following code and choose a set of qubits with the right connectivity and lowest error rates at the given time.
# In[17]:
from qiskit import BasicAer, ClassicalRegister, IBMQ
from qiskit.compiler import transpile
from qiskit.ignis.mitigation.measurement import (complete_meas_cal, # Measurement error mitigation functions
CompleteMeasFitter,
MeasurementFilter)
provider = IBMQ.load_account()
backend = provider.get_backend('ibmqx2') # calibrate using real hardware
layout = [2,3,0,4]
chip_qubits = 5
# Transpiled circuit for the real hardware
qc_qa_cx = transpile(qc, backend=backend, initial_layout=layout)
# The next step is to create the extra circuits used to mitigate the readout errors<sup>[[3]](#readouterr)</sup>.
# In[18]:
meas_cals, state_labels = complete_meas_cal(qubit_list=layout, qr=QuantumRegister(chip_qubits))
qcs = meas_cals + [qc_qa_cx]
job = backend.run(qcs, shots=10)
# The following plot<sup>[[5]](#tridi)</sup>, shows the results from running the circuit above on real hardware for $10$ different initial states. The $x$-axis represents the angle $\theta$ defining the initial state in each case. The results where obtained after mitigating the readout error and then extrapolating the errors arising during the run of the circuit from the results with the circuits with $1$, $3$ and $5$ CNOTs.
#
# <img src="images/norm_public.png">
#
# Compare to the results without error mitigation nor extrapolation from the CNOTs<sup>[5](#tridi)</sup>.
#
# <img src="images/noerrmit_public.png">
# ## 8. Problems<a id='problems'></a>
# ##### Real hardware:
#
# 1. Set the time parameter for the optimised example.
#
# <details>
# <summary> Solution (Click to expand)</summary>
# t = 2.344915690192344
#
# The best result is to set it so that the smallest eigenvalue can be represented exactly, since it's inverse will have the largest contribution in the solution
# </details>
#
# 2. Create transpiled circuits for $3$ and $5$ CNOTs from a given circuit 'qc'. When creating the circuits you will have to add barriers so that these consecutive CNOT gates do not get cancelled when using the transpile() method.
# 3. Run your circuits on the real hardware and apply a quadratic fit to the results to obtain the extrapolated value.
# ## 9. References<a id='references'></a>
# 1. J. R. Shewchuk. An Introduction to the Conjugate Gradient Method Without the Agonizing Pain. Technical Report CMU-CS-94-125, School of Computer Science, Carnegie Mellon University, Pittsburgh, Pennsylvania, March 1994.<a id='conjgrad'></a>
# 2. A. W. Harrow, A. Hassidim, and S. Lloyd, “Quantum algorithm for linear systems of equations,” Phys. Rev. Lett. 103.15 (2009), p. 150502.<a id='hhl'></a>
# 3. A. Dewes, F. R. Ong, V. Schmitt, R. Lauro, N. Boulant, P. Bertet, D. Vion, and D. Esteve, “Characterization of a two-transmon processor with individual single-shot qubit readout,” Phys. Rev. Lett. 108, 057002 (2012). <a id='readouterr'></a>
# 4. N. Stamatopoulos, D. J. Egger, Y. Sun, C. Zoufal, R. Iten, N. Shen, and S. Woerner, “Option Pricing using Quantum Computers,” arXiv:1905.02666 . <a id='richardson'></a>
# 5. A. Carrera Vazquez, A. Frisch, D. Steenken, H. S. Barowski, R. Hiptmair, and S. Woerner, “Enhancing Quantum Linear System Algorithm by Richardson Extrapolation,” (to be included).<a id='tridi'></a>
# 6. R. Iten, O. Reardon-Smith, L. Mondada, E. Redmond, R. Singh Kohli, R. Colbeck, “Introduction to UniversalQCompiler,” arXiv:1904.01072 .<a id='qcompiler'></a>
# 7. https://quantum-computing.ibm.com/ .<a id='qexperience'></a>
# 8. D. Bucher, J. Mueggenburg, G. Kus, I. Haide, S. Deutschle, H. Barowski, D. Steenken, A. Frisch, "Qiskit Aqua: Solving linear systems of equations with the HHL algorithm" https://github.com/Qiskit/qiskit-tutorials/blob/master/legacy_tutorials/aqua/linear_systems_of_equations.ipynb
|
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
from tsp_qaoa import test_solution
from qiskit.visualization import plot_histogram
import networkx as nx
import numpy as np
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution()
plot_histogram(job_2.result().get_counts(), color='midnightblue', title="New Histogram", figsize=(30, 5))
plot_histogram(job_2.result().get_counts(), color='midnightblue', title="New Histogram", figsize=(30, 5))
G
labels = nx.get_edge_attributes(G,'weight')
labels
import json
# Array of JSON Objects
products = [{"name": "HDD", "brand": "Samsung", "price": "$100"},
{"name": "Monitor", "brand": "Dell", "price": "$120"},
{"name": "Mouse", "brand": "Logitech", "price": "$10"}]
# Print the original data
print("The original JSON data:\n{0}".format(products))
# Sort the JSON data based on the value of the brand key
products.sort(key=lambda x: x["price"])
# Print the sorted JSON data
print("The sorted JSON data based on the value of the brand:\n{0}".format(products))
_LAMBDA
UNIFORM_CONVERGENCE_SAMPLE
import json
# Array of JSON Objects
# Sort the JSON data based on the value of the brand key
UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"])
# Print the sorted JSON data
UNIFORM_CONVERGENCE_SAMPLE
np.max(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - UNIFORM_CONVERGENCE_SAMPLE[220]["probabilities"])
# generamos las distancias entre para la convergencia uniforme
index = -1
for sample in UNIFORM_CONVERGENCE_SAMPLE:
mean = sample["mean"]
index += 1
distance_p_ground_state = np.max(np.abs(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - sample["probabilities"]))
UNIFORM_CONVERGENCE_SAMPLE[index]["distance_pgs"] = distance_p_ground_state
UNIFORM_CONVERGENCE_SAMPLE
import csv
header = ['iteration', 'state', 'probability', 'mean']
header_q = ['iteration', 'distance']
with open('qaoa_cu.csv', 'w', encoding='UTF8') as f:
with open('qaoa_distance.csv', 'w', encoding='UTF8') as q:
writer = csv.writer(f)
writer_q = csv.writer(q)
# write the header
writer.writerow(header)
writer_q.writerow(header_q)
iteration = 0
for sample in UNIFORM_CONVERGENCE_SAMPLE:
iteration += 1
mean = sample["mean"]
distance = sample["distance_pgs"]
state = 0
for probability in sample["probabilities"]:
state += 1
# write the data
data = [iteration, state, probability, mean]
writer.writerow(data)
writer_q.writerow([iteration, distance])
#plot_histogram(job_2, color='midnightblue', title=str(mean), figsize=(30, 5)).savefig(str(contador) + "_2.png")
#print(sample["mean"])
plot_histogram(job_2, color='midnightblue', title="New Histogram", figsize=(30, 5)).savefig('out.png')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Useful additional packages
import matplotlib.pyplot as plt
import numpy as np
from math import pi
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, transpile
from qiskit.tools.visualization import circuit_drawer
from qiskit.quantum_info import state_fidelity
from qiskit import BasicAer
backend = BasicAer.get_backend('unitary_simulator')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.u(pi/2,pi/4,pi/8,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.p(pi/2,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.id(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.x(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.y(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.z(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.h(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.s(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.sdg(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.t(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.tdg(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.rx(pi/2,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.ry(pi/2,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.rz(pi/2,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.cx(q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cy(q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cz(q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.ch(q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.crz(pi/2,q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cp(pi/2,q[0], q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cu(pi/2, pi/2, pi/2, 0, q[0], q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.swap(q[0], q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.ccx(q[0], q[1], q[2])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cswap(q[0], q[1], q[2])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.measure(q, c)
qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.reset(q[0])
qc.measure(q, c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.reset(q[0])
qc.measure(q, c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.x(q[0]).c_if(c, 0)
qc.measure(q,c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q,c)
qc.x(q[0]).c_if(c, 0)
qc.measure(q,c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
# Initializing a three-qubit quantum state
import math
desired_vector = [
1 / math.sqrt(16) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(16) * complex(1, 1),
0,
0,
1 / math.sqrt(8) * complex(1, 2),
1 / math.sqrt(16) * complex(1, 0),
0]
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.initialize(desired_vector, [q[0],q[1],q[2]])
qc.draw()
backend = BasicAer.get_backend('statevector_simulator')
job = backend.run(transpile(qc, backend))
qc_state = job.result().get_statevector(qc)
qc_state
state_fidelity(desired_vector,qc_state)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-aqt-provider
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright 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.
import math
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Final, Optional
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit import Gate, Instruction
from qiskit.circuit.library import RGate, RXGate, RXXGate, RZGate
from qiskit.circuit.tools import pi_check
from qiskit.dagcircuit import DAGCircuit
from qiskit.transpiler import Target
from qiskit.transpiler.basepasses import BasePass, TransformationPass
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.passes import Decompose, Optimize1qGatesDecomposition
from qiskit.transpiler.passmanager import PassManager
from qiskit.transpiler.passmanager_config import PassManagerConfig
from qiskit.transpiler.preset_passmanagers import common
from qiskit.transpiler.preset_passmanagers.plugin import PassManagerStagePlugin
from qiskit_aqt_provider.utils import map_exceptions
class UnboundParametersTarget(Target):
"""Marker class for transpilation targets to disable passes that require bound parameters."""
def bound_pass_manager(target: Target) -> PassManager:
"""Transpilation passes to apply on circuits after the parameters are bound.
This assumes that a preset pass manager was applied to the unbound circuits
(by setting the target to an instance of `UnboundParametersTarget`).
Args:
target: transpilation target.
"""
return PassManager(
[
# wrap the Rxx angles
WrapRxxAngles(),
# decompose the substituted Rxx gates
Decompose([f"{WrapRxxAngles.SUBSTITUTE_GATE_NAME}*"]),
# collapse the single qubit runs as ZXZ
Optimize1qGatesDecomposition(target=target),
# wrap the Rx angles, rewrite as R
RewriteRxAsR(),
]
)
def rewrite_rx_as_r(theta: float) -> Instruction:
"""Instruction equivalent to Rx(θ) as R(θ, φ) with θ ∈ [0, π] and φ ∈ [0, 2π]."""
theta = math.atan2(math.sin(theta), math.cos(theta))
phi = math.pi if theta < 0.0 else 0.0
return RGate(abs(theta), phi)
class RewriteRxAsR(TransformationPass):
"""Rewrite Rx(θ) as R(θ, φ) with θ ∈ [0, π] and φ ∈ [0, 2π]."""
@map_exceptions(TranspilerError)
def run(self, dag: DAGCircuit) -> DAGCircuit:
"""Apply the transformation pass."""
for node in dag.gate_nodes():
if node.name == "rx":
(theta,) = node.op.params
dag.substitute_node(node, rewrite_rx_as_r(float(theta)))
return dag
class AQTSchedulingPlugin(PassManagerStagePlugin):
"""Scheduling stage plugin for the :mod:`qiskit.transpiler`.
If the transpilation target is not :class:`UnboundParametersTarget`,
register a :class:`RewriteRxAsR` pass irrespective of the optimization level.
"""
def pass_manager(
self,
pass_manager_config: PassManagerConfig,
optimization_level: Optional[int] = None, # noqa: ARG002
) -> PassManager:
"""Pass manager for the scheduling phase."""
if isinstance(pass_manager_config.target, UnboundParametersTarget):
return PassManager([])
passes: list[BasePass] = [
# The Qiskit Target declares RX/RZ as basis gates.
# This allows decomposing any run of rotations into the ZXZ form, taking
# advantage of the free Z rotations.
# Since the API expects R/RZ as single-qubit operations,
# we rewrite all RX gates as R gates after optimizations have been performed.
RewriteRxAsR(),
]
return PassManager(passes)
@dataclass(frozen=True)
class CircuitInstruction:
"""Substitute for `qiskit.circuit.CircuitInstruction`.
Contrary to its Qiskit counterpart, this type allows
passing the qubits as integers.
"""
gate: Gate
qubits: tuple[int, ...]
def _rxx_positive_angle(theta: float) -> list[CircuitInstruction]:
"""List of instructions equivalent to RXX(θ) with θ >= 0."""
rxx = CircuitInstruction(RXXGate(abs(theta)), qubits=(0, 1))
if theta >= 0:
return [rxx]
return [
CircuitInstruction(RZGate(math.pi), (0,)),
rxx,
CircuitInstruction(RZGate(math.pi), (0,)),
]
def _emit_rxx_instruction(theta: float, instructions: list[CircuitInstruction]) -> Instruction:
"""Collect the passed instructions into a single one labeled 'Rxx(θ)'."""
qc = QuantumCircuit(2, name=f"{WrapRxxAngles.SUBSTITUTE_GATE_NAME}({pi_check(theta)})")
for instruction in instructions:
qc.append(instruction.gate, instruction.qubits)
return qc.to_instruction()
def wrap_rxx_angle(theta: float) -> Instruction:
"""Instruction equivalent to RXX(θ) with θ ∈ [0, π/2]."""
# fast path if -π/2 <= θ <= π/2
if abs(theta) <= math.pi / 2:
operations = _rxx_positive_angle(theta)
return _emit_rxx_instruction(theta, operations)
# exploit 2-pi periodicity of Rxx
theta %= 2 * math.pi
if abs(theta) <= math.pi / 2:
operations = _rxx_positive_angle(theta)
elif abs(theta) <= 3 * math.pi / 2:
corrected_angle = theta - np.sign(theta) * math.pi
operations = [
CircuitInstruction(RXGate(math.pi), (0,)),
CircuitInstruction(RXGate(math.pi), (1,)),
]
operations.extend(_rxx_positive_angle(corrected_angle))
else:
corrected_angle = theta - np.sign(theta) * 2 * math.pi
operations = _rxx_positive_angle(corrected_angle)
return _emit_rxx_instruction(theta, operations)
class WrapRxxAngles(TransformationPass):
"""Wrap Rxx angles to [0, π/2]."""
SUBSTITUTE_GATE_NAME: Final = "Rxx-wrapped"
@map_exceptions(TranspilerError)
def run(self, dag: DAGCircuit) -> DAGCircuit:
"""Apply the transformation pass."""
for node in dag.gate_nodes():
if node.name == "rxx":
(theta,) = node.op.params
if 0 <= float(theta) <= math.pi / 2:
continue
rxx = wrap_rxx_angle(float(theta))
dag.substitute_node(node, rxx)
return dag
class AQTTranslationPlugin(PassManagerStagePlugin):
"""Translation stage plugin for the :mod:`qiskit.transpiler`.
If the transpilation target is not :class:`UnboundParametersTarget`,
register a :class:`WrapRxxAngles` pass after the preset pass irrespective
of the optimization level.
"""
def pass_manager(
self,
pass_manager_config: PassManagerConfig,
optimization_level: Optional[int] = None,
) -> PassManager:
"""Pass manager for the translation stage."""
translation_pm = common.generate_translation_passmanager(
target=pass_manager_config.target,
basis_gates=pass_manager_config.basis_gates,
approximation_degree=pass_manager_config.approximation_degree,
coupling_map=pass_manager_config.coupling_map,
backend_props=pass_manager_config.backend_properties,
unitary_synthesis_method=pass_manager_config.unitary_synthesis_method,
unitary_synthesis_plugin_config=pass_manager_config.unitary_synthesis_plugin_config,
hls_config=pass_manager_config.hls_config,
)
if isinstance(pass_manager_config.target, UnboundParametersTarget):
return translation_pm
passes: Sequence[BasePass] = [
WrapRxxAngles(),
] + (
[
Decompose([f"{WrapRxxAngles.SUBSTITUTE_GATE_NAME}*"]),
]
if optimization_level is None or optimization_level == 0
else []
)
return translation_pm + PassManager(passes)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 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.
# pylint: disable=invalid-name
"""Tests for local invariance routines."""
import unittest
from numpy.testing import assert_allclose
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.synthesis.two_qubit.local_invariance import two_qubit_local_invariants
from qiskit.quantum_info import Operator
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestLocalInvariance(QiskitTestCase):
"""Test local invariance routines"""
def test_2q_local_invariance_simple(self):
"""Check the local invariance parameters
for known simple cases.
"""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
U = Operator(qc)
vec = two_qubit_local_invariants(U)
assert_allclose(vec, [1, 0, 3])
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.cx(qr[1], qr[0])
U = Operator(qc)
vec = two_qubit_local_invariants(U)
assert_allclose(vec, [0, 0, 1])
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.cx(qr[1], qr[0])
qc.cx(qr[0], qr[1])
U = Operator(qc)
vec = two_qubit_local_invariants(U)
assert_allclose(vec, [0, 0, -1])
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.swap(qr[1], qr[0])
U = Operator(qc)
vec = two_qubit_local_invariants(U)
assert_allclose(vec, [-1, 0, -3])
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(range(2))
qc.measure(range(2), range(2))
# apply x gate if the classical register has the value 2 (10 in binary)
qc.x(0).c_if(cr, 2)
# apply y gate if bit 0 is set to 1
qc.y(1).c_if(0, 1)
qc.draw('mpl')
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test Evolution"""
import unittest
from test.python.opflow import QiskitOpflowTestCase
import numpy as np
import scipy.linalg
import qiskit
from qiskit.circuit import Parameter, ParameterVector
from qiskit.extensions import UnitaryGate
from qiskit.opflow import (
CX,
CircuitOp,
EvolutionFactory,
EvolvedOp,
H,
I,
ListOp,
PauliTrotterEvolution,
QDrift,
SummedOp,
Suzuki,
Trotter,
X,
Y,
Z,
Zero,
)
class TestEvolution(QiskitOpflowTestCase):
"""Evolution tests."""
def test_exp_i(self):
"""exponential of Pauli test"""
op = Z.exp_i()
gate = op.to_circuit().data[0].operation
self.assertIsInstance(gate, qiskit.circuit.library.RZGate)
self.assertEqual(gate.params[0], 2)
def test_trotter_with_identity(self):
"""trotterization of operator with identity term"""
op = (2.0 * I ^ I) + (Z ^ Y)
exact_matrix = scipy.linalg.expm(-1j * op.to_matrix())
evo = PauliTrotterEvolution(trotter_mode="suzuki", reps=2)
with self.subTest("all PauliOp terms"):
circ_op = evo.convert(EvolvedOp(op))
circuit_matrix = qiskit.quantum_info.Operator(circ_op.to_circuit()).data
np.testing.assert_array_almost_equal(exact_matrix, circuit_matrix)
with self.subTest("MatrixOp identity term"):
op = (2.0 * I ^ I).to_matrix_op() + (Z ^ Y)
circ_op = evo.convert(EvolvedOp(op))
circuit_matrix = qiskit.quantum_info.Operator(circ_op.to_circuit()).data
np.testing.assert_array_almost_equal(exact_matrix, circuit_matrix)
with self.subTest("CircuitOp identity term"):
op = (2.0 * I ^ I).to_circuit_op() + (Z ^ Y)
circ_op = evo.convert(EvolvedOp(op))
circuit_matrix = qiskit.quantum_info.Operator(circ_op.to_circuit()).data
np.testing.assert_array_almost_equal(exact_matrix, circuit_matrix)
def test_pauli_evolution(self):
"""pauli evolution test"""
op = (
(-1.052373245772859 * I ^ I)
+ (0.39793742484318045 * I ^ Z)
+ (0.18093119978423156 * X ^ X)
+ (-0.39793742484318045 * Z ^ I)
+ (-0.01128010425623538 * Z ^ Z)
)
evolution = EvolutionFactory.build(operator=op)
# wf = (Pl^Pl) + (Ze^Ze)
wf = ((np.pi / 2) * op).exp_i() @ CX @ (H ^ I) @ Zero
mean = evolution.convert(wf)
self.assertIsNotNone(mean)
def test_summedop_pauli_evolution(self):
"""SummedOp[PauliOp] evolution test"""
op = SummedOp(
[
(-1.052373245772859 * I ^ I),
(0.39793742484318045 * I ^ Z),
(0.18093119978423156 * X ^ X),
(-0.39793742484318045 * Z ^ I),
(-0.01128010425623538 * Z ^ Z),
]
)
evolution = EvolutionFactory.build(operator=op)
# wf = (Pl^Pl) + (Ze^Ze)
wf = ((np.pi / 2) * op).exp_i() @ CX @ (H ^ I) @ Zero
mean = evolution.convert(wf)
self.assertIsNotNone(mean)
def test_parameterized_evolution(self):
"""parameterized evolution test"""
thetas = ParameterVector("θ", length=7)
op = (
(thetas[0] * I ^ I)
+ (thetas[1] * I ^ Z)
+ (thetas[2] * X ^ X)
+ (thetas[3] * Z ^ I)
+ (thetas[4] * Y ^ Z)
+ (thetas[5] * Z ^ Z)
)
op = op * thetas[6]
evolution = PauliTrotterEvolution(trotter_mode="trotter", reps=1)
# wf = (Pl^Pl) + (Ze^Ze)
wf = (op).exp_i() @ CX @ (H ^ I) @ Zero
mean = evolution.convert(wf)
circuit = mean.to_circuit()
# Check that all parameters are in the circuit
for p in thetas:
self.assertIn(p, circuit.parameters)
# Check that the identity-parameters only exist as global phase
self.assertNotIn(thetas[0], circuit._parameter_table.get_keys())
def test_bind_parameters(self):
"""bind parameters test"""
thetas = ParameterVector("θ", length=6)
op = (
(thetas[1] * I ^ Z)
+ (thetas[2] * X ^ X)
+ (thetas[3] * Z ^ I)
+ (thetas[4] * Y ^ Z)
+ (thetas[5] * Z ^ Z)
)
op = thetas[0] * op
evolution = PauliTrotterEvolution(trotter_mode="trotter", reps=1)
# wf = (Pl^Pl) + (Ze^Ze)
wf = (op).exp_i() @ CX @ (H ^ I) @ Zero
wf = wf.assign_parameters({thetas: np.arange(10, 16)})
mean = evolution.convert(wf)
circuit_params = mean.to_circuit().parameters
# Check that the no parameters are in the circuit
for p in thetas[1:]:
self.assertNotIn(p, circuit_params)
def test_bind_circuit_parameters(self):
"""bind circuit parameters test"""
thetas = ParameterVector("θ", length=6)
op = (
(thetas[1] * I ^ Z)
+ (thetas[2] * X ^ X)
+ (thetas[3] * Z ^ I)
+ (thetas[4] * Y ^ Z)
+ (thetas[5] * Z ^ Z)
)
op = thetas[0] * op
evolution = PauliTrotterEvolution(trotter_mode="trotter", reps=1)
# wf = (Pl^Pl) + (Ze^Ze)
wf = (op).exp_i() @ CX @ (H ^ I) @ Zero
evo = evolution.convert(wf)
mean = evo.assign_parameters({thetas: np.arange(10, 16)})
# Check that the no parameters are in the circuit
for p in thetas[1:]:
self.assertNotIn(p, mean.to_circuit().parameters)
# Check that original circuit is unchanged
for p in thetas:
self.assertIn(p, evo.to_circuit().parameters)
# TODO test with other Op types than CircuitStateFn
def test_bind_parameter_list(self):
"""bind parameters list test"""
thetas = ParameterVector("θ", length=6)
op = (
(thetas[1] * I ^ Z)
+ (thetas[2] * X ^ X)
+ (thetas[3] * Z ^ I)
+ (thetas[4] * Y ^ Z)
+ (thetas[5] * Z ^ Z)
)
op = thetas[0] * op
evolution = PauliTrotterEvolution(trotter_mode="trotter", reps=1)
# wf = (Pl^Pl) + (Ze^Ze)
wf = (op).exp_i() @ CX @ (H ^ I) @ Zero
evo = evolution.convert(wf)
param_list = np.transpose([np.arange(10, 16), np.arange(2, 8), np.arange(30, 36)]).tolist()
means = evo.assign_parameters({thetas: param_list})
self.assertIsInstance(means, ListOp)
# Check that the no parameters are in the circuit
for p in thetas[1:]:
for circop in means.oplist:
self.assertNotIn(p, circop.to_circuit().parameters)
# Check that original circuit is unchanged
for p in thetas:
self.assertIn(p, evo.to_circuit().parameters)
def test_bind_parameters_complex(self):
"""bind parameters with a complex value test"""
th1 = Parameter("th1")
th2 = Parameter("th2")
operator = th1 * X + th2 * Y
bound_operator = operator.bind_parameters({th1: 3j, th2: 2})
expected_bound_operator = SummedOp([3j * X, (2 + 0j) * Y])
self.assertEqual(bound_operator, expected_bound_operator)
def test_qdrift(self):
"""QDrift test"""
op = (2 * Z ^ Z) + (3 * X ^ X) - (4 * Y ^ Y) + (0.5 * Z ^ I)
trotterization = QDrift().convert(op)
self.assertGreater(len(trotterization.oplist), 150)
last_coeff = None
# Check that all types are correct and all coefficients are equals
for op in trotterization.oplist:
self.assertIsInstance(op, (EvolvedOp, CircuitOp))
if isinstance(op, EvolvedOp):
if last_coeff:
self.assertEqual(op.primitive.coeff, last_coeff)
else:
last_coeff = op.primitive.coeff
def test_qdrift_summed_op(self):
"""QDrift test for SummedOp"""
op = SummedOp(
[
(2 * Z ^ Z),
(3 * X ^ X),
(-4 * Y ^ Y),
(0.5 * Z ^ I),
]
)
trotterization = QDrift().convert(op)
self.assertGreater(len(trotterization.oplist), 150)
last_coeff = None
# Check that all types are correct and all coefficients are equals
for op in trotterization.oplist:
self.assertIsInstance(op, (EvolvedOp, CircuitOp))
if isinstance(op, EvolvedOp):
if last_coeff:
self.assertEqual(op.primitive.coeff, last_coeff)
else:
last_coeff = op.primitive.coeff
def test_matrix_op_evolution(self):
"""MatrixOp evolution test"""
op = (
(-1.052373245772859 * I ^ I)
+ (0.39793742484318045 * I ^ Z)
+ (0.18093119978423156 * X ^ X)
+ (-0.39793742484318045 * Z ^ I)
+ (-0.01128010425623538 * Z ^ Z) * np.pi / 2
)
exp_mat = op.to_matrix_op().exp_i().to_matrix()
ref_mat = scipy.linalg.expm(-1j * op.to_matrix())
np.testing.assert_array_almost_equal(ref_mat, exp_mat)
def test_log_i(self):
"""MatrixOp.log_i() test"""
op = (
(-1.052373245772859 * I ^ I)
+ (0.39793742484318045 * I ^ Z)
+ (0.18093119978423156 * X ^ X)
+ (-0.39793742484318045 * Z ^ I)
+ (-0.01128010425623538 * Z ^ Z) * np.pi / 2
)
# Test with CircuitOp
log_exp_op = op.to_matrix_op().exp_i().log_i().to_pauli_op()
np.testing.assert_array_almost_equal(op.to_matrix(), log_exp_op.to_matrix())
# Test with MatrixOp
log_exp_op = op.to_matrix_op().exp_i().to_matrix_op().log_i().to_pauli_op()
np.testing.assert_array_almost_equal(op.to_matrix(), log_exp_op.to_matrix())
# Test with PauliOp
log_exp_op = op.to_matrix_op().exp_i().to_pauli_op().log_i().to_pauli_op()
np.testing.assert_array_almost_equal(op.to_matrix(), log_exp_op.to_matrix())
# Test with EvolvedOp
log_exp_op = op.exp_i().to_pauli_op().log_i().to_pauli_op()
np.testing.assert_array_almost_equal(op.to_matrix(), log_exp_op.to_matrix())
# Test with proper ListOp
op = ListOp(
[
(0.39793742484318045 * I ^ Z),
(0.18093119978423156 * X ^ X),
(-0.39793742484318045 * Z ^ I),
(-0.01128010425623538 * Z ^ Z) * np.pi / 2,
]
)
log_exp_op = op.to_matrix_op().exp_i().to_matrix_op().log_i().to_pauli_op()
np.testing.assert_array_almost_equal(op.to_matrix(), log_exp_op.to_matrix())
def test_matrix_op_parameterized_evolution(self):
"""parameterized MatrixOp evolution test"""
theta = Parameter("θ")
op = (
(-1.052373245772859 * I ^ I)
+ (0.39793742484318045 * I ^ Z)
+ (0.18093119978423156 * X ^ X)
+ (-0.39793742484318045 * Z ^ I)
+ (-0.01128010425623538 * Z ^ Z)
)
op = op * theta
wf = (op.to_matrix_op().exp_i()) @ CX @ (H ^ I) @ Zero
self.assertIn(theta, wf.to_circuit().parameters)
op = op.assign_parameters({theta: 1})
exp_mat = op.to_matrix_op().exp_i().to_matrix()
ref_mat = scipy.linalg.expm(-1j * op.to_matrix())
np.testing.assert_array_almost_equal(ref_mat, exp_mat)
wf = wf.assign_parameters({theta: 3})
self.assertNotIn(theta, wf.to_circuit().parameters)
def test_mixed_evolution(self):
"""bind parameters test"""
thetas = ParameterVector("θ", length=6)
op = (
(thetas[1] * (I ^ Z).to_matrix_op())
+ (thetas[2] * (X ^ X)).to_matrix_op()
+ (thetas[3] * Z ^ I)
+ (thetas[4] * Y ^ Z).to_circuit_op()
+ (thetas[5] * (Z ^ I).to_circuit_op())
)
op = thetas[0] * op
evolution = PauliTrotterEvolution(trotter_mode="trotter", reps=1)
# wf = (Pl^Pl) + (Ze^Ze)
wf = (op).exp_i() @ CX @ (H ^ I) @ Zero
wf = wf.assign_parameters({thetas: np.arange(10, 16)})
mean = evolution.convert(wf)
circuit_params = mean.to_circuit().parameters
# Check that the no parameters are in the circuit
for p in thetas[1:]:
self.assertNotIn(p, circuit_params)
def test_reps(self):
"""Test reps and order params in Trotterization"""
reps = 7
trotter = Trotter(reps=reps)
self.assertEqual(trotter.reps, reps)
order = 5
suzuki = Suzuki(reps=reps, order=order)
self.assertEqual(suzuki.reps, reps)
self.assertEqual(suzuki.order, order)
qdrift = QDrift(reps=reps)
self.assertEqual(qdrift.reps, reps)
def test_suzuki_directly(self):
"""Test for Suzuki converter"""
operator = X + Z
evo = Suzuki()
evolution = evo.convert(operator)
matrix = np.array(
[[0.29192658 - 0.45464871j, -0.84147098j], [-0.84147098j, 0.29192658 + 0.45464871j]]
)
np.testing.assert_array_almost_equal(evolution.to_matrix(), matrix)
def test_evolved_op_to_instruction(self):
"""Test calling `to_instruction` on a plain EvolvedOp.
Regression test of Qiskit/qiskit-terra#8025.
"""
op = EvolvedOp(0.5 * X)
circuit = op.to_instruction()
unitary = scipy.linalg.expm(-0.5j * X.to_matrix())
expected = UnitaryGate(unitary)
self.assertEqual(circuit, expected)
if __name__ == "__main__":
unittest.main()
|
https://github.com/ionq-samples/getting-started
|
ionq-samples
|
%%capture
# First, we install the essential libraries to our current Python runtime.
# "%%capture" (above) captures and in this case, hides the output of this
# cell, so you can comment it out if you need help debugging this step.
%pip install 'qbraid[runtime]' matplotlib
import os
from getpass import getpass
from qbraid.runtime.ionq import IonQProvider
# Before you begin, get your API key from https://cloud.ionq.com/settings/keys
# If your API key is stored as "IONQ_API_KEY" in your local environment, this
# should find it. Otherwise you'll be prompted to enter your API key manually.
api_key = os.getenv("IONQ_API_KEY") or getpass("Enter your IonQ API key: ")
provider = IonQProvider(api_key=api_key)
# Now we set up our circuit. In this case, we're creating a circuit with two
# qubits, applying an H gate to qubit-0, a CXGate to both,.
program = """
OPENQASM 3;
include "stdgates.inc";
qubit[2] q;
h q[0];
cx q[0], q[1];
"""
# Before submitting the job, we can visualize the circuit using qasm3_drawer().
from qbraid.visualization import qasm3_drawer
qasm3_drawer(program)
device = provider.get_device("simulator")
job = device.run(program, name="qBraid example", shots=100)
results = job.result()
counts = results.measurement_counts()
print(counts)
from qbraid.visualization import plot_histogram
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev
f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2
pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits)
pw_approximation._build()
qc = QuantumCircuit(pw_approximation.num_qubits)
qc.h(list(range(num_state_qubits)))
qc.append(pw_approximation.to_instruction(), qc.qubits)
qc.draw(output='mpl')
|
https://github.com/hamburgerguy/Quantum-Algorithm-Implementations
|
hamburgerguy
|
"""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/Pitt-JonesLab/slam_decomposition
|
Pitt-JonesLab
|
"""Run this cell if in new enviroment without slam installed"""
# ! pip install git+https://github.com/Pitt-JonesLab/slam_decomposition
# #write to config file an empty directory (monkey patching for sake of portability)
# f = open("config.py", "w")
# f.write('srcpath = "content/"')
# f.close()
%matplotlib widget
from slam.utils.pd_playground import ParallelDrivenGateWidget
import numpy as np
from slam.utils.visualize import coordinate_2dlist_weyl
from ipywidgets import interact
# optimize parameter vectors to go to SWAP gate
from qiskit.circuit.library import SwapGate
from weylchamber import c1c2c3
target = SwapGate().to_matrix()
# target_coords = c1c2c3(target)
pdgw = ParallelDrivenGateWidget(
N=10,
gc=np.pi / 4,
gg=np.pi / 4,
gz1=0,
gz2=0,
phase_a=0,
phase_b=0,
phase_c=0,
phase_g=0,
)
# use widget to change parameters
bounds = (-2 * np.pi, 2 * np.pi)
interact(
pdgw.widget_wrap,
q0=bounds,
q1=bounds,
pa=bounds,
pb=bounds,
pc=bounds,
pg=bounds,
gz1=bounds,
gz2=bounds,
);
# # use widget to change parameters
pdgw = ParallelDrivenGateWidget(
N=10, gc=np.pi / 2, gg=0, phase_a=0, phase_b=0, phase_c=0, phase_g=0
)
pdgw2 = ParallelDrivenGateWidget(
N=5, gc=np.pi / 2, gg=0, phase_a=np.pi / 2, phase_b=-np.pi / 8, phase_c=0, phase_g=0
)
pdgw3 = pdgw + pdgw2
bounds = (-2 * np.pi, 2 * np.pi)
gx, gy = list(np.ones(10) * np.pi) + list(np.ones(5) * 2 * np.pi), list(
np.ones(10) * np.pi
) + list(np.ones(5) * np.pi / 2)
pdgw3.prepare_parameters_nonuniform(gx, gy)
pdgw3.iterate_time()
coordinate_2dlist_weyl(*pdgw3.coordinate_list);
# to optimize for SWAP
# # use widget to change parameters
from slam.cost_function import WeylEuclideanCost, MakhlinFunctionalCost
from scipy.optimize import minimize
# ansatz includes solution for midpoint, with 5 remaining parameters
pdgw = ParallelDrivenGateWidget(
N=10, gc=np.pi / 2, gg=0, phase_a=0, phase_b=0, phase_c=0, phase_g=0
)
pdgw2 = ParallelDrivenGateWidget(
N=5, gc=np.pi / 2, gg=0, phase_a=np.pi / 2, phase_b=0, phase_c=0, phase_g=0
)
pdgw3 = pdgw + pdgw2
bounds = (-2 * np.pi, 2 * np.pi)
gx, gy = list(np.ones(10) * np.pi) + list(np.ones(5) * np.pi), list(
np.ones(10) * -np.pi
) + list(np.ones(5) * 0)
cost_f = MakhlinFunctionalCost()
# cost_f = WeylEuclideanCost()
def cost_function(p):
pdgw2 = ParallelDrivenGateWidget(
N=5, gc=np.pi / 2, gg=0, phase_a=p[0], phase_b=p[1], phase_c=p[2], phase_g=p[3]
)
pdgw3 = pdgw + pdgw2
# gx = list(np.ones(10)*np.pi) + list(p[:len(p)//2])
# gy = list(np.ones(10)*np.pi) + list(p[len(p)//2:])
gx = list(np.ones(10) * np.pi) + list(p[4] * np.ones(5))
gy = list(np.ones(10) * np.pi) + list(p[5] * np.ones(5))
pdgw3.prepare_parameters_nonuniform(gx, gy)
# pdgw3.iterate_time()
f = pdgw.solve_end()
current_cost = cost_f.unitary_fidelity(target, f)
# print(current_cost)
return current_cost
# initial guess
# p0 = list(np.ones(5)*np.pi/2) + list(np.ones(5)*np.pi/2) # guess for every parameter
p0 = [np.pi / 2, 0, 0, 0, 2 * np.pi, 0] # one guess for every parameter
ret = minimize(cost_function, p0, method="Nelder-Mead", options={"disp": True})
# display results
# gx = list(np.ones(10)*np.pi) + list(res.x[:len(res.x)//2])
# gy = list(np.ones(10)*np.pi) + list(res.x[len(res.x)//2:])
gx = list(np.ones(10) * np.pi) + list(ret.x[4] * np.ones(5))
gy = list(np.ones(10) * np.pi) + list(ret.x[5] * np.ones(5))
pdgw2 = ParallelDrivenGateWidget(
N=5,
gc=np.pi / 2,
gg=0,
phase_a=ret.x[0],
phase_b=ret.x[1],
phase_c=ret.x[2],
phase_g=ret.x[3],
)
pdgw3 = pdgw + pdgw2
pdgw3.prepare_parameters_nonuniform(gx, gy)
pdgw3.iterate_time()
coordinate_2dlist_weyl(*pdgw3.coordinate_list);
from slam.utils.visualize import plotMatrix
plotMatrix(pdgw3.final_unitary);
from scipy.optimize import minimize
from slam.cost_function import SquareCost
from tqdm import tqdm
pdgw = ParallelDrivenGateWidget(N=15, gc=3 * np.pi / 4, gg=0, phase_c=0, phase_g=0)
pdgw.prepare_parameters_nonuniform(gx, gy)
# define cost function as the distance between the target and each of the end segement points
cost = SquareCost()
gx, gy = list(np.ones(10) * np.pi) + list(np.zeros(5)), list(
np.ones(10) * np.pi
) + list(np.zeros(5))
for n_iter in tqdm(range(1, 2)):
pdgw = ParallelDrivenGateWidget(N=15, gc=3 * np.pi / 4, gg=0, phase_c=0, phase_g=0)
def cost_function(p):
gx = list(np.ones(10) * np.pi) + list(p[: len(p) // 2])
gy = list(np.ones(10) * np.pi) + list(p[len(p) // 2 :])
pdgw.prepare_parameters_nonuniform(gx, gy)
# pdgw.iterate_time()
# f = cost.unitary_fidelity(target, pdgw.final_unitary)
f = cost.unitary_fidelity(target, pdgw.solve_end())
# print(f)
return f
# optimize
res = minimize(cost_function, list(np.zeros(10)), method="Nelder-Mead")
# print res final function value
print(res.fun)
# print(res.x)
gx = list(np.ones(10) * np.pi) + list(res.x[: len(res.x) // 2])
gy = list(np.ones(10) * np.pi) + list(res.x[len(res.x) // 2 :])
print(gx, gy)
pdgw.prepare_parameters_nonuniform(gx, gy)
pdgw.iterate_time()
coordinate_2dlist_weyl(*pdgw.coordinate_list);
# want to check for changing phase, can the final unitary ever be off bottom plane
# twirl phase variables 1000 iterations
# NOTE seems impossible
from tqdm import tqdm
from itertools import permutations
from slam.cost_function import (
WeylEuclideanCost,
SquareReducedCost,
MakhlinFunctionalCost,
SquareReducedBellCost,
)
from slam.utils.pd_playground import ParallelDrivenGateWidget
from qiskit.circuit.library import SwapGate
from weylchamber import c1c2c3
target = SwapGate().to_matrix()
# cost_f = WeylEuclideanCost()
cost_f = SquareReducedCost()
# cost_f = SquareReducedBellCost()
best_cost = None
pdgw = ParallelDrivenGateWidget(
N=10, gc=np.pi / 2, gg=0, phase_a=0, phase_b=0, phase_c=0, phase_g=0
)
# for a in tqdm(list(permutations(np.arange(-2*np.pi, 2*np.pi+np.pi/8, np.pi/2), r=6))):
def cost_function(a):
# # use widget to change parameters
pdgw2 = ParallelDrivenGateWidget(
N=3, gc=np.pi / 2, gg=0, phase_a=a[0], phase_b=a[1], phase_c=a[2], phase_g=a[3]
)
pdgw3 = ParallelDrivenGateWidget(
N=2, gc=np.pi / 2, gg=0, phase_a=a[4], phase_b=a[5], phase_c=a[6], phase_g=a[7]
)
pdgw4 = pdgw + pdgw2 + pdgw3
gx, gy = list(np.ones(10) * np.pi) + list(np.ones(3) * a[8]) + list(
np.ones(2) * a[9]
), list(np.ones(10) * np.pi) + list(np.ones(3) * a[10]) + list(np.ones(2) * a[11])
pdgw4.prepare_parameters_nonuniform(gx, gy)
# pdgw3.iterate_time()
f = pdgw4.solve_end()
# want to track minimum distance to target
current_cost = cost_f.unitary_fidelity(target, f)
return current_cost
# if best_cost is None or current_cost <= best_cost:
# best_cost = current_cost
# best_a = a
# print(best_cost, best_a)
# optimize
# try i times with random initial parameters
from scipy.optimize import minimize
i = 5
for _ in tqdm(range(i)):
res = minimize(
cost_function,
list(np.random.uniform(-2 * np.pi, 2 * np.pi, size=12)),
method="Nelder-Mead",
options={"disp": True},
)
if best_cost is None or res.fun < best_cost:
best_cost = res.fun
best_a = res.x
print(best_cost, best_a)
# 0.013629539844115302 [ 4.87911870e+00 -4.87814684e+00 -5.91729395e+00 4.54059294e+02
# -3.34409934e+00 2.00213460e-01 -5.69159762e+00 4.55756897e+02
# -3.33791862e+00 -3.28845361e+00 3.33429678e+00 -3.27741811e+00]
# #
# best_a = [ 1.40369633, -1.40379037, -6.64622192, 3.2541767, 3.34337449, -0.20441138,
# 5.68834068, 2.26490991, 3.3392069, 3.28468904, -3.34046558, 3.2873195 ]
# plot results
from slam.utils.visualize import coordinate_2dlist_weyl
a = best_a
pdgw = ParallelDrivenGateWidget(
N=10, gc=np.pi / 2, gg=0, phase_a=0, phase_b=0, phase_c=0, phase_g=0
)
pdgw2 = ParallelDrivenGateWidget(
N=3, gc=np.pi / 2, gg=0, phase_a=a[0], phase_b=a[1], phase_c=a[2], phase_g=a[3]
)
pdgw3 = ParallelDrivenGateWidget(
N=2, gc=np.pi / 2, gg=0, phase_a=a[4], phase_b=a[5], phase_c=a[6], phase_g=a[7]
)
pdgw4 = pdgw + pdgw2 + pdgw3
gx, gy = list(np.ones(10) * np.pi) + list(np.ones(3) * a[8]) + list(
np.ones(2) * a[9]
), list(np.ones(10) * np.pi) + list(np.ones(3) * a[10]) + list(np.ones(2) * a[11])
pdgw4.prepare_parameters_nonuniform(gx, gy)
pdgw4.iterate_time(R=5)
coordinate_2dlist_weyl(*pdgw4.coordinate_list);
# plot final unitary
from slam.utils.visualize import plotMatrix
from slam.cost_function import SquareCost
c = SquareCost()
print(c.unitary_fidelity(target, pdgw4.final_unitary))
c1c2c3(pdgw4.final_unitary)
plotMatrix(pdgw4.final_unitary);
|
https://github.com/JayantiSingh/Quant_co_Qiskit
|
JayantiSingh
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute
#NOT gate = X gate
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q,c)
qc.x(q[0])
qc.measure(q[0], c[0])
qc.draw(output='mpl')
# AND gate = output t of CCX gate
q = QuantumRegister(3)
c = ClassicalRegister(1)
qc = QuantumCircuit(q,c)
qc.ccx(q[0], q[1], q[2])
qc.measure(q[2], c[0])
qc.draw(output='mpl')
# NAND gate= AND+NOT= CCX+X gate
q = QuantumRegister(3)
c = ClassicalRegister(1)
qc = QuantumCircuit(q,c)
qc.ccx(q[0], q[1], q[2])
qc.x(q[2])
qc.measure(q[2], c[0])
qc.draw(output='mpl')
# OR gate= cx+cx+CCX gate
q = QuantumRegister(3)
c = ClassicalRegister(1)
qc = QuantumCircuit(q,c)
qc.cx(q[1], q[2])
qc.cx(q[0], q[2])
qc.ccx(q[0], q[1], q[2])
qc.measure(q[2], c[0])
qc.draw(output='mpl')
# XOR gate = cx+cx
q = QuantumRegister(3)
c = ClassicalRegister(1)
qc = QuantumCircuit(q,c)
qc.cx(q[1], q[2])
qc.cx(q[0], q[2])
qc.measure(q[2], c[0])
qc.draw(output='mpl')
# NOR gate= cx+cx+CCX+X
q = QuantumRegister(3)
c = ClassicalRegister(1)
qc = QuantumCircuit(q,c)
qc.cx(q[1], q[2])
qc.cx(q[0], q[2])
qc.ccx(q[0], q[1], q[2])
qc.x(q[2])
qc.measure(q[2], c[0])
qc.draw(output='mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.transpiler.passes import RemoveBarriers
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.barrier()
circuit.h(0)
circuit = RemoveBarriers()(circuit)
circuit.draw('mpl')
|
https://github.com/googlercolin/Qiskit-Course
|
googlercolin
|
# !pip install -r 'requirements.txt' --quiet
import numpy as np
import torch
from torchvision.transforms import ToTensor
from torch import no_grad
from torchvision import datasets
import torch.optim as optim
from torch.nn import (Module, Conv2d, Linear, Dropout2d, NLLLoss, MaxPool2d, Flatten, Sequential, ReLU)
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from qiskit import *
from qiskit import transpile, assemble, IBMQ
from qiskit.visualization import *
from qiskit import Aer, QuantumCircuit
from qiskit.utils import QuantumInstance, algorithm_globals
from qiskit.opflow import AerPauliExpectation
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from qiskit.circuit import ParameterVector
from qiskit_machine_learning.neural_networks import CircuitQNN, TwoLayerQNN
from qiskit_machine_learning.connectors import TorchConnector
import qiskit.providers.fake_provider as fake
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer import AerSimulator
import matplotlib.pyplot as plt
provider = IBMQ.load_account()
# Declare Quantum instance
noisy_backend = provider.get_backend('ibmq_manila')
backend_sim = AerSimulator.from_backend(noisy_backend)
qi = QuantumInstance(backend_sim)
print(backend_sim)
### Training and test data downloaded from FashionMNIST and transformed into tensors ###
training_data = datasets.FashionMNIST(
root="data",
train=True,
download=True,
transform=ToTensor()
)
test_data = datasets.FashionMNIST(
root="data",
train=False,
download=True,
transform=ToTensor()
)
### Inspecting the images in the training data set with their labels ###
labels_map = {
0: "T-Shirt",
1: "Trouser",
2: "Pullover",
3: "Dress",
4: "Coat",
5: "Sandal",
6: "Shirt",
7: "Sneaker",
8: "Bag",
9: "Ankle Boot",
}
figure = plt.figure(figsize=(8, 8))
cols, rows = 3, 3
for i in range(1, cols * rows + 1):
sample_idx = torch.randint(len(training_data), size=(1,)).item()
img, label = training_data[sample_idx]
figure.add_subplot(rows, cols, i)
plt.title(labels_map[label])
plt.axis("off")
plt.imshow(img.squeeze(), cmap="gray")
plt.show()
### Load training data into Torch DataLoader ###
X_train = training_data
n_samples = 500
batch_size = 64
# Filter out labels (originally 0-9), leaving only labels 0 and 1
idx = np.append(np.where(X_train.targets == 0)[0][:n_samples],
np.where(X_train.targets == 1)[0][:n_samples])
X_train.data = X_train.data[idx]
X_train.targets = X_train.targets[idx]
# A torch dataloader is defined with filtered data
train_loader = DataLoader(X_train, batch_size=64, shuffle=True)
# Load test data into Torch DataLoader
X_test = test_data
# Filter out labels (originally 0-9), leaving only labels 0 and 1
idx = np.append(np.where(X_test.targets == 0)[0][:n_samples],
np.where(X_test.targets == 1)[0][:n_samples])
X_test.data = X_test.data[idx]
X_test.targets = X_test.targets[idx]
# Define torch dataloader with filtered data
test_loader = DataLoader(X_test, batch_size=64, shuffle=True)
### Two layer QNN constructed ###
feature_map_lib = ZZFeatureMap(feature_dimension=2, entanglement='linear')
ansatz_lib = RealAmplitudes(2, reps=1, entanglement='linear')
print(feature_map_lib.decompose())
print(ansatz_lib.decompose())
qnn2 = TwoLayerQNN(2, feature_map_lib, ansatz_lib, input_gradients=True,
exp_val=AerPauliExpectation(), quantum_instance=qi)
print(qnn2.operator)
### Torch NN module from Qiskit ###
class Net(Module):
def __init__(self):
super().__init__()
self.conv1 = Conv2d(1, 2, kernel_size=5)
self.conv2 = Conv2d(2, 16, kernel_size=5)
self.dropout = Dropout2d()
self.fc1 = Linear(256, 64)
self.fc2 = Linear(64, 2) # 2-dimensional input to QNN
# Apply torch connector, weights chosen
self.qnn = TorchConnector(qnn2)
# uniformly at random from interval [-1,1].
self.fc3 = Linear(1, 1)
# 1-dimensional output from QNN
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(x.shape[0], -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.qnn(x) # apply QNN
x = self.fc3(x)
return torch.cat((x, 1 - x), -1)
### Model trained and the loss computed ###
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 20
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list[-1]))
### Loss convergence plotted ###
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg. Log Likelihood Loss')
plt.show()
### Model evaluated ###
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
(correct / len(test_loader) / batch_size) * 100))
### Predicted images displayed. Either T-shirt or Trouser ###
n_samples_show = 6
count = 0
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(15, 5))
model.eval()
with no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
if count == n_samples_show:
break
output = model(data[0:1])
if len(output.shape) == 1:
output = output.reshape(1, *output.shape)
pred = output.argmax(dim=1, keepdim=True)
axes[count].imshow(data[0].numpy().squeeze(), cmap='gray')
axes[count].set_xticks([])
axes[count].set_yticks([])
if pred.item() == 0:
axes[count].set_title('Predicted item: T-Shirt')
elif pred.item() == 1:
axes[count].set_title('Predicted item: Trouser')
count += 1
pi = np.pi
feature_dim = 2
reps = 2
duplicates = 1
feature_map_circuit = QuantumCircuit(feature_dim, name='feature_map_circuit')
x = ParameterVector('x', feature_dim * reps)
for i in range(reps):
for i in range(feature_dim):
feature_map_circuit.h(i)
feature_map_circuit.p(2.0*x[0], 0)
feature_map_circuit.p(2.0*x[1], 1)
feature_map_circuit.cnot(0, 1)
feature_map_circuit.p(2.0*(pi - x[0])*(pi - x[1]), 1)
feature_map_circuit.cnot(0, 1)
feature_map_circuit.draw()
num_qubits = 2
ansatz_circuit = QuantumCircuit(num_qubits, name='ansatz_circuit')
reps = 1
params = ParameterVector('θ', num_qubits + num_qubits * reps)
counter = 0
for i in range(num_qubits):
ansatz_circuit.ry(params[counter], i)
counter += 1
for j in range(reps):
for k in range(num_qubits-1):
ansatz_circuit.cnot(k, k+1)
for m in range(num_qubits):
ansatz_circuit.ry(params[counter], m)
counter += 1
ansatz_circuit.draw()
qnn2 = TwoLayerQNN(2, feature_map_circuit, ansatz_circuit, input_gradients=True,
exp_val=AerPauliExpectation(), quantum_instance=qi)
print(qnn2.operator)
### Torch NN module from Qiskit ###
class Net(Module):
def __init__(self):
super().__init__()
self.conv1 = Conv2d(1, 2, kernel_size=5)
self.conv2 = Conv2d(2, 16, kernel_size=5)
self.dropout = Dropout2d()
self.fc1 = Linear(256, 64)
self.fc2 = Linear(64, 2) # 2-dimensional input to QNN
# Apply torch connector, weights chosen
self.qnn = TorchConnector(qnn2)
# uniformly at random from interval [-1,1].
self.fc3 = Linear(1, 1)
# 1-dimensional output from QNN
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(x.shape[0], -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.qnn(x) # apply QNN
x = self.fc3(x)
return torch.cat((x, 1 - x), -1)
### Model trained and the loss computed ###
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 20
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list[-1]))
### Loss convergence plotted ###
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg. Log Likelihood Loss')
plt.show()
torch.save(model.state_dict(
), 'Models/defaultZZDefaultRealAmp.pth')
### Model evaluated ###
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
(correct / len(test_loader) / batch_size) * 100))
### Predicted images displayed. Either T-shirt or Trouser ###
n_samples_show = 6
count = 0
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(15, 5))
model.eval()
with no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
if count == n_samples_show:
break
output = model(data[0:1])
if len(output.shape) == 1:
output = output.reshape(1, *output.shape)
pred = output.argmax(dim=1, keepdim=True)
axes[count].imshow(data[0].numpy().squeeze(), cmap='gray')
axes[count].set_xticks([])
axes[count].set_yticks([])
if pred.item() == 0:
axes[count].set_title('Predicted item: T-Shirt')
elif pred.item() == 1:
axes[count].set_title('Predicted item: Trouser')
count += 1
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
# !pip install qiskit==0.7.1
# Include the necessary imports for this program
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# Create a Quantum Register with 2 qubits
qr = QuantumRegister(2)
# Create a Classical Register with 2 bits
cr = ClassicalRegister(2)
# Create a Quantum Circuit from the quantum and classical registers
circ = QuantumCircuit(qr, cr)
# Place Hadamard gate on the top wire, putting this qubit in a superposition.
circ.h(qr[0])
# Add a CX (CNOT) gate across the top two wires, entangling the qubits.
circ.cx(qr[0], qr[1])
# Create a barrier that separates the gates from the measurements
circ.barrier(qr)
# Measure the qubits into the classical registers
circ.measure(qr, cr)
# Draw the new circuit
circ.draw(output='mpl')
# Use the BasicAer statevector_simulator backend
from qiskit import BasicAer
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
# Execute the circuit on the state vector simulator
job_sim = execute(circ, backend_sv_sim)
# Grab the results from the job.
result_sim = job_sim.result()
# Obtain the state vector for the quantum circuit
quantum_state = result_sim.get_statevector(circ, decimals=3)
# Output the quantum state vector in a manner that contains a comma-delimited string.
quantum_state
# Plot the state vector on a Q-sphere
from qiskit.tools.visualization import plot_state_qsphere
plot_state_qsphere(quantum_state)
# Use the BasicAer qasm_simulator backend
from qiskit import BasicAer
backend_sim = BasicAer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator, running it 1000 times.
job_sim = execute(circ, backend_sim, shots=1000)
# Grab the results from the job.
result_sim = job_sim.result()
# Print the counts, which are contained in a Python dictionary
counts = result_sim.get_counts(circ)
print(counts)
# Plot the results on a histogram
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
# Include the necessary imports for this program
# Create a Quantum Register with 2 qubits
# Create a Classical Register with 2 bits
# Create a Quantum Circuit from the quantum and classical registers
# Place appropriate gates on the wires to achieve the desired Bell state
# Create a barrier that separates the gates from the measurements
# Measure the qubits into the classical registers
# Draw the circuit
# Use the BasicAer statevector_simulator backend
# Execute the circuit on the state vector simulator
# Grab the results from the job.
# Obtain the state vector for the quantum circuit
# Output the quantum state vector in a manner that contains a comma-delimited string.
# Plot the state vector on a Q-sphere
# Use the BasicAer qasm_simulator backend
# Execute the circuit on the qasm simulator, running it 1000 times.
# Grab the results from the job.
# Print the counts, which are contained in a Python dictionary
# Plot the results on a histogram
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
circ.measure([0, 1], [0, 1])
circ.draw("mpl")
from qiskit import transpile, schedule as build_schedule
from qiskit.providers.fake_provider import FakeHanoi
backend = FakeHanoi()
transpiled_circ = transpile(circ, backend) # Undefined Hadamard is replaced by U1
schedule = build_schedule(transpiled_circ, backend)
schedule.draw()
from qiskit import pulse
with pulse.build() as h_q0:
pulse.play(pulse.library.Gaussian(duration=256, amp=0.2, sigma=50, name='custom'),
pulse.DriveChannel(0))
circ.add_calibration('h', [0], h_q0)
schedule = build_schedule(circ, backend)
schedule.draw()
circ = QuantumCircuit(2, 2)
circ.x(0)
circ.x(0)
circ.x(1)
circ.measure([0, 1], [0, 1])
circ.draw("mpl")
schedule = build_schedule(circ, backend, method="as_late_as_possible")
schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1)]).draw()
schedule = build_schedule(circ, backend, method="as_soon_as_possible")
schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1)]).draw()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.algorithms import AmplificationProblem
# the state we desire to find is '11'
good_state = ['11']
# specify the oracle that marks the state '11' as a good solution
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
# define Grover's algorithm
problem = AmplificationProblem(oracle, is_good_state=good_state)
# now we can have a look at the Grover operator that is used in running the algorithm
# (Algorithm circuits are wrapped in a gate to appear in composition as a block
# so we have to decompose() the op to see it expanded into its component gates.)
problem.grover_operator.decompose().draw(output='mpl')
from qiskit.algorithms import Grover
from qiskit.primitives import Sampler
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
print('Result type:', type(result))
print()
print('Success!' if result.oracle_evaluation else 'Failure!')
print('Top measurement:', result.top_measurement)
from qiskit.quantum_info import Statevector
oracle = Statevector.from_label('11')
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
print('Result type:', type(result))
print()
print('Success!' if result.oracle_evaluation else 'Failure!')
print('Top measurement:', result.top_measurement)
problem.grover_operator.oracle.decompose().draw(output='mpl')
from qiskit.circuit.library.phase_oracle import PhaseOracle
from qiskit.exceptions import MissingOptionalLibraryError
# `Oracle` (`PhaseOracle`) as the `oracle` argument
expression = '(a & b)'
try:
oracle = PhaseOracle(expression)
problem = AmplificationProblem(oracle)
display(problem.grover_operator.oracle.decompose().draw(output='mpl'))
except MissingOptionalLibraryError as ex:
print(ex)
import numpy as np
# Specifying `state_preparation`
# to prepare a superposition of |01>, |10>, and |11>
oracle = QuantumCircuit(3)
oracle.ccz(0, 1, 2)
theta = 2 * np.arccos(1 / np.sqrt(3))
state_preparation = QuantumCircuit(3)
state_preparation.ry(theta, 0)
state_preparation.ch(0,1)
state_preparation.x(1)
state_preparation.h(2)
# we only care about the first two bits being in state 1, thus add both possibilities for the last qubit
problem = AmplificationProblem(oracle, state_preparation=state_preparation, is_good_state=['110', '111'])
# state_preparation
print('state preparation circuit:')
problem.grover_operator.state_preparation.draw(output='mpl')
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
print('Success!' if result.oracle_evaluation else 'Failure!')
print('Top measurement:', result.top_measurement)
oracle = QuantumCircuit(5)
oracle.ccz(0, 1, 2)
oracle.draw(output='mpl')
from qiskit.circuit.library import GroverOperator
grover_op = GroverOperator(oracle, insert_barriers=True)
grover_op.decompose().draw(output='mpl')
grover_op = GroverOperator(oracle, reflection_qubits=[0, 1, 2], insert_barriers=True)
grover_op.decompose().draw(output='mpl')
# a list of binary strings good state
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
good_state = ['11', '00']
problem = AmplificationProblem(oracle, is_good_state=good_state)
print(problem.is_good_state('11'))
# a list of integer good state
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
good_state = [0, 1]
problem = AmplificationProblem(oracle, is_good_state=good_state)
print(problem.is_good_state('11'))
from qiskit.quantum_info import Statevector
# `Statevector` good state
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
good_state = Statevector.from_label('11')
problem = AmplificationProblem(oracle, is_good_state=good_state)
print(problem.is_good_state('11'))
# Callable good state
def callable_good_state(bitstr):
if bitstr == "11":
return True
return False
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=good_state)
print(problem.is_good_state('11'))
# integer iteration
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(iterations=1)
# list iteration
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(iterations=[1, 2, 3])
# using sample_from_iterations
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(iterations=[1, 2, 3], sample_from_iterations=True)
iterations = Grover.optimal_num_iterations(num_solutions=1, num_qubits=8)
iterations
def to_DIAMACS_CNF_format(bit_rep):
return [index+1 if val==1 else -1 * (index + 1) for index, val in enumerate(bit_rep)]
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'], post_processing=to_DIAMACS_CNF_format)
problem.post_processing([1, 0, 1])
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
import numpy as np
from random import random
from qiskit import *
from qiskit.aqua.utils.controlled_circuit import get_controlled_circuit
num_bits_estimate = 3
# For 2x2 matrix one qubit is enough
q = QuantumRegister(1, name="q")
# In QPE we use n ancillas to estimate n bits from the phase
a = QuantumRegister(num_bits_estimate, name="a")
# For n ancillary qubit measurment we need n cllasical bits
c = ClassicalRegister(num_bits_estimate, name="c")
# Create a quantum circuit
circuit = QuantumCircuit(q, a, c)
# |1> eigenstate initialization
circuit.x(q[0])
circuit.draw('mpl')
E_1, E_2 = (2 * np.pi * random(), 2 * np.pi * random())
print("We are going to estimate E_2 via QPE algorithm \nE_2 = {}".format(E_2))
# circuit for unitary operator exp(iHt)
t = 1
unitary = QuantumCircuit(q)
unitary.u1(E_2 * t, q[0]) # q[0] is the only qubit in q register
unitary.x(q[0])
unitary.u1(E_1 * t, q[0])
unitary.x(q[0])
unitary.draw('mpl')
for ancillary in a:
circuit.h(ancillary)
for n in range(a.size):
for m in range(2**n):
get_controlled_circuit(unitary, a[n], circuit)
# inverse QFT without SWAP gates
for n in reversed(range(a.size)):
circuit.h(a[n])
if n != 0:
for m in reversed(range(n)):
angle = -2*np.pi / (2**(n - m + 1))
circuit.cu1(angle, a[n], a[m])
# measurements on the ancillary qubits stored in c classical register
for n in reversed(range(a.size)):
circuit.measure(a[n],c[n])
circuit.draw('mpl')
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024 # how many time execute the algorithm
job = execute(circuit, backend, shots=shots)
result = job.result()
counts = result.get_counts()
phase_bits = max(counts, key=counts.get) # take the most often obtaned result
phase = 0
for index, bit in enumerate(reversed(phase_bits)):
phase += int(bit) / 2**(index + 1)
estimated_E_2 = 2 * np.pi * phase / t
print("Eigenvalue of the Hamiltonian: {}".format(E_2))
print("Estimated eigenvalue of the Hamiltonian: {}".format(estimated_E_2))
|
https://github.com/BoxiLi/qiskit-CR-calibration
|
BoxiLi
|
import logging
from copy import deepcopy
import warnings
import numpy as np
from numpy import pi
import matplotlib.pyplot as plt
from qiskit.circuit import Gate
from qiskit import transpile
from qiskit.transpiler import InstructionProperties
from qiskit_utilities import (
save_job_data,
setup_logger,
retrieve_expdata,
get_cr_schedule,
iy_drag_calibration,
get_default_cr_params,
read_calibration_data,
create_direct_cnot_schedule,
rough_rz0_correction_calibration,
fine_rz0_correction_calibration,
initilize_qiskit_dynamics_backend
)
session = None # qiskit runtime session
# Setup a logging system.
setup_logger(filename=None, level=logging.INFO, stdout=True)
logger = logging.getLogger("qiskit_utilities")
# Create a qiskit-dynamics backend with two Transmon, see fake_backend.py for detail.
# fidelity
f0 = 5.188339840468758e9
f1 = 5.079647268847252e9
# anharmonicity
a0 = -0.341931669003125e9
a1 = -0.343248404293835e9
backend = initilize_qiskit_dynamics_backend(f0, f1, a0, a1, J=0.0030e9)
# Operating qubits
QUBIT_C, QUBIT_T = (0, 1)
# Multiple the amplitude by a ratio factor.
ratio = 1
# Compute the sampling time steps for the CR tomography experiments
if backend.name == 'DynamicsBackend':
amp = 2 * pi * 0.06
cr_times = np.arange(16*16, 1440*3, 32*4, dtype=int)
duration = 720*2 # Used for plotting only, not tomography.
else:
amp = get_default_cr_params(backend, QUBIT_C, QUBIT_T)[0]
duration = backend.defaults().instruction_schedule_map.get("cx", (QUBIT_C, QUBIT_T)).duration/16 * 4 / ratio
cr_times = 16 * np.arange(16, duration + 16, duration//30, dtype=int)
# Custom shape
gate_name = "CR-recursive-tr10-direct"
params = {
"order": "3", # order m for the initial pulse shape
"t_r": 10,
"drag_type" : "exact", # Givens rotation, use "sw" for perturbation
"duration": duration, # only for plotting
"amp": amp,
"angle": 0.0,
## If real device, use the following
# "Delta": (backend.properties().frequency(QUBIT_C) - backend.properties().frequency(QUBIT_T)) * 1.0e-9 * 2 * pi,
# "a1": 2 * pi * backend.properties().qubit_property(QUBIT_C)["anharmonicity"][0] * 1.0e-9,
## If Dynamicsbackend, use this
"Delta": 2 * pi * (f0 - f1) * 1.0e-9,
"a1": 2 * pi * a0 * 1.0e-9,
"drag_scale": [1., 1., 1.],
}
cr_params = params.copy()
ix_params = params.copy()
ix_params["amp"] = 0.0
ix_params["order"] = "2"
ix_params["drag_type"] = "01" # single-derivative DRAG
initial_calibration_data = {
"cr_params": cr_params,
"ix_params": ix_params,
"frequency_offset": 0.,
}
get_cr_schedule((QUBIT_C, QUBIT_T), backend, cr_params=cr_params, ix_params=ix_params).draw()
from qiskit_utilities import iterative_cr_pulse_calibration
iterative_cr_pulse_calibration(
(QUBIT_C, QUBIT_T),
backend,
initial_calibration_data=initial_calibration_data,
cr_times=cr_times,
session=session,
gate_name=gate_name,
verbose=True,
restart=True,
max_repeat=3,
rerun_last_calibration=True,
shots=2048,
mode="CR",
)
iy_drag_calibration((QUBIT_C, QUBIT_T), backend, gate_name, cr_times, session, verbose=True, delta_beta=10.)
# Reduce cr_times by a half
if backend.name == 'DynamicsBackend':
cr_times = np.arange(16*16, 1440*4, 32*4, dtype=int)
else:
duration = backend.defaults().instruction_schedule_map.get("cx", (QUBIT_C, QUBIT_T)).duration/16 * 4 / ratio / 2
cr_times = 16 * np.arange(16, duration + 16, duration//30, dtype=int)
from qiskit_utilities import iterative_cr_pulse_calibration
iterative_cr_pulse_calibration(
(QUBIT_C, QUBIT_T),
backend,
cr_times,
session,
gate_name=gate_name,
initial_calibration_data=None,
verbose=True,
threshold_MHz=0.015,
restart=True,
rerun_last_calibration=False,
max_repeat=3,
shots=8096,
mode="IX-pi"
)
rough_rz0_correction_calibration(backend, (QUBIT_C, QUBIT_T), gate_name, session)
fine_rz0_correction_calibration(backend, (QUBIT_C, QUBIT_T), gate_name, session, num_repeat_cnot=6)
from qiskit_experiments.library import ProcessTomography
calibration_data = read_calibration_data(backend, gate_name, (QUBIT_C, QUBIT_T))
custom_cnot_sched = create_direct_cnot_schedule(backend, (QUBIT_C, QUBIT_T), calibration_data, reverse_direction=False)
# Show the custom CNOT schedule.
custom_cnot_sched.draw()
custom_cnot = Gate("custom_cnot", 2, [])
backend_tmp = deepcopy(backend)
backend_tmp.target.add_instruction(
custom_cnot,
{(QUBIT_C, QUBIT_T): InstructionProperties(calibration=custom_cnot_sched)},
name="custom_cnot",
)
qptexp = ProcessTomography(custom_cnot, physical_qubits=[QUBIT_C, QUBIT_T])
try:
basis_gates = backend.configuration().basis_gates
except AttributeError:
basis_gates = ["measure", "sx", "x", "rz"]
transpiled_circ_list = transpile(
qptexp._transpiled_circuits(),
backend=backend_tmp,
basis_gates = basis_gates + ["custom_cnot"],
optimization_level= 1, # Turn off optimization to keep the custom pulse
)
shots=8096
if session is not None:
qpt_job = session.run(
"circuit-runner",
inputs={
"circuits": transpiled_circ_list,
"skip_transpilation": True,
"shots": shots,
},
)
else:
qpt_job = backend.run(transpiled_circ_list, shots=shots)
parameters = {
"backend": backend.name,
"qubits": (QUBIT_C, QUBIT_T),
"shots": shots,
}
logger.info(
"Quantum process tomography job: "+
str(qpt_job.job_id()) + "\n"
+ "\n".join([f"{key}: {val}" for key, val in parameters.items()])
+ "\n"
)
save_job_data(qpt_job, backend=backend, parameters=parameters)
import qutip
qptdata = retrieve_expdata(qpt_job, backend=backend, exp=qptexp)
state_result = qptdata.analysis_results("state")
choi_matrix = state_result.value.data
choi_qobj = qutip.Qobj(
choi_matrix, dims=[[[2, 2], [2, 2]], [[2, 2], [2, 2]]], superrep="choi"
)
choi_qobj = choi_qobj.permute([[1, 0], [3, 2]]) # Permute the two qubit
qutip.to_super(choi_qobj)
op_basis = [[qutip.qeye(2), qutip.sigmax(), qutip.sigmay(), qutip.sigmaz()]] * 2
chi = qutip.qpt(qutip.to_super(choi_qobj), op_basis)
qutip.qpt_plot_combined(
chi, lbls_list=[["i", "x", "y", "z"]] * 2, title="Process Matrix"
)
from qiskit.circuit.library import CXGate
from qiskit_experiments.library import InterleavedRB
mode = "with_correction"
direct = True
if mode not in ("with_correction", "without_correction", "default"):
raise ValueError("Unknown mode.")
backend_tmp = deepcopy(backend)
rb_gate = CXGate()
calibration_data = read_calibration_data(backend, gate_name, (QUBIT_C, QUBIT_T))
if mode != "default":
modified_calibration_data = deepcopy(calibration_data)
if mode == "without_correction":
modified_calibration_data["ix_params"]["beta"] = 0.
modified_calibration_data["frequency_offset"] = 0.
modified_calibration_data["x_gate_frequency_offset"] = 0.
# Direct gate
custom_cnot_sched = create_direct_cnot_schedule(backend, (QUBIT_C, QUBIT_T), modified_calibration_data, with_separate_x=False)
backend_tmp.target["cx"][(QUBIT_C, QUBIT_T)] = InstructionProperties(calibration=custom_cnot_sched)
custom_cnot_sched = create_direct_cnot_schedule(backend, (QUBIT_C, QUBIT_T), modified_calibration_data, with_separate_x=False, reverse_direction=True)
backend_tmp.target["cx"][(QUBIT_T, QUBIT_C)] = InstructionProperties(calibration=custom_cnot_sched)
seed = np.random.randint(2**16)
num_sampling = 30
lengths = [1, 10, 20, 30, 40, 50, 60]
irb_exp = InterleavedRB(
interleaved_element=rb_gate, physical_qubits=[QUBIT_C, QUBIT_T], lengths=lengths, num_samples=num_sampling, backend=backend_tmp, seed=seed)
transpiled_circ_list = transpile(
# One must use _transpiled_circuits because it will include the calibration
irb_exp._transpiled_circuits(),
backend=backend_tmp,
basis_gates= ["x", "sx", "rz", "cx"], #+ ["custom_cnot"],
# initial_layout = [QUBIT_C, QUBIT_T], # Map the circuit to the target qubits
optimization_level= 1, # Turn off optimization to keep the custom pulse
)
shots = 4096
rb_job = backend_tmp.run(
transpiled_circ_list,
shots=shots,
)
parameters = {
"backend": backend.name,
"mode": mode,
"with_separate_x": False,
"direct": direct,
"qubits": [QUBIT_C, QUBIT_T],
"gate": rb_gate.name,
"shots": shots,
"lengths": lengths,
"num_sampling": num_sampling,
"seed": seed,
"calibration_data": calibration_data,
}
logger.info(
"Randomized benchmarking job: "+
str(rb_job.job_id()) + "\n"
+ "\n".join([f"{key}: {val}" for key, val in parameters.items()])
+ "\n"
)
save_job_data(rb_job, backend=backend, parameters=parameters)
from qiskit_utilities import load_job_data
parameters = load_job_data(rb_job)["parameters"]
exp_rb = InterleavedRB(
interleaved_element=CXGate(),
physical_qubits=[QUBIT_C, QUBIT_T],
lengths=parameters["lengths"],
num_samples=parameters["num_sampling"],
backend=backend,
seed=parameters["seed"])
exp_data = retrieve_expdata(rb_job, backend, exp=exp_rb)
exp_data.figure(0)
|
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.
"""NumTensorFactors pass testing"""
import unittest
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.passes import NumTensorFactors
from qiskit.test import QiskitTestCase
class TestNumTensorsFactorPass(QiskitTestCase):
"""Tests for NumTensorFactors analysis methods."""
def test_empty_dag(self):
"""Empty DAG has 0 number of tensor factors."""
circuit = QuantumCircuit()
dag = circuit_to_dag(circuit)
pass_ = NumTensorFactors()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["num_tensor_factors"], 0)
def test_just_qubits(self):
"""A dag with 8 operations and 1 tensor factor."""
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_ = NumTensorFactors()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["num_tensor_factors"], 1)
def test_depth_one(self):
"""A dag with operations in parallel (2 tensor factors)"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
dag = circuit_to_dag(circuit)
pass_ = NumTensorFactors()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["num_tensor_factors"], 2)
if __name__ == "__main__":
unittest.main()
|
https://github.com/jvscursulim/qamp_fall22_project
|
jvscursulim
|
import copy
import time
import medmnist
import numpy as np
import torch
import torchvision
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import torchvision.transforms as transforms
import torch.nn.functional as F
from torch import cat
from medmnist import INFO, Evaluator
from tqdm import tqdm
from qiskit.circuit import QuantumCircuit, QuantumRegister, Parameter, ParameterVector
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from qiskit.utils import QuantumInstance, algorithm_globals
from qiskit.opflow import AerPauliExpectation
from qiskit_aer import Aer
from qiskit_machine_learning.neural_networks import CircuitQNN, TwoLayerQNN
from qiskit_machine_learning.connectors import TorchConnector
from skimage.transform import resize
from qpie import QPIE
from neqr import NEQR
torch.manual_seed(42)
algorithm_globals.random_seed = 42
dev = QuantumInstance(backend=Aer.get_backend("statevector_simulator"))
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
flags = ["pathmnist",
"octmnist",
"pneumoniamnist",
"chestmnist",
"dermamnist",
"retinamnist",
"breastmnist",
"bloodmnist",
"tissuemnist",
"organcmnist",
"organsmnist",
"organmnist3d",
"nodulemnist3d",
"adrenalmnist3d",
"fracturemnist3d",
"vesselmnist3d",
"synapsemnist3d"]
NUM_EPOCHS = 3
BATCH_SIZE = 128
lr = 0.001
n_qubits = 4
q_depth = 6
data_flag = flags[-1]
info = INFO[data_flag]
task = info["task"]
n_channel = info["n_channels"]
n_classes = len(info["label"])
DataClass = getattr(medmnist, info["python_class"])
data_transform = transforms.Compose([transforms.ToTensor()])
train_dataset = DataClass(split='train', transform=data_transform)
test_dataset = DataClass(split='test', transform=data_transform)
from skimage import data
brain = data.brain()
import matplotlib.pyplot as plt
plt.imshow(brain[9], cmap="gray")
qc = NEQR().image_quantum_circuit(image=resize(train_dataset.imgs[0], (2,2,2)))
qc.draw("mpl")
train_loader = data.DataLoader(dataset=train_dataset, batch_size=BATCH_SIZE, shuffle=True)
train_loader_at_eval = data.DataLoader(dataset=train_dataset, batch_size=2*BATCH_SIZE, shuffle=True)
test_loader = data.DataLoader(dataset=test_dataset, batch_size=2*BATCH_SIZE, shuffle=False)
def quantum_net(size_input_features=4, size_weights=4):
"""
The variational quantum circuit.
"""
qc = QuantumCircuit(n_qubits)
qc.h(qubit=[i for i in range(n_qubits)])
input_params = ParameterVector(name="input", length=size_input_features)
for idx, param in enumerate(input_params):
qc.ry(theta=param, qubit=idx)
for k in range(q_depth):
for i in range(0, n_qubits - 1, 2):
qc.cx(control_qubit=i, target_qubit=i+1)
for i in range(1, n_qubits - 1, 2):
qc.cx(control_qubit=i, target_qubit=i+1)
params = ParameterVector(name=f"q_weights_{k}", length=size_weights)
for idx, param in enumerate(params):
qc.ry(theta=param, qubit=idx)
qnn = CircuitQNN(qc,
qc.parameters[:4],
qc.parameters[4:],
input_gradients=True,
quantum_instance=dev
)
return qnn
class HybridCNN(nn.Module):
def __init__(self, qnn) -> None:
super().__init__()
self.layer1 = nn.Sequential(nn.Conv2d(1, 2, kernel_size=5),
nn.ReLU(),
nn.MaxPool2d(2))
self.layer2 = nn.Sequential(nn.Conv2d(2, 16, kernel_size=5),
nn.ReLU(),
nn.MaxPool2d(2))
self.dropout = nn.Dropout2d()
self.layer3 = nn.Sequential(nn.Linear(256, 64),
nn.Linear(64, 2))
self.qnn = TorchConnector(qnn)
self.layer4 = nn.Sequential(
nn.Flatten(),
nn.Sigmoid()
)
def forward(self, x):
x = self.layer1(x)
x = self.layer2(x)
x = self.dropout(x)
x = self.layer3(x)
x = x.view(x.size(0), -1)
x = self.qnn(x)
x = self.layer4(x)
return x
class HybridNet(nn.Module):
def __init__(self, qnn):
super().__init__()
self.conv1 = nn.Conv2d(1, 2, kernel_size=5)
self.conv2 = nn.Conv2d(2, 16, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(256, 64)
self.fc2 = nn.Linear(64, 2) # 2-dimensional input to QNN
self.qnn = TorchConnector(qnn) # Apply torch connector, weights chosen
# uniformly at random from interval [-1,1].
self.fc3 = nn.Linear(1, 1) # 1-dimensional output from QNN
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(x.shape[0], -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.qnn(x) # apply QNN
x = self.fc3(x)
return cat((x, 1 - x), -1)
def create_qnn():
feature_map = ZZFeatureMap(2)
ansatz = RealAmplitudes(2, reps=1)
qnn = TwoLayerQNN(2,
feature_map=feature_map,
ansatz=ansatz,
input_gradients=True,
exp_val=AerPauliExpectation(),
quantum_instance=dev)
return qnn
# qnn = quantum_net()
qnn = create_qnn()
model = HybridNet(qnn=qnn)
if task == "multi-label, binary-class":
criterion = nn.BCEWithLogitsLoss()
else:
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
for epoch in range(NUM_EPOCHS):
train_correct = 0
train_total = 0
test_correct = 0
test_total = 0
model.train()
for inputs, targets in tqdm(train_loader):
# forward + backward + optimize
optimizer.zero_grad()
outputs = model(inputs)
if task == 'multi-label, binary-class':
targets = targets.to(torch.float32)
loss = criterion(outputs, targets)
else:
targets = targets.squeeze().long()
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
def test(split):
model.eval()
y_true = torch.tensor([])
y_score = torch.tensor([])
data_loader = train_loader_at_eval if split == 'train' else test_loader
with torch.no_grad():
for inputs, targets in data_loader:
outputs = model(inputs)
if task == 'multi-label, binary-class':
targets = targets.to(torch.float32)
outputs = outputs.softmax(dim=-1)
else:
targets = targets.squeeze().long()
outputs = outputs.softmax(dim=-1)
targets = targets.float().resize_(len(targets), 1)
y_true = torch.cat((y_true, targets), 0)
y_score = torch.cat((y_score, outputs), 0)
y_true = y_true.numpy()
y_score = y_score.detach().numpy()
evaluator = Evaluator(data_flag, split)
metrics = evaluator.evaluate(y_score)
print('%s auc: %.3f acc: %.3f' % (split, *metrics))
print('==> Evaluating ...')
test('train')
test('test')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.utils import algorithm_globals
from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import (
MinimumEigenOptimizer,
RecursiveMinimumEigenOptimizer,
SolutionSample,
OptimizationResultStatus,
)
from qiskit_optimization import QuadraticProgram
from qiskit.visualization import plot_histogram
from typing import List, Tuple
import numpy as np
# create a QUBO
qubo = QuadraticProgram()
qubo.binary_var("x")
qubo.binary_var("y")
qubo.binary_var("z")
qubo.minimize(linear=[1, -2, 3], quadratic={("x", "y"): 1, ("x", "z"): -1, ("y", "z"): 2})
print(qubo.prettyprint())
op, offset = qubo.to_ising()
print("offset: {}".format(offset))
print("operator:")
print(op)
qp = QuadraticProgram()
qp.from_ising(op, offset, linear=True)
print(qp.prettyprint())
algorithm_globals.random_seed = 10598
qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA(), initial_point=[0.0, 0.0])
exact_mes = NumPyMinimumEigensolver()
qaoa = MinimumEigenOptimizer(qaoa_mes) # using QAOA
exact = MinimumEigenOptimizer(exact_mes) # using the exact classical numpy minimum eigen solver
exact_result = exact.solve(qubo)
print(exact_result.prettyprint())
qaoa_result = qaoa.solve(qubo)
print(qaoa_result.prettyprint())
print("variable order:", [var.name for var in qaoa_result.variables])
for s in qaoa_result.samples:
print(s)
def get_filtered_samples(
samples: List[SolutionSample],
threshold: float = 0,
allowed_status: Tuple[OptimizationResultStatus] = (OptimizationResultStatus.SUCCESS,),
):
res = []
for s in samples:
if s.status in allowed_status and s.probability > threshold:
res.append(s)
return res
filtered_samples = get_filtered_samples(
qaoa_result.samples, threshold=0.005, allowed_status=(OptimizationResultStatus.SUCCESS,)
)
for s in filtered_samples:
print(s)
fvals = [s.fval for s in qaoa_result.samples]
probabilities = [s.probability for s in qaoa_result.samples]
np.mean(fvals)
np.std(fvals)
samples_for_plot = {
" ".join(f"{qaoa_result.variables[i].name}={int(v)}" for i, v in enumerate(s.x)): s.probability
for s in filtered_samples
}
samples_for_plot
plot_histogram(samples_for_plot)
rqaoa = RecursiveMinimumEigenOptimizer(qaoa, min_num_vars=1, min_num_vars_optimizer=exact)
rqaoa_result = rqaoa.solve(qubo)
print(rqaoa_result.prettyprint())
filtered_samples = get_filtered_samples(
rqaoa_result.samples, threshold=0.005, allowed_status=(OptimizationResultStatus.SUCCESS,)
)
samples_for_plot = {
" ".join(f"{rqaoa_result.variables[i].name}={int(v)}" for i, v in enumerate(s.x)): s.probability
for s in filtered_samples
}
samples_for_plot
plot_histogram(samples_for_plot)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/weiT1993/qiskit_helper_functions
|
weiT1993
|
from qiskit import QuantumCircuit
from QCLG_lvl3.oracles.secret_number_oracle import SecretNUmberOracle
class BernsteinVazirani:
@classmethod
def bernstein_vazirani(cls, random_binary, eval_mode: bool) -> QuantumCircuit:
# Construct secret number oracle
secret_number_oracle = SecretNUmberOracle.create_secret_number_oracle(random_binary=random_binary, eval_mode=eval_mode)
num_of_qubits = secret_number_oracle.num_qubits
# Construct circuit according to the length of the number
dj_circuit = QuantumCircuit(num_of_qubits, num_of_qubits - 1)
dj_circuit_before_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1)
# Apply H-gates
for qubit in range(num_of_qubits - 1):
dj_circuit_before_oracle.h(qubit)
# Put output qubit in state |->
dj_circuit_before_oracle.x(num_of_qubits - 1)
dj_circuit_before_oracle.h(num_of_qubits - 1)
dj_circuit += dj_circuit_before_oracle
# Add oracle
dj_circuit += secret_number_oracle
dj_circuit_after_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1)
# Repeat H-gates
for qubit in range(num_of_qubits - 1):
dj_circuit_after_oracle.h(qubit)
dj_circuit_after_oracle.barrier()
# Measure
for i in range(num_of_qubits - 1):
dj_circuit_after_oracle.measure(i, i)
dj_circuit += dj_circuit_after_oracle
if not eval_mode:
print("Circuit before the oracle\n")
print(QuantumCircuit.draw(dj_circuit_before_oracle))
print("Circuit after the oracle\n")
print(QuantumCircuit.draw(dj_circuit_after_oracle))
print(dj_circuit)
return dj_circuit
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
#
# A quantum circuit is composed by quantum and classical bits.
#
# here are the objects that we use to create a quantum circuit
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
# we use a quantum register to keep our quantum bits.
qreg = QuantumRegister(1) # in this example we will use a single quantum bit
# To get an information from a quantum bit, it must be measured. (More details will appear.)
# The measurement result is stored classically.
# Therefore, we also use a classical regiser with classical bits
creg = ClassicalRegister(1) # in this example we will use a single classical bit
# now we can define our quantum circuit
# it is composed by a quantum and a classical register
mycircuit = QuantumCircuit(qreg,creg)
# we apply operators on quantum bits
# operators are also called as gates
# we apply NOT operator represented as "x"
# operator is a part of the circuit, and we should specify the quantum bit as the parameter
mycircuit.x(qreg[0]) # (quantum) bits are enumerated starting from 0
# NOT operator or x-gate is applied to the first qubit of the quantum register
# let's run our codes until now, and then draw our circuit
print("Everything looks fine, let's continue ...")
# we use matplotlib_circuit_drawer
# we shortly refer it as "drawer" in our codes
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
# let's draw our circuit now
drawer(mycircuit)
# re-execute me if you DO NOT see the circuit diagram
# measurement is defined by associating a quantum bit to a classical bit
mycircuit.measure(qreg[0],creg[0])
# the result will be stored in the classical bit
print("Everything looks fine, let's continue ...")
# let's draw the circuit again to see how the measurement is defined
drawer(mycircuit)
# reexecute me if you DO NOT see the circuit diagram
# we are done with design of our circuit
# now we can execute it
# we execute quantum circuits many times (WHY?)
# we use method "execute" and object "Aer" from qiskit library
from qiskit import execute, Aer
# we create a job object for execution of the circuit
# there are three parameters
# 1. mycircuit
# 2. beckend on which it will be executed: we will use local simulator
# 3. how_many_times will it be executed, let's pick it as 1024
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1024)
# we can get the result of the outcome as follows
counts = job.result().get_counts(mycircuit)
print(counts)
# usually quantum programs produce probabilistic outcomes
#
# My second quantum circuit
#
# we import all at once
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
# we will use 4 quantum bits and 4 classical bits
qreg2 = QuantumRegister(4)
creg2 = ClassicalRegister(4)
mycircuit2 = QuantumCircuit(qreg2,creg2)
# I will apply x-gate to the first quantum bit twice
mycircuit2.x(qreg2[0])
mycircuit2.x(qreg2[0])
# I will apply x-gate to the fourth quantum bit once
mycircuit2.x(qreg2[3])
# I will apply x-gate to the third quantum bit three times
mycircuit2.x(qreg2[2])
mycircuit2.x(qreg2[2])
mycircuit2.x(qreg2[2])
# I will apply x-gate to the second quantum bit four times
mycircuit2.x(qreg2[1])
mycircuit2.x(qreg2[1])
mycircuit2.x(qreg2[1])
mycircuit2.x(qreg2[1])
# if the size of quantum and classical registers are the same, we can define measurements with a single line code
mycircuit2.measure(qreg2,creg2)
# then each quantum bit and classical bit is associated with respect to their indices
# let's run our codes until now, and then draw our circuit
print("Everything looks fine, let's continue ...")
drawer(mycircuit2)
# re-execute me if you DO NOT see the circuit diagram
job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=500)
counts = job.result().get_counts(mycircuit2)
print(counts)
def print_outcomes(counts): # takes a dictionary variable
for outcome in counts: # for each key-value in dictionary
reverse_outcome = ''
for i in outcome: # each string can be considered as a list of characters
reverse_outcome = i + reverse_outcome # each new symbol comes before the old symbol(s)
print(reverse_outcome,"is observed",counts[outcome],"times")
job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=1024)
counts = job.result().get_counts(mycircuit2) # counts is a dictionary object in python
print_outcomes(counts)
from random import randrange
n = 20
r=randrange(n) # pick a number from the list {0,1,...,n-1}
print(r)
# test this method by using a loop
for i in range(10):
print(randrange(n))
#
# your solution is here
#
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.result import QuasiDistribution
from qiskit_aer.primitives import Sampler
from qiskit_finance.applications.optimization import PortfolioOptimization
from qiskit_finance.data_providers import RandomDataProvider
from qiskit_optimization.algorithms import MinimumEigenOptimizer
import numpy as np
import matplotlib.pyplot as plt
import datetime
# set number of assets (= number of qubits)
num_assets = 4
seed = 123
# Generate expected return and covariance matrix from (random) time-series
stocks = [("TICKER%s" % i) for i in range(num_assets)]
data = RandomDataProvider(
tickers=stocks,
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=seed,
)
data.run()
mu = data.get_period_return_mean_vector()
sigma = data.get_period_return_covariance_matrix()
# plot sigma
plt.imshow(sigma, interpolation="nearest")
plt.show()
q = 0.5 # set risk factor
budget = num_assets // 2 # set budget
penalty = num_assets # set parameter to scale the budget penalty term
portfolio = PortfolioOptimization(
expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget
)
qp = portfolio.to_quadratic_program()
qp
def print_result(result):
selection = result.x
value = result.fval
print("Optimal: selection {}, value {:.4f}".format(selection, value))
eigenstate = result.min_eigen_solver_result.eigenstate
probabilities = (
eigenstate.binary_probabilities()
if isinstance(eigenstate, QuasiDistribution)
else {k: np.abs(v) ** 2 for k, v in eigenstate.to_dict().items()}
)
print("\n----------------- Full result ---------------------")
print("selection\tvalue\t\tprobability")
print("---------------------------------------------------")
probabilities = sorted(probabilities.items(), key=lambda x: x[1], reverse=True)
for k, v in probabilities:
x = np.array([int(i) for i in list(reversed(k))])
value = portfolio.to_quadratic_program().objective.evaluate(x)
print("%10s\t%.4f\t\t%.4f" % (x, value, v))
exact_mes = NumPyMinimumEigensolver()
exact_eigensolver = MinimumEigenOptimizer(exact_mes)
result = exact_eigensolver.solve(qp)
print_result(result)
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 1234
cobyla = COBYLA()
cobyla.set_options(maxiter=500)
ry = TwoLocal(num_assets, "ry", "cz", reps=3, entanglement="full")
vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla)
vqe = MinimumEigenOptimizer(vqe_mes)
result = vqe.solve(qp)
print_result(result)
algorithm_globals.random_seed = 1234
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(qp)
print_result(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/rohitgit1/Quantum-Computing-Summer-School
|
rohitgit1
|
!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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
#General imports
import numpy as np
#Operator Imports
from qiskit.opflow import Z, X, I, StateFn, CircuitStateFn, SummedOp
from qiskit.opflow.gradients import Gradient, NaturalGradient, QFI, Hessian
#Circuit imports
from qiskit.circuit import QuantumCircuit, QuantumRegister, Parameter, ParameterVector, ParameterExpression
from qiskit.circuit.library import EfficientSU2
# Instantiate the quantum state
a = Parameter('a')
b = Parameter('b')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(a, q[0])
qc.rx(b, q[0])
# Instantiate the Hamiltonian observable
H = (2 * X) + Z
# Combine the Hamiltonian observable and the state
op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.)
# Print the operator corresponding to the expectation value
print(op)
params = [a, b]
# Define the values to be assigned to the parameters
value_dict = {a: np.pi / 4, b: np.pi}
# Convert the operator and the gradient target params into the respective operator
grad = Gradient().convert(operator = op, params = params)
# Print the operator corresponding to the Gradient
print(grad)
# Assign the parameters and evaluate the gradient
grad_result = grad.assign_parameters(value_dict).eval()
print('Gradient', grad_result)
# Define the Hamiltonian with fixed coefficients
H = 0.5 * X - 1 * Z
# Define the parameters w.r.t. we want to compute the gradients
params = [a, b]
# Define the values to be assigned to the parameters
value_dict = { a: np.pi / 4, b: np.pi}
# Combine the Hamiltonian observable and the state into an expectation value operator
op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.)
print(op)
# Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameters using
# the parameter shift method.
state_grad = Gradient(grad_method='param_shift').convert(operator=op, params=params)
# Print the operator corresponding to the gradient
print(state_grad)
# Assign the parameters and evaluate the gradient
state_grad_result = state_grad.assign_parameters(value_dict).eval()
print('State gradient computed with parameter shift', state_grad_result)
# Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameter using
# the linear combination of unitaries method.
state_grad = Gradient(grad_method='lin_comb').convert(operator=op, params=params)
# Print the operator corresponding to the gradient
print(state_grad)
# Assign the parameters and evaluate the gradient
state_grad_result = state_grad.assign_parameters(value_dict).eval()
print('State gradient computed with the linear combination method', state_grad_result)
# Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameter using
# the finite difference method.
state_grad = Gradient(grad_method='fin_diff').convert(operator=op, params=params)
# Print the operator corresponding to the gradient
print(state_grad)
# Assign the parameters and evaluate the gradient
state_grad_result = state_grad.assign_parameters(value_dict).eval()
print('State gradient computed with finite difference', state_grad_result)
# Besides the method to compute the circuit gradients resp. QFI, a regularization method can be chosen:
# `ridge` or `lasso` with automatic parameter search or `perturb_diag_elements` or `perturb_diag`
# which perturb the diagonal elements of the QFI.
nat_grad = NaturalGradient(grad_method='lin_comb', qfi_method='lin_comb_full', regularization='ridge').convert(
operator=op, params=params)
# Assign the parameters and evaluate the gradient
nat_grad_result = nat_grad.assign_parameters(value_dict).eval()
print('Natural gradient computed with linear combination of unitaries', nat_grad_result)
# Instantiate the Hamiltonian observable
H = X
# Instantiate the quantum state with two parameters
a = Parameter('a')
b = Parameter('b')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(a, q[0])
qc.rx(b, q[0])
# Combine the Hamiltonian observable and the state
op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.)
# Convert the operator and the hessian target coefficients into the respective operator
hessian = Hessian().convert(operator = op, params = [a, b])
# Define the values to be assigned to the parameters
value_dict = {a: np.pi / 4, b: np.pi/4}
# Assign the parameters and evaluate the Hessian w.r.t. the Hamiltonian coefficients
hessian_result = hessian.assign_parameters(value_dict).eval()
print('Hessian \n', np.real(np.array(hessian_result)))
# Define parameters
params = [a, b]
# Get the operator object representing the Hessian
state_hess = Hessian(hess_method='param_shift').convert(operator=op, params=params)
# Assign the parameters and evaluate the Hessian
hessian_result = state_hess.assign_parameters(value_dict).eval()
print('Hessian computed using the parameter shift method\n', (np.array(hessian_result)))
# Get the operator object representing the Hessian
state_hess = Hessian(hess_method='lin_comb').convert(operator=op, params=params)
# Assign the parameters and evaluate the Hessian
hessian_result = state_hess.assign_parameters(value_dict).eval()
print('Hessian computed using the linear combination of unitaries method\n', (np.array(hessian_result)))
# Get the operator object representing the Hessian using finite difference
state_hess = Hessian(hess_method='fin_diff').convert(operator=op, params=params)
# Assign the parameters and evaluate the Hessian
hessian_result = state_hess.assign_parameters(value_dict).eval()
print('Hessian computed with finite difference\n', (np.array(hessian_result)))
# Wrap the quantum circuit into a CircuitStateFn
state = CircuitStateFn(primitive=qc, coeff=1.)
# Convert the state and the parameters into the operator object that represents the QFI
qfi = QFI(qfi_method='lin_comb_full').convert(operator=state, params=params)
# Define the values for which the QFI is to be computed
values_dict = {a: np.pi / 4, b: 0.1}
# Assign the parameters and evaluate the QFI
qfi_result = qfi.assign_parameters(values_dict).eval()
print('full QFI \n', np.real(np.array(qfi_result)))
# Convert the state and the parameters into the operator object that represents the QFI
# and set the approximation to 'block_diagonal'
qfi = QFI('overlap_block_diag').convert(operator=state, params=params)
# Assign the parameters and evaluate the QFI
qfi_result = qfi.assign_parameters(values_dict).eval()
print('Block-diagonal QFI \n', np.real(np.array(qfi_result)))
# Convert the state and the parameters into the operator object that represents the QFI
# and set the approximation to 'diagonal'
qfi = QFI('overlap_diag').convert(operator=state, params=params)
# Assign the parameters and evaluate the QFI
qfi_result = qfi.assign_parameters(values_dict).eval()
print('Diagonal QFI \n', np.real(np.array(qfi_result)))
# Execution Imports
from qiskit import Aer
from qiskit.utils import QuantumInstance
# Algorithm Imports
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import CG
from qiskit.opflow import I, X, Z
from qiskit.circuit import QuantumCircuit, ParameterVector
from scipy.optimize import minimize
# Instantiate the system Hamiltonian
h2_hamiltonian = -1.05 * (I ^ I) + 0.39 * (I ^ Z) - 0.39 * (Z ^ I) - 0.01 * (Z ^ Z) + 0.18 * (X ^ X)
# This is the target energy
h2_energy = -1.85727503
# Define the Ansatz
wavefunction = QuantumCircuit(2)
params = ParameterVector('theta', length=8)
it = iter(params)
wavefunction.ry(next(it), 0)
wavefunction.ry(next(it), 1)
wavefunction.rz(next(it), 0)
wavefunction.rz(next(it), 1)
wavefunction.cx(0, 1)
wavefunction.ry(next(it), 0)
wavefunction.ry(next(it), 1)
wavefunction.rz(next(it), 0)
wavefunction.rz(next(it), 1)
# Define the expectation value corresponding to the energy
op = ~StateFn(h2_hamiltonian) @ StateFn(wavefunction)
grad = Gradient(grad_method='lin_comb')
qi_sv = QuantumInstance(Aer.get_backend('aer_simulator_statevector'),
shots=1,
seed_simulator=2,
seed_transpiler=2)
#Conjugate Gradient algorithm
optimizer = CG(maxiter=50)
# Gradient callable
vqe = VQE(wavefunction, optimizer=optimizer, gradient=grad, quantum_instance=qi_sv)
result = vqe.compute_minimum_eigenvalue(h2_hamiltonian)
print('Result:', result.optimal_value, 'Reference:', h2_energy)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
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.
"""Depth pass testing"""
import unittest
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.passes import Depth
from qiskit.test import QiskitTestCase
class TestDepthPass(QiskitTestCase):
"""Tests for Depth analysis methods."""
def test_empty_dag(self):
"""Empty DAG has 0 depth"""
circuit = QuantumCircuit()
dag = circuit_to_dag(circuit)
pass_ = Depth()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["depth"], 0)
def test_just_qubits(self):
"""A dag with 8 operations and no classic bits"""
# ┌───┐ ┌───┐┌───┐
# q0_0: ┤ H ├──■────■────■────■──┤ X ├┤ X ├
# ├───┤┌─┴─┐┌─┴─┐┌─┴─┐┌─┴─┐└─┬─┘└─┬─┘
# q0_1: ┤ H ├┤ X ├┤ X ├┤ X ├┤ X ├──■────■──
# └───┘└───┘└───┘└───┘└───┘
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_ = Depth()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["depth"], 7)
def test_depth_one(self):
"""A dag with operations in parallel and depth 1"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
dag = circuit_to_dag(circuit)
pass_ = Depth()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["depth"], 1)
def test_depth_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_ = Depth(recurse=True)
pass_(qc)
self.assertEqual(pass_.property_set["depth"], 16)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
ghz.draw(output='mpl')
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
from qiskit import *
print(qiskit.__version__)
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
def find_secret_number(secter_number):
# Using Bernstein Vazirani Algorithm
secret_number = str(secter_number)
circuit = QuantumCircuit(len(secret_number)+1, len(secret_number))
circuit.h(range(len(secret_number)))
circuit.x(len(secret_number))
circuit.h(len(secret_number))
circuit.barrier()
for position,value in enumerate(reversed(secret_number)):
if value == '1':
circuit.cx(position, len(secret_number))
circuit.barrier()
circuit.h(range(len(secret_number)))
circuit.barrier()
circuit.measure(range(len(secret_number)), range(len(secret_number)))
circuit.barrier()
# circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, backend=simulator, shots=1)
result = job.result()
counts = result.get_counts()
# print(counts)
return circuit, counts
secret_number = int(input("enter number: "))
circuit, number = find_secret_number(secret_number)
print('required number: ', number)
circuit.draw(output='mpl')
|
https://github.com/Sinestro38/Shors-Algorithm
|
Sinestro38
|
import matplotlib.pyplot as plt
import numpy as np
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.visualization import plot_histogram
from math import gcd
from numpy.random import randint
import pandas as pd
from fractions import Fraction
print("Imports Successful")
def c_amod15(a, power):
"""Controlled multiplication by a mod 15"""
if a not in [2,7,8,11,13]:
raise ValueError("'a' must be 2,7,8,11 or 13")
U = QuantumCircuit(4) p
for iteration in range(power):
if a in [2,13]:
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
if a in [7,8]:
U.swap(2,3)
U.swap(1,2)
U.swap(0,1)
if a == 11:
U.swap(1,3)
U.swap(0,2)
if a in [7,11,13]:
for q in range(4):
U.x(q)
U = U.to_gate()
U.name = "%i^%i mod 15" % (a, power)
c_U = U.control()
return c_U
def qft_dagger(n):
"""n-qubit QFTdagger the first n qubits in circ"""
qc = QuantumCircuit(n)
# Don't forget the Swaps!
for qubit in range(n//2):
qc.swap(qubit, n-qubit-1)
for j in range(n):
for m in range(j):
qc.cp(-np.pi/float(2**(j-m)), m, j)
qc.h(j)
qc.name = "QFT†"
return qc
# Specify variables
n_count = 8 # number of counting qubits
a = 7
# Create QuantumCircuit with n_count counting qubits
# plus 4 qubits for U to act on
qc = QuantumCircuit(n_count + 4, n_count)
# Initialize counting qubits
# in state |+>
for q in range(n_count):
qc.h(q)
# And auxiliary register in state |1>
qc.x(3+n_count)
# Do controlled-U operations
for q in range(n_count):
qc.append(c_amod15(a, 2**q), # second one is power of 2
[q] + [i+n_count for i in range(4)]) # i+n_count will be 0+8, 1+8, 2+8, 3+8 where n_count = 8
# Do inverse-QFT
qc.append(qft_dagger(n_count), range(n_count))
# Measure circuit
qc.measure(range(n_count), range(n_count))
qc.draw(fold=-1) # -1 means 'do not fold'
aer_sim = Aer.get_backend('aer_simulator')
t_qc = transpile(qc, aer_sim)
qobj = assemble(t_qc)
results = aer_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
rows, measured_phases = [], []
for output in counts:
decimal = int(output, 2) # Convert (base 2) string to decimal
phase = decimal/(2**n_count) # Find corresponding eigenvalue
measured_phases.append(phase)
# Add these values to the rows in our table:
rows.append([f"{output}(bin) = {decimal:>3}(dec)",
f"{decimal}/{2**n_count} = {phase:.2f}"])
# Print the rows in a table
headers=["Register Output", "Phase"]
df = pd.DataFrame(rows, columns=headers)
print(df)
rows = []
for phase in measured_phases:
frac = Fraction(phase).limit_denominator(15)
rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator])
# Print as a table
headers=["Phase", "Fraction", "Guess for r"]
df = pd.DataFrame(rows, columns=headers)
print(df)
def qpe_amod15(a):
n_count = 8
qc = QuantumCircuit(4+n_count, n_count)
for q in range(n_count):
qc.h(q) # Initialize counting qubits in state |+>
qc.x(3+n_count) # And auxiliary register in state |1>
for q in range(n_count): # Do controlled-U operations
qc.append(c_amod15(a, 2**q),
[q] + [i+n_count for i in range(4)])
qc.append(qft_dagger(n_count), range(n_count)) # Do inverse-QFT
qc.measure(range(n_count), range(n_count))
# Simulate Results
aer_sim = Aer.get_backend('aer_simulator')
# Setting memory=True below allows us to see a list of each sequential reading
t_qc = transpile(qc, aer_sim)
qobj = assemble(t_qc, shots=1)
result = aer_sim.run(qobj, memory=True).result()
readings = result.get_memory()
print("Register Reading: " + readings[0])
phase = int(readings[0],2)/(2**n_count)
print("Corresponding Phase: %f" % phase)
return phase
N = 15
a = 7
factor_found = False
attempt = 0
while not factor_found:
attempt += 1
print("\nAttempt %i:" % attempt)
phase = qpe_amod15(a) # Phase = s/r
frac = Fraction(phase).limit_denominator(N) # Denominator should (hopefully!) tell us r
r = frac.denominator
print("Result: r = %i" % r)
if phase != 0:
# Guesses for factors are gcd(x^{r/2} ±1 , 15)
guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)]
print("Guessed Factors: %i and %i" % (guesses[0], guesses[1]))
for guess in guesses:
if guess not in [1,N] and (N % guess) == 0: # Check to see if guess is a factor
print("*** Non-trivial factor found: %i ***" % guess)
factor_found = True
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0, measure=True).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit.primitives import Sampler
sampler = Sampler()
job = sampler.run(circuit)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Quasi-distribution: {result.quasi_dists[0]}")
circuit = random_circuit(2, 2, seed=1, measure=True).decompose(reps=1)
job = sampler.run(circuit)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Quasi-distribution: {result.quasi_dists[0]}")
circuits = (
random_circuit(2, 2, seed=0, measure=True).decompose(reps=1),
random_circuit(2, 2, seed=1, measure=True).decompose(reps=1),
)
job = sampler.run(circuits)
result = job.result()
[display(cir.draw("mpl")) for cir in circuits]
print(f">>> Quasi-distribution: {result.quasi_dists}")
from qiskit.circuit.library import RealAmplitudes
circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1)
circuit.measure_all()
parameter_values = [0, 1, 2, 3, 4, 5]
job = sampler.run(circuit, parameter_values)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Parameter values: {parameter_values}")
print(f">>> Quasi-distribution: {result.quasi_dists[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.backend("ibmq_qasm_simulator")
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0, measure=True).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit_ibm_runtime import Sampler
sampler = Sampler(session=backend)
job = sampler.run(circuit)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Quasi-distribution: {result.quasi_dists[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
options = Options(optimization_level=3, environment={"log_level": "INFO"})
from qiskit_ibm_runtime import Options
options = Options()
options.resilience_level = 1
options.execution.shots = 2048
sampler = Sampler(session=backend, options=options)
result = sampler.run(circuit).result()
print(f">>> Metadata: {result.metadata[0]}")
sampler = Sampler(session=backend, options=options)
result = sampler.run(circuit, shots=1024).result()
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
# optimization_level=3 adds dynamical decoupling
# resilience_level=1 adds readout error mitigation
options = Options(optimization_level=3, resilience_level=1)
sampler = Sampler(session=backend, options=options)
result = sampler.run(circuit).result()
print(f">>> Quasi-distribution: {result.quasi_dists[0]}")
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Session, Estimator
with Session(backend=backend, max_time="1h"):
sampler = Sampler()
result = sampler.run(circuit).result()
print(f">>> Quasi-distribution from the first run: {result.quasi_dists[0]}")
result = sampler.run(circuit).result()
print(f">>> Quasi-distribution from the second run: {result.quasi_dists[0]}")
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info import SparsePauliOp
estimator_circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(estimator_circuit.draw("mpl"))
observable = SparsePauliOp("XZ")
print(f">>> Observable: {observable.paulis}")
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
result = sampler.run(circuit).result()
print(f">>> Quasi Distribution from the sampler job: {result.quasi_dists[0]}")
result = estimator.run(estimator_circuit, observable).result()
print(f">>> Expectation value from the estimator job: {result.values[0]}")
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
sampler_job = sampler.run(circuit)
estimator_job = estimator.run(estimator_circuit, observable)
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Estimator, Options
# 1. Initialize account
service = QiskitRuntimeService(channel="ibm_quantum")
# 2. Specify options, such as enabling error mitigation
options = Options(resilience_level=1)
# 3. Select a backend.
backend = service.backend("ibmq_qasm_simulator")
# 4. Create a session
with Session(backend=backend):
# 5. Create primitive instances
sampler = Sampler(options=options)
estimator = Estimator(options=options)
# 6. Submit jobs
sampler_job = sampler.run(circuit)
estimator_job = estimator.run(estimator_circuit, observable)
# 7. Get results
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%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 *
from qiskit.providers.aer import QasmSimulator
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
import math
import numpy as np
from qiskit import Aer
from qiskit.utils import QuantumInstance
from qiskit.algorithms import Shor
N = 15
backend = Aer.get_backend('aer_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
shor = Shor(quantum_instance=quantum_instance)
result = shor.factor(N)
print(f"The list of factors of {N} as computed by the Shor's algorithm is {result.factors[0]}.")
print(f'Computed of qubits for circuit: {4 * math.ceil(math.log(N, 2)) + 2}')
print(f'Actual number of qubits of circuit: {shor.construct_circuit(N).num_qubits}')
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(range(2))
qc.measure(range(2), range(2))
# apply x gate if the classical register has the value 2 (10 in binary)
qc.x(0).c_if(cr, 2)
# apply y gate if bit 0 is set to 1
qc.y(1).c_if(0, 1)
qc.draw('mpl')
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from IPython.display import Image, display
Image("ryoko.png", width="70")
from IPython.display import Image, display
Image('4lightsout_ex.png')
from qiskit import *
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute
provider = IBMQ.load_account()
address = QuantumRegister(2)
data = QuantumRegister(3)
c = ClassicalRegister(5)
qc = QuantumCircuit(address,data,c)
# address preparation
qc.h([address[0],address[1]])
qc.barrier()
# address 0 -> data = 1
qc.x([address[0],address[1]])
qc.ccx(address[0],address[1],data[2])
qc.x([address[0],address[1]])
qc.barrier()
# address 1 -> data = 2
qc.x(address[0])
qc.ccx(address[0],address[1],data[1])
qc.x(address[0])
qc.barrier()
# address 2 -> data = 5
qc.x(address[1])
qc.ccx(address[0],address[1],data[2])
qc.ccx(address[0],address[1],data[0])
qc.x(address[1])
qc.barrier()
# address 3 -> data = 7
qc.ccx(address[0],address[1],data[2])
qc.ccx(address[0],address[1],data[1])
qc.ccx(address[0],address[1],data[0])
qc.barrier()
#Check the qRAM status
qc.measure(address[0:2], c[0:2])
qc.measure(data[0:3], c[2:5])
# Reverse the output string.
qc = qc.reverse_bits()
#backend = provider.get_backend('ibmq_qasm_simulator')
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend=backend, shots=8000, seed_simulator=12345, backend_options={"fusion_enable":True})
#job = execute(qc, backend=backend, shots=8192)
result = job.result()
count =result.get_counts()
print(count)
qc.draw(output='mpl')
Image('circuit_ex.png')
Image('gatesynthesis_ex.png')
Image('4lightsout_pr.png')
lightsout4=[[1, 1, 1, 0, 0, 0, 1, 0, 0],[1, 0, 1, 0, 0, 0, 1, 1, 0],[1, 0, 1, 1, 1, 1, 0, 0, 1],[1, 0, 0, 0, 0, 0, 1, 0, 0]]
import numpy as np
# import qiskit libraries
from qiskit import IBMQ, Aer,QuantumRegister, ClassicalRegister, QuantumCircuit, execute
from qiskit.tools.jupyter import *
provider = IBMQ.load_account()
#import functions to plot
from qiskit.visualization import plot_histogram
def week2b_ans_func(lightout4):
##### Build your cirucuit here
def qRAM(qc, add, board, lightout4):
# Board 1
qc.x(add[0])
qc.x(add[1])
for i, curr_light in enumerate(lightout4[0]):
if curr_light == 1:
qc.ccx(add[0], add[1], board[i])
#qc.ch(q[0], q[3])
#qc.cz(q[2], q[3])
#qc.ch(q[0], q[3])
qc.x(add[0])
qc.x(add[1])
qc.barrier()
# Board 2
qc.x(add[0])
for i, curr_light in enumerate(lightout4[1]):
if curr_light == 1:
qc.ccx(add[0], add[1], board[i])
qc.x(add[0])
qc.barrier()
# Board 3
qc.x(add[1])
for i, curr_light in enumerate(lightout4[2]):
if curr_light == 1:
qc.ccx(add[0], add[1], board[i])
qc.x(add[1])
qc.barrier()
# Board 4
for i, curr_light in enumerate(lightout4[3]):
if curr_light == 1:
qc.ccx(add[0], add[1], board[i])
qc.barrier()
def diffuser(nqubits):
qc_diff = QuantumCircuit(nqubits)
for qubit in range(nqubits):
qc_diff.h(qubit)
for qubit in range(nqubits):
qc_diff.x(qubit)
qc_diff.h(nqubits-1)
qc_diff.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli
qc_diff.h(nqubits-1)
for qubit in range(nqubits):
qc_diff.x(qubit)
for qubit in range(nqubits):
qc_diff.h(qubit)
U_f0 = qc_diff.to_gate()
U_f0.name = "V"
return U_f0
def lights_oracle(sol, board, anc, orc_out_2a):
#board_oracle = QuantumRegister(n, 'board')
#sol = QuantumRegister(n, 'solution')
#orc_out_2a = QuantumRegister(1, 'oracle_out_2a') #this has to be phase flipped
qc_1 = QuantumCircuit(sol, board, anc, orc_out_2a)
flip_matrix = [[1,1,0,1,0,0,0,0,0],
[1,1,1,0,1,0,0,0,0],
[0,1,1,0,0,1,0,0,0],
[1,0,0,1,1,0,1,0,0],
[0,1,0,1,1,1,0,1,0],
[0,0,1,0,1,1,0,0,1],
[0,0,0,1,0,0,1,1,0],
[0,0,0,0,1,0,1,1,1],
[0,0,0,0,0,1,0,1,1]]
qc_1.barrier()
for sol_bit in range(len(flip_matrix)):
for board_bit in range(len(flip_matrix[sol_bit])):
if flip_matrix[sol_bit][board_bit] == 1:
qc_1.cx(sol[sol_bit], board[board_bit])
qc_1.barrier()
for i in range(len(flip_matrix)):
qc_1.x(board[i])
qc_1.barrier()
qc_1.ccx(board[0], board[1], anc[0])
qc_1.ccx(board[2], board[3], anc[1])
qc_1.ccx(anc[0], anc[1], anc[2])
qc_1.ccx(board[4], board[5], anc[3])
qc_1.ccx(board[6], board[7], anc[4])
qc_1.ccx(anc[3], anc[4], anc[5])
qc_1.mct([board[8], anc[2], anc[5]], orc_out_2a, mode = 'noancilla')
qc_1.ccx(anc[3], anc[4], anc[5])
qc_1.ccx(board[6], board[7], anc[4])
qc_1.ccx(board[4], board[5], anc[3])
qc_1.ccx(anc[0], anc[1], anc[2])
qc_1.ccx(board[2], board[3], anc[1])
qc_1.ccx(board[0], board[1], anc[0])
#qc_1.mct([board[0], board[1],board[2],board[3],board[4],board[5],board[6],board[7],board[8]],
# orc_out_2a,
#[anc[0], anc[1],anc[2],anc[3],anc[4],anc[5],anc[6]],
# mode='noancilla')
qc_1.barrier()
for i in range(len(flip_matrix)):
qc_1.x(board[i])
qc_1.barrier()
for sol_bit in range(len(flip_matrix)):
for board_bit in range(len(flip_matrix[sol_bit])):
if flip_matrix[sol_bit][board_bit] == 1:
qc_1.cx(sol[sol_bit], board[board_bit])
return qc_1
def new_u2a(qc, sol, board, anc, orc_out_2a):
r_2a = 1
flip_matrix = [[1,1,0,1,0,0,0,0,0],
[1,1,1,0,1,0,0,0,0],
[0,1,1,0,0,1,0,0,0],
[1,0,0,1,1,0,1,0,0],
[0,1,0,1,1,1,0,1,0],
[0,0,1,0,1,1,0,0,1],
[0,0,0,1,0,0,1,1,0],
[0,0,0,0,1,0,1,1,1],
[0,0,0,0,0,1,0,1,1]]
n =len(flip_matrix)
for i_2a in range(r_2a):
qc.extend(lights_oracle(sol, board, anc, orc_out_2a))
qc.barrier()
qc.append(diffuser(n), sol)
qc.barrier()
def new_u2a_dagger(qc, sol, board, anc, orc_out_2a):
r_2a = 1
flip_matrix = [[1,1,0,1,0,0,0,0,0],
[1,1,1,0,1,0,0,0,0],
[0,1,1,0,0,1,0,0,0],
[1,0,0,1,1,0,1,0,0],
[0,1,0,1,1,1,0,1,0],
[0,0,1,0,1,1,0,0,1],
[0,0,0,1,0,0,1,1,0],
[0,0,0,0,1,0,1,1,1],
[0,0,0,0,0,1,0,1,1]]
n =len(flip_matrix)
for i_2a in range(r_2a):
qc.barrier()
qc.append(diffuser(n), sol)
qc.barrier()
orc_org = lights_oracle(sol, board, anc, orc_out_2a)
qc.extend(orc_org.inverse())
def bitcounter(qc, sol, anc):
for i in range(len(sol)):
qc.mct([sol[i], anc[0], anc[1], anc[2]], anc[3], mode = 'noancilla')
qc.mct([sol[i], anc[0], anc[1]], anc[2], mode = 'noancilla')
qc.ccx(sol[i], anc[0], anc[1])
qc.cx(sol[i], anc[0])
def bitcounter_uncompute(qc, sol, anc):
for i in range(len(sol)):
qc.cx(sol[i], anc[0])
qc.ccx(sol[i], anc[0], anc[1])
qc.mct([sol[i], anc[0], anc[1]], anc[2], mode = 'noancilla')
qc.mct([sol[i], anc[0], anc[1], anc[2]], anc[3], mode = 'noancilla')
def oracle_2b(qc, add, board, sol, anc, orc_out_2a, orc_out_2b, lightout4):
#apply QRAM
qRAM(qc, add, board, lightout4)
#apply U_2A
new_u2a(qc, sol, board, anc, orc_out_2a)
#counter
#qc.append(WeightedAdder(9), sol+anc)
bitcounter(qc, sol, anc)
#verifying that the count is less than 3
qc.x(anc[2])
qc.x(anc[3])
qc.ccx(anc[2], anc[3], orc_out_2b)
qc.x(anc[2])
qc.x(anc[3])
bitcounter_uncompute(qc, sol, anc)
#apply U_2a_dagger
new_u2a_dagger(qc, sol, board, anc, orc_out_2a)
#apply qRAM dagger - same as qRAM
qRAM(qc, add, board, lightout4)
# start building the circuit
n = len(lightout4[0])
add = QuantumRegister(2, 'address')
board = QuantumRegister(n, 'board')
sol = QuantumRegister(n, 'solution')
anc = QuantumRegister(6, 'anc')
orc_out_2a = QuantumRegister(1, 'oracle_out_2a')
orc_out_2b = QuantumRegister(1, 'oracle_out_2b')
c_out = ClassicalRegister(2, 'classical_bits')
qc = QuantumCircuit(add, board, sol, orc_out_2a, anc, orc_out_2b, c_out)
qc.h(add)
qc.h(sol)
qc.x(orc_out_2a)
qc.h(orc_out_2a)
qc.x(orc_out_2b)
qc.h(orc_out_2b)
qc.barrier()
r_2b = 2
for i_2b in range(r_2b):
oracle_2b(qc, add, board, sol, anc, orc_out_2a, orc_out_2b, lightout4)
qc.barrier()
qc.append(diffuser(2), add)
qc.barrier()
qc.measure(add, c_out)
qc = qc.reverse_bits()
#### In addition, please make sure your function can solve the problem with different inputs (lightout4). We will cross validate with different inputs.
return qc
# Submission code
from qc_grader import prepare_ex2b, grade_ex2b, submit_ex2b
# Execute your circuit with following prepare_ex2b() function.
# The prepare_ex2b() function works like the execute() function with only QuantumCircuit as an argument.
job = prepare_ex2b(week2b_ans_func)
result = job.result()
count = result.get_counts()
original_problem_set_counts = count[0]
original_problem_set_counts
# The bit string with the highest number of observations is treated as the solution.
# Check your answer by executing following code.
# The quantum cost of the QuantumCircuit is obtained as the score. The quantum cost is related to rank only in the third week.
grade_ex2b(job)
# Submit your results by executing following code. You can submit as many times as you like during the period.
submit_ex2b(job)
|
https://github.com/IlliaOvcharenko/quantum-search
|
IlliaOvcharenko
|
"""
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/ShabaniLab/q-camp
|
ShabaniLab
|
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from numpy.random import randint
import numpy as np
print("Imports Successful")
qc = QuantumCircuit(1,1)
# Alice prepares qubit in state |+>
qc.h(0)
qc.barrier()
# Alice now sends the qubit to Bob
# who measures it in the X-basis
qc.h(0)
qc.measure(0,0)
# Draw and simulate circuit
display(qc.draw())
aer_sim = Aer.get_backend('aer_simulator')
job = aer_sim.run(assemble(qc))
plot_histogram(job.result().get_counts())
qc = QuantumCircuit(1,1)
# Alice prepares qubit in state |+>
qc.h(0)
# Alice now sends the qubit to Bob
# but Eve intercepts and tries to read it
qc.measure(0, 0)
qc.barrier()
# Eve then passes this on to Bob
# who measures it in the X-basis
qc.h(0)
qc.measure(0,0)
# Draw and simulate circuit
display(qc.draw())
aer_sim = Aer.get_backend('aer_simulator')
job = aer_sim.run(assemble(qc))
plot_histogram(job.result().get_counts())
np.random.seed(seed=0)
n = 100
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
print(alice_bits)
np.random.seed(seed=0)
n = 100
## Step 1
#Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
print(alice_bases)
def encode_message(bits, bases):
message = []
for i in range(n):
qc = QuantumCircuit(1,1)
if bases[i] == 0: # Prepare qubit in Z-basis
if bits[i] == 0:
pass
else:
qc.x(0)
else: # Prepare qubit in X-basis
if bits[i] == 0:
qc.h(0)
else:
qc.x(0)
qc.h(0)
qc.barrier()
message.append(qc)
return message
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
print('bit = %i' % alice_bits[0])
print('basis = %i' % alice_bases[0])
message[0].draw()
print('bit = %i' % alice_bits[4])
print('basis = %i' % alice_bases[4])
message[4].draw()
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = randint(2, size=n)
print(bob_bases)
def measure_message(message, bases):
backend = Aer.get_backend('aer_simulator')
measurements = []
for q in range(n):
if bases[q] == 0: # measuring in Z-basis
message[q].measure(0,0)
if bases[q] == 1: # measuring in X-basis
message[q].h(0)
message[q].measure(0,0)
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(message[q], shots=1, memory=True)
result = aer_sim.run(qobj).result()
measured_bit = int(result.get_memory()[0])
measurements.append(measured_bit)
return measurements
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
message[0].draw()
message[6].draw()
print(bob_results)
def remove_garbage(a_bases, b_bases, bits):
good_bits = []
for q in range(n):
if a_bases[q] == b_bases[q]:
# If both used the same basis, add
# this to the list of 'good' bits
good_bits.append(bits[q])
return good_bits
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
print(alice_key)
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
print(bob_key)
def sample_bits(bits, selection):
sample = []
for i in selection:
# use np.mod to make sure the
# bit we sample is always in
# the list range
i = np.mod(i, len(bits))
# pop(i) removes the element of the
# list at index 'i'
sample.append(bits.pop(i))
return sample
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
## Step 5
sample_size = 15
bit_selection = randint(n, size=sample_size)
bob_sample = sample_bits(bob_key, bit_selection)
print(" bob_sample = " + str(bob_sample))
alice_sample = sample_bits(alice_key, bit_selection)
print("alice_sample = "+ str(alice_sample))
bob_sample == alice_sample
print(bob_key)
print(alice_key)
print("key length = %i" % len(alice_key))
np.random.seed(seed=3)
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
print(alice_bits)
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
## Step 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
print(alice_bases)
message[0].draw()
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
## Step 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
print(intercepted_message)
message[0].draw()
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
## Step 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
## Step 3
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
message[0].draw()
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
## Step 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
## Step 3
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
## Step 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
## Step 3
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
## Step 5
sample_size = 15
bit_selection = randint(n, size=sample_size)
bob_sample = sample_bits(bob_key, bit_selection)
print(" bob_sample = " + str(bob_sample))
alice_sample = sample_bits(alice_key, bit_selection)
print("alice_sample = "+ str(alice_sample))
bob_sample == alice_sample
n = 100
# Step 1
alice_bits = randint(2, size=n)
alice_bases = randint(2, size=n)
# Step 2
message = encode_message(alice_bits, alice_bases)
# Interception!
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
# Step 3
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
# Step 4
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
# Step 5
sample_size = 15 # Change this to something lower and see if
# Eve can intercept the message without Alice
# and Bob finding out
bit_selection = randint(n, size=sample_size)
bob_sample = sample_bits(bob_key, bit_selection)
alice_sample = sample_bits(alice_key, bit_selection)
if bob_sample != alice_sample:
print("Eve's interference was detected.")
else:
print("Eve went undetected!")
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/abhik-99/Qiskit-Summer-School
|
abhik-99
|
!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/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
# %%
# %%
# make a plot :)
import matplotlib.pyplot as plt
# plt.style.use(["science", "ieee"])
# plt.plot([0,0], [1,1]);
# plt.style.use(["science", "ieee"])
# I'm not sure why but theon't get updated until after running twice, so monkey fix like this?? styles d
def benchmark(
backends,
circuit_generator,
q_range=None,
continuously_save=False,
overwrite=False,
repeat=3,
):
for iteration in range(repeat):
benchmark_foo(
iteration,
backends,
circuit_generator,
q_range,
continuously_save,
overwrite,
)
def benchmark_foo(
i,
backends,
circuit_generator,
q_range=None,
continuously_save=False,
overwrite=False,
):
iteration = str(i)
# override qrange if provided
if q_range is None:
q_range = circuit_generator.q_range
# check if data dicts are empty
for backend in backends:
if iteration not in backend.data.keys():
backend.data[iteration] = {}
if circuit_generator.label not in backend.data[iteration].keys():
backend.data[iteration][circuit_generator.label] = {}
backend.data[iteration][circuit_generator.label]["duration"] = {}
backend.data[iteration][circuit_generator.label]["preswap_gate_count"] = {}
backend.data[iteration][circuit_generator.label]["gate_count"] = {}
backend.data[iteration][circuit_generator.label][
"preswap_gate_count_crit"
] = {}
backend.data[iteration][circuit_generator.label]["layout_score"] = {}
backend.data[iteration][circuit_generator.label]["edge_frequency"] = {}
print(f"Starting benchmark for {circuit_generator.label}")
# outer loop over circuit since this may take long time to generate
for q in q_range:
# create new variable sized lambda circuit
# wait to build circuit (may be costly), if we end up not needing it for any backend
qc = None
if overwrite:
qc = circuit_generator.circuit_lambda(q)
for backend in backends:
# condition to skip
if not overwrite:
# convert to int because if loaded from json key will be a string
if q in [
int(k)
for k in backend.data[iteration][circuit_generator.label][
"preswap_gate_count"
].keys()
]:
continue
# another condition to skip if size is invalid
if backend.backend.num_qubits < q:
continue
# resolve wait
if qc is None:
qc = circuit_generator.circuit_lambda(q)
# logging.info(f"Transpiler qc{q} for {backend.label}")
print(f"Transpiler qc{q} for {backend.label}")
backend.pass_manager.run(qc)
# save data to dict
# might be empty if not decomposing swaps, this comment is deprecated
# if (
# "duration_longest_path_length"
# in backend.pass_manager.property_set.keys()
# ):
# switch to using standard count ops method now w/o pulse normalization arg
duration = backend.pass_manager.property_set["count_ops_longest_path"]
backend.data[iteration][circuit_generator.label]["duration"][
str(q)
] = duration
gate_count = backend.pass_manager.property_set["preswap_count_ops"]
backend.data[iteration][circuit_generator.label]["preswap_gate_count"][
str(q)
] = gate_count
gate_count_critical_path = backend.pass_manager.property_set[
"preswap_count_ops_longest_path"
]
backend.data[iteration][circuit_generator.label]["preswap_gate_count_crit"][
str(q)
] = gate_count_critical_path
gate_count_post_decomp = backend.pass_manager.property_set["count_ops"]
backend.data[iteration][circuit_generator.label]["gate_count"][
str(q)
] = gate_count_post_decomp
layout_score = backend.pass_manager.property_set["layout_score"]
backend.data[iteration][circuit_generator.label]["layout_score"][
str(q)
] = float(layout_score)
frequency_list = backend.pass_manager.property_set["edge_frequency"]
backend.data[iteration][circuit_generator.label]["edge_frequency"][
str(q)
] = frequency_list
# for long tests, may want to save more regularly in case exit early
if continuously_save:
backend.save_json()
for backend in backends:
# save dict to json
backend.save_json()
# %%
# !pip install SciencePlots
# import matplotlib.pyplot as plt
# plt.style.reload_library()
# plt.style.use(['science','no-latex'])
# %%
def plot_wrap(backends, circuit_label_list, motivation=False, plot_average=True):
# fig, axs = plt.subplots(len(circuit_label_list),4, figsize=(24,24))
height = 5
if 1 or motivation:
height = 2.5
fig = plt.figure(constrained_layout=True, figsize=(7.16, height))
# fig = plt.figure(constrained_layout=True, figsize=(4.5, 3.75))
# plt.style.use(["science"])
SMALL_SIZE = 4
MEDIUM_SIZE = 6
plt.rc("font", size=SMALL_SIZE) # controls default text sizes
plt.rc("axes", titlesize=MEDIUM_SIZE) # fontsize of the axes title
plt.rc("axes", labelsize=MEDIUM_SIZE + 4) # fontsize of the x and y labels
plt.rc("xtick", labelsize=SMALL_SIZE + 2) # fontsize of the tick labels
plt.rc("ytick", labelsize=SMALL_SIZE + 2) # fontsize of the tick labels
plt.rc("legend", fontsize=MEDIUM_SIZE + 2) # legend fontsize
plt.rc("figure", titlesize=MEDIUM_SIZE + 4) # fontsize of the figure title
plt.rc("lines", markersize=1.8, linewidth=0.75)
if 1 or motivation:
nrows = 2
else:
nrows = 4
axs = fig.subplots(ncols=len(circuit_label_list), nrows=nrows)
i = 0
for circuit_label in circuit_label_list:
ax = plot(
backends,
circuit_label,
duration=2,
subfig=axs,
first=(i == 0),
index=i,
motivation=motivation,
plot_average=plot_average
# last=(i + 1 == len(circuit_label_list)),
)
i += 1
circuit_label = circuit_label.replace("_", " ")
if circuit_label == "QAOA Vanilla":
circuit_label = "QAOA"
ax.set_xlabel(f"{circuit_label}", y=0)
# for ax, row in zip(ax[:,0], subfigs):
# ax.set_ylabel(row, rotation=0, size='large')
fig.align_ylabels(axs)
handles, labels = ax.get_legend_handles_labels()
# patch labels
def fix_labels(labels):
for index, label in enumerate(labels):
if "small" in label:
label = label[:-6]
if label == "Heavy-Hex-cx":
labels[index] = "Heavy-Hex" + ("-CX" if not motivation else "")
if label == "Hex-Lattice-cx":
labels[index] = "Hex-Lattice" + ("-CX" if not motivation else "")
if label == "Lattice+AltDiagonals-cx":
labels[index] = "Lattice+AltDiagonals" + (
"-CX" if not motivation else ""
)
if label == "Square-Lattice-syc":
labels[index] = "Square-Lattice" + ("-SYC" if not motivation else "")
if label == "Modular-riswap":
labels[index] = "Tree" + (r"-$\sqrt{iSWAP}$" if not motivation else "")
if label == "Modular-RR3-riswap":
labels[index] = "Tree-I" + (
r"-$\sqrt{iSWAP}$" if not motivation else ""
)
if label == "Hypercube-riswap":
labels[index] = "Hypercube" + (
r"-$\sqrt{iSWAP}$" if not motivation else ""
)
if label == "HypercubeSNAIL-(0, 0)-riswap":
labels[index] = "Corral$_{1,1}$" + (
r"-$\sqrt{iSWAP}$" if not motivation else ""
)
if label == "HypercubeSNAIL-(0, 1)-riswap":
labels[index] = "Corral$_{1,2}$" + (
r"-$\sqrt{iSWAP}$" if not motivation else ""
)
if label == "Corral-8-(0, 0)-riswap":
labels[index] = "Corral$_{1,1}$" + (
r"-$\sqrt{iSWAP}$" if not motivation else ""
)
if label == "Corral-8-(0, 1)-riswap":
labels[index] = "Corral$_{1,2}$" + (
r"-$\sqrt{iSWAP}$" if not motivation else ""
)
if label == "Corral-42-(0, 0)-riswap":
labels[index] = "Corral$_{1,1}$" + (
r"-$\sqrt{iSWAP}$" if not motivation else ""
)
if label == "Corral-42-(0, 1)-riswap":
labels[index] = "Corral$_{1,2}$" + (
r"-$\sqrt{iSWAP}$" if not motivation else ""
)
if "Non-Swap Gate Count" in labels:
temp_index = labels.index("Non-Swap Gate Count")
temp_handle = handles.pop(temp_index)
handles.insert(0, temp_handle)
temp_label = labels.pop(temp_index)
labels.insert(0, temp_label)
return labels
labels = fix_labels(labels)
fig.legend(
handles,
labels,
loc="upper center",
ncol=4,
bbox_to_anchor=(0.5, -0.01),
markerscale=2,
)
# savefig
# filename = f"images/data1"
# import os
# i = 0
# while os.path.exists("{}{:d}.pdf".format(filename, i)):
# i += 1
# #fig.savefig("{}{:d}.pdf".format(filename, i), format="pdf", facecolor="white")
# fig.savefig("{}{:d}.svg".format(filename, i), format="svg", facecolor='None')
# %%
import numpy as np
def plot(
backends,
circuit_label,
duration=0,
subfig=None,
first=False,
index=0,
motivation=False,
plot_average=True,
):
def mark(backend_label):
if "Modular" in backend_label:
if "RR" in backend_label:
return "p"
return "*"
if "Google" in backend_label or "Square" in backend_label:
return "s"
if "IBM" in backend_label or "Heavy" in backend_label:
return "h"
if "Hex-Lattice" in backend_label:
return "^"
if "AltDiagonals" in backend_label:
return "x"
if "SNAIL" in backend_label or "Corral" in backend_label:
if "(0, 1)" in backend_label:
return "D"
return "8"
if "Hypercube" in backend_label:
return "o"
pass
def color_map(backend_label):
if "Modular" in backend_label:
if "RR" in backend_label:
return "tab:olive"
return "tab:green"
if "Google" in backend_label or "Square" in backend_label:
return "tab:red"
if "IBM" in backend_label or "Heavy" in backend_label:
return "tab:blue"
if "Hex-Lattice" in backend_label:
return "tab:cyan"
if "AltDiagonals" in backend_label:
return "tab:orange"
if "SNAIL" in backend_label or "Corral" in backend_label:
if "(0, 1)" in backend_label:
return "tab:pink"
if "(0, 2)" in backend_label:
return "tab:gray"
if "(1, 2)" in backend_label or "split" in backend_label:
return "black"
return "tab:purple"
if "Hypercube" in backend_label:
return "tab:brown"
pass
if subfig is None:
if duration == 2:
fig, (ax2, ax3, ax4, ax1) = plt.subplots(1, 4, figsize=(24, 8))
else:
raise NotImplementedError
else:
# axs = subfig.subplots(nrows=4, ncols=1)
ax2 = subfig[0][index]
ax3 = subfig[1][index]
if not motivation:
pass
# ax4 = subfig[2][index]
# ax1 = subfig[3][index]
if 1 or motivation:
ax_list = [ax2, ax3]
else:
ax_list = [ax2, ax3, ax4, ax1]
for ax in ax_list:
# ax.xaxis.set_major_locator(plt.MaxNLocator(3))
ax.yaxis.set_major_locator(plt.MaxNLocator(3))
ax.ticklabel_format(axis="y", style="sci", scilimits=(0, 0))
# elif duration==1:
# fig, (ax1) = plt.subplots(1,1, figsize=(12,8))
# else:
# fig, (ax2, ax3) = plt.subplots(1,2, figsize=(24,8))
for backend_i, backend in enumerate(backends):
if circuit_label in backend.data["0"].keys():
if motivation:
# total swap gates
x = backend.data["0"][circuit_label]["preswap_gate_count"].keys()
x = [int(el) for el in list(x)]
y_best = np.ones(len(x)) * np.inf
y_average = np.zeros(len(x))
# XXX monkey patch :(
# for iter_key in backend.data.keys():
keys = [el for el in backend.data.keys() if el.isdigit()]
for iter_key in keys:
y = backend.data[iter_key][circuit_label][
"preswap_gate_count"
].values()
x, y = zip(*zip(x, y))
y = [el["swap"] if "swap" in el.keys() else 0 for el in y]
# XXX monkey patch
x = list(x)
y = list(y)
if len(x) > 10:
for val in [4, 6, 10, 12, 14]:
if val in x:
del_index = x.index(val)
x.pop(del_index)
y.pop(del_index)
x, y = zip(*sorted(zip(x, y)))
for index, el in enumerate(y):
if y_best[index] > el:
y_best[index] = el
y_average[index] += el
y_average /= len(keys)
y_average = y_average[0 : len(x)]
if plot_average:
y = y_average
else:
y = y_best
ax2.plot(
x,
y,
marker=mark(backend.label),
label=backend.label,
color=color_map(backend.label),
)
if backend_i == 0:
pass
# skip for now
# monkey patch in a thing which prints the non swap gates
# from qiskit import transpile
# from circuit_suite import circuits
# y = [transpile(circuits[circuit_label].circuit_lambda(xi), basis_gates=['u', 'cx']).count_ops()['cx'] for xi in x]
# ax2.plot(x, y, marker='.', linestyle='-.', label="Non-Swap Gate Count", color='black')
# ax2.set_ylabel("Total SWAP Count")
# if last:
# ax2.set_xlabel("Num Qubits")
if not duration == 2:
ax2.legend()
if first:
ax2.set_ylabel("Total SWAP Count") # vs Num Qubits")
if motivation:
# critical path swap gates
x = backend.data["0"][circuit_label]["preswap_gate_count_crit"].keys()
x = [int(el) for el in list(x)]
y_best = np.ones(len(x)) * np.inf
y_average = np.zeros(len(x))
keys = [el for el in backend.data.keys() if el.isdigit()]
for iter_key in keys:
y = backend.data[iter_key][circuit_label][
"preswap_gate_count_crit"
].values()
x, y = zip(*zip(x, y))
y = [el["swap"] if "swap" in el.keys() else 0 for el in y]
# XXX monkey patch
x = list(x)
y = list(y)
if len(x) > 10:
for val in [4, 6, 10, 12, 14]:
if val in x:
del_index = x.index(val)
x.pop(del_index)
y.pop(del_index)
x, y = zip(*sorted(zip(x, y)))
for index, el in enumerate(y):
if y_best[index] > el:
y_best[index] = el
y_average[index] += el
y_average /= len(keys)
y_average = y_average[0 : len(x)]
if plot_average:
y = y_average
else:
y = y_best
ax3.plot(
x,
y,
marker=mark(backend.label),
label=backend.label,
color=color_map(backend.label),
)
if backend_i == 0:
# skip for now
pass
# monkey patch in a thing which prints the non swap gates
# from qiskit import transpile
# from qiskit.converters import circuit_to_dag
# from circuit_suite import circuits
# y = [circuit_to_dag(transpile(circuits[circuit_label].circuit_lambda(xi), basis_gates=['u', 'cx'])).count_ops_longest_path()['cx'] for xi in x]
# ax3.plot(x, y, marker='.', linestyle='--', label="Non-Swap Gate Count", color='black')
# ax3.set_ylabel("Critical Path SWAP Count")
# if last:
# ax3.set_xlabel("Num Qubits")
if first:
ax3.set_ylabel("Critical Path SWAPs") # vs Num Qubits")
if not duration == 2:
ax3.legend()
if not motivation:
# critical path swap gates
x = backend.data["0"][circuit_label]["gate_count"].keys()
x = [int(el) for el in list(x)]
y_best = np.ones(len(x)) * np.inf
y_average = np.zeros(len(x))
keys = [el for el in backend.data.keys() if el.isdigit()]
for iter_key in keys:
y = backend.data[iter_key][circuit_label]["gate_count"].values()
x, y = zip(*zip(x, y))
twoqgate_list = ["rzx", "riswap", "cx", "syc", "fSim"]
for twoqgate in twoqgate_list:
temp = [
el[twoqgate] if twoqgate in el.keys() else 0 for el in y
]
if temp[-1] != 0:
y = temp
break
# XXX monkey patch
x = list(x)
y = list(y)
if len(x) > 10:
for val in [4, 6, 10, 12, 14]:
if val in x:
del_index = x.index(val)
x.pop(del_index)
y.pop(del_index)
x, y = zip(*sorted(zip(x, y)))
for index, el in enumerate(y):
if y_best[index] > el:
y_best[index] = el
y_average[index] += el
y_average /= len(keys)
y_average = y_average[0 : len(x)]
if plot_average:
y = y_average
else:
y = y_best
ax2.plot(
x,
y,
marker=mark(backend.label),
label=backend.label,
color=color_map(backend.label),
)
# ax4.set_ylabel("Total 2Q Gate Count")
# if last:
# ax4.set_xlabel("Num Qubits")
if first:
ax2.set_ylabel("Total 2Q Count") # vs Num Qubits")
if not duration == 2:
ax2.legend()
# #duration
if not motivation:
x = backend.data["0"][circuit_label]["duration"].keys()
x = [int(el) for el in list(x)]
y_best = np.ones(len(x)) * np.inf
y_average = np.zeros(len(x))
keys = [el for el in backend.data.keys() if el.isdigit()]
for iter_key in keys:
y = backend.data[iter_key][circuit_label]["duration"].values()
# XXX monkey patch
x = list(x)
y = list(y)
if len(x) > 10:
for val in [4, 6, 10, 12, 14]:
if val in x:
del_index = x.index(val)
x.pop(del_index)
y.pop(del_index)
x, y = zip(*zip(x, y))
twoqgate_list = ["rzx", "riswap", "cx", "syc", "fSim"]
for twoqgate in twoqgate_list:
temp = [
el[twoqgate] if twoqgate in el.keys() else 0 for el in y
]
if temp[-1] != 0:
y = temp
break
for index, el in enumerate(y):
if y_best[index] > el:
y_best[index] = el
y_average[index] += el
y_average /= len(keys)
y_average = y_average[0 : len(x)]
if plot_average:
y = y_average
else:
y = y_best
ax3.plot(
x,
y,
marker=mark(backend.label),
label=backend.label,
color=color_map(backend.label),
)
# ax1.set_ylabel("Critical Path 2Q Pulse Duration")
# if last:
# ax1.set_xlabel("Num Qubits")
if first:
ax3.set_ylabel("Pulse Duration") # vs Num Qubits")
if 1 or motivation:
return ax3
return ax1
|
https://github.com/ncitron/qiskit-hack
|
ncitron
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
from qiskit.circuit.library.standard_gates import XGate, HGate
from operator import *
n = 3
N = 8 #2**n
index_colour_table = {}
colour_hash_map = {}
index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"}
colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'}
def database_oracle(index_colour_table, colour_hash_map):
circ_database = QuantumCircuit(n + n)
for i in range(N):
circ_data = QuantumCircuit(n)
idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
# qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0
# we therefore reverse the index string -> q0, ..., qn
data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour)
circ_database.append(data_gate, list(range(n+n)))
return circ_database
# drawing the database oracle circuit
print("Database Encoding")
database_oracle(index_colour_table, colour_hash_map).draw()
circ_data = QuantumCircuit(n)
m = 4
idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
print("Internal colour encoding for the colour green (as an example)");
circ_data.draw()
def oracle_grover(database, data_entry):
circ_grover = QuantumCircuit(n + n + 1)
circ_grover.append(database, list(range(n+n)))
target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target")
# control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()'
# The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class.
circ_grover.append(target_reflection_gate, list(range(n, n+n+1)))
circ_grover.append(database, list(range(n+n)))
return circ_grover
print("Grover Oracle (target example: orange)")
oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw()
def mcz_gate(num_qubits):
num_controls = num_qubits - 1
mcz_gate = QuantumCircuit(num_qubits)
target_mcz = QuantumCircuit(1)
target_mcz.z(0)
target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ")
mcz_gate.append(target_mcz, list(range(num_qubits)))
return mcz_gate.reverse_bits()
print("Multi-controlled Z (MCZ) Gate")
mcz_gate(n).decompose().draw()
def diffusion_operator(num_qubits):
circ_diffusion = QuantumCircuit(num_qubits)
qubits_list = list(range(num_qubits))
# Layer of H^n gates
circ_diffusion.h(qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of Multi-controlled Z (MCZ) Gate
circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of H^n gates
circ_diffusion.h(qubits_list)
return circ_diffusion
print("Diffusion Circuit")
diffusion_operator(n).draw()
# Putting it all together ... !!!
item = "green"
print("Searching for the index of the colour", item)
circuit = QuantumCircuit(n + n + 1, n)
circuit.x(n + n)
circuit.barrier()
circuit.h(list(range(n)))
circuit.h(n+n)
circuit.barrier()
unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator")
unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator")
M = countOf(index_colour_table.values(), item)
Q = int(np.pi * np.sqrt(N/M) / 4)
for i in range(Q):
circuit.append(unitary_oracle, list(range(n + n + 1)))
circuit.append(unitary_diffuser, list(range(n)))
circuit.barrier()
circuit.measure(list(range(n)), list(range(n)))
circuit.draw()
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(circuit)
if M==1:
print("Index of the colour", item, "is the index with most probable outcome")
else:
print("Indices of the colour", item, "are the indices the most probable outcomes")
from qiskit.visualization import plot_histogram
plot_histogram(counts)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.