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 QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
# Create a Quantum Circuit acting on a quantum register of three qubits
circ = QuantumCircuit(3)
# Add a H gate on qubit 0, putting this qubit in superposition.
circ.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
circ.cx(0, 1)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting
# the qubits in a GHZ state.
circ.cx(0, 2)
circ.draw('mpl')
from qiskit.quantum_info import Statevector
# Set the intial state of the simulator to the ground state using from_int
state = Statevector.from_int(0, 2**3)
# Evolve the state by the quantum circuit
state = state.evolve(circ)
#draw using latex
state.draw('latex')
from qiskit.visualization import array_to_latex
#Alternative way of representing in latex
array_to_latex(state)
state.draw('qsphere')
state.draw('hinton')
from qiskit.quantum_info import Operator
U = Operator(circ)
# Show the results
U.data
# Create a Quantum Circuit
meas = QuantumCircuit(3, 3)
meas.barrier(range(3))
# map the quantum measurement to the classical bits
meas.measure(range(3), range(3))
# The Qiskit circuit object supports composition.
# Here the meas has to be first and front=True (putting it before)
# as compose must put a smaller circuit into a larger one.
qc = meas.compose(circ, range(3), front=True)
#drawing the circuit
qc.draw('mpl')
# Adding the transpiler to reduce the circuit to QASM instructions
# supported by the backend
from qiskit import transpile
# Use AerSimulator
from qiskit_aer import AerSimulator
backend = AerSimulator()
# First we have to transpile the quantum circuit
# to the low-level QASM instructions used by the
# backend
qc_compiled = transpile(qc, backend)
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job_sim = backend.run(qc_compiled, shots=1024)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(qc_compiled)
print(counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeAuckland
backend = FakeAuckland()
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
depths = []
gate_counts = []
non_local_gate_counts = []
levels = [str(x) for x in range(4)]
for level in range(4):
circ = transpile(ghz, backend, optimization_level=level)
depths.append(circ.depth())
gate_counts.append(sum(circ.count_ops().values()))
non_local_gate_counts.append(circ.num_nonlocal_gates())
fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.bar(levels, depths, label='Depth')
ax1.set_xlabel("Optimization Level")
ax1.set_ylabel("Depth")
ax1.set_title("Output Circuit Depth")
ax2.bar(levels, gate_counts, label='Number of Circuit Operations')
ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates')
ax2.set_xlabel("Optimization Level")
ax2.set_ylabel("Number of gates")
ax2.legend()
ax2.set_title("Number of output circuit gates")
fig.tight_layout()
plt.show()
|
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
from qiskit import IBMQ, BasicAer, QuantumCircuit, execute
import qiskit.tools.jupyter
from qiskit.tools import job_monitor
from qiskit.visualization import plot_gate_map, plot_error_map
from qiskit.providers.ibmq import least_busy
provider = IBMQ.load_account()
%qiskit_version_table
print(qiskit.__qiskit_version__)
## qiskit terra version
print(qiskit.__version__)
%qiskit_copyright
BasicAer.backends()
# It works also for other simulators such as: Aer.backends()
%qiskit_backend_overview
backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and
not b.configuration().simulator and b.status().operational==True))
print(backend)
# Plot gate map
plot_gate_map(backend, plot_directed = True)
# Plot error map
plot_error_map(backend)
qc_open = QuantumCircuit.from_qasm_file('myfile.qasm')
qc_open.draw('mpl')
temp = QuantumCircuit(2)
temp.h(0)
temp.h(1)
temp.s(0)
temp.s(1)
qasm_str = temp.qasm() #returning a qasm string, THIS SIMPLE
qasm_str
qc_open1 = QuantumCircuit.from_qasm_str(qasm_str)
qc_open1 == qc_open
%qiskit_job_watcher
backend_sim = BasicAer.get_backend('qasm_simulator')
job = execute(qc_open1, backend_sim, shots = 1024)
job_monitor(job)
# or
job.status()
|
https://github.com/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
from qiskit import QuantumCircuit
import sys
sys.path.append("..")
from clonk.utils.riswap_gates.riswap import RiSwapGate
qc = QuantumCircuit(3)
# qc.u(0, 0, 0,0)
# qc.u(0, 0, 0,1)
# qc.append(RiSwapGate(0.5), [0,1])
# qc.u(0, 0, 0,0)
# qc.u(0, 0, 0,1)
# qc.append(RiSwapGate(0.5), [0,1])
# qc.u(0, 0, 0,0)
# qc.u(0, 0, 0,1)
qc.cswap(2, 0, 1)
qc.cswap(1, 0, 2)
qc.swap(0, 1)
qc.swap(0, 2)
print(qc.draw(output="latex_source", with_layout=False))
qc.draw(output="mpl")
from qiskit.quantum_info import Operator
Operator(qc).data
from qiskit import QuantumCircuit, QuantumRegister
from numpy import pi as pi
from qiskit.circuit.library.standard_gates import *
q = QuantumRegister(3, "q")
cx_to_zx90 = QuantumCircuit(3, global_phase=pi / 4)
for inst, qargs, cargs in [
(RZXGate(pi / 2), [q[0], q[2]], []),
(SdgGate(), [q[0]], []),
(SXdgGate(), [q[2]], []),
]:
cx_to_zx90.append(inst, qargs, cargs)
print(cx_to_zx90.draw(output="latex_source"))
cx_to_zx90.draw(output="mpl")
from qiskit.circuit.library.basis_change import QFT
qc = QFT(4)
qc.decompose().draw(output="mpl")
# print(qc.decompose().draw(output='latex_source'))
import numpy as np
print(np.array(CPhaseGate(pi / 2, 0, 1)))
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# 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.
"""Test examples scripts."""
import os
import subprocess
import sys
import unittest
from qiskit.test import QiskitTestCase, online_test, slow_test
examples_dir = os.path.abspath(
os.path.join(
os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "examples"),
"python",
)
)
ibmq_examples_dir = os.path.join(examples_dir, "ibmq")
class TestPythonExamples(QiskitTestCase):
"""Test example scripts"""
@unittest.skipIf(
sys.platform == "darwin",
"Multiprocess spawn fails on macOS python >=3.8 without __name__ == '__main__' guard",
)
def test_all_examples(self):
"""Execute the example python files and pass if it returns 0."""
examples = []
if os.path.isdir(examples_dir):
examples = [x for x in os.listdir(examples_dir) if x.endswith(".py")]
for example in examples:
with self.subTest(example=example):
example_path = os.path.join(examples_dir, example)
cmd = [sys.executable, example_path]
with subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env={**os.environ, "PYTHONIOENCODING": "utf8"},
) as run_example:
stdout, stderr = run_example.communicate()
error_string = (
f"Running example {example} failed with return code"
f"{run_example.returncode}\n"
f"stdout:{stdout}\nstderr: {stderr}"
)
self.assertEqual(run_example.returncode, 0, error_string)
@unittest.skipIf(
sys.platform == "darwin",
"Multiprocess spawn fails on macOS python >=3.8 without __name__ == '__main__' guard",
)
@online_test
@slow_test
def test_all_ibmq_examples(self, qe_token, qe_url):
"""Execute the ibmq example python files and pass if it returns 0."""
from qiskit import IBMQ
IBMQ.enable_account(qe_token, qe_url)
self.addCleanup(IBMQ.disable_account, token=qe_token, url=qe_url)
ibmq_examples = []
if os.path.isdir(ibmq_examples_dir):
ibmq_examples = [x for x in os.listdir(ibmq_examples_dir) if x.endswith(".py")]
for example in ibmq_examples:
with self.subTest(example=example):
example_path = os.path.join(ibmq_examples_dir, example)
cmd = [sys.executable, example_path]
with subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env={**os.environ, "PYTHONIOENCODING": "utf8"},
) as run_example:
stdout, stderr = run_example.communicate()
error_string = (
f"Running example {example} failed with return code"
f"{run_example.returncode}\n"
f"stdout:{stdout}\nstderr: {stderr}"
)
self.assertEqual(run_example.returncode, 0, error_string)
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2024 IBM. All Rights Reserved.
#
# 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.
"""Unit-testing linear_function_collection"""
from qiskit import QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit_transpiler_service.ai.collection import CollectCliffords
def test_clifford_collection_pass(random_circuit_transpiled):
collect = PassManager(
[
CollectCliffords(),
]
)
collected_circuit = collect.run(random_circuit_transpiled)
assert isinstance(collected_circuit, QuantumCircuit)
def test_clifford_collection_pass_collect(cz_circ):
collect = PassManager(
[
CollectCliffords(min_block_size=1, max_block_size=5),
]
)
collected_circuit = collect.run(cz_circ)
assert isinstance(collected_circuit, QuantumCircuit)
assert any(g.operation.name.lower() == "clifford" for g in collected_circuit)
def test_clifford_collection_pass_no_collect(rzz_circ):
collect = PassManager(
[
CollectCliffords(min_block_size=7, max_block_size=12),
]
)
collected_circuit = collect.run(rzz_circ)
assert all(g.operation.name.lower() != "clifford" for g in collected_circuit)
def test_clifford_collection_max_block_size(cz_circ):
collect = PassManager(
[
CollectCliffords(max_block_size=7),
]
)
collected_circuit = collect.run(cz_circ)
assert all(len(g.qubits) <= 7 for g in collected_circuit)
def test_clifford_collection_min_block_size(cz_circ):
collect = PassManager(
[
CollectCliffords(min_block_size=7, max_block_size=12),
]
)
collected_circuit = collect.run(cz_circ)
assert all(
len(g.qubits) >= 7 or g.operation.name.lower() != "clifford"
for g in collected_circuit
)
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
### removed cx gate ###
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../utils/")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling
print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
# from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
print(str(backend))
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
#! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# we have to feed initial_layout to calibration matrix
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
meas_calibs[0].draw("mpl")
dt_now = datetime.datetime.now()
print(dt_now)
filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl"
print(filename)
with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open(filename, "wb") as f:
pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
filename = "job_ids_ibmq_jakarta_100step_20220413_030821_.pkl" # change here
with open(filename, "rb") as f:
job_ids_dict = pickle.load(f)
job_ids = job_ids_dict["job_ids"]
cal_job_id = job_ids_dict["cal_job_id"]
retrieved_jobs = []
for job_id in job_ids:
retrieved_jobs.append(backend.retrieve_job(job_id))
retrieved_cal_job = backend.retrieve_job(cal_job_id)
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/Tojarieh97/VQE
|
Tojarieh97
|
%load_ext autoreload
%autoreload 2
from qiskit.circuit.library.standard_gates import RXGate, RZGate, RYGate, CXGate, CZGate, SGate, HGate
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
import numpy as np
def get_linear_entangelment_ansatz(num_of_qubits, thetas, input_state, circuit_depth=3):
quantum_register = QuantumRegister(num_of_qubits, name="qubit")
quantum_circuit = QuantumCircuit(quantum_register)
quantum_circuit.initialize(input_state)
for iteration in range(circuit_depth):
for qubit_index in range(num_of_qubits):
RY_theta_index = iteration*2*num_of_qubits + qubit_index
RZ_theta_index = RY_theta_index + num_of_qubits
quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]])
quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]])
for qubit_index in range(num_of_qubits - 1):
quantum_circuit.append(CXGate(), [quantum_register[qubit_index], quantum_register[qubit_index + 1]])
for qubit_index in range(num_of_qubits):
RY_theta_index = 2*num_of_qubits*circuit_depth + qubit_index
RZ_theta_index = RY_theta_index + num_of_qubits
quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]])
quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]])
return quantum_circuit
def get_full_entangelment_ansatz(num_of_qubits, thetas, input_state, circuit_depth=3):
quantum_register = QuantumRegister(num_of_qubits, name="qubit")
quantum_circuit = QuantumCircuit(quantum_register)
quantum_circuit.initialize(input_state)
for iteration in range(circuit_depth):
for qubit_index in range(num_of_qubits):
RY_theta_index = iteration*2*num_of_qubits + qubit_index
RZ_theta_index = RY_theta_index + num_of_qubits
quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]])
quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]])
for qubit_index in range(num_of_qubits - 1):
for target_qubit_index in range(qubit_index + 1, num_of_qubits):
quantum_circuit.append(CXGate(), [quantum_register[qubit_index], quantum_register[target_qubit_index]])
for qubit_index in range(num_of_qubits):
RY_theta_index = 2*num_of_qubits*circuit_depth + qubit_index
RZ_theta_index = RY_theta_index + num_of_qubits
quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]])
quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]])
return quantum_circuit
initial_thetas = np.random.uniform(low=0, high=360, size=32)
initial_eigenvector = np.identity(16)[0]
print(get_linear_entangelment_ansatz(4, initial_thetas, 3))
initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=24)
initial_eigenvector = np.identity(8)[0]
print(get_linear_entangelment_ansatz(3, initial_thetas, 3))
initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=16)
initial_eigenvector = np.identity(4)[0]
print(get_linear_entangelment_ansatz(2, initial_thetas, 3))
initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=32)
initial_eigenvector = np.identity(16)[0]
print(get_full_entangelment_ansatz(4, initial_thetas, 3))
initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=24)
initial_eigenvector = np.identity(8)[0]
print(get_full_entangelment_ansatz(3, initial_thetas, 3))
initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=16)
initial_eigenvector = np.identity(4)[0]
print(get_full_entangelment_ansatz(2, initial_thetas, 3))
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.visualization import plot_histogram
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
groverCircuit = QuantumCircuit(qr,cr)
groverCircuit.h(qr)
groverCircuit.x(qr)
groverCircuit.cz(qr[0],qr[1])
groverCircuit.x(qr)
groverCircuit.h(qr)
groverCircuit.z(qr)
groverCircuit.cz(qr[0],qr[1])
groverCircuit.h(qr)
groverCircuit.draw(output="mpl")
backend_sim = Aer.get_backend('statevector_simulator')
job_sim = execute(groverCircuit, backend_sim)
statevec = job_sim.result().get_statevector()
print(statevec)
groverCircuit.measure(qr,cr)
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(groverCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Load IBM Q account and get the least busy backend device
provider = IBMQ.load_account()
device = least_busy(provider.backends(simulator=False))
print("Running on current least busy device: ", device)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
job = execute(groverCircuit, backend=device, shots=1024, max_credits=10)
job_monitor(job, interval = 2)
# Get the results from the computation
results = job.result()
answer = results.get_counts(groverCircuit)
plot_histogram(answer)
def phase_oracle(circuit, register):
circuit.cz(qr[2],qr[0])
circuit.cz(qr[2],qr[1])
def n_controlled_Z(circuit, controls, target):
"""Implement a Z gate with multiple controls"""
if (len(controls) > 2):
raise ValueError('The controlled Z with more than 2 controls is not implemented')
elif (len(controls) == 1):
circuit.h(target)
circuit.cx(controls[0], target)
circuit.h(target)
elif (len(controls) == 2):
circuit.h(target)
circuit.ccx(controls[0], controls[1], target)
circuit.h(target)
def inversion_about_average(circuit, register, n, barriers):
"""Apply inversion about the average step of Grover's algorithm."""
circuit.h(register)
circuit.x(register)
if barriers:
circuit.barrier()
n_controlled_Z(circuit, [register[j] for j in range(n-1)], register[n-1])
if barriers:
circuit.barrier()
circuit.x(register)
circuit.h(register)
barriers = True
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
groverCircuit = QuantumCircuit(qr,cr)
groverCircuit.h(qr)
if barriers:
groverCircuit.barrier()
phase_oracle(groverCircuit, qr)
if barriers:
groverCircuit.barrier()
inversion_about_average(groverCircuit, qr, 3, barriers)
if barriers:
groverCircuit.barrier()
groverCircuit.measure(qr,cr)
groverCircuit.draw(output="mpl")
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(groverCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(groverCircuit, backend=backend, shots=shots)
job_monitor(job, interval = 2)
# Get the results from the computation
results = job.result()
answer = results.get_counts(groverCircuit)
plot_histogram(answer)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/JayRGopal/Quantum-Error-Correction
|
JayRGopal
|
from qiskit import *
from oracle_generation import generate_oracle
get_bin = lambda x, n: format(x, 'b').zfill(n)
def gen_circuits(min,max,size):
circuits = []
secrets = []
ORACLE_SIZE = size
for i in range(min,max+1):
cur_str = get_bin(i,ORACLE_SIZE-1)
(circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str)
circuits.append(circuit)
secrets.append(secret)
return (circuits, secrets)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# 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 the MergeAdjacentBarriers pass"""
import random
import unittest
from qiskit.transpiler.passes import MergeAdjacentBarriers
from qiskit.converters import circuit_to_dag
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
class TestMergeAdjacentBarriers(QiskitTestCase):
"""Test the MergeAdjacentBarriers pass"""
def test_two_identical_barriers(self):
"""Merges two barriers that are identical into one
░ ░ ░
q_0: |0>─░──░─ -> q_0: |0>─░─
░ ░ ░
"""
qr = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr)
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_numerous_identical_barriers(self):
"""Merges 5 identical barriers in a row into one
░ ░ ░ ░ ░ ░ ░
q_0: |0>─░──░──░──░──░──░─ -> q_0: |0>─░─
░ ░ ░ ░ ░ ░ ░
"""
qr = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr)
circuit.barrier(qr)
circuit.barrier(qr)
circuit.barrier(qr)
circuit.barrier(qr)
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_of_different_sizes(self):
"""Test two barriers of different sizes are merged into one
░ ░ ░
q_0: |0>─░──░─ q_0: |0>─░─
░ ░ -> ░
q_1: |0>────░─ q_1: |0>─░─
░ ░
"""
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr[0])
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_not_overlapping_barriers(self):
"""Test two barriers with no overlap are not merged
(NB in these pictures they look like 1 barrier but they are
actually 2 distinct barriers, this is just how the text
drawer draws them)
░ ░
q_0: |0>─░─ q_0: |0>─░─
░ -> ░
q_1: |0>─░─ q_1: |0>─░─
░ ░
"""
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr[0])
circuit.barrier(qr[1])
expected = QuantumCircuit(qr)
expected.barrier(qr[0])
expected.barrier(qr[1])
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_obstacle_before(self):
"""Test with an obstacle before the larger barrier
░ ░ ░
q_0: |0>──░───░─ q_0: |0>──────░─
┌───┐ ░ -> ┌───┐ ░
q_1: |0>┤ H ├─░─ q_1: |0>┤ H ├─░─
└───┘ ░ └───┘ ░
"""
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr[0])
circuit.h(qr[1])
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.h(qr[1])
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_obstacle_after(self):
"""Test with an obstacle after the larger barrier
░ ░ ░
q_0: |0>─░───░── q_0: |0>─░──────
░ ┌───┐ -> ░ ┌───┐
q_1: |0>─░─┤ H ├ q_1: |0>─░─┤ H ├
░ └───┘ ░ └───┘
"""
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr)
circuit.barrier(qr[0])
circuit.h(qr[1])
expected = QuantumCircuit(qr)
expected.barrier(qr)
expected.h(qr[1])
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_blocking_obstacle(self):
"""Test that barriers don't merge if there is an obstacle that
is blocking
░ ┌───┐ ░ ░ ┌───┐ ░
q_0: |0>─░─┤ H ├─░─ -> q_0: |0>─░─┤ H ├─░─
░ └───┘ ░ ░ └───┘ ░
"""
qr = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr)
circuit.h(qr)
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
expected.h(qr)
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_blocking_obstacle_long(self):
"""Test that barriers don't merge if there is an obstacle that
is blocking
░ ┌───┐ ░ ░ ┌───┐ ░
q_0: |0>─░─┤ H ├─░─ q_0: |0>─░─┤ H ├─░─
░ └───┘ ░ -> ░ └───┘ ░
q_1: |0>─────────░─ q_1: |0>─────────░─
░ ░
"""
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr[0])
circuit.h(qr[0])
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr[0])
expected.h(qr[0])
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_blocking_obstacle_narrow(self):
"""Test that barriers don't merge if there is an obstacle that
is blocking
░ ┌───┐ ░ ░ ┌───┐ ░
q_0: |0>─░─┤ H ├─░─ q_0: |0>─░─┤ H ├─░─
░ └───┘ ░ -> ░ └───┘ ░
q_1: |0>─░───────░─ q_1: |0>─░───────░─
░ ░ ░ ░
"""
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr)
circuit.h(qr[0])
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
expected.h(qr[0])
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_blocking_obstacle_twoQ(self):
"""Test that barriers don't merge if there is an obstacle that
is blocking
░ ░ ░ ░
q_0: |0>─░───────░─ q_0: |0>─░───────░─
░ ░ ░ ░
q_1: |0>─░───■───── -> q_1: |0>─░───■─────
░ ┌─┴─┐ ░ ░ ┌─┴─┐ ░
q_2: |0>───┤ X ├─░─ q_2: |0>───┤ X ├─░─
└───┘ ░ └───┘ ░
"""
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(0, 1)
circuit.cx(1, 2)
circuit.barrier(0, 2)
expected = QuantumCircuit(qr)
expected.barrier(0, 1)
expected.cx(1, 2)
expected.barrier(0, 2)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_output_deterministic(self):
"""Test that the output barriers have a deterministic ordering (independent of
PYTHONHASHSEED). This is important to guarantee that any subsequent topological iterations
through the circuit are also deterministic; it's in general not possible for all transpiler
passes to produce identical outputs across all valid topological orderings, especially if
those passes have some stochastic element."""
order = list(range(20))
random.Random(2023_02_10).shuffle(order)
circuit = QuantumCircuit(20)
circuit.barrier([5, 2, 3])
circuit.barrier([7, 11, 14, 2, 4])
circuit.barrier(order)
# All the barriers should get merged together.
expected = QuantumCircuit(20)
expected.barrier(range(20))
output = MergeAdjacentBarriers()(circuit)
self.assertEqual(expected, output)
# This assertion is that the ordering of the arguments in the barrier is fixed.
self.assertEqual(list(output.data[0].qubits), list(output.qubits))
if __name__ == "__main__":
unittest.main()
|
https://github.com/DaisukeIto-ynu/KosakaQ
|
DaisukeIto-ynu
|
# 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.
"""Qiskit runtime program."""
import logging
import re
from typing import Optional, List, Dict
from types import SimpleNamespace
from qiskit.providers.ibmq.exceptions import IBMQInputValueError, IBMQNotAuthorizedError
from .exceptions import QiskitRuntimeError, RuntimeProgramNotFound
from ..api.clients.runtime import RuntimeClient
from ..api.exceptions import RequestsApiError
logger = logging.getLogger(__name__)
class RuntimeProgram:
"""Class representing program metadata.
This class contains the metadata describing a program, such as its
name, ID, description, etc.
You can use the :class:`~qiskit.providers.ibmq.runtime.IBMRuntimeService`
to retrieve the metadata of a specific program or all programs. For example::
from qiskit import IBMQ
provider = IBMQ.load_account()
# To retrieve metadata of all programs.
programs = provider.runtime.programs()
# To retrieve metadata of a single program.
program = provider.runtime.program(program_id='circuit-runner')
print(f"Program {program.name} takes parameters {program.parameters().metadata}")
"""
def __init__(
self,
program_name: str,
program_id: str,
description: str,
parameters: Optional[Dict] = None,
return_values: Optional[Dict] = None,
interim_results: Optional[Dict] = None,
max_execution_time: int = 0,
backend_requirements: Optional[Dict] = None,
creation_date: str = "",
update_date: str = "",
is_public: Optional[bool] = False,
data: str = "",
api_client: Optional[RuntimeClient] = None
) -> None:
"""RuntimeProgram constructor.
Args:
program_name: Program name.
program_id: Program ID.
description: Program description.
parameters: Documentation on program parameters.
return_values: Documentation on program return values.
interim_results: Documentation on program interim results.
max_execution_time: Maximum execution time.
backend_requirements: Backend requirements.
creation_date: Program creation date.
update_date: Program last updated date.
is_public: ``True`` if program is visible to all. ``False`` if it's only visible to you.
data: Program data.
api_client: Runtime api client.
"""
self._name = program_name
self._id = program_id
self._description = description
self._max_execution_time = max_execution_time
self._backend_requirements = backend_requirements or {}
self._parameters = parameters or {}
self._return_values = return_values or {}
self._interim_results = interim_results or {}
self._creation_date = creation_date
self._update_date = update_date
self._is_public = is_public
self._data = data
self._api_client = api_client
def __str__(self) -> str:
def _format_common(schema: Dict) -> None:
"""Add title, description and property details to `formatted`."""
if "description" in schema:
formatted.append(" "*4 + "Description: {}".format(schema["description"]))
if "type" in schema:
formatted.append(" "*4 + "Type: {}".format(str(schema["type"])))
if "properties" in schema:
formatted.append(" "*4 + "Properties:")
for property_name, property_value in schema["properties"].items():
formatted.append(" "*8 + "- " + property_name + ":")
for key, value in property_value.items():
formatted.append(" "*12 + "{}: {}".format(sentence_case(key), str(value)))
formatted.append(" "*12 + "Required: " +
str(property_name in schema.get("required", [])))
def sentence_case(camel_case_text: str) -> str:
"""Converts camelCase to Sentence case"""
if camel_case_text == '':
return camel_case_text
sentence_case_text = re.sub('([A-Z])', r' \1', camel_case_text)
return sentence_case_text[:1].upper() + sentence_case_text[1:].lower()
formatted = [f'{self.program_id}:',
f" Name: {self.name}",
f" Description: {self.description}",
f" Creation date: {self.creation_date}",
f" Update date: {self.update_date}",
f" Max execution time: {self.max_execution_time}"]
formatted.append(" Input parameters:")
if self._parameters:
_format_common(self._parameters)
else:
formatted.append(" "*4 + "none")
formatted.append(" Interim results:")
if self._interim_results:
_format_common(self._interim_results)
else:
formatted.append(" "*4 + "none")
formatted.append(" Returns:")
if self._return_values:
_format_common(self._return_values)
else:
formatted.append(" "*4 + "none")
return '\n'.join(formatted)
def to_dict(self) -> Dict:
"""Convert program metadata to dictionary format.
Returns:
Program metadata in dictionary format.
"""
return {
"program_id": self.program_id,
"name": self.name,
"description": self.description,
"max_execution_time": self.max_execution_time,
"backend_requirements": self.backend_requirements,
"parameters": self.parameters(),
"return_values": self.return_values,
"interim_results": self.interim_results,
"is_public": self._is_public
}
def parameters(self) -> 'ParameterNamespace':
"""Program parameter namespace.
You can use the returned namespace to assign parameter values and pass
the namespace to :meth:`qiskit.providers.ibmq.runtime.IBMRuntimeService.run`.
The namespace allows you to use auto-completion to find program parameters.
Note that each call to this method returns a new namespace instance and
does not include any modification to the previous instance.
Returns:
Program parameter namespace.
"""
return ParameterNamespace(self._parameters)
@property
def program_id(self) -> str:
"""Program ID.
Returns:
Program ID.
"""
return self._id
@property
def name(self) -> str:
"""Program name.
Returns:
Program name.
"""
return self._name
@property
def description(self) -> str:
"""Program description.
Returns:
Program description.
"""
return self._description
@property
def return_values(self) -> Dict:
"""Program return value definitions.
Returns:
Return value definitions for this program.
"""
return self._return_values
@property
def interim_results(self) -> Dict:
"""Program interim result definitions.
Returns:
Interim result definitions for this program.
"""
return self._interim_results
@property
def max_execution_time(self) -> int:
"""Maximum execution time in seconds.
A program execution exceeding this time will be forcibly terminated.
Returns:
Maximum execution time.
"""
return self._max_execution_time
@property
def backend_requirements(self) -> Dict:
"""Backend requirements.
Returns:
Backend requirements for this program.
"""
return self._backend_requirements
@property
def creation_date(self) -> str:
"""Program creation date.
Returns:
Program creation date.
"""
return self._creation_date
@property
def update_date(self) -> str:
"""Program last updated date.
Returns:
Program last updated date.
"""
return self._update_date
@property
def is_public(self) -> bool:
"""Whether the program is visible to all.
Returns:
Whether the program is public.
"""
return self._is_public
@property
def data(self) -> str:
"""Program data.
Returns:
Program data.
Raises:
IBMQNotAuthorizedError: if user is not the program author.
"""
if not self._data:
self._refresh()
if not self._data:
raise IBMQNotAuthorizedError(
'Only program authors are authorized to retrieve program data')
return self._data
def _refresh(self) -> None:
"""Refresh program data and metadata
Raises:
RuntimeProgramNotFound: If the program does not exist.
QiskitRuntimeError: If the request failed.
"""
try:
response = self._api_client.program_get(self._id)
except RequestsApiError as ex:
if ex.status_code == 404:
raise RuntimeProgramNotFound(f"Program not found: {ex.message}") from None
raise QiskitRuntimeError(f"Failed to get program: {ex}") from None
self._backend_requirements = {}
self._parameters = {}
self._return_values = {}
self._interim_results = {}
if "spec" in response:
self._backend_requirements = response["spec"].get('backend_requirements', {})
self._parameters = response["spec"].get('parameters', {})
self._return_values = response["spec"].get('return_values', {})
self._interim_results = response["spec"].get('interim_results', {})
self._name = response['name']
self._id = response['id']
self._description = response.get('description', "")
self._max_execution_time = response.get('cost', 0)
self._creation_date = response.get('creation_date', "")
self._update_date = response.get('update_date', "")
self._is_public = response.get('is_public', False)
self._data = response.get('data', "")
class ParameterNamespace(SimpleNamespace):
""" A namespace for program parameters with validation.
This class provides a namespace for program parameters with auto-completion
and validation support.
"""
def __init__(self, parameters: Dict):
"""ParameterNamespace constructor.
Args:
parameters: The program's input parameters.
"""
super().__init__()
# Allow access to the raw program parameters dict
self.__metadata = parameters
# For localized logic, create store of parameters in dictionary
self.__program_params: dict = {}
for parameter_name, parameter_value in parameters.get("properties", {}).items():
# (1) Add parameters to a dict by name
setattr(self, parameter_name, None)
# (2) Store the program params for validation
self.__program_params[parameter_name] = parameter_value
@property
def metadata(self) -> Dict:
"""Returns the parameter metadata"""
return self.__metadata
def validate(self) -> None:
"""Validate program input values.
Note:
This method only verifies that required parameters have values. It
does not fail the validation if the namespace has extraneous parameters.
Raises:
IBMQInputValueError: if validation fails
"""
# Iterate through the user's stored inputs
for parameter_name, parameter_value in self.__program_params.items():
# Set invariants: User-specified parameter value (value) and if it's required (req)
value = getattr(self, parameter_name, None)
# Check there exists a program parameter of that name.
if value is None and parameter_name in self.metadata.get("required", []):
raise IBMQInputValueError('Param (%s) missing required value!' % parameter_name)
def __str__(self) -> str:
"""Creates string representation of object"""
# Header
header = '| {:10.10} | {:12.12} | {:12.12} ' \
'| {:8.8} | {:>15} |'.format(
'Name',
'Value',
'Type',
'Required',
'Description'
)
params_str = '\n'.join([
'| {:10.10} | {:12.12} | {:12.12}| {:8.8} | {:>15} |'.format(
parameter_name,
str(getattr(self, parameter_name, "None")),
str(parameter_value.get("type", "None")),
str(parameter_name in self.metadata.get("required", [])),
str(parameter_value.get("description", "None"))
) for parameter_name, parameter_value in self.__program_params.items()])
return "ParameterNamespace (Values):\n%s\n%s\n%s" \
% (header, '-' * len(header), params_str)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(3, 'q')
anc = QuantumRegister(1, 'ancilla')
cr = ClassicalRegister(3, 'c')
qc = QuantumCircuit(qr, anc, cr)
qc.x(anc[0])
qc.h(anc[0])
qc.h(qr[0:3])
qc.cx(qr[0:3], anc[0])
qc.h(qr[0:3])
qc.barrier(qr)
qc.measure(qr, cr)
qc.draw('mpl')
|
https://github.com/Fabiha-Noshin/Quantum-Algorithms-with-Qiskit
|
Fabiha-Noshin
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ, QuantumRegister
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
from qiskit.aqua.algorithms import Grover
from qiskit.aqua import QuantumInstance
from qiskit.quantum_info.operators import Operator
required_state = ['00100'] # The state that I want to find
# Creating oracle for 5 qubits and according to required state
oracle_matrix = np.array([[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]])
controls = QuantumRegister(5)
oracle = QuantumCircuit(controls)
oracle_circuit = Operator(oracle_matrix)
oracle.unitary(oracle_circuit, [0,1,2,3,4], label='oracle')
oracle.draw('mpl')
# Applying the required oracle to the grover circuit:
grover_circuit = Grover(oracle=oracle, good_state=required_state)
grover_circuit.grover_operator.draw('mpl')
# Running the whole circuit in a similator:
simulator = Aer.get_backend('qasm_simulator')
result = grover_circuit.run(quantum_instance=simulator)
print('Result type: ',type(result))
print('Success!' if result.oracle_evaluation else 'Failure!')
print('Top measurement: ', result.top_measurement)
# Running the whole circuit in a real quantum device:
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
shots = 256
# Load local account information
IBMQ.load_account()
# Get the least busy backend
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 5
and not x.configuration().simulator
and x.status().operational==True))
print("least busy backend: ", backend)
result = grover_circuit.run(quantum_instance=backend, shots=8000)
print('Result type: ',type(result))
print('Success!' if result.oracle_evaluation else 'Failure!')
print('Top measurement: ', result.top_measurement)
|
https://github.com/JavaFXpert/qiskit-runtime-lab
|
JavaFXpert
|
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.backend("ibmq_qasm_simulator")
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from numpy import pi
qreg_q = QuantumRegister(3, 'q')
creg_c = ClassicalRegister(3, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
circuit.ry(1.91063324, qreg_q[0])
circuit.ch(qreg_q[0], qreg_q[1])
circuit.cx(qreg_q[1], qreg_q[2])
circuit.cx(qreg_q[0], qreg_q[1])
circuit.x(qreg_q[0])
circuit.barrier(qreg_q[0], qreg_q[1], qreg_q[2])
circuit.measure(qreg_q[0], creg_c[0])
circuit.measure(qreg_q[1], creg_c[1])
circuit.measure(qreg_q[2], creg_c[2])
display(circuit.draw("mpl"))
from qiskit_ibm_runtime import Sampler
sampler = Sampler(backend=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-probability distribution: {result.quasi_dists[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit.visualization import plot_histogram
plot_histogram(job.result().quasi_dists[0].binary_probabilities())
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
def trotter_gate(dt, to_instruction = True):
qc = QuantumCircuit(2)
qc.rx(2 * dt, 0)
qc.rz(2 * dt, 1)
qc.h(1)
qc.cx(1, 0)
qc.rz(-2 * dt, 0)
qc.rx(-2 * dt, 1)
qc.rz(2 * dt, 1)
qc.cx(1, 0)
qc.h(1)
qc.rz(2 * dt, 0)
return qc.to_instruction() if to_instruction else qc
trotter_gate(np.pi / 6, to_instruction=False).draw("mpl")
def make_initial_state(qc, initial_state):
"""
logical qubit index
little endian
"""
for i, state in enumerate(initial_state):
if state == "1":
qc.x(i)
qc = QuantumCircuit(3)
make_initial_state(qc, "101")
qc.draw("mpl")
def subspace_encoder(qc, targets):
"""
naive method, can be optimized for init state |110>
little endian
"""
n = qc.num_qubits
qc.cx(targets[2],targets[1])
qc.cx(targets[1],targets[0])
def subspace_encoder_init110(qc, targets):
"""
optimized encoder for init state |110>
endian: |q_0, q_1, q_2> (little endian)
encode |110> to |0>|10>
"""
n = qc.num_qubits
qc.x(targets[0])
def subspace_decoder(qc, targets):
"""
naive method
little endian
"""
n = qc.num_qubits
qc.cx(targets[1], targets[0])
qc.cx(targets[2], targets[1])
qc = QuantumCircuit(3)
make_initial_state(qc, "110")
subspace_encoder_init110(qc, targets=[0,1,2])
qc.draw("mpl")
def trotterize(qc, trot_gate, num_steps, targets):
for _ in range(num_steps):
qc.append(trot_gate, qargs = targets)
qc = QuantumCircuit(3)
make_initial_state(qc, "110")
subspace_encoder_init110(qc, targets=[0,1,2])
qc.barrier()
trotterize(qc, trotter_gate(np.pi / 6), 1, targets=[1, 2])
qc = transpile(qc, optimization_level = 3, basis_gates=["sx", "rz", "cx"])
qc.draw("mpl")
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
st_qcs_list = []
# Number of trotter steps
max_trotter_step = 50 ### CAN BE >= 4
trotter_steps = list(range(1, max_trotter_step + 1, 3))
for num_steps in trotter_steps:
print("trotter step: ", num_steps)
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="lq")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "101") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder(qc, targets=[0,1,2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
st_qcs_list.append(t3_st_qcs)
st_qcs_list[-1][-1].draw("mpl")
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
# print("provider:", provider)
# backend = provider.get_backend("ibmq_jakarta")
jobs = []
shots = 1 << 13
# Number of trotter steps
for i, num_steps in enumerate(trotter_steps):
print("trotter step: ", num_steps)
# execute: reps = 1
job = execute(st_qcs_list[i], backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
print()
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
results = []
for job in jobs:
results.append( job.result() )
mit_results = []
for job in jobs:
mit_results.append( meas_fitter.filter.apply(job.result()) )
print(len(results), len(mit_results))
# Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits
def state_tomo(result, st_qcs):
# The expected final state; necessary to determine state tomography fidelity
target_state = (One^Zero^One).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Fit state tomography results
tomo_fitter = StateTomographyFitter(result, st_qcs)
rho_fit = tomo_fitter.fit(method='lstsq')
# Compute fidelity
fid = state_fidelity(rho_fit, target_state)
return fid
# Compute tomography fidelities for each repetition
raw_fids = []
for result in results:
fid = state_tomo(result, st_qcs)
raw_fids.append(fid)
# print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
# Compute tomography fidelities for each repetition
fids = []
for result in mit_results:
fid = state_tomo(result, st_qcs)
fids.append(fid)
# print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
plt.clf()
plt.style.use('ggplot')
plt.figure(dpi=200)
plt.title("state fidelity from Trotter step 1 to "+str(trotter_steps))
plt.plot(trotter_steps, raw_fids, label="raw fidelity")
plt.plot(trotter_steps, fids, label="fidelity after QREM")
plt.xlabel("number of trotter steps")
plt.ylabel("fidelity")
plt.grid(linestyle='dotted')
for step, fid in zip(trotter_steps, raw_fids):
print(step, fid)
for step, fid in zip(trotter_steps, fids):
print(step, fid)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
from qiskit_ibm_runtime import QiskitRuntimeService
# Save an IBM Quantum account.
QiskitRuntimeService.save_account(channel='ibm_quantum',
#channel='ibm_cloud',
token='17efde49764005e8eeb00dd065d44bc208778be72d44b475e508d20504818786f842988b0e506515c78debdd1b0c4b570717863db5e4f85569fb43c4c8626b8a',
overwrite=True)
service = QiskitRuntimeService(
channel='ibm_quantum',
instance='ibm-q/open/main'
#instance='ibm-q-research-2/federal-uni-sant-1/main'
)
program_inputs = {'iterations': 1}
options = {"backend_name": "ibmq_qasm_simulator"}
job = service.run(program_id="hello-world",
options=options,
inputs=program_inputs
)
#print(f"job id: {job.job_id()}")
result = job.result()
print(result)
backend = service.get_backend("ibmq_qasm_simulator")
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info import SparsePauliOp
from qiskit.primitives import Estimator
from qiskit import QuantumCircuit
#circuit = random_circuit(2, 2, seed=1).decompose(reps=1)
circuit = QuantumCircuit(2)
circuit.x(0)
circuit.draw(output='mpl')
observable = SparsePauliOp("IZ") # ordem ...210
#options = {"backend_name": "ibmq_qasm_simulator"}
estimator = Estimator()#options=options)
job = estimator.run(circuit, observable)
result = job.result()
display(circuit.draw("mpl"))
print(f" > Observable: {observable.paulis}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
import math
qc1 = QuantumCircuit(2); qc2 = QuantumCircuit(2)
qc1.h(1)
qc2.h(0); qc2.p(-math.pi/2, 0)
circuits = (
#random_circuit(2, 2, seed=0).decompose(reps=1),
#random_circuit(2, 2, seed=1).decompose(reps=1),
qc1, qc2
)
observables = (
SparsePauliOp("XZ"),
SparsePauliOp("IY"),
)
estimator = Estimator()
job = estimator.run(circuits, observables)
result = job.result()
[display(cir.draw("mpl")) for cir in circuits]
print(f" > Observables: {[obs.paulis for obs in observables]}")
print(f" > Expectation values: {result.values.tolist()}")
print(f" > Metadata: {result.metadata}")
circuits = (
random_circuit(2, 2, seed=0).decompose(reps=1),
random_circuit(2, 2, seed=1).decompose(reps=1),
)
observables = (
SparsePauliOp("XZ"),
SparsePauliOp("IY"),
)
estimator = Estimator()
job_0 = estimator.run(circuits[0], observables[0])
job_1 = estimator.run(circuits[1], observables[1])
result_0 = job_0.result()
result_1 = job_1.result()
[display(cir.draw("mpl")) for cir in circuits]
print(f" > Observables: {[obs.paulis for obs in observables]}")
print(f" > Expectation values [0]: {result_0.values.tolist()[0]}")
print(f" > Metadata [0]: {result_0.metadata[0]}")
print(f" > Expectation values [1]: {result_1.values.tolist()[0]}")
print(f" > Metadata [1]: {result_1.metadata[0]}")
from qiskit.circuit.library import RealAmplitudes
circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1)
observable = SparsePauliOp("ZI")
parameter_values = [0, 1, 2, 3, 4, 5]
estimator = Estimator()
job = estimator.run(circuit, observable, parameter_values)
result = job.result()
display(circuit.draw("mpl"))
print(f" > Observable: {observable.paulis}")
print(f" > Parameter values: {parameter_values}")
print(f" > Expectation value: {result.values}")
print(f" > Metadata: {result.metadata[0]}")
circuit = RealAmplitudes(num_qubits=2, reps=1).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info import SparsePauliOp
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Estimator, Options
circuit = random_circuit(2, 2, seed=1).decompose(reps=1)
observable = SparsePauliOp("IY")
options = Options()
options.optimization_level = 2
options.resilience_level = 2
service = QiskitRuntimeService()
with Session(service=service, backend="ibmq_qasm_simulator") as session:
estimator = Estimator(session=session, options=options)
job = estimator.run(circuit, observable)
result = job.result()
display(circuit.draw("mpl"))
print(f" > Observable: {observable.paulis}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info import SparsePauliOp
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Estimator, Options
circuit = random_circuit(2, 2, seed=1).decompose(reps=1)
observable = SparsePauliOp("IY")
options = Options()
options.optimization_level = 2
options.resilience_level = 2
service = QiskitRuntimeService()
with Session(service=service, backend="ibmq_belem") as session:
estimator = Estimator(session=session, options=options)
job = estimator.run(circuit, observable)
result = job.result()
display(circuit.draw("mpl"))
print(f" > Observable: {observable.paulis}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Session, Options
circuit = random_circuit(2, 2, seed=1).decompose(reps=1)
observable = SparsePauliOp("IY")
options = Options()
options.optimization_level = 2
options.resilience_level = 2
service = QiskitRuntimeService()
backend = service.get_backend("ibmq_belem")
with Session(service=service, backend=backend):
estimator = Estimator()
job = estimator.run(circuit, observable)
result = job.result()
display(circuit.draw("mpl"))
print(f" > Observable: {observable.paulis}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit.circuit.random import random_circuit
from qiskit.primitives import Sampler
circuit = random_circuit(2, 2, seed=1).decompose(reps=1)
circuit.measure_all()
sampler = Sampler()
job = sampler.run(circuit)
result = job.result()
display(circuit.draw("mpl"))
print(f" > Quasi probability distribution: {result.quasi_dists[0]}")
#print(f" > Metadata: {result.metadata[0]}")
#print(result.quasi_dists,result.quasi_dists[0][1])
print(result.quasi_dists[0][0]+result.quasi_dists[0][1]+result.quasi_dists[0][2]+result.quasi_dists[0][3])
from qiskit.circuit.random import random_circuit
from qiskit.primitives import Sampler
circuits = (
random_circuit(2, 2, seed=0).decompose(reps=1),
random_circuit(2, 2, seed=1).decompose(reps=1),
)
[c.measure_all() for c in circuits]
sampler = Sampler()
job = sampler.run(circuits)
result = job.result()
[display(cir.draw("mpl")) for cir in circuits]
print(f" > Quasi probability distributions: {result.quasi_dists}")
#print(f" > Metadata: {result.metadata}")
from qiskit.circuit.library import RealAmplitudes
# RealAmplitudes is one way to generate a parametrized circuit
from qiskit.primitives import Sampler
circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1)
circuit.measure_all()
parameter_values = [0, 1, 2, 3, 4, 5]
sampler = Sampler()
job = sampler.run(circuit, parameter_values)
result = job.result()
display(circuit.draw("mpl"))
print(f" > Parameter values: {parameter_values}")
print(f" > Quasi probability distribution: {result.quasi_dists[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit.circuit.random import random_circuit
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Options
backend = service.get_backend("ibmq_qasm_simulator")
circuit = random_circuit(2, 2, seed=2).decompose(reps=1)
circuit.measure_all()
options = Options()
options.optimization_level = 2
options.resilience_level = 0
service = QiskitRuntimeService()
with Session(service=service, backend=backend):
sampler = Sampler()
job = sampler.run(circuit)
result = job.result()
display(circuit.draw("mpl"))
print(f" > Quasi probability distribution: {result.quasi_dists[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit.circuit.random import random_circuit
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Options
backend = service.get_backend("ibmq_quito")
circuit = random_circuit(2, 2, seed=2).decompose(reps=1)
circuit.measure_all()
options = Options()
options.optimization_level = 2
options.resilience_level = 0
service = QiskitRuntimeService()
with Session(service=service, backend=backend):
sampler = Sampler()
job = sampler.run(circuit)
print(job.job_id())
result = job.result()
display(circuit.draw("mpl"))
print(f" > Quasi probability distribution: {result.quasi_dists[0]}")
print(f" > Metadata: {result.metadata[0]}")
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.wrapper import available_backends, get_backend
from qiskit.wrapper import execute as q_execute
q = QuantumRegister(2, name='q')
c = ClassicalRegister(2, name='c')
qc = QuantumCircuit(q,c)
qc.h(q[0])
qc.h(q[1])
qc.cx(q[0], q[1])
qc.measure(q, c)
z = 0.995004165 + 1j * 0.099833417
z = z / abs(z)
u_error = np.array([[1, 0], [0, z]])
noise_params = {'U':
{'gate_time': 1,
'p_depol': 0.001,
'p_pauli': [0, 0, 0.01],
'U_error': u_error
}
}
config = {"noise_params": noise_params}
ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config)
ret = ret.result()
print(ret.get_counts())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import transpile, QuantumCircuit
import qiskit.quantum_info as qi
from qiskit_aer import AerSimulator
from qiskit_aer.noise import NoiseModel, amplitude_damping_error
from qiskit.tools.visualization import plot_histogram
# CNOT matrix operator with qubit-0 as control and qubit-1 as target
cx_op = qi.Operator([[1, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 0]])
# iSWAP matrix operator
iswap_op = qi.Operator([[1, 0, 0, 0],
[0, 0, 1j, 0],
[0, 1j, 0, 0],
[0, 0, 0, 1]])
# CNOT in terms of iSWAP and single-qubit gates
cx_circ = QuantumCircuit(2, name='cx<iSWAP>')
# Add gates
cx_circ.sdg(1)
cx_circ.h(1)
cx_circ.sdg(0)
cx_circ.unitary(iswap_op, [0, 1], label='iswap')
cx_circ.sdg(0)
cx_circ.h(0)
cx_circ.sdg(0)
cx_circ.unitary(iswap_op, [0, 1], label='iswap')
cx_circ.s(1)
print(cx_circ)
# Simulate the unitary for the circuit using Operator:
unitary = qi.Operator(cx_circ)
print(unitary)
f_ave = qi.average_gate_fidelity(cx_op, unitary)
print("Average Gate Fidelity: F = {:f}".format(f_ave))
'unitary' in AerSimulator().configuration().basis_gates
# Error parameters
param_q0 = 0.05 # damping parameter for qubit-0
param_q1 = 0.1 # damping parameter for qubit-1
# Construct the error
qerror_q0 = amplitude_damping_error(param_q0)
qerror_q1 = amplitude_damping_error(param_q1)
iswap_error = qerror_q1.tensor(qerror_q0)
# Build the noise model by adding the error to the "iswap" gate
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(iswap_error, 'iswap')
noise_model.add_basis_gates(['unitary'])
print(noise_model.basis_gates)
# Bell state circuit where iSWAPS should be inserted at barrier locations
bell_circ = QuantumCircuit(2, 2, name='bell')
bell_circ.h(0)
bell_circ.append(cx_circ, [0, 1])
bell_circ.measure([0,1], [0,1])
print(bell_circ)
# Create ideal simulator backend and transpile circuit
sim_ideal = AerSimulator()
tbell_circ = transpile(bell_circ, sim_ideal)
ideal_result = sim_ideal.run(tbell_circ).result()
ideal_counts = ideal_result.get_counts(0)
plot_histogram(ideal_counts,
title='Ideal output for iSWAP bell-state preparation')
# Create noisy simulator and transpile circuit
sim_noise = AerSimulator(noise_model=noise_model)
tbell_circ_noise = transpile(bell_circ, sim_noise)
# Run on the simulator without noise
noise_result = sim_noise.run(tbell_circ_noise).result()
noise_counts = noise_result.get_counts(bell_circ)
plot_histogram(noise_counts,
title='Noisy output for iSWAP bell-state preparation')
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.result import QuasiDistribution
from qiskit_aer.primitives import Sampler
from qiskit_finance.applications.optimization import PortfolioOptimization
from qiskit_finance.data_providers import RandomDataProvider
from qiskit_optimization.algorithms import MinimumEigenOptimizer
import numpy as np
import matplotlib.pyplot as plt
import datetime
# set number of assets (= number of qubits)
num_assets = 4
seed = 123
# Generate expected return and covariance matrix from (random) time-series
stocks = [("TICKER%s" % i) for i in range(num_assets)]
data = RandomDataProvider(
tickers=stocks,
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=seed,
)
data.run()
mu = data.get_period_return_mean_vector()
sigma = data.get_period_return_covariance_matrix()
# plot sigma
plt.imshow(sigma, interpolation="nearest")
plt.show()
q = 0.5 # set risk factor
budget = num_assets // 2 # set budget
penalty = num_assets # set parameter to scale the budget penalty term
portfolio = PortfolioOptimization(
expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget
)
qp = portfolio.to_quadratic_program()
qp
def print_result(result):
selection = result.x
value = result.fval
print("Optimal: selection {}, value {:.4f}".format(selection, value))
eigenstate = result.min_eigen_solver_result.eigenstate
probabilities = (
eigenstate.binary_probabilities()
if isinstance(eigenstate, QuasiDistribution)
else {k: np.abs(v) ** 2 for k, v in eigenstate.to_dict().items()}
)
print("\n----------------- Full result ---------------------")
print("selection\tvalue\t\tprobability")
print("---------------------------------------------------")
probabilities = sorted(probabilities.items(), key=lambda x: x[1], reverse=True)
for k, v in probabilities:
x = np.array([int(i) for i in list(reversed(k))])
value = portfolio.to_quadratic_program().objective.evaluate(x)
print("%10s\t%.4f\t\t%.4f" % (x, value, v))
exact_mes = NumPyMinimumEigensolver()
exact_eigensolver = MinimumEigenOptimizer(exact_mes)
result = exact_eigensolver.solve(qp)
print_result(result)
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 1234
cobyla = COBYLA()
cobyla.set_options(maxiter=500)
ry = TwoLocal(num_assets, "ry", "cz", reps=3, entanglement="full")
vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla)
vqe = MinimumEigenOptimizer(vqe_mes)
result = vqe.solve(qp)
print_result(result)
algorithm_globals.random_seed = 1234
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(qp)
print_result(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/matteoacrossi/oqs-jupyterbook
|
matteoacrossi
|
import numpy as np
from bokeh.layouts import row, column
from bokeh.models import ColumnDataSource, Slider, CustomJS, Text
from bokeh.plotting import Figure, show
from bokeh.io import output_notebook
def c1t(t, lam = 1., R = .25, c10 = 1.):
expt = lam * t / 2
if R == .5:
output = c10 * np.exp(-expt) * (1 + expt)
#elif R == 0:
# output = c10 * np.exp(-expt) * (np.cosh(expt * sqt) + np.sinh(expt*sqt) / sqt)
elif R < .5:
sqt = np.sqrt(1-2*R)
output = c10 * np.exp(-expt) * (np.cosh(expt * sqt) + np.sinh(expt*sqt) / sqt)
elif R > .5:
sqt = np.sqrt(-1+2*R)
output = c10 * np.exp(-expt) * (np.cos(expt * sqt) + np.sin(expt*sqt) / sqt)
return output
ts = [t*0.02 for t in range(0, 500)]
Rmin = 0
Rmax = 10
Rstep = .2
Rrange = np.arange(Rmin, Rmax, Rstep)
Rrange_str = [str(i) for i in range(len(Rrange))]
lamrange = np.arange(.1,2.,.1)
lamrange_str = [str(lam) for lam in range(len(lamrange))]
Rrange_str_R = ['R = {:.1f}'.format(R) for R in Rrange]
#Rrange_str = ['{:.1f}'.format(i) for i in Rrange] # truncate to two decimals
# make a dictionary of form {'0': 0.0, '1': 0.2, .. }
Rrange_dict = {Rrange_str[i]:Rrange.round(2)[i] for i,_ in enumerate(Rrange)} # rounding to two decimals
ys = {r_str:{lam_str:[c1t(t, R = Rrange[int(r_str)], lam = lamrange[int(lam_str)])**2 for t in ts] for lam_str in lamrange_str} for r_str in Rrange_str}
#ys = {r_str:[c1t(t, R = Rrange_dict[r_str])**2 for t in ts] for r_str in Rrange_str}
initial_r = Rrange_str[1]
initial_lam = lamrange_str[1]
rs = {Rrange_str[i] : [Rrange_str_R[i]] for i,_ in enumerate(Rrange)}
ys['0'].keys()
# Wrap the data in two ColumnDataSources
source_visible = ColumnDataSource(data=dict(
x = ts, y = ys[initial_r][initial_lam]))
source_available = ColumnDataSource(data=ys)
# Define plot elements
plot = Figure(plot_width=400, plot_height=400, x_range=(-.1, 10), y_range=(-.01, 1))
plot.line('x', 'y', source=source_visible, legend_label="ρ₁₁", line_width=3, line_alpha=0.6)
#plot.text(10,10,text='lalala',source=)
# Add text
text_source = ColumnDataSource({'r_value': ['%s' % Rrange_str_R[1]]})
r_available = ColumnDataSource(data=rs)
text = Text(x=7.5, y=.8, text='r_value', text_font_size='15pt')
plot.add_glyph(text_source, text)
# Add slider
slider = Slider(value=int(initial_r),
start=np.min([int(i) for i in ys.keys()]),
end=np.max([int(i) for i in ys.keys()]),
step=1,
show_value = False)
slider2 = Slider(value=int(initial_lam),
start=np.min([int(i) for i in ys['0'].keys()]),
end=np.max([int(i) for i in ys['0'].keys()]),
step=1,
show_value = False)
# Define CustomJS callback, which updates the plot based on selected function
# by updating the source_visible ColumnDataSource.
slider.callback = CustomJS(
args=dict(source_visible=source_visible,
source_available=source_available,
text_source = text_source,
r_available = r_available), code="""
var r_idx = cb_obj.value;
// Get the data from the data sources
var data_visible = source_visible.data;
var data_available = source_available.data;
// Change y-axis data according to the selected value
data_visible.y = data_available[r_idx];
// text
text_source.data = {'r_value': [String(r_available.data[r_idx])]};
// Update the plot
source_visible.change.emit();
""")
slider2.callback = CustomJS(
args=dict(source_visible=source_visible,
source_available=source_available,
text_source = text_source,
r_available = r_available), code="""
var lam_idx = cb_obj.value;
// Get the data from the data sources
var data_visible = source_visible.data;
var data_available = source_available.data;
// Change y-axis data according to the selected value
data_visible.y = data_available[lam_idx];
// Update the plot
source_visible.change.emit();
""")
layout = row(plot, slider)
output_notebook()
show(layout)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-class-docstring,missing-function-docstring
"""Test Counts class."""
import unittest
import numpy as np
from qiskit.result import counts
from qiskit import exceptions
from qiskit.result import utils
class TestCounts(unittest.TestCase):
def test_just_counts(self):
raw_counts = {"0x0": 21, "0x2": 12}
expected = {"0": 21, "10": 12}
result = counts.Counts(raw_counts)
self.assertEqual(expected, result)
def test_counts_with_exta_formatting_data(self):
raw_counts = {"0x0": 4, "0x2": 10}
expected = {"0 0 00": 4, "0 0 10": 10}
result = counts.Counts(
raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4
)
self.assertEqual(result, expected)
def test_marginal_counts(self):
raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_counts(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_marginal_distribution(self):
raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_distribution(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_marginal_distribution_numpy_indices(self):
raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8}
expected = {"00": 4, "01": 27, "10": 23}
indices = np.asarray([0, 1])
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_distribution(counts_obj, indices)
self.assertEqual(expected, result)
def test_int_outcomes(self):
raw_counts = {"0x0": 21, "0x2": 12, "0x3": 5, "0x2E": 265}
expected = {0: 21, 2: 12, 3: 5, 46: 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.int_outcomes()
self.assertEqual(expected, result)
def test_most_frequent(self):
raw_counts = {"0x0": 21, "0x2": 12, "0x3": 5, "0x2E": 265}
expected = "101110"
counts_obj = counts.Counts(raw_counts)
result = counts_obj.most_frequent()
self.assertEqual(expected, result)
def test_most_frequent_duplicate(self):
raw_counts = {"0x0": 265, "0x2": 12, "0x3": 5, "0x2E": 265}
counts_obj = counts.Counts(raw_counts)
self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent)
def test_hex_outcomes(self):
raw_counts = {"0x0": 21, "0x2": 12, "0x3": 5, "0x2E": 265}
expected = {"0x0": 21, "0x2": 12, "0x3": 5, "0x2e": 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.hex_outcomes()
self.assertEqual(expected, result)
def test_just_int_counts(self):
raw_counts = {0: 21, 2: 12}
expected = {"0": 21, "10": 12}
result = counts.Counts(raw_counts)
self.assertEqual(expected, result)
def test_int_counts_with_exta_formatting_data(self):
raw_counts = {0: 4, 2: 10}
expected = {"0 0 00": 4, "0 0 10": 10}
result = counts.Counts(
raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4
)
self.assertEqual(result, expected)
def test_marginal_int_counts(self):
raw_counts = {0: 4, 1: 7, 2: 10, 6: 5, 9: 11, 13: 9, 14: 8}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_counts(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_marginal_distribution_int_counts(self):
raw_counts = {0: 4, 1: 7, 2: 10, 6: 5, 9: 11, 13: 9, 14: 8}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_distribution(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_marginal_distribution_int_counts_numpy_64_bit(self):
raw_counts = {
0: np.int64(4),
1: np.int64(7),
2: np.int64(10),
6: np.int64(5),
9: np.int64(11),
13: np.int64(9),
14: np.int64(8),
}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_distribution(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_marginal_distribution_int_counts_numpy_8_bit(self):
raw_counts = {
0: np.int8(4),
1: np.int8(7),
2: np.int8(10),
6: np.int8(5),
9: np.int8(11),
13: np.int8(9),
14: np.int8(8),
}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_distribution(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_int_outcomes_with_int_counts(self):
raw_counts = {0: 21, 2: 12, 3: 5, 46: 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.int_outcomes()
self.assertEqual(raw_counts, result)
def test_most_frequent_int_counts(self):
raw_counts = {0: 21, 2: 12, 3: 5, 46: 265}
expected = "101110"
counts_obj = counts.Counts(raw_counts)
result = counts_obj.most_frequent()
self.assertEqual(expected, result)
def test_most_frequent_duplicate_int_counts(self):
raw_counts = {0: 265, 2: 12, 3: 5, 46: 265}
counts_obj = counts.Counts(raw_counts)
self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent)
def test_hex_outcomes_int_counts(self):
raw_counts = {0: 265, 2: 12, 3: 5, 46: 265}
expected = {"0x0": 265, "0x2": 12, "0x3": 5, "0x2e": 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.hex_outcomes()
self.assertEqual(expected, result)
def test_invalid_input_type(self):
self.assertRaises(TypeError, counts.Counts, {2.4: 1024})
def test_just_bitstring_counts(self):
raw_counts = {"0": 21, "10": 12}
expected = {"0": 21, "10": 12}
result = counts.Counts(raw_counts)
self.assertEqual(expected, result)
def test_bistring_counts_with_exta_formatting_data(self):
raw_counts = {"0": 4, "10": 10}
expected = {"0 0 00": 4, "0 0 10": 10}
result = counts.Counts(
raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4
)
self.assertEqual(result, expected)
def test_marginal_bitstring_counts(self):
raw_counts = {"0": 4, "1": 7, "10": 10, "110": 5, "1001": 11, "1101": 9, "1110": 8}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_counts(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_marginal_distribution_bitstring_counts(self):
raw_counts = {"0": 4, "1": 7, "10": 10, "110": 5, "1001": 11, "1101": 9, "1110": 8}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_distribution(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_int_outcomes_with_bitstring_counts(self):
raw_counts = {"0": 21, "10": 12, "11": 5, "101110": 265}
expected = {0: 21, 2: 12, 3: 5, 46: 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.int_outcomes()
self.assertEqual(expected, result)
def test_most_frequent_bitstring_counts(self):
raw_counts = {"0": 21, "10": 12, "11": 5, "101110": 265}
expected = "101110"
counts_obj = counts.Counts(raw_counts)
result = counts_obj.most_frequent()
self.assertEqual(expected, result)
def test_most_frequent_duplicate_bitstring_counts(self):
raw_counts = {"0": 265, "10": 12, "11": 5, "101110": 265}
counts_obj = counts.Counts(raw_counts)
self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent)
def test_hex_outcomes_bitstring_counts(self):
raw_counts = {"0": 265, "10": 12, "11": 5, "101110": 265}
expected = {"0x0": 265, "0x2": 12, "0x3": 5, "0x2e": 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.hex_outcomes()
self.assertEqual(expected, result)
def test_qudit_counts(self):
raw_counts = {
"00": 121,
"01": 109,
"02": 114,
"10": 113,
"11": 106,
"12": 114,
"20": 117,
"21": 104,
"22": 102,
}
result = counts.Counts(raw_counts)
self.assertEqual(raw_counts, result)
def test_qudit_counts_raises_with_format(self):
raw_counts = {
"00": 121,
"01": 109,
"02": 114,
"10": 113,
"11": 106,
"12": 114,
"20": 117,
"21": 104,
"22": 102,
}
self.assertRaises(exceptions.QiskitError, counts.Counts, raw_counts, creg_sizes=[["c0", 4]])
def test_qudit_counts_hex_outcome(self):
raw_counts = {
"00": 121,
"01": 109,
"02": 114,
"10": 113,
"11": 106,
"12": 114,
"20": 117,
"21": 104,
"22": 102,
}
counts_obj = counts.Counts(raw_counts)
self.assertRaises(exceptions.QiskitError, counts_obj.hex_outcomes)
def test_qudit_counts_int_outcome(self):
raw_counts = {
"00": 121,
"01": 109,
"02": 114,
"10": 113,
"11": 106,
"12": 114,
"20": 117,
"21": 104,
"22": 102,
}
counts_obj = counts.Counts(raw_counts)
self.assertRaises(exceptions.QiskitError, counts_obj.int_outcomes)
def test_qudit_counts_most_frequent(self):
raw_counts = {
"00": 121,
"01": 109,
"02": 114,
"10": 113,
"11": 106,
"12": 114,
"20": 117,
"21": 104,
"22": 102,
}
counts_obj = counts.Counts(raw_counts)
self.assertEqual("00", counts_obj.most_frequent())
def test_just_0b_bitstring_counts(self):
raw_counts = {"0b0": 21, "0b10": 12}
expected = {"0": 21, "10": 12}
result = counts.Counts(raw_counts)
self.assertEqual(expected, result)
def test_0b_bistring_counts_with_exta_formatting_data(self):
raw_counts = {"0b0": 4, "0b10": 10}
expected = {"0 0 00": 4, "0 0 10": 10}
result = counts.Counts(
raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4
)
self.assertEqual(result, expected)
def test_marginal_0b_string_counts(self):
raw_counts = {
"0b0": 4,
"0b1": 7,
"0b10": 10,
"0b110": 5,
"0b1001": 11,
"0b1101": 9,
"0b1110": 8,
}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_counts(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_marginal_distribution_0b_string_counts(self):
raw_counts = {
"0b0": 4,
"0b1": 7,
"0b10": 10,
"0b110": 5,
"0b1001": 11,
"0b1101": 9,
"0b1110": 8,
}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_distribution(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_int_outcomes_with_0b_bitstring_counts(self):
raw_counts = {"0b0": 21, "0b10": 12, "0b11": 5, "0b101110": 265}
expected = {0: 21, 2: 12, 3: 5, 46: 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.int_outcomes()
self.assertEqual(expected, result)
def test_most_frequent_0b_bitstring_counts(self):
raw_counts = {"0b0": 21, "0b10": 12, "0b11": 5, "0b101110": 265}
expected = "101110"
counts_obj = counts.Counts(raw_counts)
result = counts_obj.most_frequent()
self.assertEqual(expected, result)
def test_most_frequent_duplicate_0b_bitstring_counts(self):
raw_counts = {"0b0": 265, "0b10": 12, "0b11": 5, "0b101110": 265}
counts_obj = counts.Counts(raw_counts)
self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent)
def test_hex_outcomes_0b_bitstring_counts(self):
raw_counts = {"0b0": 265, "0b10": 12, "0b11": 5, "0b101110": 265}
expected = {"0x0": 265, "0x2": 12, "0x3": 5, "0x2e": 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.hex_outcomes()
self.assertEqual(expected, result)
def test_empty_bitstring_counts(self):
raw_counts = {}
expected = {}
result = counts.Counts(raw_counts)
self.assertEqual(expected, result)
def test_empty_bistring_counts_with_exta_formatting_data(self):
raw_counts = {}
expected = {}
result = counts.Counts(
raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4
)
self.assertEqual(result, expected)
def test_int_outcomes_with_empty_counts(self):
raw_counts = {}
expected = {}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.int_outcomes()
self.assertEqual(expected, result)
def test_most_frequent_empty_bitstring_counts(self):
raw_counts = {}
counts_obj = counts.Counts(raw_counts)
self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent)
def test_hex_outcomes_empty_bitstring_counts(self):
raw_counts = {}
expected = {}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.hex_outcomes()
self.assertEqual(expected, result)
|
https://github.com/yaleqc/vqe-error-mitigation
|
yaleqc
|
import numpy as np
import pylab
from qiskit import Aer
from qiskit.aqua import QuantumInstance, aqua_globals
from qiskit.aqua.algorithms import VQE, NumPyMinimumEigensolver
from qiskit.aqua.components.optimizers import SPSA
from qiskit.circuit.library import TwoLocal
from qiskit.aqua.operators import I, X, Z
H2_op = (-1.052373245772859 * I ^ I) + \
(0.39793742484318045 * I ^ Z) + \
(-0.39793742484318045 * Z ^ I) + \
(-0.01128010425623538 * Z ^ Z) + \
(0.18093119978423156 * X ^ X)
print(f'Number of qubits: {H2_op.num_qubits}')
npme = NumPyMinimumEigensolver()
result = npme.compute_minimum_eigenvalue(operator=H2_op)
ref_value = result.eigenvalue.real
print(f'Reference value: {ref_value:.5f}')
seed = 170
iterations = 125
aqua_globals.random_seed = seed
backend = Aer.get_backend('qasm_simulator')
qi = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
counts = []
values = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
var_form = TwoLocal(rotation_blocks='ry', entanglement_blocks='cz')
spsa = SPSA(maxiter=iterations)
vqe = VQE(var_form=var_form, optimizer=spsa, callback=store_intermediate_result, quantum_instance=qi)
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}')
pylab.rcParams['figure.figsize'] = (12, 4)
pylab.plot(counts, values)
pylab.xlabel('Eval count')
pylab.ylabel('Energy')
pylab.title('Convergence with no noise')
import os
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer import QasmSimulator
from qiskit.test.mock import FakeVigo
device_backend = FakeVigo()
backend = Aer.get_backend('qasm_simulator')
counts1 = []
values1 = []
noise_model = None
os.environ['QISKIT_IN_PARALLEL'] = 'TRUE'
device = QasmSimulator.from_backend(device_backend)
coupling_map = device.configuration().coupling_map
noise_model = NoiseModel.from_backend(device)
basis_gates = noise_model.basis_gates
print(noise_model)
print()
aqua_globals.random_seed = seed
qi = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed,
coupling_map=coupling_map, noise_model=noise_model,)
def store_intermediate_result1(eval_count, parameters, mean, std):
counts1.append(eval_count)
values1.append(mean)
var_form = TwoLocal(rotation_blocks='ry', entanglement_blocks='cz')
spsa = SPSA(maxiter=iterations)
vqe = VQE(var_form=var_form, optimizer=spsa, callback=store_intermediate_result1, quantum_instance=qi)
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 counts1 or values1:
pylab.rcParams['figure.figsize'] = (12, 4)
pylab.plot(counts1, values1)
pylab.xlabel('Eval count')
pylab.ylabel('Energy')
pylab.title('Convergence with noise')
from qiskit.ignis.mitigation.measurement import CompleteMeasFitter
counts2 = []
values2 = []
if noise_model is not None:
aqua_globals.random_seed = seed
qi = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed,
coupling_map=coupling_map, noise_model=noise_model,
measurement_error_mitigation_cls=CompleteMeasFitter,
cals_matrix_refresh_period=30)
def store_intermediate_result2(eval_count, parameters, mean, std):
counts2.append(eval_count)
values2.append(mean)
var_form = TwoLocal(rotation_blocks='ry', entanglement_blocks='cz')
spsa = SPSA(maxiter=iterations)
vqe = VQE(var_form=var_form, optimizer=spsa, callback=store_intermediate_result2, quantum_instance=qi)
result2 = vqe.compute_minimum_eigenvalue(operator=H2_op)
print(f'VQE on Aer qasm simulator (with noise and measurement error mitigation): {result2.eigenvalue.real:.5f}')
print(f'Delta from reference energy value is {(result2.eigenvalue.real - ref_value):.5f}')
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 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 of scikit-quant optimizers."""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from ddt import ddt, data, unpack
import numpy
from qiskit import BasicAer
from qiskit.circuit.library import RealAmplitudes
from qiskit.utils import QuantumInstance, algorithm_globals
from qiskit.exceptions import MissingOptionalLibraryError
from qiskit.opflow import PauliSumOp
from qiskit_algorithms import VQE
from qiskit_algorithms.optimizers import BOBYQA, SNOBFIT, IMFIL
@ddt
class TestOptimizers(QiskitAlgorithmsTestCase):
"""Test scikit-quant optimizers."""
def setUp(self):
"""Set the problem."""
super().setUp()
algorithm_globals.random_seed = 50
with self.assertWarns(DeprecationWarning):
self.qubit_op = PauliSumOp.from_list(
[
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
]
)
def _optimize(self, optimizer):
"""launch vqe"""
with self.assertWarns(DeprecationWarning):
qe = QuantumInstance(
BasicAer.get_backend("statevector_simulator"),
seed_simulator=algorithm_globals.random_seed,
seed_transpiler=algorithm_globals.random_seed,
)
with self.assertWarns(DeprecationWarning):
vqe = VQE(ansatz=RealAmplitudes(), optimizer=optimizer, quantum_instance=qe)
result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op)
self.assertAlmostEqual(result.eigenvalue.real, -1.857, places=1)
def test_bobyqa(self):
"""BOBYQA optimizer test."""
try:
optimizer = BOBYQA(maxiter=150)
self._optimize(optimizer)
except MissingOptionalLibraryError as ex:
self.skipTest(str(ex))
@unittest.skipIf(
tuple(map(int, numpy.__version__.split("."))) >= (1, 24, 0),
"scikit's SnobFit currently incompatible with NumPy 1.24.0.",
)
def test_snobfit(self):
"""SNOBFIT optimizer test."""
try:
optimizer = SNOBFIT(maxiter=100, maxfail=100, maxmp=20)
self._optimize(optimizer)
except MissingOptionalLibraryError as ex:
self.skipTest(str(ex))
@unittest.skipIf(
tuple(map(int, numpy.__version__.split("."))) >= (1, 24, 0),
"scikit's SnobFit currently incompatible with NumPy 1.24.0.",
)
@data((None,), ([(-1, 1), (None, None)],))
@unpack
def test_snobfit_missing_bounds(self, bounds):
"""SNOBFIT optimizer test with missing bounds."""
try:
optimizer = SNOBFIT()
with self.assertRaises(ValueError):
optimizer.minimize(
fun=lambda _: 1, # using dummy function (never called)
x0=[0.1, 0.1], # dummy initial point
bounds=bounds,
)
except MissingOptionalLibraryError as ex:
self.skipTest(str(ex))
def test_imfil(self):
"""IMFIL test."""
try:
optimizer = IMFIL(maxiter=100)
self._optimize(optimizer)
except MissingOptionalLibraryError as ex:
self.skipTest(str(ex))
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_right():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will start at t=80
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog.draw()
|
https://github.com/Bikramaditya0154/Quantum-Simulation-of-the-ground-states-of-Li-and-Li-2-using-Variational-Quantum-EIgensolver
|
Bikramaditya0154
|
from qiskit import Aer
from qiskit_nature.drivers import UnitsType, Molecule
from qiskit_nature.drivers.second_quantization import (
ElectronicStructureDriverType,
ElectronicStructureMoleculeDriver,
)
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
molecule = Molecule(
geometry=[["Li", [0.0, 0.0, 0.0]]], charge=2, multiplicity=2
)
driver = ElectronicStructureMoleculeDriver(
molecule, basis="sto3g", driver_type=ElectronicStructureDriverType.PYSCF
)
es_problem = ElectronicStructureProblem(driver)
qubit_converter = QubitConverter(JordanWignerMapper())
from qiskit.providers.aer import StatevectorSimulator
from qiskit import Aer
from qiskit.utils import QuantumInstance
from qiskit_nature.algorithms import VQEUCCFactory
quantum_instance = QuantumInstance(backend=Aer.get_backend("aer_simulator_statevector"))
vqe_solver = VQEUCCFactory(quantum_instance=quantum_instance)
from qiskit.algorithms import VQE
from qiskit.circuit.library import TwoLocal
tl_circuit = TwoLocal(
rotation_blocks=["h", "rx"],
entanglement_blocks="cz",
entanglement="full",
reps=2,
parameter_prefix="y",
)
another_solver = VQE(
ansatz=tl_circuit,
quantum_instance=QuantumInstance(Aer.get_backend("aer_simulator_statevector")),
)
from qiskit_nature.algorithms import GroundStateEigensolver
calc = GroundStateEigensolver(qubit_converter, vqe_solver)
res = calc.solve(es_problem)
print(res)
|
https://github.com/baronefr/perceptron-dqa
|
baronefr
|
import quimb as qu
import quimb.tensor as qtn
import numpy as np
import numpy.fft as fft
import matplotlib.pyplot as plt
from tqdm import tqdm
# to use alternative backends:
#qtn.contraction.set_contract_backend('torch')
N = 12 # number of spins/sites/parameters/qubits
P = 100 # total number of QA steps // should be 100/1000
dt = 0.5 # time interval
# Note: tau (annealing time) will be fixed as P*dt
max_bond = 10 # MPS max bond dimension
N_xi = 9 # dataset size (number of patterns)
def apply_compress(mpo, mps, max_bond = 8, method = 'svd'):
"""Apply mpo to mps and compress to max bond dimension."""
# note: prev default arg method = 'svds'
return mpo._apply_mps(mps, compress=True, method=method, max_bond=max_bond)
def create_dataset(N : int, features : int):
"""Create dataset as described by ref. paper, i.e. random +-1 values."""
x = np.random.randint(2, size=(N, features))
x[ x == 0 ] = -1 # data is encoded as +- 1
return x
def make_Ux(N, beta_p, dtype = np.complex128):
"""Return as MPO the U_x evolution operator at time-parameter beta_p."""
tb = np.array( [[np.cos(beta_p), 1j*np.sin(beta_p)],[1j*np.sin(beta_p), np.cos(beta_p)]], dtype=dtype)
arrays = [ np.expand_dims(tb, axis=0) ] + \
[ np.expand_dims(tb, axis=(0,1)) for _ in range(N-2) ] + \
[ np.expand_dims(tb, axis=0) ]
return qtn.tensor_1d.MatrixProductOperator( arrays )
def Wz(N, Uk : np.array, xi : int, marginal = False, dtype = np.complex128):
"""The tensors of Eq. 17 of reference paper."""
bond_dim = len(Uk)
shape = (bond_dim,2,2) if marginal else (bond_dim,bond_dim,2,2)
tensor = np.zeros( shape, dtype = dtype )
coeff = np.power( Uk/np.sqrt(N+1), 1/N)
exx = 1j * np.arange(bond_dim) * np.pi / (N + 1) # check: N+1
for kk in range(bond_dim):
spin_matrix = np.diag(
[ coeff[kk]*np.exp(exx[kk]*(1-xi)),
coeff[kk]*np.exp(exx[kk]*(1+xi)) ]
)
if marginal: tensor[kk,:,:] = spin_matrix
else: tensor[kk,kk,:,:] = spin_matrix
return tensor
def make_Uz(N : int, Uk : np.array, xi : np.array, bond_dim=None, dtype = np.complex128):
"""Return as MPO the U_z evolution operator at time s_p (defined indirectly by Uk)."""
# Uk must be a vector for all k values, while p is fixed
# xi must be a single sample from dataset
assert len(xi) == N, 'not matching dims'
arrays = [ Wz(N, Uk, xi[0], marginal = True, dtype = dtype) ] + \
[ Wz(N, Uk, xi[i+1], dtype = dtype) for i in range(N-2) ] + \
[ Wz(N, Uk, xi[N-1], marginal = True, dtype = dtype) ]
return qtn.tensor_1d.MatrixProductOperator( arrays )
def Ux_p(N, d, beta_p):
""" Build factorized Ux(beta_p) (bond dimension = 1) on N sites"""
Ux_i = np.identity(d)*np.cos(beta_p) + 1.0j*(np.ones(d)-np.identity(d))*np.sin(beta_p) # single site operator
Ux = qtn.MPO_product_operator([Ux_i]*N, upper_ind_id='u{}', lower_ind_id='s{}')
return Ux
def Uz_p_mu(N, d, p, mu, Uz_FT_, patterns):
""" Build Uz^mu(gamma_p) (bond dimension = N+1) on N sites
- p in range(1,P+1)
"""
Uz_i = []
# leftermost tensor (i = 1)
i = 1
tens = np.zeros((N+1,d,d), dtype=np.complex128)
for s_i in range(d):
tens[:,s_i,s_i] = np.power(Uz_FT_[:,p-1]/np.sqrt(N+1), 1/N) * np.exp(1.0j * (np.pi/(N+1)) * np.arange(N+1) * (1-patterns[mu,i-1]*(-1)**s_i))
Uz_i.append(tens.copy())
# bulk tensors (2 <= i <= N-1)
for i in range(2,N):
tens = np.zeros((N+1,N+1,d,d), dtype=np.complex128)
for s_i in range(d):
np.fill_diagonal(tens[:,:,s_i,s_i],
np.power(Uz_FT_[:,p-1]/np.sqrt(N+1), 1/N) * np.exp(1.0j * (np.pi/(N+1)) * np.arange(N+1) * (1-patterns[mu,i-1]*(-1)**s_i)))
Uz_i.append(tens.copy())
# rightermost tensor (i = N)
i = N
tens = np.zeros((N+1,d,d), dtype=np.complex128)
for s_i in range(d):
tens[:,s_i,s_i] = np.power(Uz_FT_[:,p-1]/np.sqrt(N+1), 1/N) * np.exp(1.0j * (np.pi/(N+1)) * np.arange(N+1) * (1-patterns[mu,i-1]*(-1)**s_i))
Uz_i.append(tens.copy())
Uz = qtn.tensor_1d.MatrixProductOperator(Uz_i, upper_ind_id='u{}', lower_ind_id='s{}') # lower is contracted with psi
return Uz
def h_perceptron(m, N):
""" Cost function to be minimized in the perceptron model, depending on the overlap m.
The total H_z Hamiltonian is obtained as a sum of these cost functions evaluated at each pattern csi_mu.
h(m) = 0 if m>=0 else -m/sqrt(N)
"""
m = np.array(m)
return np.where(m>=0, 0, -m/np.sqrt(N)).squeeze()
def f_perceptron(x, N):
""" Cost function to be minimized in the perceptron model, depending on the Hamming distance x.
The total H_z Hamiltonian is obtained as a sum of these cost functions evaluated at each pattern csi_mu.
f(x) = h(N - 2x) = h(m(x)) with m(x) = N - 2x
"""
m = N - 2*np.asarray(x)
return h_perceptron(m, N)
fx_FT = fft.fft(f_perceptron(range(N+1), N), norm="ortho")
def Hz_mu_singleK(N, mu, K, f_FT_, patterns, dtype=np.complex128):
""" Build factorized Hz^{mu,k} (bond dimension = 1) on N sites"""
Hz_i = []
for i in range(N):
tens = np.zeros((2,2), dtype=dtype)
for s_i in range(2):
tens[s_i,s_i] = np.power(f_FT_[K]/np.sqrt(N+1), 1/N) * \
np.exp( 1.0j * (np.pi/(N+1)) * K *\
(1-patterns[mu,i]*((-1)**s_i)) )
Hz_i.append(tens) # removed copy
Hz = qtn.MPO_product_operator(Hz_i, upper_ind_id='u{}', lower_ind_id='s{}')
return Hz
# this is really the same!
def Hz_mu_singleK(N, mu, K, f_FT_, patterns):
""" Build factorized Hz^{mu,k} (bond dimension = 1) on N sites"""
d = 2
Hz_i = []
for i in range(1,N+1):
tens = np.zeros((d,d), dtype=np.complex128)
for s_i in range(d):
tens[s_i,s_i] = np.power(f_FT_[K]/np.sqrt(N+1), 1/N) * np.exp(1.0j * (np.pi/(N+1)) * K * (1-patterns[mu,i-1]*(-1)**s_i))
Hz_i.append(tens.copy())
Hz = qtn.MPO_product_operator(Hz_i)#, upper_ind_id='u{}', lower_ind_id='s{}')
return Hz
def compute_loss(psi, N, fxft, xi):
N_tens = psi.num_tensors
eps = 0.0
for mu in range(N_xi):
for kk in range(N+1):
mpo = Hz_mu_singleK(N, mu, kk, fxft, xi) # store!
pp = psi.copy()
pH = pp.H
pp.align_(mpo, pH)
#pH = psi.reindex({f"s{i}":f"u{i}" for i in range(N_tens)}).H
tnet = pH & mpo & pp
eps += (tnet.contract()/N_tens)
return eps
try:
xi = np.load('../data/patterns_9-12.npy')
except:
xi = create_dataset(N, N_xi)
# this is the initial state, an MPS of bond_dim = 1
psi = qu.tensor.tensor_builder.MPS_product_state(
[ np.array([[2**-0.5, 2**-0.5]], dtype=np.complex128) ] * N,
tags=['psi'],
)
tau = dt * P
# keep track of loss function
loss = []
# etc
cc = []
# fourier transform of U_z -> U_k
Uk_FT = np.zeros((N+1,P), dtype=np.complex128)
for p in range(0,P):
Uk_FT[:,p] = fft.fft( np.exp(-1.0j*((p+1)/P)*dt*f_perceptron(range(N+1), N)), norm="ortho")
compute_loss(psi, N, fx_FT, xi)
crop_p = None
loss.append( (0, compute_loss(psi, N, fx_FT, xi)) )
print('dQA---')
print(' tau = {}, P = {}, dt = {}'.format(tau, P, dt) )
if crop_p is not None:
print(' [!] simulation will be stopped at iter', crop_p)
# finally... RUN!
with tqdm(total=P, desc='QAnnealing') as pbar:
for pp in range(P):
s_p = (pp+1)/P
beta_p = (1-s_p)*dt
#gamma_p = s_p*dt # not needed
# loop over patterns
for mu in range(N_xi):
Uz = make_Uz(N, Uk_FT[:,pp], xi[mu])
#Uz = Uz_p_mu(N, 2, pp+1, mu, Uk_FT, patterns=xi) # from Paolo
curr_bdim = psi.tensors[int(N/2)].shape[0]
cc.append( curr_bdim )
#psi = Uz._apply_mps( psi, compress = False)
psi = apply_compress(Uz, psi, max_bond=max_bond, method='svd')
Ux = make_Ux(N, beta_p = beta_p)
#Ux = Ux_p(N, 2, beta_p=beta_p) # from Paolo
psi = Ux.apply( psi, compress = False)
# evaluate <psi | H | psi>
expv = compute_loss(psi, N, fx_FT, xi)
loss.append( (s_p, expv) )
# etc
pbar.update(1)
pbar.set_postfix_str("loss = {}, bd = {}".format( np.round(expv, 5), curr_bdim ) )
if crop_p is not None:
if pp == crop_p: break
plt.plot( *zip(*loss) )
plt.yscale('log')
plt.title('dQA')
plt.show()
loss[-1]
plt.plot(cc)
# [INFO] to eventually save the curve...
#np.save('../data/quimb-demo-dqa.npy', np.array([el[1] for el in loss]))
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
from qiskit import QuantumCircuit
def prepare_bell_state(state_number,qc):
if state_number == 1: # |Φ+⟩
qc.h(0)
qc.cx(0, 1)
elif state_number == 2: # |Φ-⟩
qc.h(0)
qc.cx(0, 1)
qc.z(0)
elif state_number == 3: # |Ψ+⟩
qc.h(0)
qc.cx(0, 1)
qc.x(1)
elif state_number == 4: # |Ψ-⟩
qc.h(0)
qc.cx(0, 1)
qc.x(1)
qc.z(0)
else:
raise ValueError("State number must be 1, 2, 3, or 4.")
return qc
from qiskit import execute, Aer
from qiskit.visualization import plot_histogram
import numpy as np
def cxHI_simul(bell_state):
# Create a 2-qubit quantum circuit
qc = QuantumCircuit(2)
prepare_bell_state(bell_state,qc)
# Apply CNOT gate with the first qubit as control and the second as target
qc.cx(0, 1)
# Apply H gate on the first qubit
qc.h(0)
# Draw the circuit
qc.draw(output='mpl')
# (Optional) Simulate the circuit
simulator = Aer.get_backend('statevector_simulator')
result = execute(qc, simulator).result()
statevector = result.get_statevector()
statevector = np.asarray(result.get_statevector())
rounded_statevector = [round(x.real, 3) + round(x.imag, 3) * 1j for x in statevector]
print("Rounded Statevector:", rounded_statevector)
qc.measure_all()
# szimulálás
job = execute(qc, simulator, shots=1024)
result = job.result()
counts = result.get_counts(qc)
print(counts)
# bell állapotok előkészítése
for i in range(1,5):
cxHI_simul(i)
|
https://github.com/TheGupta2012/QickStart-Challenges
|
TheGupta2012
|
## Enter Team ID
import os
os.environ["TEAMID"] = "Excalibur"
from qiskit import QuantumCircuit
def make_bell_state():
qc = QuantumCircuit(2)
### your code here
qc.x(0)
qc.h(0)
qc.cx(0,1)
### your code here
return qc
def test_function_1():
circuit = make_bell_state()
return circuit
test_function_1().draw()
from grader.graders.problem_1.grader import grader1
grader1.evaluate(make_bell_state)
def superposition_operation(n):
qc = QuantumCircuit(n)
### Your code here
for i in range(n):
qc.h(i)
### Your code here
return qc
def test_function_2():
n = 5
operation = superposition_operation(n)
return operation
test_function_2().draw()
from grader.graders.problem_1.grader import grader2
grader2.evaluate(superposition_operation)
def make_even_odd(n):
even = QuantumCircuit(n)
odd = QuantumCircuit(n)
### your code here
for i in range(1,n):
even.h(i)
odd.h(i)
odd.x(0)
### your code here
return (even, odd)
def test_function_3():
n = 3
even, odd = make_even_odd(n)
return even, odd
even, odd = test_function_3()
display(even.draw('mpl'))
odd.draw('mpl')
from grader.graders.problem_1.grader import grader3
grader3.evaluate(make_even_odd)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/QForestCommunity/launchpad
|
QForestCommunity
|
import qiskit
qiskit.__qiskit_version__
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import Aer, execute, QuantumCircuit
from qiskit.circuit.library.standard_gates import RYGate
from qiskit.tools.visualization import circuit_drawer
from numpy import pi, e, sqrt, arccos, log2
from scipy.integrate import quad
%matplotlib inline
import matplotlib.pyplot as plt
def distribution(x):
"""
Returns the value of a chosen probability distribution at the given value
of x. Mess around with this function to see how the encoder works!
The current distribution being used is N(0, 2).
"""
# Use these with normal distributions
mu = 0
sigma = 2
return (((e ** (-0.5 * ((x - mu) / sigma) ** 2)) / (sigma * sqrt(2 * pi))) / 0.99993665)
def integrate(dist, lower, upper):
"""
Perform integration using numpy's quad method. We can use parametrized
distributions as well by using this syntax instead:
quad(integrand, lower, upper, args=(tupleOfArgsForIntegrand))
"""
return quad(dist, lower, upper)[0]
def computeRegionProbability(dist, regBounds, numRegions, j):
"""
Given a distribution dist, a list of adjacent regions regBounds, the
current level of discretization numRegions, a region number j, computes
the probability that the value random variable following dist lies in
region j given that it lies in the larger region made up of regions
[(j // 2) * 2, ((j + 2) // 2) * 2]
"""
totalRegions = len(regBounds) - 1
k = 2 * j
prob = integrate(dist, regBounds[(totalRegions // numRegions) * k],
regBounds[(totalRegions // numRegions) * (k + 1)]) / integrate(
dist, regBounds[(totalRegions // numRegions) * ((k // 2) * 2)],
regBounds[(totalRegions // numRegions) * (((k + 2) // 2) * 2)])
return prob
def encodeDist(dist, regBounds):
numQubits = int(log2(len(regBounds) - 1))
a = QuantumRegister(2 * numQubits - 2)
c = ClassicalRegister(numQubits)
qc = QuantumCircuit(a, c)
for i in range(numQubits):
numRegions = int(2 ** (i + 1))
for j in range(numRegions // 2):
prob = computeRegionProbability(dist, regBounds, numRegions, j)
if not i:
qc.ry(2 * arccos(sqrt(prob)), a[2 * numQubits - 3])
else:
cGate = RYGate(2 * arccos(sqrt(prob))).control(i)
def getFlipList(i, j, numQubits):
"""
Given the current level of desired level of discretization, the
current level of discretization i and a region number j,
returns the binary bit string associated with j in the form of
a list of bits to be flipped.
"""
binString = str(bin(j))[2:]
binString = ("0" * (numQubits - len(binString))) + binString
bitFlips = []
for k in range(numQubits - i, numQubits):
if binString[k] == '0':
bitFlips.append(3 * numQubits - 3 - k - i)
return bitFlips
for k in listOfFlips:
qc.x(a[k])
qubitsUsed = [a[k] for k in
range(2 * numQubits - 2 - i, 2 * numQubits - 2)]
qubitsUsed.append(a[2 * numQubits - 3 - i])
qc.append(cGate, qubitsUsed)
for k in listOfFlips:
qc.x(a[k])
return qc, a, c
def encodeDist(dist, regBounds):
"""
Discretize the distribution dist into multiple regions with boundaries
given by regBounds, and store the associated quantum superposition
state in a new quantum register reg. Please make sure the number of
regions is a power of 2, i.e. len(regBounds) = (2 ** n) + 1.
Additionally, the number of regions is limited to a maximum of
2^(n // 2 + 1), where n is the number of qubits available in the backend
being used - this is due to the requirement of (n - 2) ancilla qubits in
order to perform (n - 1) control operations with minimal possible depth.
Returns a new quantum circuit containing the instructions and registers
needed to create the superposition state, along with the size of the
quantum register.
"""
numQubits = int(log2(len(regBounds) - 1))
a = QuantumRegister(2 * numQubits - 2)
c = ClassicalRegister(numQubits)
qc = QuantumCircuit(a, c)
for i in range(numQubits):
numRegions = int(2 ** (i + 1))
for j in range(numRegions // 2):
prob = computeRegionProbability(dist, regBounds, numRegions, j)
if not i:
qc.ry(2 * arccos(sqrt(prob)), a[2 * numQubits - 3])
else:
cGate = RYGate(2 * arccos(sqrt(prob))).control(i)
listOfFlips = getFlipList(i, j, numQubits)
for k in listOfFlips:
qc.x(a[k])
qubitsUsed = [a[k] for k in
range(2 * numQubits - 2 - i, 2 * numQubits - 2)]
qubitsUsed.append(a[2 * numQubits - 3 - i])
qc.append(cGate, qubitsUsed)
for k in listOfFlips:
qc.x(a[k])
return qc, a, c
def pad(x, numQubits):
"""
Utility function that returns a left padded version of the bit string
passed.
"""
string = str(x)[2:]
string = ('0' * (numQubits - len(string))) + string
return string
regBounds = [i for i in range(-16, 17)]
qc, a, c = encodeDist(distribution, regBounds)
numQubits = (qc.num_qubits + 2) // 2
for i in range(numQubits - 2, 2 * numQubits - 2):
qc.measure(a[i], c[i - (numQubits - 2)])
backend = Aer.get_backend('qasm_simulator')
shots = 100000
job = execute(qc, backend=backend, shots=shots)
results = job.result().get_counts()
resultsX = []
resultsY = []
for i in [pad(bin(x), numQubits) for x in range(2 ** (numQubits))]:
resultsX.append(i)
if i in results.keys():
resultsY.append(results[i])
else:
resultsY.append(0)
truthDisc = [integrate(distribution, regBounds[i], regBounds[i + 1]) * shots for i in range(
len(regBounds) - 1)]
plt.figure(figsize=[16, 9])
plt.plot(resultsX, resultsY)
plt.plot(resultsX, truthDisc, '--')
plt.legend(['quantum estimate', 'classical estimate'])
plt.show()
circuit_drawer(qc, output='mpl')
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# 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.
# pylint: disable=invalid-name
# pylint: disable=missing-param-doc,missing-type-doc,unused-argument
"""
Visualization functions for quantum states.
"""
from typing import Optional, List, Union
from functools import reduce
import colorsys
import numpy as np
from qiskit import user_config
from qiskit.quantum_info.states.statevector import Statevector
from qiskit.quantum_info.operators.operator import Operator
from qiskit.quantum_info.operators.symplectic import PauliList, SparsePauliOp
from qiskit.quantum_info.states.densitymatrix import DensityMatrix
from qiskit.utils.deprecation import deprecate_arg, deprecate_func
from qiskit.utils import optionals as _optionals
from qiskit.circuit.tools.pi_check import pi_check
from .array import _num_to_latex, array_to_latex
from .utils import matplotlib_close_if_inline
from .exceptions import VisualizationError
@deprecate_arg("rho", new_alias="state", since="0.15.1")
@_optionals.HAS_MATPLOTLIB.require_in_call
def plot_state_hinton(
state, title="", figsize=None, ax_real=None, ax_imag=None, *, rho=None, filename=None
):
"""Plot a hinton diagram for the density matrix of a quantum state.
The hinton diagram represents the values of a matrix using
squares, whose size indicate the magnitude of their corresponding value
and their color, its sign. A white square means the value is positive and
a black one means negative.
Args:
state (Statevector or DensityMatrix or ndarray): An N-qubit quantum state.
title (str): a string that represents the plot title
figsize (tuple): Figure size in inches.
filename (str): file path to save image to.
ax_real (matplotlib.axes.Axes): An optional Axes object to be used for
the visualization output. If none is specified a new matplotlib
Figure will be created and used. If this is specified without an
ax_imag only the real component plot will be generated.
Additionally, if specified there will be no returned Figure since
it is redundant.
ax_imag (matplotlib.axes.Axes): An optional Axes object to be used for
the visualization output. If none is specified a new matplotlib
Figure will be created and used. If this is specified without an
ax_imag only the real component plot will be generated.
Additionally, if specified there will be no returned Figure since
it is redundant.
Returns:
:class:`matplotlib:matplotlib.figure.Figure` :
The matplotlib.Figure of the visualization if
neither ax_real or ax_imag is set.
Raises:
MissingOptionalLibraryError: Requires matplotlib.
VisualizationError: if input is not a valid N-qubit state.
Examples:
.. plot::
:include-source:
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_hinton
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3 , 0)
qc.rx(np.pi/5, 1)
state = DensityMatrix(qc)
plot_state_hinton(state, title="New Hinton Plot")
"""
from matplotlib import pyplot as plt
# Figure data
rho = DensityMatrix(state)
num = rho.num_qubits
if num is None:
raise VisualizationError("Input is not a multi-qubit quantum state.")
max_weight = 2 ** np.ceil(np.log(np.abs(rho.data).max()) / np.log(2))
datareal = np.real(rho.data)
dataimag = np.imag(rho.data)
if figsize is None:
figsize = (8, 5)
if not ax_real and not ax_imag:
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize)
else:
if ax_real:
fig = ax_real.get_figure()
else:
fig = ax_imag.get_figure()
ax1 = ax_real
ax2 = ax_imag
# Reversal is to account for Qiskit's endianness.
column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
row_names = [bin(i)[2:].zfill(num) for i in range(2**num)][::-1]
ly, lx = datareal.shape
# Real
if ax1:
ax1.patch.set_facecolor("gray")
ax1.set_aspect("equal", "box")
ax1.xaxis.set_major_locator(plt.NullLocator())
ax1.yaxis.set_major_locator(plt.NullLocator())
for (x, y), w in np.ndenumerate(datareal):
# Convert from matrix co-ordinates to plot co-ordinates.
plot_x, plot_y = y, lx - x - 1
color = "white" if w > 0 else "black"
size = np.sqrt(np.abs(w) / max_weight)
rect = plt.Rectangle(
[0.5 + plot_x - size / 2, 0.5 + plot_y - size / 2],
size,
size,
facecolor=color,
edgecolor=color,
)
ax1.add_patch(rect)
ax1.set_xticks(0.5 + np.arange(lx))
ax1.set_yticks(0.5 + np.arange(ly))
ax1.set_xlim([0, lx])
ax1.set_ylim([0, ly])
ax1.set_yticklabels(row_names, fontsize=14)
ax1.set_xticklabels(column_names, fontsize=14, rotation=90)
ax1.set_title("Re[$\\rho$]", fontsize=14)
# Imaginary
if ax2:
ax2.patch.set_facecolor("gray")
ax2.set_aspect("equal", "box")
ax2.xaxis.set_major_locator(plt.NullLocator())
ax2.yaxis.set_major_locator(plt.NullLocator())
for (x, y), w in np.ndenumerate(dataimag):
# Convert from matrix co-ordinates to plot co-ordinates.
plot_x, plot_y = y, lx - x - 1
color = "white" if w > 0 else "black"
size = np.sqrt(np.abs(w) / max_weight)
rect = plt.Rectangle(
[0.5 + plot_x - size / 2, 0.5 + plot_y - size / 2],
size,
size,
facecolor=color,
edgecolor=color,
)
ax2.add_patch(rect)
ax2.set_xticks(0.5 + np.arange(lx))
ax2.set_yticks(0.5 + np.arange(ly))
ax2.set_xlim([0, lx])
ax2.set_ylim([0, ly])
ax2.set_yticklabels(row_names, fontsize=14)
ax2.set_xticklabels(column_names, fontsize=14, rotation=90)
ax2.set_title("Im[$\\rho$]", fontsize=14)
fig.tight_layout()
if title:
fig.suptitle(title, fontsize=16)
if ax_real is None and ax_imag is None:
matplotlib_close_if_inline(fig)
if filename is None:
return fig
else:
return fig.savefig(filename)
@_optionals.HAS_MATPLOTLIB.require_in_call
def plot_bloch_vector(
bloch, title="", ax=None, figsize=None, coord_type="cartesian", font_size=None
):
"""Plot the Bloch sphere.
Plot a Bloch sphere with the specified coordinates, that can be given in both
cartesian and spherical systems.
Args:
bloch (list[double]): array of three elements where [<x>, <y>, <z>] (Cartesian)
or [<r>, <theta>, <phi>] (spherical in radians)
<theta> is inclination angle from +z direction
<phi> is azimuth from +x direction
title (str): a string that represents the plot title
ax (matplotlib.axes.Axes): An Axes to use for rendering the bloch
sphere
figsize (tuple): Figure size in inches. Has no effect is passing ``ax``.
coord_type (str): a string that specifies coordinate type for bloch
(Cartesian or spherical), default is Cartesian
font_size (float): Font size.
Returns:
:class:`matplotlib:matplotlib.figure.Figure` : A matplotlib figure instance if ``ax = None``.
Raises:
MissingOptionalLibraryError: Requires matplotlib.
Examples:
.. plot::
:include-source:
from qiskit.visualization import plot_bloch_vector
plot_bloch_vector([0,1,0], title="New Bloch Sphere")
.. plot::
:include-source:
import numpy as np
from qiskit.visualization import plot_bloch_vector
# You can use spherical coordinates instead of cartesian.
plot_bloch_vector([1, np.pi/2, np.pi/3], coord_type='spherical')
"""
from .bloch import Bloch
if figsize is None:
figsize = (5, 5)
B = Bloch(axes=ax, font_size=font_size)
if coord_type == "spherical":
r, theta, phi = bloch[0], bloch[1], bloch[2]
bloch[0] = r * np.sin(theta) * np.cos(phi)
bloch[1] = r * np.sin(theta) * np.sin(phi)
bloch[2] = r * np.cos(theta)
B.add_vectors(bloch)
B.render(title=title)
if ax is None:
fig = B.fig
fig.set_size_inches(figsize[0], figsize[1])
matplotlib_close_if_inline(fig)
return fig
return None
@deprecate_arg("rho", new_alias="state", since="0.15.1")
@_optionals.HAS_MATPLOTLIB.require_in_call
def plot_bloch_multivector(
state,
title="",
figsize=None,
*,
rho=None,
reverse_bits=False,
filename=None,
font_size=None,
title_font_size=None,
title_pad=1,
):
r"""Plot a Bloch sphere for each qubit.
Each component :math:`(x,y,z)` of the Bloch sphere labeled as 'qubit i' represents the expected
value of the corresponding Pauli operator acting only on that qubit, that is, the expected value
of :math:`I_{N-1} \otimes\dotsb\otimes I_{i+1}\otimes P_i \otimes I_{i-1}\otimes\dotsb\otimes
I_0`, where :math:`N` is the number of qubits, :math:`P\in \{X,Y,Z\}` and :math:`I` is the
identity operator.
Args:
state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state.
title (str): a string that represents the plot title
figsize (tuple): size of each individual Bloch sphere figure, in inches.
reverse_bits (bool): If True, plots qubits following Qiskit's convention [Default:False].
font_size (float): Font size for the Bloch ball figures.
title_font_size (float): Font size for the title.
title_pad (float): Padding for the title (suptitle `y` position is `y=1+title_pad/100`).
Returns:
:class:`matplotlib:matplotlib.figure.Figure` :
A matplotlib figure instance.
Raises:
MissingOptionalLibraryError: Requires matplotlib.
VisualizationError: if input is not a valid N-qubit state.
Examples:
.. plot::
:include-source:
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)
.. plot::
:include-source:
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
# You can reverse the order of the qubits.
from qiskit.quantum_info import DensityMatrix
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.t(1)
qc.s(0)
qc.cx(0,1)
matrix = DensityMatrix(qc)
plot_bloch_multivector(matrix, title='My Bloch Spheres', reverse_bits=True)
"""
from matplotlib import pyplot as plt
# Data
bloch_data = (
_bloch_multivector_data(state)[::-1] if reverse_bits else _bloch_multivector_data(state)
)
num = len(bloch_data)
if figsize is not None:
width, height = figsize
width *= num
else:
width, height = plt.figaspect(1 / num)
default_title_font_size = font_size if font_size is not None else 16
title_font_size = title_font_size if title_font_size is not None else default_title_font_size
fig = plt.figure(figsize=(width, height))
for i in range(num):
pos = num - 1 - i if reverse_bits else i
ax = fig.add_subplot(1, num, i + 1, projection="3d")
plot_bloch_vector(
bloch_data[i], "qubit " + str(pos), ax=ax, figsize=figsize, font_size=font_size
)
fig.suptitle(title, fontsize=title_font_size, y=1.0 + title_pad / 100)
matplotlib_close_if_inline(fig)
if filename is None:
return fig
else:
return fig.savefig(filename)
@deprecate_arg("rho", new_alias="state", since="0.15.1")
@_optionals.HAS_MATPLOTLIB.require_in_call
def plot_state_city(
state,
title="",
figsize=None,
color=None,
alpha=1,
ax_real=None,
ax_imag=None,
*,
rho=None,
filename=None,
):
"""Plot the cityscape of quantum state.
Plot two 3d bar graphs (two dimensional) of the real and imaginary
part of the density matrix rho.
Args:
state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state.
title (str): a string that represents the plot title
figsize (tuple): Figure size in inches.
color (list): A list of len=2 giving colors for real and
imaginary components of matrix elements.
alpha (float): Transparency value for bars
ax_real (matplotlib.axes.Axes): An optional Axes object to be used for
the visualization output. If none is specified a new matplotlib
Figure will be created and used. If this is specified without an
ax_imag only the real component plot will be generated.
Additionally, if specified there will be no returned Figure since
it is redundant.
ax_imag (matplotlib.axes.Axes): An optional Axes object to be used for
the visualization output. If none is specified a new matplotlib
Figure will be created and used. If this is specified without an
ax_real only the imaginary component plot will be generated.
Additionally, if specified there will be no returned Figure since
it is redundant.
Returns:
:class:`matplotlib:matplotlib.figure.Figure` :
The matplotlib.Figure of the visualization if the
``ax_real`` and ``ax_imag`` kwargs are not set
Raises:
MissingOptionalLibraryError: Requires matplotlib.
ValueError: When 'color' is not a list of len=2.
VisualizationError: if input is not a valid N-qubit state.
Examples:
.. plot::
:include-source:
# You can choose different colors for the real and imaginary parts of the density matrix.
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = DensityMatrix(qc)
plot_state_city(state, color=['midnightblue', 'crimson'], title="New State City")
.. plot::
:include-source:
# You can make the bars more transparent to better see the ones that are behind
# if they overlap.
import numpy as np
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
state = Statevector(qc)
plot_state_city(state, alpha=0.6)
"""
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
rho = DensityMatrix(state)
num = rho.num_qubits
if num is None:
raise VisualizationError("Input is not a multi-qubit quantum state.")
# get the real and imag parts of rho
datareal = np.real(rho.data)
dataimag = np.imag(rho.data)
# get the labels
column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
row_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
lx = len(datareal[0]) # Work out matrix dimensions
ly = len(datareal[:, 0])
xpos = np.arange(0, lx, 1) # Set up a mesh of positions
ypos = np.arange(0, ly, 1)
xpos, ypos = np.meshgrid(xpos + 0.25, ypos + 0.25)
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(lx * ly)
dx = 0.5 * np.ones_like(zpos) # width of bars
dy = dx.copy()
dzr = datareal.flatten()
dzi = dataimag.flatten()
if color is None:
color = ["#648fff", "#648fff"]
else:
if len(color) != 2:
raise ValueError("'color' must be a list of len=2.")
if color[0] is None:
color[0] = "#648fff"
if color[1] is None:
color[1] = "#648fff"
if ax_real is None and ax_imag is None:
# set default figure size
if figsize is None:
figsize = (15, 5)
fig = plt.figure(figsize=figsize)
ax1 = fig.add_subplot(1, 2, 1, projection="3d")
ax2 = fig.add_subplot(1, 2, 2, projection="3d")
elif ax_real is not None:
fig = ax_real.get_figure()
ax1 = ax_real
ax2 = ax_imag
else:
fig = ax_imag.get_figure()
ax1 = None
ax2 = ax_imag
max_dzr = max(dzr)
min_dzr = min(dzr)
min_dzi = np.min(dzi)
max_dzi = np.max(dzi)
# There seems to be a rounding error in which some zero bars are negative
dzr = np.clip(dzr, 0, None)
if ax1 is not None:
fc1 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzr, color[0])
for idx, cur_zpos in enumerate(zpos):
if dzr[idx] > 0:
zorder = 2
else:
zorder = 0
b1 = ax1.bar3d(
xpos[idx],
ypos[idx],
cur_zpos,
dx[idx],
dy[idx],
dzr[idx],
alpha=alpha,
zorder=zorder,
)
b1.set_facecolors(fc1[6 * idx : 6 * idx + 6])
xlim, ylim = ax1.get_xlim(), ax1.get_ylim()
x = [xlim[0], xlim[1], xlim[1], xlim[0]]
y = [ylim[0], ylim[0], ylim[1], ylim[1]]
z = [0, 0, 0, 0]
verts = [list(zip(x, y, z))]
pc1 = Poly3DCollection(verts, alpha=0.15, facecolor="k", linewidths=1, zorder=1)
if min(dzr) < 0 < max(dzr):
ax1.add_collection3d(pc1)
ax1.set_xticks(np.arange(0.5, lx + 0.5, 1))
ax1.set_yticks(np.arange(0.5, ly + 0.5, 1))
if max_dzr != min_dzr:
ax1.axes.set_zlim3d(np.min(dzr), max(np.max(dzr) + 1e-9, max_dzi))
else:
if min_dzr == 0:
ax1.axes.set_zlim3d(np.min(dzr), max(np.max(dzr) + 1e-9, np.max(dzi)))
else:
ax1.axes.set_zlim3d(auto=True)
ax1.get_autoscalez_on()
ax1.xaxis.set_ticklabels(row_names, fontsize=14, rotation=45, ha="right", va="top")
ax1.yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5, ha="left", va="center")
ax1.set_zlabel("Re[$\\rho$]", fontsize=14)
for tick in ax1.zaxis.get_major_ticks():
tick.label1.set_fontsize(14)
if ax2 is not None:
fc2 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzi, color[1])
for idx, cur_zpos in enumerate(zpos):
if dzi[idx] > 0:
zorder = 2
else:
zorder = 0
b2 = ax2.bar3d(
xpos[idx],
ypos[idx],
cur_zpos,
dx[idx],
dy[idx],
dzi[idx],
alpha=alpha,
zorder=zorder,
)
b2.set_facecolors(fc2[6 * idx : 6 * idx + 6])
xlim, ylim = ax2.get_xlim(), ax2.get_ylim()
x = [xlim[0], xlim[1], xlim[1], xlim[0]]
y = [ylim[0], ylim[0], ylim[1], ylim[1]]
z = [0, 0, 0, 0]
verts = [list(zip(x, y, z))]
pc2 = Poly3DCollection(verts, alpha=0.2, facecolor="k", linewidths=1, zorder=1)
if min(dzi) < 0 < max(dzi):
ax2.add_collection3d(pc2)
ax2.set_xticks(np.arange(0.5, lx + 0.5, 1))
ax2.set_yticks(np.arange(0.5, ly + 0.5, 1))
if min_dzi != max_dzi:
eps = 0
ax2.axes.set_zlim3d(np.min(dzi), max(np.max(dzr) + 1e-9, np.max(dzi) + eps))
else:
if min_dzi == 0:
ax2.set_zticks([0])
eps = 1e-9
ax2.axes.set_zlim3d(np.min(dzi), max(np.max(dzr) + 1e-9, np.max(dzi) + eps))
else:
ax2.axes.set_zlim3d(auto=True)
ax2.xaxis.set_ticklabels(row_names, fontsize=14, rotation=45, ha="right", va="top")
ax2.yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5, ha="left", va="center")
ax2.set_zlabel("Im[$\\rho$]", fontsize=14)
for tick in ax2.zaxis.get_major_ticks():
tick.label1.set_fontsize(14)
ax2.get_autoscalez_on()
fig.suptitle(title, fontsize=16)
if ax_real is None and ax_imag is None:
matplotlib_close_if_inline(fig)
if filename is None:
return fig
else:
return fig.savefig(filename)
@deprecate_arg("rho", new_alias="state", since="0.15.1")
@_optionals.HAS_MATPLOTLIB.require_in_call
def plot_state_paulivec(
state, title="", figsize=None, color=None, ax=None, *, rho=None, filename=None
):
r"""Plot the Pauli-vector representation of a quantum state as bar graph.
The Pauli-vector of a density matrix :math:`\rho` is defined by the expectation of each
possible tensor product of single-qubit Pauli operators (including the identity), that is
.. math ::
\rho = \frac{1}{2^n} \sum_{\sigma \in \{I, X, Y, Z\}^{\otimes n}}
\mathrm{Tr}(\sigma \rho) \sigma.
This function plots the coefficients :math:`\mathrm{Tr}(\sigma\rho)` as bar graph.
Args:
state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state.
title (str): a string that represents the plot title
figsize (tuple): Figure size in inches.
color (list or str): Color of the coefficient value bars.
ax (matplotlib.axes.Axes): An optional Axes object to be used for
the visualization output. If none is specified a new matplotlib
Figure will be created and used. Additionally, if specified there
will be no returned Figure since it is redundant.
Returns:
:class:`matplotlib:matplotlib.figure.Figure` :
The matplotlib.Figure of the visualization if the
``ax`` kwarg is not set
Raises:
MissingOptionalLibraryError: Requires matplotlib.
VisualizationError: if input is not a valid N-qubit state.
Examples:
.. plot::
:include-source:
# You can set a color for all the bars.
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
.. plot::
:include-source:
# If you introduce a list with less colors than bars, the color of the bars will
# alternate following the sequence from the list.
import numpy as np
from qiskit.quantum_info import DensityMatrix
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0, 1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
matrix = DensityMatrix(qc)
plot_state_paulivec(matrix, color=['crimson', 'midnightblue', 'seagreen'])
"""
from matplotlib import pyplot as plt
labels, values = _paulivec_data(state)
numelem = len(values)
if figsize is None:
figsize = (7, 5)
if color is None:
color = "#648fff"
ind = np.arange(numelem) # the x locations for the groups
width = 0.5 # the width of the bars
if ax is None:
return_fig = True
fig, ax = plt.subplots(figsize=figsize)
else:
return_fig = False
fig = ax.get_figure()
ax.grid(zorder=0, linewidth=1, linestyle="--")
ax.bar(ind, values, width, color=color, zorder=2)
ax.axhline(linewidth=1, color="k")
# add some text for labels, title, and axes ticks
ax.set_ylabel("Coefficients", fontsize=14)
ax.set_xticks(ind)
ax.set_yticks([-1, -0.5, 0, 0.5, 1])
ax.set_xticklabels(labels, fontsize=14, rotation=70)
ax.set_xlabel("Pauli", fontsize=14)
ax.set_ylim([-1, 1])
ax.set_facecolor("#eeeeee")
for tick in ax.xaxis.get_major_ticks() + ax.yaxis.get_major_ticks():
tick.label1.set_fontsize(14)
ax.set_title(title, fontsize=16)
if return_fig:
matplotlib_close_if_inline(fig)
if filename is None:
return fig
else:
return fig.savefig(filename)
def n_choose_k(n, k):
"""Return the number of combinations for n choose k.
Args:
n (int): the total number of options .
k (int): The number of elements.
Returns:
int: returns the binomial coefficient
"""
if n == 0:
return 0
return reduce(lambda x, y: x * y[0] / y[1], zip(range(n - k + 1, n + 1), range(1, k + 1)), 1)
def lex_index(n, k, lst):
"""Return the lex index of a combination..
Args:
n (int): the total number of options .
k (int): The number of elements.
lst (list): list
Returns:
int: returns int index for lex order
Raises:
VisualizationError: if length of list is not equal to k
"""
if len(lst) != k:
raise VisualizationError("list should have length k")
comb = [n - 1 - x for x in lst]
dualm = sum(n_choose_k(comb[k - 1 - i], i + 1) for i in range(k))
return int(dualm)
def bit_string_index(s):
"""Return the index of a string of 0s and 1s."""
n = len(s)
k = s.count("1")
if s.count("0") != n - k:
raise VisualizationError("s must be a string of 0 and 1")
ones = [pos for pos, char in enumerate(s) if char == "1"]
return lex_index(n, k, ones)
def phase_to_rgb(complex_number):
"""Map a phase of a complexnumber to a color in (r,g,b).
complex_number is phase is first mapped to angle in the range
[0, 2pi] and then to the HSL color wheel
"""
angles = (np.angle(complex_number) + (np.pi * 5 / 4)) % (np.pi * 2)
rgb = colorsys.hls_to_rgb(angles / (np.pi * 2), 0.5, 0.5)
return rgb
@deprecate_arg("rho", new_alias="state", since="0.15.1")
@_optionals.HAS_MATPLOTLIB.require_in_call
@_optionals.HAS_SEABORN.require_in_call
def plot_state_qsphere(
state,
figsize=None,
ax=None,
show_state_labels=True,
show_state_phases=False,
use_degrees=False,
*,
rho=None,
filename=None,
):
"""Plot the qsphere representation of a quantum state.
Here, the size of the points is proportional to the probability
of the corresponding term in the state and the color represents
the phase.
Args:
state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state.
figsize (tuple): Figure size in inches.
ax (matplotlib.axes.Axes): An optional Axes object to be used for
the visualization output. If none is specified a new matplotlib
Figure will be created and used. Additionally, if specified there
will be no returned Figure since it is redundant.
show_state_labels (bool): An optional boolean indicating whether to
show labels for each basis state.
show_state_phases (bool): An optional boolean indicating whether to
show the phase for each basis state.
use_degrees (bool): An optional boolean indicating whether to use
radians or degrees for the phase values in the plot.
Returns:
:class:`matplotlib:matplotlib.figure.Figure` :
A matplotlib figure instance if the ``ax`` kwarg is not set
Raises:
MissingOptionalLibraryError: Requires matplotlib.
VisualizationError: if input is not a valid N-qubit state.
QiskitError: Input statevector does not have valid dimensions.
Examples:
.. plot::
:include-source:
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)
.. plot::
:include-source:
# You can show the phase of each state and use
# degrees instead of radians
from qiskit.quantum_info import DensityMatrix
import numpy as np
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_qsphere
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
qc.z(1)
matrix = DensityMatrix(qc)
plot_state_qsphere(matrix,
show_state_phases = True, use_degrees = True)
"""
from matplotlib import gridspec
from matplotlib import pyplot as plt
from matplotlib.patches import Circle
import seaborn as sns
from scipy import linalg
from .bloch import Arrow3D
rho = DensityMatrix(state)
num = rho.num_qubits
if num is None:
raise VisualizationError("Input is not a multi-qubit quantum state.")
# get the eigenvectors and eigenvalues
eigvals, eigvecs = linalg.eigh(rho.data)
if figsize is None:
figsize = (7, 7)
if ax is None:
return_fig = True
fig = plt.figure(figsize=figsize)
else:
return_fig = False
fig = ax.get_figure()
gs = gridspec.GridSpec(nrows=3, ncols=3)
ax = fig.add_subplot(gs[0:3, 0:3], projection="3d")
ax.axes.set_xlim3d(-1.0, 1.0)
ax.axes.set_ylim3d(-1.0, 1.0)
ax.axes.set_zlim3d(-1.0, 1.0)
ax.axes.grid(False)
ax.view_init(elev=5, azim=275)
# Force aspect ratio
# MPL 3.2 or previous do not have set_box_aspect
if hasattr(ax.axes, "set_box_aspect"):
ax.axes.set_box_aspect((1, 1, 1))
# start the plotting
# Plot semi-transparent sphere
u = np.linspace(0, 2 * np.pi, 25)
v = np.linspace(0, np.pi, 25)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(
x, y, z, rstride=1, cstride=1, color=plt.rcParams["grid.color"], alpha=0.2, linewidth=0
)
# Get rid of the panes
ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the spines
ax.xaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.yaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.zaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
# traversing the eigvals/vecs backward as sorted low->high
for idx in range(eigvals.shape[0] - 1, -1, -1):
if eigvals[idx] > 0.001:
# get the max eigenvalue
state = eigvecs[:, idx]
loc = np.absolute(state).argmax()
# remove the global phase from max element
angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)
angleset = np.exp(-1j * angles)
state = angleset * state
d = num
for i in range(2**num):
# get x,y,z points
element = bin(i)[2:].zfill(num)
weight = element.count("1")
zvalue = -2 * weight / d + 1
number_of_divisions = n_choose_k(d, weight)
weight_order = bit_string_index(element)
angle = (float(weight) / d) * (np.pi * 2) + (
weight_order * 2 * (np.pi / number_of_divisions)
)
if (weight > d / 2) or (
(weight == d / 2) and (weight_order >= number_of_divisions / 2)
):
angle = np.pi - angle - (2 * np.pi / number_of_divisions)
xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle)
yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle)
# get prob and angle - prob will be shade and angle color
prob = np.real(np.dot(state[i], state[i].conj()))
prob = min(prob, 1) # See https://github.com/Qiskit/qiskit-terra/issues/4666
colorstate = phase_to_rgb(state[i])
alfa = 1
if yvalue >= 0.1:
alfa = 1.0 - yvalue
if not np.isclose(prob, 0) and show_state_labels:
rprime = 1.3
angle_theta = np.arctan2(np.sqrt(1 - zvalue**2), zvalue)
xvalue_text = rprime * np.sin(angle_theta) * np.cos(angle)
yvalue_text = rprime * np.sin(angle_theta) * np.sin(angle)
zvalue_text = rprime * np.cos(angle_theta)
element_text = "$\\vert" + element + "\\rangle$"
if show_state_phases:
element_angle = (np.angle(state[i]) + (np.pi * 4)) % (np.pi * 2)
if use_degrees:
element_text += "\n$%.1f^\\circ$" % (element_angle * 180 / np.pi)
else:
element_angle = pi_check(element_angle, ndigits=3).replace("pi", "\\pi")
element_text += "\n$%s$" % (element_angle)
ax.text(
xvalue_text,
yvalue_text,
zvalue_text,
element_text,
ha="center",
va="center",
size=12,
)
ax.plot(
[xvalue],
[yvalue],
[zvalue],
markerfacecolor=colorstate,
markeredgecolor=colorstate,
marker="o",
markersize=np.sqrt(prob) * 30,
alpha=alfa,
)
a = Arrow3D(
[0, xvalue],
[0, yvalue],
[0, zvalue],
mutation_scale=20,
alpha=prob,
arrowstyle="-",
color=colorstate,
lw=2,
)
ax.add_artist(a)
# add weight lines
for weight in range(d + 1):
theta = np.linspace(-2 * np.pi, 2 * np.pi, 100)
z = -2 * weight / d + 1
r = np.sqrt(1 - z**2)
x = r * np.cos(theta)
y = r * np.sin(theta)
ax.plot(x, y, z, color=(0.5, 0.5, 0.5), lw=1, ls=":", alpha=0.5)
# add center point
ax.plot(
[0],
[0],
[0],
markerfacecolor=(0.5, 0.5, 0.5),
markeredgecolor=(0.5, 0.5, 0.5),
marker="o",
markersize=3,
alpha=1,
)
else:
break
n = 64
theta = np.ones(n)
colors = sns.hls_palette(n)
ax2 = fig.add_subplot(gs[2:, 2:])
ax2.pie(theta, colors=colors[5 * n // 8 :] + colors[: 5 * n // 8], radius=0.75)
ax2.add_artist(Circle((0, 0), 0.5, color="white", zorder=1))
offset = 0.95 # since radius of sphere is one.
if use_degrees:
labels = ["Phase\n(Deg)", "0", "90", "180 ", "270"]
else:
labels = ["Phase", "$0$", "$\\pi/2$", "$\\pi$", "$3\\pi/2$"]
ax2.text(0, 0, labels[0], horizontalalignment="center", verticalalignment="center", fontsize=14)
ax2.text(
offset, 0, labels[1], horizontalalignment="center", verticalalignment="center", fontsize=14
)
ax2.text(
0, offset, labels[2], horizontalalignment="center", verticalalignment="center", fontsize=14
)
ax2.text(
-offset, 0, labels[3], horizontalalignment="center", verticalalignment="center", fontsize=14
)
ax2.text(
0, -offset, labels[4], horizontalalignment="center", verticalalignment="center", fontsize=14
)
if return_fig:
matplotlib_close_if_inline(fig)
if filename is None:
return fig
else:
return fig.savefig(filename)
@_optionals.HAS_MATPLOTLIB.require_in_call
def generate_facecolors(x, y, z, dx, dy, dz, color):
"""Generates shaded facecolors for shaded bars.
This is here to work around a Matplotlib bug
where alpha does not work in Bar3D.
Args:
x (array_like): The x- coordinates of the anchor point of the bars.
y (array_like): The y- coordinates of the anchor point of the bars.
z (array_like): The z- coordinates of the anchor point of the bars.
dx (array_like): Width of bars.
dy (array_like): Depth of bars.
dz (array_like): Height of bars.
color (array_like): sequence of valid color specifications, optional
Returns:
list: Shaded colors for bars.
Raises:
MissingOptionalLibraryError: If matplotlib is not installed
"""
import matplotlib.colors as mcolors
cuboid = np.array(
[
# -z
(
(0, 0, 0),
(0, 1, 0),
(1, 1, 0),
(1, 0, 0),
),
# +z
(
(0, 0, 1),
(1, 0, 1),
(1, 1, 1),
(0, 1, 1),
),
# -y
(
(0, 0, 0),
(1, 0, 0),
(1, 0, 1),
(0, 0, 1),
),
# +y
(
(0, 1, 0),
(0, 1, 1),
(1, 1, 1),
(1, 1, 0),
),
# -x
(
(0, 0, 0),
(0, 0, 1),
(0, 1, 1),
(0, 1, 0),
),
# +x
(
(1, 0, 0),
(1, 1, 0),
(1, 1, 1),
(1, 0, 1),
),
]
)
# indexed by [bar, face, vertex, coord]
polys = np.empty(x.shape + cuboid.shape)
# handle each coordinate separately
for i, p, dp in [(0, x, dx), (1, y, dy), (2, z, dz)]:
p = p[..., np.newaxis, np.newaxis]
dp = dp[..., np.newaxis, np.newaxis]
polys[..., i] = p + dp * cuboid[..., i]
# collapse the first two axes
polys = polys.reshape((-1,) + polys.shape[2:])
facecolors = []
if len(color) == len(x):
# bar colors specified, need to expand to number of faces
for c in color:
facecolors.extend([c] * 6)
else:
# a single color specified, or face colors specified explicitly
facecolors = list(mcolors.to_rgba_array(color))
if len(facecolors) < len(x):
facecolors *= 6 * len(x)
normals = _generate_normals(polys)
return _shade_colors(facecolors, normals)
def _generate_normals(polygons):
"""Takes a list of polygons and return an array of their normals.
Normals point towards the viewer for a face with its vertices in
counterclockwise order, following the right hand rule.
Uses three points equally spaced around the polygon.
This normal of course might not make sense for polygons with more than
three points not lying in a plane, but it's a plausible and fast
approximation.
Args:
polygons (list): list of (M_i, 3) array_like, or (..., M, 3) array_like
A sequence of polygons to compute normals for, which can have
varying numbers of vertices. If the polygons all have the same
number of vertices and array is passed, then the operation will
be vectorized.
Returns:
normals: (..., 3) array_like
A normal vector estimated for the polygon.
"""
if isinstance(polygons, np.ndarray):
# optimization: polygons all have the same number of points, so can
# vectorize
n = polygons.shape[-2]
i1, i2, i3 = 0, n // 3, 2 * n // 3
v1 = polygons[..., i1, :] - polygons[..., i2, :]
v2 = polygons[..., i2, :] - polygons[..., i3, :]
else:
# The subtraction doesn't vectorize because polygons is jagged.
v1 = np.empty((len(polygons), 3))
v2 = np.empty((len(polygons), 3))
for poly_i, ps in enumerate(polygons):
n = len(ps)
i1, i2, i3 = 0, n // 3, 2 * n // 3
v1[poly_i, :] = ps[i1, :] - ps[i2, :]
v2[poly_i, :] = ps[i2, :] - ps[i3, :]
return np.cross(v1, v2)
def _shade_colors(color, normals, lightsource=None):
"""
Shade *color* using normal vectors given by *normals*.
*color* can also be an array of the same length as *normals*.
"""
from matplotlib.colors import Normalize, LightSource
import matplotlib.colors as mcolors
if lightsource is None:
# chosen for backwards-compatibility
lightsource = LightSource(azdeg=225, altdeg=19.4712)
def mod(v):
return np.sqrt(v[0] ** 2 + v[1] ** 2 + v[2] ** 2)
shade = np.array(
[np.dot(n / mod(n), lightsource.direction) if mod(n) else np.nan for n in normals]
)
mask = ~np.isnan(shade)
if mask.any():
norm = Normalize(min(shade[mask]), max(shade[mask]))
shade[~mask] = min(shade[mask])
color = mcolors.to_rgba_array(color)
# shape of color should be (M, 4) (where M is number of faces)
# shape of shade should be (M,)
# colors should have final shape of (M, 4)
alpha = color[:, 3]
colors = (0.5 + norm(shade)[:, np.newaxis] * 0.5) * color
colors[:, 3] = alpha
else:
colors = np.asanyarray(color).copy()
return colors
def state_to_latex(
state: Union[Statevector, DensityMatrix], dims: bool = None, convention: str = "ket", **args
) -> str:
"""Return a Latex representation of a state. Wrapper function
for `qiskit.visualization.array_to_latex` for convention 'vector'.
Adds dims if necessary.
Intended for use within `state_drawer`.
Args:
state: State to be drawn
dims (bool): Whether to display the state's `dims`
convention (str): Either 'vector' or 'ket'. For 'ket' plot the state in the ket-notation.
Otherwise plot as a vector
**args: Arguments to be passed directly to `array_to_latex` for convention 'ket'
Returns:
Latex representation of the state
"""
if dims is None: # show dims if state is not only qubits
if set(state.dims()) == {2}:
dims = False
else:
dims = True
prefix = ""
suffix = ""
if dims:
prefix = "\\begin{align}\n"
dims_str = state._op_shape.dims_l()
suffix = f"\\\\\n\\text{{dims={dims_str}}}\n\\end{{align}}"
operator_shape = state._op_shape
# we only use the ket convetion for qubit statevectors
# this means the operator shape should hve no input dimensions and all output dimensions equal to 2
is_qubit_statevector = len(operator_shape.dims_r()) == 0 and set(operator_shape.dims_l()) == {2}
if convention == "ket" and is_qubit_statevector:
latex_str = _state_to_latex_ket(state._data, **args)
else:
latex_str = array_to_latex(state._data, source=True, **args)
return prefix + latex_str + suffix
@deprecate_func(
additional_msg="For similar functionality, see sympy's ``nsimplify`` and ``latex`` functions.",
since="0.23.0",
)
def num_to_latex_ket(raw_value: complex, first_term: bool, decimals: int = 10) -> Optional[str]:
"""Convert a complex number to latex code suitable for a ket expression
Args:
raw_value: Value to convert
first_term: If True then generate latex code for the first term in an expression
decimals: Number of decimal places to round to (default: 10).
Returns:
String with latex code or None if no term is required
"""
if np.around(np.abs(raw_value), decimals=decimals) == 0:
return None
return _num_to_latex(raw_value, first_term=first_term, decimals=decimals, coefficient=True)
@deprecate_func(
additional_msg="For similar functionality, see sympy's ``nsimplify`` and ``latex`` functions.",
since="0.23.0",
)
def numbers_to_latex_terms(numbers: List[complex], decimals: int = 10) -> List[str]:
"""Convert a list of numbers to latex formatted terms
The first non-zero term is treated differently. For this term a leading + is suppressed.
Args:
numbers: List of numbers to format
decimals: Number of decimal places to round to (default: 10).
Returns:
List of formatted terms
"""
first_term = True
terms = []
for number in numbers:
term = num_to_latex_ket(number, first_term, decimals)
if term is not None:
first_term = False
terms.append(term)
return terms
def _numbers_to_latex_terms(numbers: List[complex], decimals: int = 10) -> List[str]:
"""Convert a list of numbers to latex formatted terms
The first non-zero term is treated differently. For this term a leading + is suppressed.
Args:
numbers: List of numbers to format
decimals: Number of decimal places to round to (default: 10).
Returns:
List of formatted terms
"""
first_term = True
terms = []
for number in numbers:
term = _num_to_latex(number, decimals=decimals, first_term=first_term, coefficient=True)
terms.append(term)
first_term = False
return terms
def _state_to_latex_ket(
data: List[complex], max_size: int = 12, prefix: str = "", decimals: int = 10
) -> str:
"""Convert state vector to latex representation
Args:
data: State vector
max_size: Maximum number of non-zero terms in the expression. If the number of
non-zero terms is larger than the max_size, then the representation is truncated.
prefix: Latex string to be prepended to the latex, intended for labels.
decimals: Number of decimal places to round to (default: 10).
Returns:
String with LaTeX representation of the state vector
"""
num = int(np.log2(len(data)))
def ket_name(i):
return bin(i)[2:].zfill(num)
data = np.around(data, decimals)
nonzero_indices = np.where(data != 0)[0].tolist()
if len(nonzero_indices) > max_size:
nonzero_indices = (
nonzero_indices[: max_size // 2] + [0] + nonzero_indices[-max_size // 2 + 1 :]
)
latex_terms = _numbers_to_latex_terms(data[nonzero_indices], decimals)
nonzero_indices[max_size // 2] = None
else:
latex_terms = _numbers_to_latex_terms(data[nonzero_indices], decimals)
latex_str = ""
for idx, ket_idx in enumerate(nonzero_indices):
if ket_idx is None:
latex_str += r" + \ldots "
else:
term = latex_terms[idx]
ket = ket_name(ket_idx)
latex_str += f"{term} |{ket}\\rangle"
return prefix + latex_str
class TextMatrix:
"""Text representation of an array, with `__str__` method so it
displays nicely in Jupyter notebooks"""
def __init__(self, state, max_size=8, dims=None, prefix="", suffix=""):
self.state = state
self.max_size = max_size
if dims is None: # show dims if state is not only qubits
if (isinstance(state, (Statevector, DensityMatrix)) and set(state.dims()) == {2}) or (
isinstance(state, Operator)
and len(state.input_dims()) == len(state.output_dims())
and set(state.input_dims()) == set(state.output_dims()) == {2}
):
dims = False
else:
dims = True
self.dims = dims
self.prefix = prefix
self.suffix = suffix
if isinstance(max_size, int):
self.max_size = max_size
elif isinstance(state, DensityMatrix):
# density matrices are square, so threshold for
# summarization is shortest side squared
self.max_size = min(max_size) ** 2
else:
self.max_size = max_size[0]
def __str__(self):
threshold = self.max_size
data = np.array2string(
self.state._data, prefix=self.prefix, threshold=threshold, separator=","
)
dimstr = ""
if self.dims:
data += ",\n"
dimstr += " " * len(self.prefix)
if isinstance(self.state, (Statevector, DensityMatrix)):
dimstr += f"dims={self.state._op_shape.dims_l()}"
else:
dimstr += f"input_dims={self.state.input_dims()}, "
dimstr += f"output_dims={self.state.output_dims()}"
return self.prefix + data + dimstr + self.suffix
def __repr__(self):
return self.__str__()
def state_drawer(state, output=None, **drawer_args):
"""Returns a visualization of the state.
**repr**: ASCII TextMatrix of the state's ``_repr_``.
**text**: ASCII TextMatrix that can be printed in the console.
**latex**: An IPython Latex object for displaying in Jupyter Notebooks.
**latex_source**: Raw, uncompiled ASCII source to generate array using LaTeX.
**qsphere**: Matplotlib figure, rendering of statevector using `plot_state_qsphere()`.
**hinton**: Matplotlib figure, rendering of statevector using `plot_state_hinton()`.
**bloch**: Matplotlib figure, rendering of statevector using `plot_bloch_multivector()`.
**city**: Matplotlib figure, rendering of statevector using `plot_state_city()`.
**paulivec**: Matplotlib figure, rendering of statevector using `plot_state_paulivec()`.
Args:
output (str): Select the output method to use for drawing the
circuit. Valid choices are ``text``, ``latex``, ``latex_source``,
``qsphere``, ``hinton``, ``bloch``, ``city`` or ``paulivec``.
Default is `'text`'.
drawer_args: Arguments to be passed to the relevant drawer. For
'latex' and 'latex_source' see ``array_to_latex``
Returns:
:class:`matplotlib.figure` or :class:`str` or
:class:`TextMatrix` or :class:`IPython.display.Latex`:
Drawing of the state.
Raises:
MissingOptionalLibraryError: when `output` is `latex` and IPython is not installed.
ValueError: when `output` is not a valid selection.
"""
config = user_config.get_config()
# Get default 'output' from config file else use 'repr'
default_output = "repr"
if output is None:
if config:
default_output = config.get("state_drawer", "repr")
output = default_output
output = output.lower()
# Choose drawing backend:
drawers = {
"text": TextMatrix,
"latex_source": state_to_latex,
"qsphere": plot_state_qsphere,
"hinton": plot_state_hinton,
"bloch": plot_bloch_multivector,
"city": plot_state_city,
"paulivec": plot_state_paulivec,
}
if output == "latex":
_optionals.HAS_IPYTHON.require_now("state_drawer")
from IPython.display import Latex
draw_func = drawers["latex_source"]
return Latex(f"$${draw_func(state, **drawer_args)}$$")
if output == "repr":
return state.__repr__()
try:
draw_func = drawers[output]
return draw_func(state, **drawer_args)
except KeyError as err:
raise ValueError(
"""'{}' is not a valid option for drawing {} objects. Please choose from:
'text', 'latex', 'latex_source', 'qsphere', 'hinton',
'bloch', 'city' or 'paulivec'.""".format(
output, type(state).__name__
)
) from err
def _bloch_multivector_data(state):
"""Return list of Bloch vectors for each qubit
Args:
state (DensityMatrix or Statevector): an N-qubit state.
Returns:
list: list of Bloch vectors (x, y, z) for each qubit.
Raises:
VisualizationError: if input is not an N-qubit state.
"""
rho = DensityMatrix(state)
num = rho.num_qubits
if num is None:
raise VisualizationError("Input is not a multi-qubit quantum state.")
pauli_singles = PauliList(["X", "Y", "Z"])
bloch_data = []
for i in range(num):
if num > 1:
paulis = PauliList.from_symplectic(
np.zeros((3, (num - 1)), dtype=bool), np.zeros((3, (num - 1)), dtype=bool)
).insert(i, pauli_singles, qubit=True)
else:
paulis = pauli_singles
bloch_state = [np.real(np.trace(np.dot(mat, rho.data))) for mat in paulis.matrix_iter()]
bloch_data.append(bloch_state)
return bloch_data
def _paulivec_data(state):
"""Return paulivec data for plotting.
Args:
state (DensityMatrix or Statevector): an N-qubit state.
Returns:
tuple: (labels, values) for Pauli vector.
Raises:
VisualizationError: if input is not an N-qubit state.
"""
rho = SparsePauliOp.from_operator(DensityMatrix(state))
if rho.num_qubits is None:
raise VisualizationError("Input is not a multi-qubit quantum state.")
return rho.paulis.to_labels(), np.real(rho.coeffs * 2**rho.num_qubits)
|
https://github.com/18520339/uts-quantum-computing
|
18520339
|
from qiskit import QuantumCircuit, transpile, assemble
from qiskit.circuit.library import QFT
class CtrlMultCircuit(QuantumCircuit):
def __init__(self, a, binary_power, N):
super().__init__(N.bit_length())
self.a = a
self.power = 2 ** binary_power # Convert binary to decimal
self.N = N
self.name = f'{self.a}^{self.power} mod {self.N}'
self._create_circuit()
def _create_circuit(self):
for dec_power in range(self.power):
a_exp = self.a ** dec_power % self.N
for i in range(self.num_qubits):
if a_exp >> i & 1: self.x(i)
for j in range(i + 1, self.num_qubits):
if a_exp >> j & 1: self.swap(i, j)
class QPECircuit(QuantumCircuit):
def __init__(self, a, N):
super().__init__(2 * N.bit_length(), N.bit_length())
self.a = a
self.N = N
self._create_circuit()
def _modular_exponentiation(self):
for qbit_idx in range(self.num_qubits // 2):
self.append(
CtrlMultCircuit(self.a, qbit_idx, self.N).to_gate().control(),
[qbit_idx] + list(range(self.num_qubits // 2, 2 * self.num_qubits // 2))
)
def _create_circuit(self):
self.h(range(self.num_qubits // 2)) # Apply Hadamard gates to the first n qubits
self.x(self.num_qubits - 1)
self.barrier()
self._modular_exponentiation() # Apply controlled modular exponentiation
self.barrier()
self.append(
QFT(self.num_qubits // 2, inverse=True),
range(self.num_qubits // 2) # Apply inverse QFT to the first n qubits
)
def collapse(self, simulator):
self.measure(range(self.num_qubits // 2), range(self.num_qubits // 2))
transpiled_circuit = transpile(self, simulator)
self.collapse_result = simulator.run(transpiled_circuit, memory=True).result()
return self.collapse_result
|
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/Glebegor/Quantum-programming-algorithms
|
Glebegor
|
import numpy as np
import networkx as nx
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble
from qiskit.quantum_info import Statevector
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.visualization import plot_histogram
from qiskit.providers.aer.extensions.snapshot_statevector import *
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
import matplotlib.pyplot as plt
LAMBDA = 10
SEED = 10
SHOTS = 10000
# returns the bit index for an alpha and j
def bit(i_city, l_time, num_cities):
return i_city * num_cities + l_time
# e^(cZZ)
def append_zz_term(qc, q_i, q_j, gamma, constant_term):
qc.cx(q_i, q_j)
qc.rz(2*gamma*constant_term,q_j)
qc.cx(q_i, q_j)
# e^(cZ)
def append_z_term(qc, q_i, gamma, constant_term):
qc.rz(2*gamma*constant_term, q_i)
# e^(cX)
def append_x_term(qc,qi,beta):
qc.rx(-2*beta, qi)
def get_not_edge_in(G):
N = G.number_of_nodes()
not_edge = []
for i in range(N):
for j in range(N):
if i != j:
buffer_tupla = (i,j)
in_edges = False
for edge_i, edge_j in G.edges():
if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)):
in_edges = True
if in_edges == False:
not_edge.append((i, j))
return not_edge
def get_classical_simplified_z_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# z term #
z_classic_term = [0] * N**2
# first term
for l in range(N):
for i in range(N):
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += -1 * _lambda
# second term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_jl
z_jl_index = bit(j, l, N)
z_classic_term[z_jl_index] += _lambda / 2
# third term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_ij
z_ij_index = bit(i, j, N)
z_classic_term[z_ij_index] += _lambda / 2
# fourth term
not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 4
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
z_classic_term[z_jlplus_index] += _lambda / 4
# fifthy term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
z_classic_term[z_il_index] += weight_ij / 4
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
z_classic_term[z_il_index] += weight_ji / 4
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ji / 4
return z_classic_term
def tsp_obj_2(x, G,_lambda):
# obtenemos el valor evaluado en f(x_1, x_2,... x_n)
not_edge = get_not_edge_in(G)
N = G.number_of_nodes()
tsp_cost=0
#Distancia
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# x_il
x_il_index = bit(edge_i, l, N)
# x_jlplus
l_plus = (l+1) % N
x_jlplus_index = bit(edge_j, l_plus, N)
tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij
# add order term because G.edges() do not include order tuples #
# x_i'l
x_il_index = bit(edge_j, l, N)
# x_j'lplus
x_jlplus_index = bit(edge_i, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji
#Constraint 1
for l in range(N):
penal1 = 1
for i in range(N):
x_il_index = bit(i, l, N)
penal1 -= int(x[x_il_index])
tsp_cost += _lambda * penal1**2
#Contstraint 2
for i in range(N):
penal2 = 1
for l in range(N):
x_il_index = bit(i, l, N)
penal2 -= int(x[x_il_index])
tsp_cost += _lambda*penal2**2
#Constraint 3
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# x_il
x_il_index = bit(i, l, N)
# x_j(l+1)
l_plus = (l+1) % N
x_jlplus_index = bit(j, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda
return tsp_cost
def get_classical_simplified_zz_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# zz term #
zz_classic_term = [[0] * N**2 for i in range(N**2) ]
# first term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
# z_jl
z_jl_index = bit(j, l, N)
zz_classic_term[z_il_index][z_jl_index] += _lambda / 2
# second term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
# z_ij
z_ij_index = bit(i, j, N)
zz_classic_term[z_il_index][z_ij_index] += _lambda / 2
# third term
not_edge = get_not_edge_in(G)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4
# fourth term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4
return zz_classic_term
def get_classical_simplified_hamiltonian(G, _lambda):
# z term #
z_classic_term = get_classical_simplified_z_term(G, _lambda)
# zz term #
zz_classic_term = get_classical_simplified_zz_term(G, _lambda)
return z_classic_term, zz_classic_term
def get_cost_circuit(G, gamma, _lambda):
N = G.number_of_nodes()
N_square = N**2
qc = QuantumCircuit(N_square,N_square)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda)
# z term
for i in range(N_square):
if z_classic_term[i] != 0:
append_z_term(qc, i, gamma, z_classic_term[i])
# zz term
for i in range(N_square):
for j in range(N_square):
if zz_classic_term[i][j] != 0:
append_zz_term(qc, i, j, gamma, zz_classic_term[i][j])
return qc
def get_mixer_operator(G,beta):
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
for n in range(N**2):
append_x_term(qc, n, beta)
return qc
def get_QAOA_circuit(G, beta, gamma, _lambda):
assert(len(beta)==len(gamma))
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
# init min mix state
qc.h(range(N**2))
p = len(beta)
for i in range(p):
qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda))
qc = qc.compose(get_mixer_operator(G, beta[i]))
qc.barrier(range(N**2))
qc.snapshot_statevector("final_state")
qc.measure(range(N**2),range(N**2))
return qc
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
# Sample expectation value
def compute_tsp_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj_2(meas, G, LAMBDA)
energy += obj_for_meas*meas_count
total_counts += meas_count
mean = energy/total_counts
return mean
def get_black_box_objective_2(G,p):
backend = Aer.get_backend('qasm_simulator')
sim = Aer.get_backend('aer_simulator')
# function f costo
def f(theta):
beta = theta[:p]
gamma = theta[p:]
# Anzats
qc = get_QAOA_circuit(G, beta, gamma, LAMBDA)
result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result()
final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0]
state_vector = Statevector(final_state_vector)
probabilities = state_vector.probabilities()
probabilities_states = invert_counts(state_vector.probabilities_dict())
expected_value = 0
for state,probability in probabilities_states.items():
cost = tsp_obj_2(state, G, LAMBDA)
expected_value += cost*probability
counts = result.get_counts()
mean = compute_tsp_energy_2(invert_counts(counts),G)
return mean
return f
def crear_grafo(cantidad_ciudades):
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
return G, mejor_costo, mejor_camino
def run_QAOA(p,ciudades, grafo):
if grafo == None:
G, mejor_costo, mejor_camino = crear_grafo(ciudades)
print("Mejor Costo")
print(mejor_costo)
print("Mejor Camino")
print(mejor_camino)
print("Bordes del grafo")
print(G.edges())
print("Nodos")
print(G.nodes())
print("Pesos")
labels = nx.get_edge_attributes(G,'weight')
print(labels)
else:
G = grafo
intial_random = []
# beta, mixer Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,np.pi))
# gamma, cost Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,2*np.pi))
init_point = np.array(intial_random)
obj = get_black_box_objective_2(G,p)
res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
print(res_sample)
if __name__ == '__main__':
# Run QAOA parametros: profundidad p, numero d ciudades,
run_QAOA(5, 3, None)
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2024 IBM. All Rights Reserved.
#
# 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.
"""Unit-testing linear_function_ai"""
import pytest
from qiskit import QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit_transpiler_service.ai.collection import CollectLinearFunctions
from qiskit_transpiler_service.ai.synthesis import AILinearFunctionSynthesis
def test_linear_function_pass(random_circuit_transpiled, backend, caplog):
ai_optimize_lf = PassManager(
[
CollectLinearFunctions(),
AILinearFunctionSynthesis(backend_name=backend),
]
)
ai_optimized_circuit = ai_optimize_lf.run(random_circuit_transpiled)
assert isinstance(ai_optimized_circuit, QuantumCircuit)
def test_linear_function_wrong_backend(caplog):
circuit = QuantumCircuit(10)
for i in range(8):
circuit.cx(i, i + 1)
for i in range(8):
circuit.h(i)
for i in range(8):
circuit.cx(i, i + 1)
ai_optimize_lf = PassManager(
[
CollectLinearFunctions(),
AILinearFunctionSynthesis(backend_name="a_wrong_backend"),
]
)
ai_optimized_circuit = ai_optimize_lf.run(circuit)
assert "couldn't synthesize the circuit" in caplog.text
assert "Keeping the original circuit" in caplog.text
assert isinstance(ai_optimized_circuit, QuantumCircuit)
def test_linear_always_replace(backend, caplog):
orig_qc = QuantumCircuit(3)
orig_qc.cx(0, 1)
orig_qc.cx(1, 2)
ai_optimize_lf = PassManager(
[
CollectLinearFunctions(),
AILinearFunctionSynthesis(
backend_name=backend, replace_only_if_better=False
),
]
)
ai_optimized_circuit = ai_optimize_lf.run(orig_qc)
assert "Keeping the original circuit" not in caplog.text
assert isinstance(ai_optimized_circuit, QuantumCircuit)
def test_linear_function_only_replace_if_better(backend, caplog):
orig_qc = QuantumCircuit(3)
orig_qc.cx(0, 1)
orig_qc.cx(1, 2)
ai_optimize_lf = PassManager(
[
CollectLinearFunctions(min_block_size=2),
AILinearFunctionSynthesis(backend_name=backend),
]
)
ai_optimized_circuit = ai_optimize_lf.run(orig_qc)
assert ai_optimized_circuit == orig_qc
assert "Keeping the original circuit" in caplog.text
assert isinstance(ai_optimized_circuit, QuantumCircuit)
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
import numpy as np
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.converters import QuadraticProgramToQubo
import dimod
qp = QuadraticProgram("Example")
n = 3
for j in range(n):
qp.binary_var('x' + "_" + str(j))
linear_objective = np.array([-1,0,-1])
Q = np.array([[-2,0,1],
[0,2,-2],
[1,-2,0]]) / 2
quadratic_objective = {}
for i in range(n):
for j in range(i, n):
var_i = 'x' + "_" + str(i)
if i == j:
quadratic_objective[var_i, var_i] = Q[i, i]
else:
var_j = 'x' + "_" + str(j)
quadratic_objective[var_i, var_j] = Q[i, j] + Q[j, i]
qp.linear_constraint(linear=np.array([0,1,-1]), sense='==', rhs=0,
name='linear_cstr')
qp.minimize(linear=linear_objective, quadratic=quadratic_objective)
print(qp)
conv = QuadraticProgramToQubo()
qubo = conv.convert(qp)
print(f"Auto calculated {conv.penalty=}")
print(qubo)
bqm_binary = dimod.as_bqm(qubo.objective.linear.to_array(), qubo.objective.quadratic.to_array(), dimod.BINARY)
print(bqm_binary)
bqm_ising = bqm_binary.to_ising()
print("Ising Model form coefficients:")
print(bqm_ising)
|
https://github.com/JanLahmann/RasQberry
|
JanLahmann
|
# https://raspberrypi.stackexchange.com/questions/85109/run-rpi-ws281x-without-sudo
# https://github.com/joosteto/ws2812-spi
# start with python3 RasQ-LED.py
import subprocess, time, math
from dotenv import dotenv_values
config = dotenv_values("/home/pi/RasQberry/rasqberry_environment.env")
n_qbit = int(config["N_QUBIT"])
LED_COUNT = int(config["LED_COUNT"])
LED_PIN = int(config["LED_PIN"])
#Import Qiskit classes
from qiskit import IBMQ, execute
from qiskit import Aer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
# set the backend
backend = Aer.get_backend('qasm_simulator')
#Set number of shots
shots = 1
def init_circuit():
# Create a Quantum Register with n qubits
global qr
qr = QuantumRegister(n_qbit)
# Create a Classical Register with n bits
global cr
cr = ClassicalRegister(n_qbit)
# Create a Quantum Circuit acting on the qr and cr register
global circuit
circuit = QuantumCircuit(qr, cr)
global counts
counts = {}
global measurement
measurement = ""
def set_up_circuit(factor):
global circuit
circuit = QuantumCircuit(qr, cr)
if factor == 0:
factor = n_qbit
# relevant qubits are the first qubits in each subgroup
relevant_qbit = 0
for i in range(0, n_qbit):
if (i % factor) == 0:
circuit.h(qr[i])
relevant_qbit = i
else:
circuit.cx(qr[relevant_qbit], qr[i])
circuit.measure(qr, cr)
def get_factors(number):
factor_list = []
# search for factors, including factor 1 and n_qbit itself
for i in range(1, math.ceil(number / 2) + 1):
if number % i == 0:
factor_list.append(i)
factor_list.append(n_qbit)
return factor_list
def circ_execute():
# execute the circuit
job = execute(circuit, backend, shots=shots)
result = job.result()
counts = result.get_counts(circuit)
global measurement
measurement = list(counts.items())[0][0]
print("measurement: ", measurement)
# alternative with statevector_simulator
# simulator = Aer.get_backend('statevector_simulator')
# result = execute(circuit, simulator).result()
# statevector = result.get_statevector(circuit)
# bin(statevector.tolist().index(1.+0.j))[2:]
def call_display_on_strip(measurement):
subprocess.call(["sudo","python3","/home/pi/RasQberry/demos/bin/RasQ-LED-display.py", measurement])
# n is the size of the entangled blocks
def run_circ(n):
init_circuit()
if n == 1:
print("build circuit without entanglement")
set_up_circuit(1)
elif n == 0 or n == n_qbit:
print("build circuit with complete entanglement")
set_up_circuit(n_qbit)
else:
print("build circuit with entangled blocks of size " + str(n))
set_up_circuit(n)
circ_execute()
call_display_on_strip(measurement)
def action():
while True:
#print(menu)
player_action = input("select circuit to execute (1/2/3/q) ")
if player_action == '1':
run_circ(1)
elif player_action == '2':
run_circ(n_qbit)
elif player_action == "3":
factors = get_factors(n_qbit)
for factor in factors:
run_circ(factor)
time.sleep(3)
elif player_action == 'q':
subprocess.call(["sudo","python3","/home/pi/RasQberry/demos/bin/RasQ-LED-display.py", "0", "-c"])
quit()
else:
print("Please type \'1\', \'2\', \'3\' or \'q\'")
def loop(duration):
print()
print("RasQ-LED creates groups of entangled Qubits and displays the measurment result using colors of the LEDs.")
print("A H(adamard) gate is applied to the first Qubit of each group; then CNOT gates to create entanglement of the whole group.")
print("The size of the groups starts with 1, then in steps up to all Qubits.")
print()
for i in range(duration):
factors = get_factors(n_qbit)
for factor in factors:
run_circ(factor)
time.sleep(3)
subprocess.call(["sudo","python3","/home/pi/RasQberry/demos/bin/RasQ-LED-display.py", "0", "-c"])
loop(5)
#action()
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# 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.
"""Assembler Test."""
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import pulse
from qiskit.compiler.assembler import assemble
from qiskit.assembler.disassemble import disassemble
from qiskit.assembler.run_config import RunConfig
from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Gate, Instruction, Parameter
from qiskit.circuit.library import RXGate
from qiskit.pulse.transforms import target_qobj_transform
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeOpenPulse2Q
import qiskit.quantum_info as qi
def _parametric_to_waveforms(schedule):
instructions = list(schedule.instructions)
for i, time_instruction_tuple in enumerate(schedule.instructions):
time, instruction = time_instruction_tuple
if not isinstance(instruction.pulse, pulse.library.Waveform):
new_inst = pulse.Play(instruction.pulse.get_waveform(), instruction.channel)
instructions[i] = (time, new_inst)
return tuple(instructions)
class TestQuantumCircuitDisassembler(QiskitTestCase):
"""Tests for disassembling circuits to qobj."""
def test_disassemble_single_circuit(self):
"""Test disassembling a single circuit."""
qr = QuantumRegister(2, name="q")
cr = ClassicalRegister(2, name="c")
circ = QuantumCircuit(qr, cr, name="circ")
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.measure(qr, cr)
qubit_lo_freq = [5e9, 5e9]
meas_lo_freq = [6.7e9, 6.7e9]
qobj = assemble(
circ,
shots=2000,
memory=True,
qubit_lo_freq=qubit_lo_freq,
meas_lo_freq=meas_lo_freq,
)
circuits, run_config_out, headers = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 2)
self.assertEqual(run_config_out.shots, 2000)
self.assertEqual(run_config_out.memory, True)
self.assertEqual(run_config_out.qubit_lo_freq, qubit_lo_freq)
self.assertEqual(run_config_out.meas_lo_freq, meas_lo_freq)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], circ)
self.assertEqual({}, headers)
def test_disassemble_multiple_circuits(self):
"""Test disassembling multiple circuits, all should have the same config."""
qr0 = QuantumRegister(2, name="q0")
qc0 = ClassicalRegister(2, name="c0")
circ0 = QuantumCircuit(qr0, qc0, name="circ0")
circ0.h(qr0[0])
circ0.cx(qr0[0], qr0[1])
circ0.measure(qr0, qc0)
qr1 = QuantumRegister(3, name="q1")
qc1 = ClassicalRegister(3, name="c1")
circ1 = QuantumCircuit(qr1, qc1, name="circ0")
circ1.h(qr1[0])
circ1.cx(qr1[0], qr1[1])
circ1.cx(qr1[0], qr1[2])
circ1.measure(qr1, qc1)
qobj = assemble([circ0, circ1], shots=100, memory=False, seed=6)
circuits, run_config_out, headers = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 3)
self.assertEqual(run_config_out.memory_slots, 3)
self.assertEqual(run_config_out.shots, 100)
self.assertEqual(run_config_out.memory, False)
self.assertEqual(run_config_out.seed, 6)
self.assertEqual(len(circuits), 2)
for circuit in circuits:
self.assertIn(circuit, [circ0, circ1])
self.assertEqual({}, headers)
def test_disassemble_no_run_config(self):
"""Test disassembling with no run_config, relying on default."""
qr = QuantumRegister(2, name="q")
qc = ClassicalRegister(2, name="c")
circ = QuantumCircuit(qr, qc, name="circ")
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.measure(qr, qc)
qobj = assemble(circ)
circuits, run_config_out, headers = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 2)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], circ)
self.assertEqual({}, headers)
def test_disassemble_initialize(self):
"""Test disassembling a circuit with an initialize."""
q = QuantumRegister(2, name="q")
circ = QuantumCircuit(q, name="circ")
circ.initialize([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)], q[:])
qobj = assemble(circ)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 0)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], circ)
self.assertEqual({}, header)
def test_disassemble_isometry(self):
"""Test disassembling a circuit with an isometry."""
q = QuantumRegister(2, name="q")
circ = QuantumCircuit(q, name="circ")
circ.iso(qi.random_unitary(4).data, circ.qubits, [])
qobj = assemble(circ)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 0)
self.assertEqual(len(circuits), 1)
# params array
assert_allclose(circuits[0]._data[0].operation.params[0], circ._data[0].operation.params[0])
# all other data
self.assertEqual(
circuits[0]._data[0].operation.params[1:], circ._data[0].operation.params[1:]
)
self.assertEqual(circuits[0]._data[0].qubits, circ._data[0].qubits)
self.assertEqual(circuits[0]._data[0].clbits, circ._data[0].clbits)
self.assertEqual(circuits[0]._data[1:], circ._data[1:])
self.assertEqual({}, header)
def test_opaque_instruction(self):
"""Test the disassembler handles opaque instructions correctly."""
opaque_inst = Instruction(name="my_inst", num_qubits=4, num_clbits=2, params=[0.5, 0.4])
q = QuantumRegister(6, name="q")
c = ClassicalRegister(4, name="c")
circ = QuantumCircuit(q, c, name="circ")
circ.append(opaque_inst, [q[0], q[2], q[5], q[3]], [c[3], c[0]])
qobj = assemble(circ)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 6)
self.assertEqual(run_config_out.memory_slots, 4)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], circ)
self.assertEqual({}, header)
def test_circuit_with_conditionals(self):
"""Verify disassemble sets conditionals correctly."""
qr = QuantumRegister(2)
cr1 = ClassicalRegister(1)
cr2 = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr1, cr2)
qc.measure(qr[0], cr1) # Measure not required for a later conditional
qc.measure(qr[1], cr2[1]) # Measure required for a later conditional
qc.h(qr[1]).c_if(cr2, 3)
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 3)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def test_circuit_with_simple_conditional(self):
"""Verify disassemble handles a simple conditional on the only bits."""
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0]).c_if(cr, 1)
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 1)
self.assertEqual(run_config_out.memory_slots, 1)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def test_circuit_with_single_bit_conditions(self):
"""Verify disassemble handles a simple conditional on a single bit of a register."""
# This circuit would fail to perfectly round-trip if 'cr' below had only one bit in it.
# This is because the format of QasmQobj is insufficient to disambiguate single-bit
# conditions from conditions on registers with only one bit. Since single-bit conditions are
# mostly a hack for the QasmQobj format at all, `disassemble` always prefers to return the
# register if it can. It would also fail if registers overlap.
qr = QuantumRegister(1)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0]).c_if(cr[0], 1)
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, len(qr))
self.assertEqual(run_config_out.memory_slots, len(cr))
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def test_circuit_with_mcx(self):
"""Verify disassemble handles mcx gate - #6271."""
qr = QuantumRegister(5)
cr = ClassicalRegister(5)
qc = QuantumCircuit(qr, cr)
qc.mcx([0, 1, 2], 4)
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 5)
self.assertEqual(run_config_out.memory_slots, 5)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def test_multiple_conditionals_multiple_registers(self):
"""Verify disassemble handles multiple conditionals and registers."""
qr = QuantumRegister(3)
cr1 = ClassicalRegister(3)
cr2 = ClassicalRegister(5)
cr3 = ClassicalRegister(6)
cr4 = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr1, cr2, cr3, cr4)
qc.x(qr[1])
qc.h(qr)
qc.cx(qr[1], qr[0]).c_if(cr3, 14)
qc.ccx(qr[0], qr[2], qr[1]).c_if(cr4, 1)
qc.h(qr).c_if(cr1, 3)
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 3)
self.assertEqual(run_config_out.memory_slots, 15)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def test_circuit_with_bit_conditional_1(self):
"""Verify disassemble handles conditional on a single bit."""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0]).c_if(cr[1], True)
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 2)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def test_circuit_with_bit_conditional_2(self):
"""Verify disassemble handles multiple single bit conditionals."""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
cr1 = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr, cr1)
qc.h(qr[0]).c_if(cr1[1], False)
qc.h(qr[1]).c_if(cr[0], True)
qc.cx(qr[0], qr[1]).c_if(cr1[0], False)
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 4)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def assertCircuitCalibrationsEqual(self, in_circuits, out_circuits):
"""Verify circuit calibrations are equivalent pre-assembly and post-disassembly"""
self.assertEqual(len(in_circuits), len(out_circuits))
for in_qc, out_qc in zip(in_circuits, out_circuits):
in_cals = in_qc.calibrations
out_cals = out_qc.calibrations
self.assertEqual(in_cals.keys(), out_cals.keys())
for gate_name in in_cals:
self.assertEqual(in_cals[gate_name].keys(), out_cals[gate_name].keys())
for gate_params, in_sched in in_cals[gate_name].items():
out_sched = out_cals[gate_name][gate_params]
self.assertEqual(*map(_parametric_to_waveforms, (in_sched, out_sched)))
def test_single_circuit_calibrations(self):
"""Test that disassembler parses single circuit QOBJ calibrations (from QOBJ-level)."""
theta = Parameter("theta")
qc = QuantumCircuit(2)
qc.h(0)
qc.rx(np.pi, 0)
qc.rx(theta, 1)
qc = qc.assign_parameters({theta: np.pi})
with pulse.build() as h_sched:
pulse.play(pulse.library.Drag(1, 0.15, 4, 2), pulse.DriveChannel(0))
with pulse.build() as x180:
pulse.play(pulse.library.Gaussian(1, 0.2, 5), pulse.DriveChannel(0))
qc.add_calibration("h", [0], h_sched)
qc.add_calibration(RXGate(np.pi), [0], x180)
qobj = assemble(qc, FakeOpenPulse2Q())
output_circuits, _, _ = disassemble(qobj)
self.assertCircuitCalibrationsEqual([qc], output_circuits)
def test_parametric_pulse_circuit_calibrations(self):
"""Test that disassembler parses parametric pulses back to pulse gates."""
with pulse.build() as h_sched:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
qc = QuantumCircuit(2)
qc.h(0)
qc.add_calibration("h", [0], h_sched)
backend = FakeOpenPulse2Q()
backend.configuration().parametric_pulses = ["drag"]
qobj = assemble(qc, backend)
output_circuits, _, _ = disassemble(qobj)
out_qc = output_circuits[0]
self.assertCircuitCalibrationsEqual([qc], output_circuits)
self.assertTrue(
all(
qc_sched.instructions == out_qc_sched.instructions
for (_, qc_gate), (_, out_qc_gate) in zip(
qc.calibrations.items(), out_qc.calibrations.items()
)
for qc_sched, out_qc_sched in zip(qc_gate.values(), out_qc_gate.values())
),
)
def test_multi_circuit_uncommon_calibrations(self):
"""Test that disassembler parses uncommon calibrations (stored at QOBJ experiment-level)."""
with pulse.build() as sched:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
qc_0 = QuantumCircuit(2)
qc_0.h(0)
qc_0.append(RXGate(np.pi), [1])
qc_0.add_calibration("h", [0], sched)
qc_0.add_calibration(RXGate(np.pi), [1], sched)
qc_1 = QuantumCircuit(2)
qc_1.h(0)
circuits = [qc_0, qc_1]
qobj = assemble(circuits, FakeOpenPulse2Q())
output_circuits, _, _ = disassemble(qobj)
self.assertCircuitCalibrationsEqual(circuits, output_circuits)
def test_multi_circuit_common_calibrations(self):
"""Test that disassembler parses common calibrations (stored at QOBJ-level)."""
with pulse.build() as sched:
pulse.play(pulse.library.Drag(1, 0.15, 4, 2), pulse.DriveChannel(0))
qc_0 = QuantumCircuit(2)
qc_0.h(0)
qc_0.append(RXGate(np.pi), [1])
qc_0.add_calibration("h", [0], sched)
qc_0.add_calibration(RXGate(np.pi), [1], sched)
qc_1 = QuantumCircuit(2)
qc_1.h(0)
qc_1.add_calibration(RXGate(np.pi), [1], sched)
circuits = [qc_0, qc_1]
qobj = assemble(circuits, FakeOpenPulse2Q())
output_circuits, _, _ = disassemble(qobj)
self.assertCircuitCalibrationsEqual(circuits, output_circuits)
def test_single_circuit_delay_calibrations(self):
"""Test that disassembler parses delay instruction back to delay gate."""
qc = QuantumCircuit(2)
qc.append(Gate("test", 1, []), [0])
test_sched = pulse.Delay(64, pulse.DriveChannel(0)) + pulse.Delay(
160, pulse.DriveChannel(0)
)
qc.add_calibration("test", [0], test_sched)
qobj = assemble(qc, FakeOpenPulse2Q())
output_circuits, _, _ = disassemble(qobj)
self.assertEqual(len(qc.calibrations), len(output_circuits[0].calibrations))
self.assertEqual(qc.calibrations.keys(), output_circuits[0].calibrations.keys())
self.assertTrue(
all(
qc_cal.keys() == out_qc_cal.keys()
for qc_cal, out_qc_cal in zip(
qc.calibrations.values(), output_circuits[0].calibrations.values()
)
)
)
self.assertEqual(
qc.calibrations["test"][((0,), ())], output_circuits[0].calibrations["test"][((0,), ())]
)
class TestPulseScheduleDisassembler(QiskitTestCase):
"""Tests for disassembling pulse schedules to qobj."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.backend_config = self.backend.configuration()
self.backend_config.parametric_pulses = ["constant", "gaussian", "gaussian_square", "drag"]
def test_disassemble_single_schedule(self):
"""Test disassembling a single schedule."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build(self.backend) as sched:
with pulse.align_right():
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.set_phase(1.0, d0)
pulse.shift_phase(3.11, d0)
pulse.set_frequency(1e9, d0)
pulse.shift_frequency(1e7, d0)
pulse.delay(20, d0)
pulse.delay(10, d1)
pulse.play(pulse.library.Constant(8, 0.1), d1)
pulse.measure_all()
qobj = assemble(sched, backend=self.backend, shots=2000)
scheds, run_config_out, _ = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.memory_slots, 2)
self.assertEqual(run_config_out.shots, 2000)
self.assertEqual(run_config_out.memory, False)
self.assertEqual(run_config_out.meas_level, 2)
self.assertEqual(run_config_out.meas_lo_freq, self.backend.defaults().meas_freq_est)
self.assertEqual(run_config_out.qubit_lo_freq, self.backend.defaults().qubit_freq_est)
self.assertEqual(run_config_out.rep_time, 99)
self.assertEqual(len(scheds), 1)
self.assertEqual(scheds[0], target_qobj_transform(sched))
def test_disassemble_multiple_schedules(self):
"""Test disassembling multiple schedules, all should have the same config."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build(self.backend) as sched0:
with pulse.align_right():
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.set_phase(1.0, d0)
pulse.shift_phase(3.11, d0)
pulse.set_frequency(1e9, d0)
pulse.shift_frequency(1e7, d0)
pulse.delay(20, d0)
pulse.delay(10, d1)
pulse.play(pulse.library.Constant(8, 0.1), d1)
pulse.measure_all()
with pulse.build(self.backend) as sched1:
with pulse.align_right():
pulse.play(pulse.library.Constant(8, 0.1), d0)
pulse.play(pulse.library.Waveform([0.0, 1.0]), d1)
pulse.set_phase(1.1, d0)
pulse.shift_phase(3.5, d0)
pulse.set_frequency(2e9, d0)
pulse.shift_frequency(3e7, d1)
pulse.delay(20, d1)
pulse.delay(10, d0)
pulse.play(pulse.library.Constant(8, 0.4), d1)
pulse.measure_all()
qobj = assemble([sched0, sched1], backend=self.backend, shots=2000)
scheds, run_config_out, _ = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.memory_slots, 2)
self.assertEqual(run_config_out.shots, 2000)
self.assertEqual(run_config_out.memory, False)
self.assertEqual(len(scheds), 2)
self.assertEqual(scheds[0], target_qobj_transform(sched0))
self.assertEqual(scheds[1], target_qobj_transform(sched1))
def test_disassemble_parametric_pulses(self):
"""Test disassembling multiple schedules all should have the same config."""
d0 = pulse.DriveChannel(0)
with pulse.build(self.backend) as sched:
with pulse.align_right():
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.play(pulse.library.Gaussian(10, 1.0, 2.0), d0)
pulse.play(pulse.library.GaussianSquare(10, 1.0, 2.0, 3), d0)
pulse.play(pulse.library.Drag(10, 1.0, 2.0, 0.1), d0)
qobj = assemble(sched, backend=self.backend, shots=2000)
scheds, _, _ = disassemble(qobj)
self.assertEqual(scheds[0], target_qobj_transform(sched))
def test_disassemble_schedule_los(self):
"""Test disassembling schedule los."""
d0 = pulse.DriveChannel(0)
m0 = pulse.MeasureChannel(0)
d1 = pulse.DriveChannel(1)
m1 = pulse.MeasureChannel(1)
sched0 = pulse.Schedule()
sched1 = pulse.Schedule()
schedule_los = [
{d0: 4.5e9, d1: 5e9, m0: 6e9, m1: 7e9},
{d0: 5e9, d1: 4.5e9, m0: 7e9, m1: 6e9},
]
qobj = assemble([sched0, sched1], backend=self.backend, schedule_los=schedule_los)
_, run_config_out, _ = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.schedule_los, schedule_los)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import QuantumCircuit
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import NormalDistribution
# can be used in case a principal component analysis has been done to derive the uncertainty model, ignored in this example.
A = np.eye(2)
b = np.zeros(2)
# specify the number of qubits that are used to represent the different dimenions of the uncertainty model
num_qubits = [2, 2]
# specify the lower and upper bounds for the different dimension
low = [0, 0]
high = [0.12, 0.24]
mu = [0.12, 0.24]
sigma = 0.01 * np.eye(2)
# construct corresponding distribution
bounds = list(zip(low, high))
u = NormalDistribution(num_qubits, mu, sigma, bounds)
# plot contour of probability density function
x = np.linspace(low[0], high[0], 2 ** num_qubits[0])
y = np.linspace(low[1], high[1], 2 ** num_qubits[1])
z = u.probabilities.reshape(2 ** num_qubits[0], 2 ** num_qubits[1])
plt.contourf(x, y, z)
plt.xticks(x, size=15)
plt.yticks(y, size=15)
plt.grid()
plt.xlabel("$r_1$ (%)", size=15)
plt.ylabel("$r_2$ (%)", size=15)
plt.colorbar()
plt.show()
# specify cash flow
cf = [1.0, 2.0]
periods = range(1, len(cf) + 1)
# plot cash flow
plt.bar(periods, cf)
plt.xticks(periods, size=15)
plt.yticks(size=15)
plt.grid()
plt.xlabel("periods", size=15)
plt.ylabel("cashflow ($)", size=15)
plt.show()
# estimate real value
cnt = 0
exact_value = 0.0
for x1 in np.linspace(low[0], high[0], pow(2, num_qubits[0])):
for x2 in np.linspace(low[1], high[1], pow(2, num_qubits[1])):
prob = u.probabilities[cnt]
for t in range(len(cf)):
# evaluate linear approximation of real value w.r.t. interest rates
exact_value += prob * (
cf[t] / pow(1 + b[t], t + 1)
- (t + 1) * cf[t] * np.dot(A[:, t], np.asarray([x1, x2])) / pow(1 + b[t], t + 2)
)
cnt += 1
print("Exact value: \t%.4f" % exact_value)
# specify approximation factor
c_approx = 0.125
# create fixed income pricing application
from qiskit_finance.applications.estimation import FixedIncomePricing
fixed_income = FixedIncomePricing(
num_qubits=num_qubits,
pca_matrix=A,
initial_interests=b,
cash_flow=cf,
rescaling_factor=c_approx,
bounds=bounds,
uncertainty_model=u,
)
fixed_income._objective.draw()
fixed_income_circ = QuantumCircuit(fixed_income._objective.num_qubits)
# load probability distribution
fixed_income_circ.append(u, range(u.num_qubits))
# apply function
fixed_income_circ.append(fixed_income._objective, range(fixed_income._objective.num_qubits))
fixed_income_circ.draw()
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
# construct amplitude estimation
problem = fixed_income.to_estimation_problem()
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % exact_value)
print("Estimated value: \t%.4f" % (fixed_income.interpret(result)))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_hinton
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3 , 0)
qc.rx(np.pi/5, 1)
state = DensityMatrix(qc)
plot_state_hinton(state, title="New Hinton Plot")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
# These column vectors can be stored in numpy arrays so that we can operate
# on them with the circuit diagram's corresponding matrix (which is to be evaluated)
# as follows:
zero_zero = np.array([[1],[0],[0],[0]])
zero_one = np.array([[0],[1],[0],[0]])
one_zero = np.array([[0],[0],[1],[0]])
one_one = np.array([[0],[0],[0],[1]])
Psi = {'zero_zero': zero_zero, 'zero_one': zero_one, 'one_zero': one_zero, 'one_one': one_one}
# ^We can conveniently store all possible input states in a dictionary and then print to check the representations:
for key, val in Psi.items():
print(key, ':', '\n', val)
# storing CNOT as a numpy array:
CNOT_1 = np.matrix([[1, 0, 0, 0],[0, 1, 0, 0],[0, 0, 0, 1],[0, 0, 1, 0]])
print(CNOT_1)
print('FINAL STATE OF i):')
#Apply CNOT to each possible state for |Psi> to find |Psi'>
for key, val in Psi.items():
print(key, 'becomes..\n', CNOT_1*val)
# storing this in a numpy array:
H_2 = .5*np.matrix([[1, 1, 1, 1],[1, -1, 1, -1],[1, 1, -1, -1],[1, -1, -1, 1]])
print('H_2:')
print(H_2)
# storing this in a numpy array:
CNOT_2 = np.matrix([[1, 0, 0, 0],[0, 0, 0, 1],[0, 0, 1, 0],[0, 1, 0, 0]])
A = H_2*CNOT_2*H_2
print(A)
print(CNOT_1)
for key, val in Psi.items():
print(key, 'becomes...\n', A*val)
# import necessary libraries
import numpy as np
from pprint import pprint
# import Qiskit
from qiskit import execute, Aer, IBMQ
from qiskit.backends.ibmq import least_busy
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.tools.visualization import plot_histogram
# useful additional packages
from qiskit.tools.visualization import plot_histogram
IBMQ.load_accounts()
# This initial state register
# can be realized in python by creating an instance of the
# Qiskit quantum register of 2 qubits
# and 2 classical ancilla bits for measuring the states
n = 2
i_q = QuantumRegister(n, name="i_q")
i_c = ClassicalRegister(n, name="i_c")
IBMQ.available_backends() #check backends - if you've set up your APIToken properly you
#should be able to see the quantum chips and simulators at IBM
for backend in IBMQ.available_backends(): #check backend status
print(backend.name())
pprint(backend.status())
def execute_and_plot(circuits, backend = Aer.get_backend('qasm_simulator')):
"""Executes circuits and plots the final
state histograms the for each circuit.
Adapted from 'execute_and_plot' function
in the beginners_guide_composer_examples
notebook provided in IBM's Qiskit
tutorial library on GitHub.
Args:
circuits (list): list of circuits to execute
backend (string): allows for specifying the backend
to execute on. Defaults to local qasm simulator
downloaded with Qiskit library, but can be specified
to run on an actual quantum chip by using the string
names of the available backends at IBM.
"""
# Store the results of the circuit implementation
# using the .execute() method
results = execute(circuits, backend = backend).result()
plot_histogram(results.get_counts())
# .get_counts():
# method returns a dictionary that maps each possible
# final state to the number of instances of
# said state over n evaluations
# (n defaults to 1024 for local qasm simulator),
# where multiple evaluations are a necessity since
# quantum computation outputs are probability
# dependent
# Initialize circuit:
cnot_i_00 = QuantumCircuit(i_q, i_c, name="cnot_i_00")
# Note: qubits are assumed by Qiskit
# to be initialized in the |0> state
# Apply gates according to diagram:
cnot_i_00.cx(i_q[0], i_q[1]) # Apply CNOT on line 2 controlled by line 1
# Measure final state:
cnot_i_00.measure(i_q[0], i_c[0]) # Write qubit 1 state onto classical ancilla bit 1
cnot_i_00.measure(i_q[1], i_c[1]) # Write qubit 2 state onto classical ancilla bit 2
# Display final state probabilities:
execute_and_plot(cnot_i_00)
print(cnot_i_00.qasm())
# Initialize circuit:
cnot_i_01 = QuantumCircuit(i_q, i_c, name="cnot_i_01")
cnot_i_01.x(i_q[0]) # Set the 1st qubit to |1> by flipping
# the initialized |0> with an X gate before implementing
# the circuit
# Apply gates according to diagram:
cnot_i_01.cx(i_q[0], i_q[1]) # Apply CNOT controlled by line 1
# Measure final state:
cnot_i_01.measure(i_q[0], i_c[0])
cnot_i_01.measure(i_q[1], i_c[1])
# Display final state probabilities:
execute_and_plot(cnot_i_01)
# Initialize circuit:
cnot_i_10 = QuantumCircuit(i_q, i_c, name="cnot_i_10")
cnot_i_10.x(i_q[1]) # Set the 2nd qubit to |1>
# Apply gates according to diagram:
cnot_i_10.cx(i_q[0], i_q[1]) # Apply CNOT controlled by line 1
# Measure final state:
cnot_i_10.measure(i_q[0], i_c[0])
cnot_i_10.measure(i_q[1], i_c[1])
# Display final state probabilities:
execute_and_plot(cnot_i_10)
# Initialize circuit:
cnot_i_11 = QuantumCircuit(i_q, i_c, name="cnot_i_11")
cnot_i_11.x(i_q[0]) # Set the 1st qubit to |1>
cnot_i_11.x(i_q[1]) # Set the 2nd qubit to |1>
# Apply gates according to diagram:
cnot_i_11.cx(i_q[0], i_q[1]) # Apply CNOT controlled by line 1
# Measure final states:
cnot_i_11.measure(i_q[0], i_c[0])
cnot_i_11.measure(i_q[1], i_c[1])
# Display final state probabilities:
execute_and_plot(cnot_i_11)
# For circuit ii, we can again create a quantum register of size
# 2 with 2 classical ancilla bits for measurement
n = 2
ii_q = QuantumRegister(n, name="ii_q")
ii_c = ClassicalRegister(n, name="ii_c")
IBMQ.available_backends() #check backends - if you've set up your APIToken properly you
#should be able to see the quantum chips and simulators at IBM
for backend in IBMQ.available_backends(): #check backend status
print(backend.name())
pprint(backend.status())
# Initialize circuit:
cnot_ii_00 = QuantumCircuit(ii_q, ii_c, name="cnot_ii_00")
cnot_ii_01.x(ii_q[0])
# Apply gates according to diagram:
cnot_ii_00.h(ii_q) # Apply hadamards in parallel.
# Note that specifying a register (rather than a qubit)
# for some gate method argument applies the gate to all
# qubits in the register
cnot_ii_00.cx(ii_q[1], ii_q[0]) # Apply CNOT controlled by line 2
cnot_ii_00.h(ii_q) # Apply hadamards in parallel.
# Measure final state:
cnot_ii_00.measure(ii_q[0], ii_c[0])
cnot_ii_00.measure(ii_q[1], ii_c[1])
# Display final state probabilities
execute_and_plot(cnot_ii_00)
# Initialize circuit:
cnot_ii_01 = QuantumCircuit(ii_q, ii_c, name="cnot_ii_01")
cnot_ii_01.x(ii_q[0]) # Set the 1st qubit to |1>
# Apply gates according to diagram:
cnot_ii_00.h(ii_q) # Apply hadamards in parallel
cnot_ii_01.cx(ii_q[1], ii_q[0]) # Apply CNOT controlled by line 2
cnot_ii_00.h(ii_q) # Apply hadamards in parallel
# Measure final state:
cnot_ii_01.measure(ii_q[0], ii_c[0])
cnot_ii_01.measure(ii_q[1], ii_c[1])
# Display final state probabilities:
execute_and_plot(cnot_ii_01)
# Initialize circuits
cnot_ii_10 = QuantumCircuit(ii_q, ii_c, name="cnot_ii_10")
cnot_ii_10.x(ii_q[1]) # Set the 2nd qubit to |1>
# Apply gates according to diagram:
cnot_ii_00.h(ii_q) # Apply hadamards in parallel
cnot_ii_10.cx(ii_q[1], ii_q[0]) # Apply CNOT controlled by line 2
cnot_ii_00.h(ii_q) # Apply hadamards in parallel
# Measure final state:
cnot_ii_10.measure(ii_q[0], ii_c[0])
cnot_ii_10.measure(ii_q[1], ii_c[1])
# Display final state probabilities:
execute_and_plot(cnot_ii_10)
# Initialize circuits:
cnot_ii_11 = QuantumCircuit(ii_q, ii_c, name="cnot_ii_11")
cnot_ii_11.x(ii_q[0]) # Set the 1st qubit to |1>
cnot_ii_11.x(ii_q[1]) # Set the 2nd qubit to |1>
# Apply gates according to diagram:
cnot_ii_00.h(ii_q) # Apply hadamards in parallel
cnot_ii_11.cx(ii_q[1], ii_q[0]) # Apply CNOT controlled by line 2
cnot_ii_00.h(ii_q) # Apply hadamards in parallel
# Measure final state
cnot_ii_11.measure(ii_q[0], ii_c[0])
cnot_ii_11.measure(ii_q[1], ii_c[1])
# Display final state probabilities
execute_and_plot(cnot_ii_11)
def circuit_i():
i_q = QuantumRegister(2, name='i_q')
i_c = ClassicalRegister(2, name='i_c')
initial_states = ['00','01','10','11']
initial_circuits = {state: QuantumCircuit(i_q, i_c, name='%s'%(state)) \
for state in initial_states}
final_circuits = {}
for state in initial_states:
if state[0] is '1':
initial_circuits[state].x(i_q[0])
if state[1] is '1':
initial_circuits[state].x(i_q[1])
initial_circuits[state].cx(i_q[0], i_q[1])
initial_circuits[state].measure(i_q[0], i_c[0])
initial_circuits[state].measure(i_q[1], i_c[1])
final_circuits[state] = initial_circuits[state]
return initial_circuits
def circuit_ii():
ii_q = QuantumRegister(2, name='ii_q')
ii_c = ClassicalRegister(2, name='ii_c')
initial_states = ['00','01','10','11']
circuits = {state: QuantumCircuit(ii_q, ii_c, name='%s'%(state)) \
for state in initial_states}
for state in initial_states:
if state[0] is '1':
circuits[state].x(ii_q[0])
if state[1] is '1':
circuits[state].x(ii_q[1])
circuits[state].h(ii_q)
circuits[state].cx(ii_q[1], ii_q[0])
circuits[state].h(ii_q)
circuits[state].measure(ii_q[0], ii_c[0])
circuits[state].measure(ii_q[1], ii_c[1])
return circuits
i = circuit_i()
ii = circuit_ii()
# Use the IBMQ Quantum Experience
backend = least_busy(IBMQ.backends())
# Use local qasm simulator
# backend = Aer.get_backend('qasm_simulator')
results_i = execute(list(i.values()), backend=backend).result()
results_ii = execute(list(ii.values()), backend=backend).result()
results_i_mapping = {circuit: results_i.get_counts(circuit) for circuit in list(results_i.get_names())}
results_ii_mapping = {circuit: results_ii.get_counts(circuit) for circuit in list(results_ii.get_names())}
print(results_i_mapping)
print(results_ii_mapping)
print('results_i')
for circuit in list(results_i.get_names()):
plot_histogram(results_i.get_counts(circuit))
print('results_ii')
for circuit in list(results_ii.get_names()):
plot_histogram(results_ii.get_counts(circuit))
|
https://github.com/DaisukeIto-ynu/KosakaQ
|
DaisukeIto-ynu
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Interactive error map for IBM Quantum Experience devices."""
import math
from typing import Tuple, Union
import numpy as np
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import matplotlib as mpl
from qiskit.providers.ibmq.ibmqbackend import IBMQBackend
from .plotly_wrapper import PlotlyWidget, PlotlyFigure
from ..device_layouts import DEVICE_LAYOUTS
from ..colormaps import (HELIX_LIGHT, HELIX_LIGHT_CMAP,
HELIX_DARK, HELIX_DARK_CMAP)
from ..exceptions import VisualizationValueError, VisualizationTypeError
def iplot_error_map(
backend: IBMQBackend,
figsize: Tuple[int] = (800, 500),
show_title: bool = True,
remove_badcal_edges: bool = True,
background_color: str = 'white',
as_widget: bool = False
) -> Union[PlotlyFigure, PlotlyWidget]:
"""Plot the error map of a device.
Args:
backend: Plot the error map for this backend.
figsize: Figure size in pixels.
show_title: Whether to show figure title.
remove_badcal_edges: Whether to remove bad CX gate calibration data.
background_color: Background color, either 'white' or 'black'.
as_widget: ``True`` if the figure is to be returned as a ``PlotlyWidget``.
Otherwise the figure is to be returned as a ``PlotlyFigure``.
Returns:
The error map figure.
Raises:
VisualizationValueError: If an invalid input is received.
VisualizationTypeError: If the specified `backend` is a simulator.
Example:
.. jupyter-execute::
:hide-code:
:hide-output:
from qiskit.test.ibmq_mock import mock_get_backend
mock_get_backend('FakeVigo')
.. jupyter-execute::
from qiskit import IBMQ
from qiskit.providers.ibmq.visualization import iplot_error_map
IBMQ.load_account()
provider = IBMQ.get_provider(group='open', project='main')
backend = provider.get_backend('ibmq_vigo')
iplot_error_map(backend, as_widget=True)
"""
meas_text_color = '#000000'
if background_color == 'white':
color_map = HELIX_LIGHT_CMAP
text_color = '#000000'
plotly_cmap = HELIX_LIGHT
elif background_color == 'black':
color_map = HELIX_DARK_CMAP
text_color = '#FFFFFF'
plotly_cmap = HELIX_DARK
else:
raise VisualizationValueError(
'"{}" is not a valid background_color selection.'.format(background_color))
if backend.configuration().simulator:
raise VisualizationTypeError('Requires a device backend, not a simulator.')
config = backend.configuration()
n_qubits = config.n_qubits
cmap = config.coupling_map
if n_qubits in DEVICE_LAYOUTS.keys():
grid_data = DEVICE_LAYOUTS[n_qubits]
else:
fig = go.Figure()
fig.update_layout(showlegend=False,
plot_bgcolor=background_color,
paper_bgcolor=background_color,
width=figsize[0], height=figsize[1],
margin=dict(t=60, l=0, r=0, b=0)
)
out = PlotlyWidget(fig)
return out
props = backend.properties().to_dict()
t1s = []
t2s = []
for qubit_props in props['qubits']:
count = 0
for item in qubit_props:
if item['name'] == 'T1':
t1s.append(item['value'])
count += 1
elif item['name'] == 'T2':
t2s.append(item['value'])
count += 1
if count == 2:
break
# U2 error rates
single_gate_errors = [0]*n_qubits
for gate in props['gates']:
if gate['gate'] == 'u2':
_qubit = gate['qubits'][0]
single_gate_errors[_qubit] = gate['parameters'][0]['value']
# Convert to percent
single_gate_errors = 100 * np.asarray(single_gate_errors)
avg_1q_err = np.mean(single_gate_errors)
max_1q_err = max(single_gate_errors)
single_norm = mpl.colors.Normalize(
vmin=min(single_gate_errors), vmax=max_1q_err)
q_colors = [mpl.colors.rgb2hex(color_map(single_norm(err))) for err in single_gate_errors]
line_colors = []
cx_idx = []
if n_qubits > 1 and cmap:
cx_errors = []
for cmap_qubits in cmap:
for gate in props['gates']:
if gate['qubits'] == cmap_qubits:
cx_errors.append(gate['parameters'][0]['value'])
break
else:
continue
# Convert to percent
cx_errors = 100 * np.asarray(cx_errors)
# remove bad cx edges
if remove_badcal_edges:
cx_idx = np.where(cx_errors != 100.0)[0]
else:
cx_idx = np.arange(len(cx_errors))
avg_cx_err = np.mean(cx_errors[cx_idx])
for err in cx_errors:
if err != 100.0 or not remove_badcal_edges:
cx_norm = mpl.colors.Normalize(
vmin=min(cx_errors[cx_idx]), vmax=max(cx_errors[cx_idx]))
line_colors.append(mpl.colors.rgb2hex(color_map(cx_norm(err))))
else:
line_colors.append("#ff0000")
# Measurement errors
read_err = []
for qubit in range(n_qubits):
for item in props['qubits'][qubit]:
if item['name'] == 'readout_error':
read_err.append(item['value'])
read_err = 100 * np.asarray(read_err)
avg_read_err = np.mean(read_err)
max_read_err = np.max(read_err)
if n_qubits < 10:
num_left = n_qubits
num_right = 0
else:
num_left = math.ceil(n_qubits / 2)
num_right = n_qubits - num_left
x_max = max([d[1] for d in grid_data])
y_max = max([d[0] for d in grid_data])
max_dim = max(x_max, y_max)
qubit_size = 32
font_size = 14
offset = 0
if cmap:
if y_max / max_dim < 0.33:
qubit_size = 24
font_size = 10
offset = 1
if n_qubits > 5:
right_meas_title = "Readout Error (%)"
else:
right_meas_title = None
if cmap and cx_idx.size > 0:
cx_title = "CNOT Error Rate [Avg. {}%]".format(np.round(avg_cx_err, 3))
else:
cx_title = None
fig = make_subplots(rows=2, cols=11, row_heights=[0.95, 0.05],
vertical_spacing=0.15,
specs=[[{"colspan": 2}, None, {"colspan": 6},
None, None, None,
None, None, {"colspan": 2},
None, None],
[{"colspan": 4}, None, None,
None, None, None,
{"colspan": 4}, None, None,
None, None]],
subplot_titles=("Readout Error (%)", None, right_meas_title,
"Hadamard Error Rate [Avg. {}%]".format(
np.round(avg_1q_err, 3)),
cx_title)
)
# Add lines for couplings
if cmap and n_qubits > 1 and cx_idx.size > 0:
for ind, edge in enumerate(cmap):
is_symmetric = False
if edge[::-1] in cmap:
is_symmetric = True
y_start = grid_data[edge[0]][0] + offset
x_start = grid_data[edge[0]][1]
y_end = grid_data[edge[1]][0] + offset
x_end = grid_data[edge[1]][1]
if is_symmetric:
if y_start == y_end:
x_end = (x_end - x_start) / 2 + x_start
x_mid = x_end
y_mid = y_start
elif x_start == x_end:
y_end = (y_end - y_start) / 2 + y_start
x_mid = x_start
y_mid = y_end
else:
x_end = (x_end - x_start) / 2 + x_start
y_end = (y_end - y_start) / 2 + y_start
x_mid = x_end
y_mid = y_end
else:
if y_start == y_end:
x_mid = (x_end - x_start) / 2 + x_start
y_mid = y_end
elif x_start == x_end:
x_mid = x_end
y_mid = (y_end - y_start) / 2 + y_start
else:
x_mid = (x_end - x_start) / 2 + x_start
y_mid = (y_end - y_start) / 2 + y_start
fig.add_trace(
go.Scatter(x=[x_start, x_mid, x_end],
y=[-y_start, -y_mid, -y_end],
mode="lines",
line=dict(width=6,
color=line_colors[ind]),
hoverinfo='text',
hovertext='CX<sub>err</sub>{B}_{A} = {err} %'.format(
A=edge[0], B=edge[1], err=np.round(cx_errors[ind], 3))
),
row=1, col=3)
# Add the qubits themselves
qubit_text = []
qubit_str = "<b>Qubit {}</b><br>H<sub>err</sub> = {} %"
qubit_str += "<br>T1 = {} \u03BCs<br>T2 = {} \u03BCs"
for kk in range(n_qubits):
qubit_text.append(qubit_str.format(kk,
np.round(single_gate_errors[kk], 3),
np.round(t1s[kk], 2),
np.round(t2s[kk], 2)))
if n_qubits > 20:
qubit_size = 23
font_size = 11
if n_qubits > 50:
qubit_size = 20
font_size = 9
qtext_color = []
for ii in range(n_qubits):
if background_color == 'black':
if single_gate_errors[ii] > 0.8*max_1q_err:
qtext_color.append('black')
else:
qtext_color.append('white')
else:
qtext_color.append('white')
fig.add_trace(go.Scatter(
x=[d[1] for d in grid_data],
y=[-d[0]-offset for d in grid_data],
mode="markers+text",
marker=go.scatter.Marker(size=qubit_size,
color=q_colors,
opacity=1),
text=[str(ii) for ii in range(n_qubits)],
textposition="middle center",
textfont=dict(size=font_size, color=qtext_color),
hoverinfo="text",
hovertext=qubit_text), row=1, col=3)
fig.update_xaxes(row=1, col=3, visible=False)
_range = None
if offset:
_range = [-3.5, 0.5]
fig.update_yaxes(row=1,
col=3,
visible=False,
range=_range)
# H error rate colorbar
min_1q_err = min(single_gate_errors)
max_1q_err = max(single_gate_errors)
if n_qubits > 1:
fig.add_trace(go.Heatmap(z=[np.linspace(min_1q_err,
max_1q_err, 100),
np.linspace(min_1q_err,
max_1q_err, 100)],
colorscale=plotly_cmap,
showscale=False,
hoverinfo='none'), row=2, col=1)
fig.update_yaxes(row=2,
col=1,
visible=False)
fig.update_xaxes(row=2,
col=1,
tickvals=[0, 49, 99],
ticktext=[np.round(min_1q_err, 3),
np.round((max_1q_err-min_1q_err)/2+min_1q_err, 3),
np.round(max_1q_err, 3)])
# CX error rate colorbar
if cmap and n_qubits > 1 and cx_idx.size > 0:
min_cx_err = min(cx_errors)
max_cx_err = max(cx_errors)
if min_cx_err == max_cx_err:
min_cx_err = 0 # Force more than 1 color.
fig.add_trace(go.Heatmap(z=[np.linspace(min_cx_err,
max_cx_err, 100),
np.linspace(min_cx_err,
max_cx_err, 100)],
colorscale=plotly_cmap,
showscale=False,
hoverinfo='none'), row=2, col=7)
fig.update_yaxes(row=2, col=7, visible=False)
min_cx_idx_err = min(cx_errors[cx_idx])
max_cx_idx_err = max(cx_errors[cx_idx])
fig.update_xaxes(row=2, col=7,
tickvals=[0, 49, 99],
ticktext=[np.round(min_cx_idx_err, 3),
np.round((max_cx_idx_err-min_cx_idx_err)/2+min_cx_idx_err, 3),
np.round(max_cx_idx_err, 3)])
hover_text = "<b>Qubit {}</b><br>M<sub>err</sub> = {} %"
# Add the left side meas errors
for kk in range(num_left-1, -1, -1):
fig.add_trace(go.Bar(x=[read_err[kk]], y=[kk],
orientation='h',
marker=dict(color='#eedccb'),
hoverinfo="text",
hoverlabel=dict(font=dict(color=meas_text_color)),
hovertext=[hover_text.format(kk,
np.round(read_err[kk], 3)
)]
),
row=1, col=1)
fig.add_trace(go.Scatter(x=[avg_read_err, avg_read_err],
y=[-0.25, num_left-1+0.25],
mode='lines',
hoverinfo='none',
line=dict(color=text_color,
width=2,
dash='dot')), row=1, col=1)
fig.update_yaxes(row=1, col=1,
tickvals=list(range(num_left)),
autorange="reversed")
fig.update_xaxes(row=1, col=1,
range=[0, 1.1*max_read_err],
tickvals=[0, np.round(avg_read_err, 2),
np.round(max_read_err, 2)],
showline=True, linewidth=1, linecolor=text_color,
tickcolor=text_color,
ticks="outside",
showgrid=False,
zeroline=False)
# Add the right side meas errors, if any
if num_right:
for kk in range(n_qubits-1, num_left-1, -1):
fig.add_trace(go.Bar(x=[-read_err[kk]],
y=[kk],
orientation='h',
marker=dict(color='#eedccb'),
hoverinfo="text",
hoverlabel=dict(font=dict(color=meas_text_color)),
hovertext=[hover_text.format(kk,
np.round(read_err[kk], 3))]
),
row=1, col=9)
fig.add_trace(go.Scatter(x=[-avg_read_err, -avg_read_err],
y=[num_left-0.25, n_qubits-1+0.25],
mode='lines',
hoverinfo='none',
line=dict(color=text_color,
width=2,
dash='dot')
), row=1, col=9)
fig.update_yaxes(row=1,
col=9,
tickvals=list(range(n_qubits-1, num_left-1, -1)),
side='right',
autorange="reversed",
)
fig.update_xaxes(row=1,
col=9,
range=[-1.1*max_read_err, 0],
tickvals=[0, -np.round(avg_read_err, 2), -np.round(max_read_err, 2)],
ticktext=[0, np.round(avg_read_err, 2), np.round(max_read_err, 2)],
showline=True, linewidth=1, linecolor=text_color,
tickcolor=text_color,
ticks="outside",
showgrid=False,
zeroline=False)
# Makes the subplot titles smaller than the 16pt default
for ann in fig['layout']['annotations']:
ann['font'] = dict(size=13)
title_text = "{} Error Map".format(backend.name()) if show_title else ''
fig.update_layout(showlegend=False,
plot_bgcolor=background_color,
paper_bgcolor=background_color,
width=figsize[0], height=figsize[1],
title=dict(text=title_text, x=0.452),
title_font_size=20,
font=dict(color=text_color),
margin=dict(t=60, l=0, r=40, b=0)
)
if as_widget:
return PlotlyWidget(fig)
return PlotlyFigure(fig)
|
https://github.com/jvscursulim/qamp_fall22_project
|
jvscursulim
|
# Importing Libraries
import torch
from torch import cat, no_grad, manual_seed
from torch.utils.data import DataLoader
from torchvision import transforms
import torch.optim as optim
from torch.nn import (
Module,
Conv2d,
Linear,
Dropout2d,
NLLLoss
)
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from qiskit_machine_learning.neural_networks import EstimatorQNN
from qiskit_machine_learning.connectors import TorchConnector
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from qiskit import QuantumCircuit
from qiskit.visualization import circuit_drawer
# Imports for CIFAR-10s
from torchvision.datasets import CIFAR10
from torchvision import transforms
def prepare_data(X, labels_to_keep, batch_size):
# Filtering out labels (originally 0-9), leaving only labels 0 and 1
filtered_indices = [i for i in range(len(X.targets)) if X.targets[i] in labels_to_keep]
X.data = X.data[filtered_indices]
X.targets = [X.targets[i] for i in filtered_indices]
# Defining dataloader with filtered data
loader = DataLoader(X, batch_size=batch_size, shuffle=True)
return loader
# Set seed for reproducibility
manual_seed(42)
# CIFAR-10 data transformation
transform = transforms.Compose([
transforms.ToTensor(), # convert the images to tensors
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) # Normalization usign mean and std.
])
labels_to_keep = [0, 1]
batch_size = 1
# Preparing Train Data
X_train = CIFAR10(root="./data", train=True, download=True, transform=transform)
train_loader = prepare_data(X_train, labels_to_keep, batch_size)
# Preparing Test Data
X_test = CIFAR10(root="./data", train=False, download=True, transform=transform)
test_loader = prepare_data(X_test, labels_to_keep, batch_size)
print(f"Training dataset size: {len(train_loader.dataset)}")
print(f"Test dataset size: {len(test_loader.dataset)}")
# Defining and creating QNN
def create_qnn():
feature_map = ZZFeatureMap(2) # ZZFeatureMap with 2 bits, entanglement between qubits based on the pairwise product of input features.
ansatz = RealAmplitudes(2, reps=1) # parameters (angles, in the case of RealAmplitudes) that are adjusted during the training process to optimize the quantum model for a specific task.
qc = QuantumCircuit(2)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
qnn = EstimatorQNN(
circuit=qc,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
input_gradients=True,
)
return qnn
qnn = create_qnn()
# Visualizing the QNN circuit
circuit_drawer(qnn.circuit, output='mpl')
# Defining torch NN module
class Net(Module):
def __init__(self, qnn):
super().__init__()
self.conv1 = Conv2d(3, 16, kernel_size=3, padding=1)
self.conv2 = Conv2d(16, 32, kernel_size=3, padding=1)
self.dropout = Dropout2d()
self.fc1 = Linear(32 * 8 * 8, 64)
self.fc2 = Linear(64, 2) # 2-dimensional input to QNN
self.qnn = TorchConnector(qnn)
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)
x = self.fc3(x)
return cat((x, 1 - x), -1)
# Creating model
model = Net(qnn)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
# Defining model, optimizer, and loss function
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = NLLLoss()
# Starting training
epochs = 10
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device) # Move data to GPU
optimizer.zero_grad(set_to_none=True)
output = model(data)
loss = loss_func(output, target)
loss.backward()
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss) / len(total_loss))
print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1]))
# Plotting loss convergence
plt.plot(loss_list)
plt.title("Hybrid NN Training Convergence")
plt.xlabel("Training Iterations")
plt.ylabel("Neg. Log Likelihood Loss")
plt.show()
# Saving the model
torch.save( model.state_dict(), "model_cifar10_10EPOCHS.pt")
# Loading the model
qnn_cifar10 = create_qnn()
model_cifar10 = Net(qnn_cifar10)
model_cifar10.load_state_dict(torch.load("model_cifar10.pt"))
correct = 0
total = 0
model_cifar10.eval()
with torch.no_grad():
for data, target in test_loader:
output = model_cifar10(data)
_, predicted = torch.max(output.data, 1)
total += target.size(0)
correct += (predicted == target).sum().item()
# Calculating and print test accuracy
test_accuracy = correct / total * 100
print(f"Test Accuracy: {test_accuracy:.2f}%")
# Plotting predicted labels
n_samples_show = 6
count = 0
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
model_cifar10.eval()
with no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
if count == n_samples_show:
break
output = model_cifar10(data)
if len(output.shape) == 1:
output = output.reshape(1, *output.shape)
pred = output.argmax(dim=1, keepdim=True)
axes[count].imshow(np.transpose(data[0].numpy(), (1, 2, 0)))
axes[count].set_xticks([])
axes[count].set_yticks([])
axes[count].set_title("Predicted {0}\n Actual {1}".format(pred.item(), target.item()))
count += 1
plt.show()
|
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
import pennylane as qml
H = qml.Hamiltonian(
[1, 1, 0.5],
[qml.PauliX(0), qml.PauliZ(1), qml.PauliX(0) @ qml.PauliX(1)]
)
print(H)
dev = qml.device('default.qubit', wires=2)
t = 1
n = 2
@qml.qnode(dev)
def circuit():
qml.ApproxTimeEvolution(H, t, n)
return [qml.expval(qml.PauliZ(i)) for i in range(2)]
print(qml.draw(circuit, expansion_strategy='device')())
def circ(theta):
qml.RX(theta, wires=0)
qml.Hadamard(wires=1)
qml.CNOT(wires=[0, 1])
@qml.qnode(dev)
def circuit(param):
circ(param)
return [qml.expval(qml.PauliZ(i)) for i in range(2)]
print(qml.draw(circuit)(0.5))
@qml.qnode(dev)
def circuit(params, **kwargs):
qml.layer(circ, 3, params)
return [qml.expval(qml.PauliZ(i)) for i in range(2)]
print(qml.draw(circuit)([0.3, 0.4, 0.5]))
from pennylane import qaoa
from pennylane import numpy as np
from matplotlib import pyplot as plt
import networkx as nx
edges = [(0, 1), (1, 2), (2, 0), (2, 3)]
graph = nx.Graph(edges)
nx.draw(graph, with_labels=True)
plt.show()
cost_h, mixer_h = qaoa.min_vertex_cover(graph, constrained=False)
print("Cost Hamiltonian", cost_h)
print("Mixer Hamiltonian", mixer_h)
def qaoa_layer(gamma, alpha):
qaoa.cost_layer(gamma, cost_h)
qaoa.mixer_layer(alpha, mixer_h)
wires = range(4)
depth = 2
def circuit(params, **kwargs):
for w in wires:
qml.Hadamard(wires=w)
qml.layer(qaoa_layer, depth, params[0], params[1])
!pip install pennylane-qulacs["cpu"]
dev = qml.device("qulacs.simulator", wires=wires)
@qml.qnode(dev)
def cost_function(params):
circuit(params)
return qml.expval(cost_h)
optimizer = qml.GradientDescentOptimizer()
steps = 70
params = np.array([[0.5, 0.5], [0.5, 0.5]], requires_grad=True)
for i in range(steps):
params = optimizer.step(cost_function, params)
print("Optimal Parameters")
print(params)
@qml.qnode(dev)
def probability_circuit(gamma, alpha):
circuit([gamma, alpha])
return qml.probs(wires=wires)
probs = probability_circuit(params[0], params[1])
plt.style.use("seaborn")
plt.bar(range(2 ** len(wires)), probs)
plt.show()
reward_h = qaoa.edge_driver(nx.Graph([(0, 2)]), ['11'])
new_cost_h = cost_h + 2 * reward_h
def qaoa_layer(gamma, alpha):
qaoa.cost_layer(gamma, new_cost_h)
qaoa.mixer_layer(alpha, mixer_h)
def circuit(params, **kwargs):
for w in wires:
qml.Hadamard(wires=w)
qml.layer(qaoa_layer, depth, params[0], params[1])
@qml.qnode(dev)
def cost_function(params):
circuit(params)
return qml.expval(new_cost_h)
params = np.array([[0.5, 0.5], [0.5, 0.5]], requires_grad=True)
for i in range(steps):
params = optimizer.step(cost_function, params)
print("Optimal Parameters")
print(params)
@qml.qnode(dev)
def probability_circuit(gamma, alpha):
circuit([gamma, alpha])
return qml.probs(wires=wires)
probs = probability_circuit(params[0], params[1])
plt.style.use("seaborn")
plt.bar(range(2 ** len(wires)), probs)
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# If you introduce a list with less colors than bars, the color of the bars will
# alternate following the sequence from the list.
import numpy as np
from qiskit.quantum_info import DensityMatrix
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0, 1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
matrix = DensityMatrix(qc)
plot_state_paulivec(matrix, color=['crimson', 'midnightblue', 'seagreen'])
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
import pickle
plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
def trotter_gate(dt, to_instruction = True):
qc = QuantumCircuit(2)
qc.rx(2*dt,0)
qc.rz(2*dt,1)
qc.h(1)
qc.cx(1,0)
qc.rz(-2*dt, 0)
qc.rx(-2*dt, 1)
qc.rz(2*dt, 1)
qc.cx(1,0)
qc.h(1)
qc.rz(2*dt, 0)
return qc.to_instruction() if to_instruction else qc
trotter_gate(np.pi / 6, to_instruction=False).draw("mpl")
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
Trot_gate = trotter_gate(dt)
# Number of trotter steps
trotter_steps = 100 ### CAN BE >= 4
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(7)
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
qc.x([5]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Simulate time evolution under H_heis3 Hamiltonian
for _ in range(trotter_steps):
qc.append(Trot_gate, [qr[3], qr[5]])
qc.cx(qr[3], qr[1])
qc.cx(qr[5], qr[3])
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time/trotter_steps})
t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_qc = transpile(t3_qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(t3_qc, [qr[1], qr[3], qr[5]])
# Display circuit for confirmation
# st_qcs[-1].decompose().draw() # view decomposition of trotter gates
st_qcs[-1].draw("mpl") # only view trotter gates
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
shots = 8192
reps = 8
jobs = []
for _ in range(reps):
# execute
job = execute(st_qcs, backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3)
print('Job ID', cal_job.job_id())
with open("jakarta_100step_2.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
mit_results = []
for job in jobs:
mit_results.append( meas_fitter.filter.apply(job.result()) )
# Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits
def state_tomo(result, st_qcs):
# The expected final state; necessary to determine state tomography fidelity
target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Fit state tomography results
tomo_fitter = StateTomographyFitter(result, st_qcs)
rho_fit = tomo_fitter.fit(method='lstsq')
# Compute fidelity
fid = state_fidelity(rho_fit, target_state)
return fid
# Compute tomography fidelities for each repetition
fids = []
for result in mit_results:
fid = state_tomo(result, st_qcs)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/arnavdas88/QuGlassyIsing
|
arnavdas88
|
from qiskit.providers.aer import QasmSimulator
from qiskit.providers.aer import AerSimulator
from qiskit import Aer, transpile
from qiskit.circuit.library import TwoLocal
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import EfficientSU2
from qiskit.visualization import plot_histogram
from qiskit_glassydynamics.helpers import ising
counts = []
values = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
J_hamiltonian = ising.Ising2DHamiltonian( (5, 5) )
Bz_hamiltonian = ising.FieldHamiltonian( (5, 5) , 'Z')
Bx_hamiltonian = ising.FieldHamiltonian( (5, 5) , 'X')
print("=== Z ===")
print(J_hamiltonian)
print()
print("=== Bz ===")
print(Bz_hamiltonian)
print()
print("=== Bx ===")
print(Bx_hamiltonian)
H = - 1. * J_hamiltonian + 1. * Bz_hamiltonian - 1. * Bx_hamiltonian
print()
print("=== H ===")
print(H)
# 2D Ising Simulation
# you can swap this for a real quantum device and keep the rest of the code the same!
backend = QasmSimulator()
# COBYLA usually works well for small problems like this one
optimizer = COBYLA(maxiter=2000)
# EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library
ansatz = EfficientSU2(5, reps=1)
# set the algorithm
vqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result)
# run it with the Hamiltonian we defined above
result = vqe.compute_minimum_eigenvalue(H)
print(result)
plot_histogram(result.eigenstate)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Operator
from qiskit.transpiler.passes import UnitarySynthesis
circuit = QuantumCircuit(1)
circuit.rx(0.8, 0)
unitary = Operator(circuit).data
unitary_circ = QuantumCircuit(1)
unitary_circ.unitary(unitary, [0])
synth = UnitarySynthesis(basis_gates=["h", "s"], method="sk")
out = synth(unitary_circ)
out.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.measure(0, 0)
qc.x(0).c_if(cr, 0)
qc.measure(0, 0)
qc.draw('mpl')
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
import math
import matplotlib.pyplot as plt
%matplotlib inline
class TSP:
def __init__(self):
self.flat_mat = flat_mat
self.n = 0
self.melhor_dist = 1e11
self.pontos = []
self.melhores_pontos = []
def busca_exaustiva(self, flat_mat, n, ite):
if ite == n:
dist = 0
for j in range(1, n):
dist += flat_mat[self.pontos[j-1] * n + self.pontos[j]]
dist += flat_mat[self.pontos[n-1] * n + self.pontos[0]]
if dist < self.melhor_dist:
self.melhor_dist = dist
self.melhores_pontos = self.pontos[:]
return
for i in range(n):
if self.pontos[i] == -1:
self.pontos[i] = ite
self.busca_exaustiva(flat_mat, n, ite + 1)
self.pontos[i] = -1
def dist_mat(self):
x = []
y = []
flat_mat = [] #matriz 1 dimensao contendo todas as distancias possiveis entre os pontos para facilitar cálculo.
while True:
try:
temp = input("Digite a coordenada x y: ").split()
x.append(float(temp[0]))
y.append(float(temp[1]))
except:
break
for i in range(len(x)):
for j in range(len(y)):
flat_mat.append(math.sqrt((x[i] - x[j])**2 + (y[i] - y[j])**2))
return flat_mat, x, y
def get_results(self):
self.flat_mat, x, _ = self.dist_mat()
self.n = len(x)
self.pontos = [-1]*self.n
self.pontos[0] = 0
self.busca_exaustiva(self.flat_mat, self.n, 1)
return self.melhor_dist, self.melhores_pontos
Tsp = TSP()
distancia, pontos = Tsp.get_results()
print("Melhor distancia encontrada: ", distancia)
print("Melhor caminho encontrado: ", pontos)
#plota gráfico
def connectpoints(x,y,p1,p2):
x1, x2 = x[p1], x[p2]
y1, y2 = y[p1], y[p2]
plt.plot([x1,x2],[y1,y2],'ro-')
for i in range(1, len(pontos)):
connectpoints(x,y,pontos[i-1],pontos[i])
connectpoints(x,y,pontos[len(x)-1],pontos[0])
plt.title("Percurso")
plt.show()
%%time
%%cmd
python TSP.py < in-1.txt
type out-1.txt
python TSP.py < in-2.txt
type out-2.txt
python TSP.py < in-3.txt
type out-3.txt
python TSP.py < in-4.txt
type out-4.txt
from qiskit import IBMQ
import numpy as np
#IBMQ.save_account('seu-tokenIBMQ-para-rodar-localmente')
IBMQ.load_account()
from qiskit import Aer
from qiskit.tools.visualization import plot_histogram
from qiskit.circuit.library import TwoLocal
from qiskit.optimization.applications.ising import max_cut, tsp
from qiskit.aqua.algorithms import VQE, NumPyMinimumEigensolver
from qiskit.aqua.components.optimizers import SPSA
from qiskit.aqua import aqua_globals
from qiskit.aqua import QuantumInstance
from qiskit.optimization.applications.ising.common import sample_most_likely
from qiskit.optimization.algorithms import MinimumEigenOptimizer
from qiskit.optimization.problems import QuadraticProgram
import logging
from qiskit.aqua import set_qiskit_aqua_logging
#Preparando os dados segundo os imputs do usuario para serem resolvidos pelo qiskit max 4 pontos por limitação de qubits
coord = []
flat_mat, x, y = TSP().dist_mat()
dist_mat = np.array(flat_mat).reshape(len(x),len(x))
for i, j in zip(x, y):
coord.append([i,j])
ins = tsp.TspData('TSP_Q', dim=len(x), coord=np.array(coord), w=dist_mat)
qubitOp, offset = tsp.get_operator(ins)
print('Offset:', offset)
print('Ising Hamiltonian:')
print(qubitOp.print_details())
#Usando o numpyMinimumEigensolver como o solver do problema para resolver de forma quantica
ee = NumPyMinimumEigensolver(qubitOp)
result = ee.run()
print('energy:', result.eigenvalue.real)
print('tsp objective:', result.eigenvalue.real + offset)
x_Q = sample_most_likely(result.eigenstate)
print('feasible:', tsp.tsp_feasible(x_Q))
z = tsp.get_tsp_solution(x_Q)
print('solution:', z)
print('solution objective:', tsp.tsp_value(z, ins.w))
for i in range(1, len(z)):
connectpoints(x,y,z[i-1],z[i])
connectpoints(x,y,z[len(x)-1],z[0])
plt.title("Percurso")
plt.show()
#instanciando o simulador ou o computador real importante lembrar que nao ira funcionar para mais de 4 pontos pelo numero de qubits disponibilizados pela IBM que sao apenas 16 para o simulador qasm e 15 para a maquina quantica
provider = IBMQ.get_provider(hub = 'ibm-q')
device = provider.get_backend('ibmq_16_melbourne')
aqua_globals.random_seed = np.random.default_rng(123)
seed = 10598
backend = Aer.get_backend('qasm_simulator')
#descomentar essa linha caso queira rodar na maquina real
#backend = device
quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed)
#rodando no simulador quantico
spsa = SPSA(maxiter=10)
ry = TwoLocal(qubitOp.num_qubits, 'ry', 'cz', reps=5, entanglement='linear')
vqe = VQE(qubitOp, ry, spsa, quantum_instance=quantum_instance)
result = vqe.run(quantum_instance)
print('energy:', result.eigenvalue.real)
print('time:', result.optimizer_time)
x = sample_most_likely(result.eigenstate)
print('feasible:', tsp.tsp_feasible(x_Q))
z = tsp.get_tsp_solution(x_Q)
print('solution:', z)
print('solution objective:', tsp.tsp_value(z, ins.w))
|
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))
ghz.draw(output='mpl')
|
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.
from copy import copy
from typing import Any, Optional
from qiskit.primitives import BackendSampler
from qiskit_aqt_provider import transpiler_plugin
from qiskit_aqt_provider.aqt_resource import AQTResource, make_transpiler_target
class AQTSampler(BackendSampler):
""":class:`BaseSamplerV1 <qiskit.primitives.BaseSamplerV1>` primitive for AQT backends."""
_backend: AQTResource
def __init__(
self,
backend: AQTResource,
options: Optional[dict[str, Any]] = None,
skip_transpilation: bool = False,
) -> None:
"""Initialize a ``Sampler`` primitive using an AQT backend.
Args:
backend: AQT resource to evaluate circuits on.
options: options passed through to the underlying
:class:`BackendSampler <qiskit.primitives.BackendSampler>`.
skip_transpilation: if :data:`True`, do not transpile circuits
before passing them to the execution backend.
Examples:
Initialize a :class:`Sampler <qiskit.primitives.BaseSamplerV1>` primitive
on a AQT offline simulator:
>>> import qiskit
>>> from qiskit_aqt_provider import AQTProvider
>>> from qiskit_aqt_provider.primitives import AQTSampler
>>>
>>> backend = AQTProvider("").get_backend("offline_simulator_no_noise")
>>> sampler = AQTSampler(backend)
Configuring :class:`options <qiskit_aqt_provider.aqt_options.AQTOptions>`
on the backend will affect all circuit evaluations triggered by
the `Sampler` primitive:
>>> qc = qiskit.QuantumCircuit(2)
>>> _ = qc.cx(0, 1)
>>> _ = qc.measure_all()
>>>
>>> sampler.run(qc).result().metadata[0]["shots"]
100
>>> backend.options.shots = 123
>>> sampler.run(qc).result().metadata[0]["shots"]
123
The same effect is achieved by passing options to the
:class:`AQTSampler` initializer:
>>> sampler = AQTSampler(backend, options={"shots": 120})
>>> sampler.run(qc).result().metadata[0]["shots"]
120
Passing the option in the
:meth:`AQTSampler.run <qiskit.primitives.BaseSamplerV1.run>` call
restricts the effect to a single evaluation:
>>> sampler.run(qc, shots=130).result().metadata[0]["shots"]
130
>>> sampler.run(qc).result().metadata[0]["shots"]
120
"""
# Signal the transpiler to disable passes that require bound
# parameters.
# This allows the underlying sampler to apply most of
# the transpilation passes, and cache the results.
mod_backend = copy(backend)
mod_backend._target = make_transpiler_target(
transpiler_plugin.UnboundParametersTarget, backend.num_qubits
)
# if `with_progress_bar` is not explicitly set in the options, disable it
options_copy = (options or {}).copy()
options_copy.update(with_progress_bar=options_copy.get("with_progress_bar", False))
super().__init__(
mod_backend,
bound_pass_manager=transpiler_plugin.bound_pass_manager(mod_backend.target),
options=options_copy,
skip_transpilation=skip_transpilation,
)
@property
def backend(self) -> AQTResource:
"""Computing resource used for circuit evaluation."""
return self._backend
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
r"""
.. _pulse_builder:
=============
Pulse Builder
=============
..
We actually want people to think of these functions as being defined within the ``qiskit.pulse``
namespace, not the submodule ``qiskit.pulse.builder``.
.. currentmodule: qiskit.pulse
Use the pulse builder DSL to write pulse programs with an imperative syntax.
.. warning::
The pulse builder interface is still in active development. It may have
breaking API changes without deprecation warnings in future releases until
otherwise indicated.
The pulse builder provides an imperative API for writing pulse programs
with less difficulty than the :class:`~qiskit.pulse.Schedule` API.
It contextually constructs a pulse schedule and then emits the schedule for
execution. For example, to play a series of pulses on channels is as simple as:
.. plot::
:include-source:
from qiskit import pulse
dc = pulse.DriveChannel
d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4)
with pulse.build(name='pulse_programming_in') as pulse_prog:
pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3)
pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4)
pulse_prog.draw()
To begin pulse programming we must first initialize our program builder
context with :func:`build`, after which we can begin adding program
statements. For example, below we write a simple program that :func:`play`\s
a pulse:
.. plot::
:include-source:
from qiskit import execute, pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(100, 1.0), d0)
pulse_prog.draw()
The builder initializes a :class:`.pulse.Schedule`, ``pulse_prog``
and then begins to construct the program within the context. The output pulse
schedule will survive after the context is exited and can be executed like a
normal Qiskit schedule using ``qiskit.execute(pulse_prog, backend)``.
Pulse programming has a simple imperative style. This leaves the programmer
to worry about the raw experimental physics of pulse programming and not
constructing cumbersome data structures.
We can optionally pass a :class:`~qiskit.providers.Backend` to
:func:`build` to enable enhanced functionality. Below, we prepare a Bell state
by automatically compiling the required pulses from their gate-level
representations, while simultaneously applying a long decoupling pulse to a
neighboring qubit. We terminate the experiment with a measurement to observe the
state we prepared. This program which mixes circuits and pulses will be
automatically lowered to be run as a pulse program:
.. plot::
:include-source:
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse3Q
# TODO: This example should use a real mock backend.
backend = FakeOpenPulse3Q()
d2 = pulse.DriveChannel(2)
with pulse.build(backend) as bell_prep:
pulse.u2(0, math.pi, 0)
pulse.cx(0, 1)
with pulse.build(backend) as decoupled_bell_prep_and_measure:
# We call our bell state preparation schedule constructed above.
with pulse.align_right():
pulse.call(bell_prep)
pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2)
pulse.barrier(0, 1, 2)
registers = pulse.measure_all()
decoupled_bell_prep_and_measure.draw()
With the pulse builder we are able to blend programming on qubits and channels.
While the pulse schedule is based on instructions that operate on
channels, the pulse builder automatically handles the mapping from qubits to
channels for you.
In the example below we demonstrate some more features of the pulse builder:
.. code-block::
import math
from qiskit import pulse, QuantumCircuit
from qiskit.pulse import library
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
# Create a pulse.
gaussian_pulse = library.gaussian(10, 1.0, 2)
# Get the qubit's corresponding drive channel from the backend.
d0 = pulse.drive_channel(0)
d1 = pulse.drive_channel(1)
# Play a pulse at t=0.
pulse.play(gaussian_pulse, d0)
# Play another pulse directly after the previous pulse at t=10.
pulse.play(gaussian_pulse, d0)
# The default scheduling behavior is to schedule pulses in parallel
# across channels. For example, the statement below
# plays the same pulse on a different channel at t=0.
pulse.play(gaussian_pulse, d1)
# We also provide pulse scheduling alignment contexts.
# The default alignment context is align_left.
# The sequential context schedules pulse instructions sequentially in time.
# This context starts at t=10 due to earlier pulses above.
with pulse.align_sequential():
pulse.play(gaussian_pulse, d0)
# Play another pulse after at t=20.
pulse.play(gaussian_pulse, d1)
# We can also nest contexts as each instruction is
# contained in its local scheduling context.
# The output of a child context is a context-schedule
# with the internal instructions timing fixed relative to
# one another. This is schedule is then called in the parent context.
# Context starts at t=30.
with pulse.align_left():
# Start at t=30.
pulse.play(gaussian_pulse, d0)
# Start at t=30.
pulse.play(gaussian_pulse, d1)
# Context ends at t=40.
# Alignment context where all pulse instructions are
# aligned to the right, ie., as late as possible.
with pulse.align_right():
# Shift the phase of a pulse channel.
pulse.shift_phase(math.pi, d1)
# Starts at t=40.
pulse.delay(100, d0)
# Ends at t=140.
# Starts at t=130.
pulse.play(gaussian_pulse, d1)
# Ends at t=140.
# Acquire data for a qubit and store in a memory slot.
pulse.acquire(100, 0, pulse.MemorySlot(0))
# We also support a variety of macros for common operations.
# Measure all qubits.
pulse.measure_all()
# Delay on some qubits.
# This requires knowledge of which channels belong to which qubits.
# delay for 100 cycles on qubits 0 and 1.
pulse.delay_qubits(100, 0, 1)
# Call a quantum circuit. The pulse builder lazily constructs a quantum
# circuit which is then transpiled and scheduled before inserting into
# a pulse schedule.
# NOTE: Quantum register indices correspond to physical qubit indices.
qc = QuantumCircuit(2, 2)
qc.cx(0, 1)
pulse.call(qc)
# Calling a small set of standard gates and decomposing to pulses is
# also supported with more natural syntax.
pulse.u3(0, math.pi, 0, 0)
pulse.cx(0, 1)
# It is also be possible to call a preexisting schedule
tmp_sched = pulse.Schedule()
tmp_sched += pulse.Play(gaussian_pulse, d0)
pulse.call(tmp_sched)
# We also support:
# frequency instructions
pulse.set_frequency(5.0e9, d0)
# phase instructions
pulse.shift_phase(0.1, d0)
# offset contexts
with pulse.phase_offset(math.pi, d0):
pulse.play(gaussian_pulse, d0)
The above is just a small taste of what is possible with the builder. See the rest of the module
documentation for more information on its capabilities.
.. autofunction:: build
Channels
========
Methods to return the correct channels for the respective qubit indices.
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as drive_sched:
d0 = pulse.drive_channel(0)
print(d0)
.. parsed-literal::
DriveChannel(0)
.. autofunction:: acquire_channel
.. autofunction:: control_channels
.. autofunction:: drive_channel
.. autofunction:: measure_channel
Instructions
============
Pulse instructions are available within the builder interface. Here's an example:
.. plot::
:include-source:
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as drive_sched:
d0 = pulse.drive_channel(0)
a0 = pulse.acquire_channel(0)
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.delay(20, d0)
pulse.shift_phase(3.14/2, d0)
pulse.set_phase(3.14, d0)
pulse.shift_frequency(1e7, d0)
pulse.set_frequency(5e9, d0)
with pulse.build() as temp_sched:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0)
pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0)
pulse.call(temp_sched)
pulse.acquire(30, a0, pulse.MemorySlot(0))
drive_sched.draw()
.. autofunction:: acquire
.. autofunction:: barrier
.. autofunction:: call
.. autofunction:: delay
.. autofunction:: play
.. autofunction:: reference
.. autofunction:: set_frequency
.. autofunction:: set_phase
.. autofunction:: shift_frequency
.. autofunction:: shift_phase
.. autofunction:: snapshot
Contexts
========
Builder aware contexts that modify the construction of a pulse program. For
example an alignment context like :func:`align_right` may
be used to align all pulses as late as possible in a pulse program.
.. plot::
:include-source:
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_right():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will start at t=80
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog.draw()
.. autofunction:: align_equispaced
.. autofunction:: align_func
.. autofunction:: align_left
.. autofunction:: align_right
.. autofunction:: align_sequential
.. autofunction:: circuit_scheduler_settings
.. autofunction:: frequency_offset
.. autofunction:: phase_offset
.. autofunction:: transpiler_settings
Macros
======
Macros help you add more complex functionality to your pulse program.
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as measure_sched:
mem_slot = pulse.measure(0)
print(mem_slot)
.. parsed-literal::
MemorySlot(0)
.. autofunction:: measure
.. autofunction:: measure_all
.. autofunction:: delay_qubits
Circuit Gates
=============
To use circuit level gates within your pulse program call a circuit
with :func:`call`.
.. warning::
These will be removed in future versions with the release of a circuit
builder interface in which it will be possible to calibrate a gate in
terms of pulses and use that gate in a circuit.
.. code-block::
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as u3_sched:
pulse.u3(math.pi, 0, math.pi, 0)
.. autofunction:: cx
.. autofunction:: u1
.. autofunction:: u2
.. autofunction:: u3
.. autofunction:: x
Utilities
=========
The utility functions can be used to gather attributes about the backend and modify
how the program is built.
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as u3_sched:
print('Number of qubits in backend: {}'.format(pulse.num_qubits()))
samples = 160
print('There are {} samples in {} seconds'.format(
samples, pulse.samples_to_seconds(160)))
seconds = 1e-6
print('There are {} seconds in {} samples.'.format(
seconds, pulse.seconds_to_samples(1e-6)))
.. parsed-literal::
Number of qubits in backend: 1
There are 160 samples in 3.5555555555555554e-08 seconds
There are 1e-06 seconds in 4500 samples.
.. autofunction:: active_backend
.. autofunction:: active_transpiler_settings
.. autofunction:: active_circuit_scheduler_settings
.. autofunction:: num_qubits
.. autofunction:: qubit_channels
.. autofunction:: samples_to_seconds
.. autofunction:: seconds_to_samples
"""
import collections
import contextvars
import functools
import itertools
import uuid
import warnings
from contextlib import contextmanager
from functools import singledispatchmethod
from typing import (
Any,
Callable,
ContextManager,
Dict,
Iterable,
List,
Mapping,
Optional,
Set,
Tuple,
TypeVar,
Union,
NewType,
)
import numpy as np
from qiskit import circuit
from qiskit.circuit.library import standard_gates as gates
from qiskit.circuit.parameterexpression import ParameterExpression, ParameterValueType
from qiskit.pulse import (
channels as chans,
configuration,
exceptions,
instructions,
macros,
library,
transforms,
)
from qiskit.providers.backend import BackendV2
from qiskit.pulse.instructions import directives
from qiskit.pulse.schedule import Schedule, ScheduleBlock
from qiskit.pulse.transforms.alignments import AlignmentKind
#: contextvars.ContextVar[BuilderContext]: active builder
BUILDER_CONTEXTVAR = contextvars.ContextVar("backend")
T = TypeVar("T")
StorageLocation = NewType("StorageLocation", Union[chans.MemorySlot, chans.RegisterSlot])
def _compile_lazy_circuit_before(function: Callable[..., T]) -> Callable[..., T]:
"""Decorator thats schedules and calls the lazily compiled circuit before
executing the decorated builder method."""
@functools.wraps(function)
def wrapper(self, *args, **kwargs):
self._compile_lazy_circuit()
return function(self, *args, **kwargs)
return wrapper
def _requires_backend(function: Callable[..., T]) -> Callable[..., T]:
"""Decorator a function to raise if it is called without a builder with a
set backend.
"""
@functools.wraps(function)
def wrapper(self, *args, **kwargs):
if self.backend is None:
raise exceptions.BackendNotSet(
'This function requires the builder to have a "backend" set.'
)
return function(self, *args, **kwargs)
return wrapper
class _PulseBuilder:
"""Builder context class."""
__alignment_kinds__ = {
"left": transforms.AlignLeft(),
"right": transforms.AlignRight(),
"sequential": transforms.AlignSequential(),
}
def __init__(
self,
backend=None,
block: Optional[ScheduleBlock] = None,
name: Optional[str] = None,
default_alignment: Union[str, AlignmentKind] = "left",
default_transpiler_settings: Mapping = None,
default_circuit_scheduler_settings: Mapping = None,
):
"""Initialize the builder context.
.. note::
At some point we may consider incorporating the builder into
the :class:`~qiskit.pulse.Schedule` class. However, the risk of
this is tying the user interface to the intermediate
representation. For now we avoid this at the cost of some code
duplication.
Args:
backend (Backend): Input backend to use in
builder. If not set certain functionality will be unavailable.
block: Initital ``ScheduleBlock`` to build on.
name: Name of pulse program to be built.
default_alignment: Default scheduling alignment for builder.
One of ``left``, ``right``, ``sequential`` or an instance of
:class:`~qiskit.pulse.transforms.alignments.AlignmentKind` subclass.
default_transpiler_settings: Default settings for the transpiler.
default_circuit_scheduler_settings: Default settings for the
circuit to pulse scheduler.
Raises:
PulseError: When invalid ``default_alignment`` or `block` is specified.
"""
#: Backend: Backend instance for context builder.
self._backend = backend
#: Union[None, ContextVar]: Token for this ``_PulseBuilder``'s ``ContextVar``.
self._backend_ctx_token = None
#: QuantumCircuit: Lazily constructed quantum circuit
self._lazy_circuit = None
#: Dict[str, Any]: Transpiler setting dictionary.
self._transpiler_settings = default_transpiler_settings or {}
#: Dict[str, Any]: Scheduler setting dictionary.
self._circuit_scheduler_settings = default_circuit_scheduler_settings or {}
#: List[ScheduleBlock]: Stack of context.
self._context_stack = []
#: str: Name of the output program
self._name = name
# Add root block if provided. Schedule will be built on top of this.
if block is not None:
if isinstance(block, ScheduleBlock):
root_block = block
elif isinstance(block, Schedule):
root_block = self._naive_typecast_schedule(block)
else:
raise exceptions.PulseError(
f"Input `block` type {block.__class__.__name__} is "
"not a valid format. Specify a pulse program."
)
self._context_stack.append(root_block)
# Set default alignment context
alignment = _PulseBuilder.__alignment_kinds__.get(default_alignment, default_alignment)
if not isinstance(alignment, AlignmentKind):
raise exceptions.PulseError(
f"Given `default_alignment` {repr(default_alignment)} is "
"not a valid transformation. Set one of "
f'{", ".join(_PulseBuilder.__alignment_kinds__.keys())}, '
"or set an instance of `AlignmentKind` subclass."
)
self.push_context(alignment)
def __enter__(self) -> ScheduleBlock:
"""Enter this builder context and yield either the supplied schedule
or the schedule created for the user.
Returns:
The schedule that the builder will build on.
"""
self._backend_ctx_token = BUILDER_CONTEXTVAR.set(self)
output = self._context_stack[0]
output._name = self._name or output.name
return output
@_compile_lazy_circuit_before
def __exit__(self, exc_type, exc_val, exc_tb):
"""Exit the builder context and compile the built pulse program."""
self.compile()
BUILDER_CONTEXTVAR.reset(self._backend_ctx_token)
@property
def backend(self):
"""Returns the builder backend if set.
Returns:
Optional[Backend]: The builder's backend.
"""
return self._backend
@_compile_lazy_circuit_before
def push_context(self, alignment: AlignmentKind):
"""Push new context to the stack."""
self._context_stack.append(ScheduleBlock(alignment_context=alignment))
@_compile_lazy_circuit_before
def pop_context(self) -> ScheduleBlock:
"""Pop the last context from the stack."""
if len(self._context_stack) == 1:
raise exceptions.PulseError("The root context cannot be popped out.")
return self._context_stack.pop()
def get_context(self) -> ScheduleBlock:
"""Get current context.
Notes:
New instruction can be added by `.append_subroutine` or `.append_instruction` method.
Use above methods rather than directly accessing to the current context.
"""
return self._context_stack[-1]
@property
@_requires_backend
def num_qubits(self):
"""Get the number of qubits in the backend."""
# backendV2
if isinstance(self.backend, BackendV2):
return self.backend.num_qubits
return self.backend.configuration().n_qubits
@property
def transpiler_settings(self) -> Mapping:
"""The builder's transpiler settings."""
return self._transpiler_settings
@transpiler_settings.setter
@_compile_lazy_circuit_before
def transpiler_settings(self, settings: Mapping):
self._compile_lazy_circuit()
self._transpiler_settings = settings
@property
def circuit_scheduler_settings(self) -> Mapping:
"""The builder's circuit to pulse scheduler settings."""
return self._circuit_scheduler_settings
@circuit_scheduler_settings.setter
@_compile_lazy_circuit_before
def circuit_scheduler_settings(self, settings: Mapping):
self._compile_lazy_circuit()
self._circuit_scheduler_settings = settings
@_compile_lazy_circuit_before
def compile(self) -> ScheduleBlock:
"""Compile and output the built pulse program."""
# Not much happens because we currently compile as we build.
# This should be offloaded to a true compilation module
# once we define a more sophisticated IR.
while len(self._context_stack) > 1:
current = self.pop_context()
self.append_subroutine(current)
return self._context_stack[0]
def _compile_lazy_circuit(self):
"""Call a context QuantumCircuit (lazy circuit) and append the output pulse schedule
to the builder's context schedule.
Note that the lazy circuit is not stored as a call instruction.
"""
if self._lazy_circuit:
lazy_circuit = self._lazy_circuit
# reset lazy circuit
self._lazy_circuit = self._new_circuit()
self.call_subroutine(self._compile_circuit(lazy_circuit))
def _compile_circuit(self, circ) -> Schedule:
"""Take a QuantumCircuit and output the pulse schedule associated with the circuit."""
from qiskit import compiler # pylint: disable=cyclic-import
transpiled_circuit = compiler.transpile(circ, self.backend, **self.transpiler_settings)
sched = compiler.schedule(
transpiled_circuit, self.backend, **self.circuit_scheduler_settings
)
return sched
def _new_circuit(self):
"""Create a new circuit for lazy circuit scheduling."""
return circuit.QuantumCircuit(self.num_qubits)
@_compile_lazy_circuit_before
def append_instruction(self, instruction: instructions.Instruction):
"""Add an instruction to the builder's context schedule.
Args:
instruction: Instruction to append.
"""
self._context_stack[-1].append(instruction)
def append_reference(self, name: str, *extra_keys: str):
"""Add external program as a :class:`~qiskit.pulse.instructions.Reference` instruction.
Args:
name: Name of subroutine.
extra_keys: Assistance keys to uniquely specify the subroutine.
"""
inst = instructions.Reference(name, *extra_keys)
self.append_instruction(inst)
@_compile_lazy_circuit_before
def append_subroutine(self, subroutine: Union[Schedule, ScheduleBlock]):
"""Append a :class:`ScheduleBlock` to the builder's context schedule.
This operation doesn't create a reference. Subroutine is directly
appended to current context schedule.
Args:
subroutine: ScheduleBlock to append to the current context block.
Raises:
PulseError: When subroutine is not Schedule nor ScheduleBlock.
"""
if not isinstance(subroutine, (ScheduleBlock, Schedule)):
raise exceptions.PulseError(
f"'{subroutine.__class__.__name__}' is not valid data format in the builder. "
"'Schedule' and 'ScheduleBlock' can be appended to the builder context."
)
if len(subroutine) == 0:
return
if isinstance(subroutine, Schedule):
subroutine = self._naive_typecast_schedule(subroutine)
self._context_stack[-1].append(subroutine)
@singledispatchmethod
def call_subroutine(
self,
subroutine: Union[circuit.QuantumCircuit, Schedule, ScheduleBlock],
name: Optional[str] = None,
value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None,
**kw_params: ParameterValueType,
):
"""Call a schedule or circuit defined outside of the current scope.
The ``subroutine`` is appended to the context schedule as a call instruction.
This logic just generates a convenient program representation in the compiler.
Thus, this doesn't affect execution of inline subroutines.
See :class:`~pulse.instructions.Call` for more details.
Args:
subroutine: Target schedule or circuit to append to the current context.
name: Name of subroutine if defined.
value_dict: Parameter object and assigned value mapping. This is more precise way to
identify a parameter since mapping is managed with unique object id rather than
name. Especially there is any name collision in a parameter table.
kw_params: Parameter values to bind to the target subroutine
with string parameter names. If there are parameter name overlapping,
these parameters are updated with the same assigned value.
Raises:
PulseError:
- When input subroutine is not valid data format.
"""
raise exceptions.PulseError(
f"Subroutine type {subroutine.__class__.__name__} is "
"not valid data format. Call QuantumCircuit, "
"Schedule, or ScheduleBlock."
)
@call_subroutine.register
def _(
self,
target_block: ScheduleBlock,
name: Optional[str] = None,
value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None,
**kw_params: ParameterValueType,
):
if len(target_block) == 0:
return
# Create local parameter assignment
local_assignment = {}
for param_name, value in kw_params.items():
params = target_block.get_parameters(param_name)
if not params:
raise exceptions.PulseError(
f"Parameter {param_name} is not defined in the target subroutine. "
f'{", ".join(map(str, target_block.parameters))} can be specified.'
)
for param in params:
local_assignment[param] = value
if value_dict:
if local_assignment.keys() & value_dict.keys():
warnings.warn(
"Some parameters provided by 'value_dict' conflict with one through "
"keyword arguments. Parameter values in the keyword arguments "
"are overridden by the dictionary values.",
UserWarning,
)
local_assignment.update(value_dict)
if local_assignment:
target_block = target_block.assign_parameters(local_assignment, inplace=False)
if name is None:
# Add unique string, not to accidentally override existing reference entry.
keys = (target_block.name, uuid.uuid4().hex)
else:
keys = (name,)
self.append_reference(*keys)
self.get_context().assign_references({keys: target_block}, inplace=True)
@call_subroutine.register
def _(
self,
target_schedule: Schedule,
name: Optional[str] = None,
value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None,
**kw_params: ParameterValueType,
):
if len(target_schedule) == 0:
return
self.call_subroutine(
self._naive_typecast_schedule(target_schedule),
name=name,
value_dict=value_dict,
**kw_params,
)
@call_subroutine.register
def _(
self,
target_circuit: circuit.QuantumCircuit,
name: Optional[str] = None,
value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None,
**kw_params: ParameterValueType,
):
if len(target_circuit) == 0:
return
self._compile_lazy_circuit()
self.call_subroutine(
self._compile_circuit(target_circuit),
name=name,
value_dict=value_dict,
**kw_params,
)
@_requires_backend
def call_gate(self, gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True):
"""Call the circuit ``gate`` in the pulse program.
The qubits are assumed to be defined on physical qubits.
If ``lazy == True`` this circuit will extend a lazily constructed
quantum circuit. When an operation occurs that breaks the underlying
circuit scheduling assumptions such as adding a pulse instruction or
changing the alignment context the circuit will be
transpiled and scheduled into pulses with the current active settings.
Args:
gate: Gate to call.
qubits: Qubits to call gate on.
lazy: If false the circuit will be transpiled and pulse scheduled
immediately. Otherwise, it will extend the active lazy circuit
as defined above.
"""
try:
iter(qubits)
except TypeError:
qubits = (qubits,)
if lazy:
self._call_gate(gate, qubits)
else:
self._compile_lazy_circuit()
self._call_gate(gate, qubits)
self._compile_lazy_circuit()
def _call_gate(self, gate, qargs):
if self._lazy_circuit is None:
self._lazy_circuit = self._new_circuit()
self._lazy_circuit.append(gate, qargs=qargs)
@staticmethod
def _naive_typecast_schedule(schedule: Schedule):
# Naively convert into ScheduleBlock
from qiskit.pulse.transforms import inline_subroutines, flatten, pad
preprocessed_schedule = inline_subroutines(flatten(schedule))
pad(preprocessed_schedule, inplace=True, pad_with=instructions.TimeBlockade)
# default to left alignment, namely ASAP scheduling
target_block = ScheduleBlock(name=schedule.name)
for _, inst in preprocessed_schedule.instructions:
target_block.append(inst, inplace=True)
return target_block
def get_dt(self):
"""Retrieve dt differently based on the type of Backend"""
if isinstance(self.backend, BackendV2):
return self.backend.dt
return self.backend.configuration().dt
def build(
backend=None,
schedule: Optional[ScheduleBlock] = None,
name: Optional[str] = None,
default_alignment: Optional[Union[str, AlignmentKind]] = "left",
default_transpiler_settings: Optional[Dict[str, Any]] = None,
default_circuit_scheduler_settings: Optional[Dict[str, Any]] = None,
) -> ContextManager[ScheduleBlock]:
"""Create a context manager for launching the imperative pulse builder DSL.
To enter a building context and starting building a pulse program:
.. code-block::
from qiskit import execute, pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(100, 0.5), d0)
While the output program ``pulse_prog`` cannot be executed as we are using
a mock backend. If a real backend is being used, executing the program is
done with:
.. code-block:: python
qiskit.execute(pulse_prog, backend)
Args:
backend (Backend): A Qiskit backend. If not supplied certain
builder functionality will be unavailable.
schedule: A pulse ``ScheduleBlock`` in which your pulse program will be built.
name: Name of pulse program to be built.
default_alignment: Default scheduling alignment for builder.
One of ``left``, ``right``, ``sequential`` or an alignment context.
default_transpiler_settings: Default settings for the transpiler.
default_circuit_scheduler_settings: Default settings for the
circuit to pulse scheduler.
Returns:
A new builder context which has the active builder initialized.
"""
return _PulseBuilder(
backend=backend,
block=schedule,
name=name,
default_alignment=default_alignment,
default_transpiler_settings=default_transpiler_settings,
default_circuit_scheduler_settings=default_circuit_scheduler_settings,
)
# Builder Utilities
def _active_builder() -> _PulseBuilder:
"""Get the active builder in the active context.
Returns:
The active active builder in this context.
Raises:
exceptions.NoActiveBuilder: If a pulse builder function is called
outside of a builder context.
"""
try:
return BUILDER_CONTEXTVAR.get()
except LookupError as ex:
raise exceptions.NoActiveBuilder(
"A Pulse builder function was called outside of "
"a builder context. Try calling within a builder "
'context, eg., "with pulse.build() as schedule: ...".'
) from ex
def active_backend():
"""Get the backend of the currently active builder context.
Returns:
Backend: The active backend in the currently active
builder context.
Raises:
exceptions.BackendNotSet: If the builder does not have a backend set.
"""
builder = _active_builder().backend
if builder is None:
raise exceptions.BackendNotSet(
'This function requires the active builder to have a "backend" set.'
)
return builder
def append_schedule(schedule: Union[Schedule, ScheduleBlock]):
"""Call a schedule by appending to the active builder's context block.
Args:
schedule: Schedule or ScheduleBlock to append.
"""
_active_builder().append_subroutine(schedule)
def append_instruction(instruction: instructions.Instruction):
"""Append an instruction to the active builder's context schedule.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.builder.append_instruction(pulse.Delay(10, d0))
print(pulse_prog.instructions)
.. parsed-literal::
((0, Delay(10, DriveChannel(0))),)
"""
_active_builder().append_instruction(instruction)
def num_qubits() -> int:
"""Return number of qubits in the currently active backend.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
print(pulse.num_qubits())
.. parsed-literal::
2
.. note:: Requires the active builder context to have a backend set.
"""
if isinstance(active_backend(), BackendV2):
return active_backend().num_qubits
return active_backend().configuration().n_qubits
def seconds_to_samples(seconds: Union[float, np.ndarray]) -> Union[int, np.ndarray]:
"""Obtain the number of samples that will elapse in ``seconds`` on the
active backend.
Rounds down.
Args:
seconds: Time in seconds to convert to samples.
Returns:
The number of samples for the time to elapse
"""
dt = _active_builder().get_dt()
if isinstance(seconds, np.ndarray):
return (seconds / dt).astype(int)
return int(seconds / dt)
def samples_to_seconds(samples: Union[int, np.ndarray]) -> Union[float, np.ndarray]:
"""Obtain the time in seconds that will elapse for the input number of
samples on the active backend.
Args:
samples: Number of samples to convert to time in seconds.
Returns:
The time that elapses in ``samples``.
"""
return samples * _active_builder().get_dt()
def qubit_channels(qubit: int) -> Set[chans.Channel]:
"""Returns the set of channels associated with a qubit.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
print(pulse.qubit_channels(0))
.. parsed-literal::
{MeasureChannel(0), ControlChannel(0), DriveChannel(0), AcquireChannel(0), ControlChannel(1)}
.. note:: Requires the active builder context to have a backend set.
.. note:: A channel may still be associated with another qubit in this list
such as in the case where significant crosstalk exists.
"""
# implement as the inner function to avoid API change for a patch release in 0.24.2.
def get_qubit_channels_v2(backend: BackendV2, qubit: int):
r"""Return a list of channels which operate on the given ``qubit``.
Returns:
List of ``Channel``\s operated on my the given ``qubit``.
"""
channels = []
# add multi-qubit channels
for node_qubits in backend.coupling_map:
if qubit in node_qubits:
control_channel = backend.control_channel(node_qubits)
if control_channel:
channels.extend(control_channel)
# add single qubit channels
channels.append(backend.drive_channel(qubit))
channels.append(backend.measure_channel(qubit))
channels.append(backend.acquire_channel(qubit))
return channels
# backendV2
if isinstance(active_backend(), BackendV2):
return set(get_qubit_channels_v2(active_backend(), qubit))
return set(active_backend().configuration().get_qubit_channels(qubit))
def _qubits_to_channels(*channels_or_qubits: Union[int, chans.Channel]) -> Set[chans.Channel]:
"""Returns the unique channels of the input qubits."""
channels = set()
for channel_or_qubit in channels_or_qubits:
if isinstance(channel_or_qubit, int):
channels |= qubit_channels(channel_or_qubit)
elif isinstance(channel_or_qubit, chans.Channel):
channels.add(channel_or_qubit)
else:
raise exceptions.PulseError(
f'{channel_or_qubit} is not a "Channel" or qubit (integer).'
)
return channels
def active_transpiler_settings() -> Dict[str, Any]:
"""Return the current active builder context's transpiler settings.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
transpiler_settings = {'optimization_level': 3}
with pulse.build(backend,
default_transpiler_settings=transpiler_settings):
print(pulse.active_transpiler_settings())
.. parsed-literal::
{'optimization_level': 3}
"""
return dict(_active_builder().transpiler_settings)
def active_circuit_scheduler_settings() -> Dict[str, Any]:
"""Return the current active builder context's circuit scheduler settings.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
circuit_scheduler_settings = {'method': 'alap'}
with pulse.build(
backend,
default_circuit_scheduler_settings=circuit_scheduler_settings):
print(pulse.active_circuit_scheduler_settings())
.. parsed-literal::
{'method': 'alap'}
"""
return dict(_active_builder().circuit_scheduler_settings)
# Contexts
@contextmanager
def align_left() -> ContextManager[None]:
"""Left alignment pulse scheduling context.
Pulse instructions within this context are scheduled as early as possible
by shifting them left to the earliest available time.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_left():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will start at t=0
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog = pulse.transforms.block_to_schedule(pulse_prog)
assert pulse_prog.ch_start_time(d0) == pulse_prog.ch_start_time(d1)
Yields:
None
"""
builder = _active_builder()
builder.push_context(transforms.AlignLeft())
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def align_right() -> AlignmentKind:
"""Right alignment pulse scheduling context.
Pulse instructions within this context are scheduled as late as possible
by shifting them right to the latest available time.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_right():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will start at t=80
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog = pulse.transforms.block_to_schedule(pulse_prog)
assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_stop_time(d1)
Yields:
None
"""
builder = _active_builder()
builder.push_context(transforms.AlignRight())
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def align_sequential() -> AlignmentKind:
"""Sequential alignment pulse scheduling context.
Pulse instructions within this context are scheduled sequentially in time
such that no two instructions will be played at the same time.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_sequential():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will also start at t=100
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog = pulse.transforms.block_to_schedule(pulse_prog)
assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_start_time(d1)
Yields:
None
"""
builder = _active_builder()
builder.push_context(transforms.AlignSequential())
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def align_equispaced(duration: Union[int, ParameterExpression]) -> AlignmentKind:
"""Equispaced alignment pulse scheduling context.
Pulse instructions within this context are scheduled with the same interval spacing such that
the total length of the context block is ``duration``.
If the total free ``duration`` cannot be evenly divided by the number of instructions
within the context, the modulo is split and then prepended and appended to
the returned schedule. Delay instructions are automatically inserted in between pulses.
This context is convenient to write a schedule for periodical dynamic decoupling or
the Hahn echo sequence.
Examples:
.. plot::
:include-source:
from qiskit import pulse
d0 = pulse.DriveChannel(0)
x90 = pulse.Gaussian(10, 0.1, 3)
x180 = pulse.Gaussian(10, 0.2, 3)
with pulse.build() as hahn_echo:
with pulse.align_equispaced(duration=100):
pulse.play(x90, d0)
pulse.play(x180, d0)
pulse.play(x90, d0)
hahn_echo.draw()
Args:
duration: Duration of this context. This should be larger than the schedule duration.
Yields:
None
Notes:
The scheduling is performed for sub-schedules within the context rather than
channel-wise. If you want to apply the equispaced context for each channel,
you should use the context independently for channels.
"""
builder = _active_builder()
builder.push_context(transforms.AlignEquispaced(duration=duration))
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def align_func(
duration: Union[int, ParameterExpression], func: Callable[[int], float]
) -> AlignmentKind:
"""Callback defined alignment pulse scheduling context.
Pulse instructions within this context are scheduled at the location specified by
arbitrary callback function `position` that takes integer index and returns
the associated fractional location within [0, 1].
Delay instruction is automatically inserted in between pulses.
This context may be convenient to write a schedule of arbitrary dynamical decoupling
sequences such as Uhrig dynamical decoupling.
Examples:
.. plot::
:include-source:
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()
Args:
duration: Duration of context. This should be larger than the schedule duration.
func: A function that takes an index of sub-schedule and returns the
fractional coordinate of of that sub-schedule.
The returned value should be defined within [0, 1].
The pulse index starts from 1.
Yields:
None
Notes:
The scheduling is performed for sub-schedules within the context rather than
channel-wise. If you want to apply the numerical context for each channel,
you need to apply the context independently to channels.
"""
builder = _active_builder()
builder.push_context(transforms.AlignFunc(duration=duration, func=func))
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def general_transforms(alignment_context: AlignmentKind) -> ContextManager[None]:
"""Arbitrary alignment transformation defined by a subclass instance of
:class:`~qiskit.pulse.transforms.alignments.AlignmentKind`.
Args:
alignment_context: Alignment context instance that defines schedule transformation.
Yields:
None
Raises:
PulseError: When input ``alignment_context`` is not ``AlignmentKind`` subclasses.
"""
if not isinstance(alignment_context, AlignmentKind):
raise exceptions.PulseError("Input alignment context is not `AlignmentKind` subclass.")
builder = _active_builder()
builder.push_context(alignment_context)
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def transpiler_settings(**settings) -> ContextManager[None]:
"""Set the currently active transpiler settings for this context.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
print(pulse.active_transpiler_settings())
with pulse.transpiler_settings(optimization_level=3):
print(pulse.active_transpiler_settings())
.. parsed-literal::
{}
{'optimization_level': 3}
"""
builder = _active_builder()
curr_transpiler_settings = builder.transpiler_settings
builder.transpiler_settings = collections.ChainMap(settings, curr_transpiler_settings)
try:
yield
finally:
builder.transpiler_settings = curr_transpiler_settings
@contextmanager
def circuit_scheduler_settings(**settings) -> ContextManager[None]:
"""Set the currently active circuit scheduler settings for this context.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
print(pulse.active_circuit_scheduler_settings())
with pulse.circuit_scheduler_settings(method='alap'):
print(pulse.active_circuit_scheduler_settings())
.. parsed-literal::
{}
{'method': 'alap'}
"""
builder = _active_builder()
curr_circuit_scheduler_settings = builder.circuit_scheduler_settings
builder.circuit_scheduler_settings = collections.ChainMap(
settings, curr_circuit_scheduler_settings
)
try:
yield
finally:
builder.circuit_scheduler_settings = curr_circuit_scheduler_settings
@contextmanager
def phase_offset(phase: float, *channels: chans.PulseChannel) -> ContextManager[None]:
"""Shift the phase of input channels on entry into context and undo on exit.
Examples:
.. code-block::
import math
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
with pulse.phase_offset(math.pi, d0):
pulse.play(pulse.Constant(10, 1.0), d0)
assert len(pulse_prog.instructions) == 3
Args:
phase: Amount of phase offset in radians.
channels: Channels to offset phase of.
Yields:
None
"""
for channel in channels:
shift_phase(phase, channel)
try:
yield
finally:
for channel in channels:
shift_phase(-phase, channel)
@contextmanager
def frequency_offset(
frequency: float, *channels: chans.PulseChannel, compensate_phase: bool = False
) -> ContextManager[None]:
"""Shift the frequency of inputs channels on entry into context and undo on exit.
Examples:
.. code-block:: python
:emphasize-lines: 7, 16
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build(backend) as pulse_prog:
# shift frequency by 1GHz
with pulse.frequency_offset(1e9, d0):
pulse.play(pulse.Constant(10, 1.0), d0)
assert len(pulse_prog.instructions) == 3
with pulse.build(backend) as pulse_prog:
# Shift frequency by 1GHz.
# Undo accumulated phase in the shifted frequency frame
# when exiting the context.
with pulse.frequency_offset(1e9, d0, compensate_phase=True):
pulse.play(pulse.Constant(10, 1.0), d0)
assert len(pulse_prog.instructions) == 4
Args:
frequency: Amount of frequency offset in Hz.
channels: Channels to offset frequency of.
compensate_phase: Compensate for accumulated phase accumulated with
respect to the channels' frame at its initial frequency.
Yields:
None
"""
builder = _active_builder()
# TODO: Need proper implementation of compensation. t0 may depend on the parent context.
# For example, the instruction position within the equispaced context depends on
# the current total number of instructions, thus adding more instruction after
# offset context may change the t0 when the parent context is transformed.
t0 = builder.get_context().duration
for channel in channels:
shift_frequency(frequency, channel)
try:
yield
finally:
if compensate_phase:
duration = builder.get_context().duration - t0
accumulated_phase = 2 * np.pi * ((duration * builder.get_dt() * frequency) % 1)
for channel in channels:
shift_phase(-accumulated_phase, channel)
for channel in channels:
shift_frequency(-frequency, channel)
# Channels
def drive_channel(qubit: int) -> chans.DriveChannel:
"""Return ``DriveChannel`` for ``qubit`` on the active builder backend.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
assert pulse.drive_channel(0) == pulse.DriveChannel(0)
.. note:: Requires the active builder context to have a backend set.
"""
# backendV2
if isinstance(active_backend(), BackendV2):
return active_backend().drive_channel(qubit)
return active_backend().configuration().drive(qubit)
def measure_channel(qubit: int) -> chans.MeasureChannel:
"""Return ``MeasureChannel`` for ``qubit`` on the active builder backend.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
assert pulse.measure_channel(0) == pulse.MeasureChannel(0)
.. note:: Requires the active builder context to have a backend set.
"""
# backendV2
if isinstance(active_backend(), BackendV2):
return active_backend().measure_channel(qubit)
return active_backend().configuration().measure(qubit)
def acquire_channel(qubit: int) -> chans.AcquireChannel:
"""Return ``AcquireChannel`` for ``qubit`` on the active builder backend.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
assert pulse.acquire_channel(0) == pulse.AcquireChannel(0)
.. note:: Requires the active builder context to have a backend set.
"""
# backendV2
if isinstance(active_backend(), BackendV2):
return active_backend().acquire_channel(qubit)
return active_backend().configuration().acquire(qubit)
def control_channels(*qubits: Iterable[int]) -> List[chans.ControlChannel]:
"""Return ``ControlChannel`` for ``qubit`` on the active builder backend.
Return the secondary drive channel for the given qubit -- typically
utilized for controlling multi-qubit interactions.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
assert pulse.control_channels(0, 1) == [pulse.ControlChannel(0)]
.. note:: Requires the active builder context to have a backend set.
Args:
qubits: Tuple or list of ordered qubits of the form
`(control_qubit, target_qubit)`.
Returns:
List of control channels associated with the supplied ordered list
of qubits.
"""
# backendV2
if isinstance(active_backend(), BackendV2):
return active_backend().control_channel(qubits)
return active_backend().configuration().control(qubits=qubits)
# Base Instructions
def delay(duration: int, channel: chans.Channel, name: Optional[str] = None):
"""Delay on a ``channel`` for a ``duration``.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.delay(10, d0)
Args:
duration: Number of cycles to delay for on ``channel``.
channel: Channel to delay on.
name: Name of the instruction.
"""
append_instruction(instructions.Delay(duration, channel, name=name))
def play(
pulse: Union[library.Pulse, np.ndarray], channel: chans.PulseChannel, name: Optional[str] = None
):
"""Play a ``pulse`` on a ``channel``.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(10, 1.0), d0)
Args:
pulse: Pulse to play.
channel: Channel to play pulse on.
name: Name of the pulse.
"""
if not isinstance(pulse, library.Pulse):
pulse = library.Waveform(pulse)
append_instruction(instructions.Play(pulse, channel, name=name))
def acquire(
duration: int,
qubit_or_channel: Union[int, chans.AcquireChannel],
register: StorageLocation,
**metadata: Union[configuration.Kernel, configuration.Discriminator],
):
"""Acquire for a ``duration`` on a ``channel`` and store the result
in a ``register``.
Examples:
.. code-block::
from qiskit import pulse
acq0 = pulse.AcquireChannel(0)
mem0 = pulse.MemorySlot(0)
with pulse.build() as pulse_prog:
pulse.acquire(100, acq0, mem0)
# measurement metadata
kernel = pulse.configuration.Kernel('linear_discriminator')
pulse.acquire(100, acq0, mem0, kernel=kernel)
.. note:: The type of data acquire will depend on the execution ``meas_level``.
Args:
duration: Duration to acquire data for
qubit_or_channel: Either the qubit to acquire data for or the specific
:class:`~qiskit.pulse.channels.AcquireChannel` to acquire on.
register: Location to store measured result.
metadata: Additional metadata for measurement. See
:class:`~qiskit.pulse.instructions.Acquire` for more information.
Raises:
exceptions.PulseError: If the register type is not supported.
"""
if isinstance(qubit_or_channel, int):
qubit_or_channel = chans.AcquireChannel(qubit_or_channel)
if isinstance(register, chans.MemorySlot):
append_instruction(
instructions.Acquire(duration, qubit_or_channel, mem_slot=register, **metadata)
)
elif isinstance(register, chans.RegisterSlot):
append_instruction(
instructions.Acquire(duration, qubit_or_channel, reg_slot=register, **metadata)
)
else:
raise exceptions.PulseError(f'Register of type: "{type(register)}" is not supported')
def set_frequency(frequency: float, channel: chans.PulseChannel, name: Optional[str] = None):
"""Set the ``frequency`` of a pulse ``channel``.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.set_frequency(1e9, d0)
Args:
frequency: Frequency in Hz to set channel to.
channel: Channel to set frequency of.
name: Name of the instruction.
"""
append_instruction(instructions.SetFrequency(frequency, channel, name=name))
def shift_frequency(frequency: float, channel: chans.PulseChannel, name: Optional[str] = None):
"""Shift the ``frequency`` of a pulse ``channel``.
Examples:
.. code-block:: python
:emphasize-lines: 6
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.shift_frequency(1e9, d0)
Args:
frequency: Frequency in Hz to shift channel frequency by.
channel: Channel to shift frequency of.
name: Name of the instruction.
"""
append_instruction(instructions.ShiftFrequency(frequency, channel, name=name))
def set_phase(phase: float, channel: chans.PulseChannel, name: Optional[str] = None):
"""Set the ``phase`` of a pulse ``channel``.
Examples:
.. code-block:: python
:emphasize-lines: 8
import math
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.set_phase(math.pi, d0)
Args:
phase: Phase in radians to set channel carrier signal to.
channel: Channel to set phase of.
name: Name of the instruction.
"""
append_instruction(instructions.SetPhase(phase, channel, name=name))
def shift_phase(phase: float, channel: chans.PulseChannel, name: Optional[str] = None):
"""Shift the ``phase`` of a pulse ``channel``.
Examples:
.. code-block::
import math
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.shift_phase(math.pi, d0)
Args:
phase: Phase in radians to shift channel carrier signal by.
channel: Channel to shift phase of.
name: Name of the instruction.
"""
append_instruction(instructions.ShiftPhase(phase, channel, name))
def snapshot(label: str, snapshot_type: str = "statevector"):
"""Simulator snapshot.
Examples:
.. code-block::
from qiskit import pulse
with pulse.build() as pulse_prog:
pulse.snapshot('first', 'statevector')
Args:
label: Label for snapshot.
snapshot_type: Type of snapshot.
"""
append_instruction(instructions.Snapshot(label, snapshot_type=snapshot_type))
def call(
target: Optional[Union[circuit.QuantumCircuit, Schedule, ScheduleBlock]],
name: Optional[str] = None,
value_dict: Optional[Dict[ParameterValueType, ParameterValueType]] = None,
**kw_params: ParameterValueType,
):
"""Call the subroutine within the currently active builder context with arbitrary
parameters which will be assigned to the target program.
.. note::
If the ``target`` program is a :class:`.ScheduleBlock`, then a :class:`.Reference`
instruction will be created and appended to the current context.
The ``target`` program will be immediately assigned to the current scope as a subroutine.
If the ``target`` program is :class:`.Schedule`, it will be wrapped by the
:class:`.Call` instruction and appended to the current context to avoid
a mixed representation of :class:`.ScheduleBlock` and :class:`.Schedule`.
If the ``target`` program is a :class:`.QuantumCircuit` it will be scheduled
and the new :class:`.Schedule` will be added as a :class:`.Call` instruction.
Examples:
1. Calling a schedule block (recommended)
.. code-block::
from qiskit import circuit, pulse
from qiskit.providers.fake_provider import FakeBogotaV2
backend = FakeBogotaV2()
with pulse.build() as x_sched:
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
with pulse.build() as pulse_prog:
pulse.call(x_sched)
print(pulse_prog)
.. parsed-literal::
ScheduleBlock(
ScheduleBlock(
Play(
Gaussian(duration=160, amp=(0.1+0j), sigma=40),
DriveChannel(0)
),
name="block0",
transform=AlignLeft()
),
name="block1",
transform=AlignLeft()
)
The actual program is stored in the reference table attached to the schedule.
.. code-block::
print(pulse_prog.references)
.. parsed-literal::
ReferenceManager:
- ('block0', '634b3b50bd684e26a673af1fbd2d6c81'): ScheduleBlock(Play(Gaussian(...
In addition, you can call a parameterized target program with parameter assignment.
.. code-block::
amp = circuit.Parameter("amp")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0))
with pulse.build() as pulse_prog:
pulse.call(subroutine, amp=0.1)
pulse.call(subroutine, amp=0.3)
print(pulse_prog)
.. parsed-literal::
ScheduleBlock(
ScheduleBlock(
Play(
Gaussian(duration=160, amp=(0.1+0j), sigma=40),
DriveChannel(0)
),
name="block2",
transform=AlignLeft()
),
ScheduleBlock(
Play(
Gaussian(duration=160, amp=(0.3+0j), sigma=40),
DriveChannel(0)
),
name="block2",
transform=AlignLeft()
),
name="block3",
transform=AlignLeft()
)
If there is a name collision between parameters, you can distinguish them by specifying
each parameter object in a python dictionary. For example,
.. code-block::
amp1 = circuit.Parameter('amp')
amp2 = circuit.Parameter('amp')
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp1, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, amp2, 40), pulse.DriveChannel(1))
with pulse.build() as pulse_prog:
pulse.call(subroutine, value_dict={amp1: 0.1, amp2: 0.3})
print(pulse_prog)
.. parsed-literal::
ScheduleBlock(
ScheduleBlock(
Play(Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0)),
Play(Gaussian(duration=160, amp=(0.3+0j), sigma=40), DriveChannel(1)),
name="block4",
transform=AlignLeft()
),
name="block5",
transform=AlignLeft()
)
2. Calling a schedule
.. code-block::
x_sched = backend.instruction_schedule_map.get("x", (0,))
with pulse.build(backend) as pulse_prog:
pulse.call(x_sched)
print(pulse_prog)
.. parsed-literal::
ScheduleBlock(
Call(
Schedule(
(
0,
Play(
Drag(
duration=160,
amp=(0.18989731546729305+0j),
sigma=40,
beta=-1.201258305015517,
name='drag_86a8'
),
DriveChannel(0),
name='drag_86a8'
)
),
name="x"
),
name='x'
),
name="block6",
transform=AlignLeft()
)
Currently, the backend calibrated gates are provided in the form of :class:`~.Schedule`.
The parameter assignment mechanism is available also for schedules.
However, the called schedule is not treated as a reference.
3. Calling a quantum circuit
.. code-block::
backend = FakeBogotaV2()
qc = circuit.QuantumCircuit(1)
qc.x(0)
with pulse.build(backend) as pulse_prog:
pulse.call(qc)
print(pulse_prog)
.. parsed-literal::
ScheduleBlock(
Call(
Schedule(
(
0,
Play(
Drag(
duration=160,
amp=(0.18989731546729305+0j),
sigma=40,
beta=-1.201258305015517,
name='drag_86a8'
),
DriveChannel(0),
name='drag_86a8'
)
),
name="circuit-87"
),
name='circuit-87'
),
name="block7",
transform=AlignLeft()
)
.. warning::
Calling a circuit from a schedule is not encouraged. Currently, the Qiskit execution model
is migrating toward the pulse gate model, where schedules are attached to
circuits through the :meth:`.QuantumCircuit.add_calibration` method.
Args:
target: Target circuit or pulse schedule to call.
name: Optional. A unique name of subroutine if defined. When the name is explicitly
provided, one cannot call different schedule blocks with the same name.
value_dict: Optional. Parameters assigned to the ``target`` program.
If this dictionary is provided, the ``target`` program is copied and
then stored in the main built schedule and its parameters are assigned to the given values.
This dictionary is keyed on :class:`~.Parameter` objects,
allowing parameter name collision to be avoided.
kw_params: Alternative way to provide parameters.
Since this is keyed on the string parameter name,
the parameters having the same name are all updated together.
If you want to avoid name collision, use ``value_dict`` with :class:`~.Parameter`
objects instead.
"""
_active_builder().call_subroutine(target, name, value_dict, **kw_params)
def reference(name: str, *extra_keys: str):
"""Refer to undefined subroutine by string keys.
A :class:`~qiskit.pulse.instructions.Reference` instruction is implicitly created
and a schedule can be separately registered to the reference at a later stage.
.. code-block:: python
from qiskit import pulse
with pulse.build() as main_prog:
pulse.reference("x_gate", "q0")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
main_prog.assign_references(subroutine_dict={("x_gate", "q0"): subroutine})
Args:
name: Name of subroutine.
extra_keys: Helper keys to uniquely specify the subroutine.
"""
_active_builder().append_reference(name, *extra_keys)
# Directives
def barrier(*channels_or_qubits: Union[chans.Channel, int], name: Optional[str] = None):
"""Barrier directive for a set of channels and qubits.
This directive prevents the compiler from moving instructions across
the barrier. Consider the case where we want to enforce that one pulse
happens after another on separate channels, this can be done with:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build(backend) as barrier_pulse_prog:
pulse.play(pulse.Constant(10, 1.0), d0)
pulse.barrier(d0, d1)
pulse.play(pulse.Constant(10, 1.0), d1)
Of course this could have been accomplished with:
.. code-block::
from qiskit.pulse import transforms
with pulse.build(backend) as aligned_pulse_prog:
with pulse.align_sequential():
pulse.play(pulse.Constant(10, 1.0), d0)
pulse.play(pulse.Constant(10, 1.0), d1)
barrier_pulse_prog = transforms.target_qobj_transform(barrier_pulse_prog)
aligned_pulse_prog = transforms.target_qobj_transform(aligned_pulse_prog)
assert barrier_pulse_prog == aligned_pulse_prog
The barrier allows the pulse compiler to take care of more advanced
scheduling alignment operations across channels. For example
in the case where we are calling an outside circuit or schedule and
want to align a pulse at the end of one call:
.. code-block::
import math
d0 = pulse.DriveChannel(0)
with pulse.build(backend) as pulse_prog:
with pulse.align_right():
pulse.x(1)
# Barrier qubit 1 and d0.
pulse.barrier(1, d0)
# Due to barrier this will play before the gate on qubit 1.
pulse.play(pulse.Constant(10, 1.0), d0)
# This will end at the same time as the pulse above due to
# the barrier.
pulse.x(1)
.. note:: Requires the active builder context to have a backend set if
qubits are barriered on.
Args:
channels_or_qubits: Channels or qubits to barrier.
name: Name for the barrier
"""
channels = _qubits_to_channels(*channels_or_qubits)
if len(channels) > 1:
append_instruction(directives.RelativeBarrier(*channels, name=name))
# Macros
def macro(func: Callable):
"""Wrap a Python function and activate the parent builder context at calling time.
This enables embedding Python functions as builder macros. This generates a new
:class:`pulse.Schedule` that is embedded in the parent builder context with
every call of the decorated macro function. The decorated macro function will
behave as if the function code was embedded inline in the parent builder context
after parameter substitution.
Examples:
.. plot::
:include-source:
from qiskit import pulse
@pulse.macro
def measure(qubit: int):
pulse.play(pulse.GaussianSquare(16384, 256, 15872), pulse.measure_channel(qubit))
mem_slot = pulse.MemorySlot(qubit)
pulse.acquire(16384, pulse.acquire_channel(qubit), mem_slot)
return mem_slot
with pulse.build(backend=backend) as sched:
mem_slot = measure(0)
print(f"Qubit measured into {mem_slot}")
sched.draw()
Args:
func: The Python function to enable as a builder macro. There are no
requirements on the signature of the function, any calls to pulse
builder methods will be added to builder context the wrapped function
is called from.
Returns:
Callable: The wrapped ``func``.
"""
func_name = getattr(func, "__name__", repr(func))
@functools.wraps(func)
def wrapper(*args, **kwargs):
_builder = _active_builder()
# activate the pulse builder before calling the function
with build(backend=_builder.backend, name=func_name) as built:
output = func(*args, **kwargs)
_builder.call_subroutine(built)
return output
return wrapper
def measure(
qubits: Union[List[int], int],
registers: Union[List[StorageLocation], StorageLocation] = None,
) -> Union[List[StorageLocation], StorageLocation]:
"""Measure a qubit within the currently active builder context.
At the pulse level a measurement is composed of both a stimulus pulse and
an acquisition instruction which tells the systems measurement unit to
acquire data and process it. We provide this measurement macro to automate
the process for you, but if desired full control is still available with
:func:`acquire` and :func:`play`.
To use the measurement it is as simple as specifying the qubit you wish to
measure:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
qubit = 0
with pulse.build(backend) as pulse_prog:
# Do something to the qubit.
qubit_drive_chan = pulse.drive_channel(0)
pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan)
# Measure the qubit.
reg = pulse.measure(qubit)
For now it is not possible to do much with the handle to ``reg`` but in the
future we will support using this handle to a result register to build
up ones program. It is also possible to supply this register:
.. code-block::
with pulse.build(backend) as pulse_prog:
pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan)
# Measure the qubit.
mem0 = pulse.MemorySlot(0)
reg = pulse.measure(qubit, mem0)
assert reg == mem0
.. note:: Requires the active builder context to have a backend set.
Args:
qubits: Physical qubit to measure.
registers: Register to store result in. If not selected the current
behavior is to return the :class:`MemorySlot` with the same
index as ``qubit``. This register will be returned.
Returns:
The ``register`` the qubit measurement result will be stored in.
"""
backend = active_backend()
try:
qubits = list(qubits)
except TypeError:
qubits = [qubits]
if registers is None:
registers = [chans.MemorySlot(qubit) for qubit in qubits]
else:
try:
registers = list(registers)
except TypeError:
registers = [registers]
measure_sched = macros.measure(
qubits=qubits,
backend=backend,
qubit_mem_slots={qubit: register.index for qubit, register in zip(qubits, registers)},
)
# note this is not a subroutine.
# just a macro to automate combination of stimulus and acquisition.
# prepare unique reference name based on qubit and memory slot index.
qubits_repr = "&".join(map(str, qubits))
mslots_repr = "&".join((str(r.index) for r in registers))
_active_builder().call_subroutine(measure_sched, name=f"measure_{qubits_repr}..{mslots_repr}")
if len(qubits) == 1:
return registers[0]
else:
return registers
def measure_all() -> List[chans.MemorySlot]:
r"""Measure all qubits within the currently active builder context.
A simple macro function to measure all of the qubits in the device at the
same time. This is useful for handling device ``meas_map`` and single
measurement constraints.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
# Measure all qubits and return associated registers.
regs = pulse.measure_all()
.. note::
Requires the active builder context to have a backend set.
Returns:
The ``register``\s the qubit measurement results will be stored in.
"""
backend = active_backend()
qubits = range(num_qubits())
registers = [chans.MemorySlot(qubit) for qubit in qubits]
measure_sched = macros.measure(
qubits=qubits,
backend=backend,
qubit_mem_slots={qubit: qubit for qubit in qubits},
)
# note this is not a subroutine.
# just a macro to automate combination of stimulus and acquisition.
_active_builder().call_subroutine(measure_sched, name="measure_all")
return registers
def delay_qubits(duration: int, *qubits: Union[int, Iterable[int]]):
r"""Insert delays on all of the :class:`channels.Channel`\s that correspond
to the input ``qubits`` at the same time.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse3Q
backend = FakeOpenPulse3Q()
with pulse.build(backend) as pulse_prog:
# Delay for 100 cycles on qubits 0, 1 and 2.
regs = pulse.delay_qubits(100, 0, 1, 2)
.. note:: Requires the active builder context to have a backend set.
Args:
duration: Duration to delay for.
qubits: Physical qubits to delay on. Delays will be inserted based on
the channels returned by :func:`pulse.qubit_channels`.
"""
qubit_chans = set(itertools.chain.from_iterable(qubit_channels(qubit) for qubit in qubits))
with align_left():
for chan in qubit_chans:
delay(duration, chan)
# Gate instructions
def call_gate(gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True):
"""Call a gate and lazily schedule it to its corresponding
pulse instruction.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.pulse import builder
from qiskit.circuit.library import standard_gates as gates
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
builder.call_gate(gates.CXGate(), (0, 1))
We can see the role of the transpiler in scheduling gates by optimizing
away two consecutive CNOT gates:
.. code-block::
with pulse.build(backend) as pulse_prog:
with pulse.transpiler_settings(optimization_level=3):
builder.call_gate(gates.CXGate(), (0, 1))
builder.call_gate(gates.CXGate(), (0, 1))
assert pulse_prog == pulse.Schedule()
.. note:: If multiple gates are called in a row they may be optimized by
the transpiler, depending on the
:func:`pulse.active_transpiler_settings``.
.. note:: Requires the active builder context to have a backend set.
Args:
gate: Circuit gate instance to call.
qubits: Qubits to call gate on.
lazy: If ``false`` the gate will be compiled immediately, otherwise
it will be added onto a lazily evaluated quantum circuit to be
compiled when the builder is forced to by a circuit assumption
being broken, such as the inclusion of a pulse instruction or
new alignment context.
"""
_active_builder().call_gate(gate, qubits, lazy=lazy)
def cx(control: int, target: int): # pylint: disable=invalid-name
"""Call a :class:`~qiskit.circuit.library.standard_gates.CXGate` on the
input physical qubits.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
pulse.cx(0, 1)
"""
call_gate(gates.CXGate(), (control, target))
def u1(theta: float, qubit: int): # pylint: disable=invalid-name
"""Call a :class:`~qiskit.circuit.library.standard_gates.U1Gate` on the
input physical qubit.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
pulse.u1(math.pi, 1)
"""
call_gate(gates.U1Gate(theta), qubit)
def u2(phi: float, lam: float, qubit: int): # pylint: disable=invalid-name
"""Call a :class:`~qiskit.circuit.library.standard_gates.U2Gate` on the
input physical qubit.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
pulse.u2(0, math.pi, 1)
"""
call_gate(gates.U2Gate(phi, lam), qubit)
def u3(theta: float, phi: float, lam: float, qubit: int): # pylint: disable=invalid-name
"""Call a :class:`~qiskit.circuit.library.standard_gates.U3Gate` on the
input physical qubit.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
pulse.u3(math.pi, 0, math.pi, 1)
"""
call_gate(gates.U3Gate(theta, phi, lam), qubit)
def x(qubit: int):
"""Call a :class:`~qiskit.circuit.library.standard_gates.XGate` on the
input physical qubit.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
pulse.x(0)
"""
call_gate(gates.XGate(), qubit)
|
https://github.com/adelshb/Quantum-Machine-Learning-for-Titanic-on-IBM-Q
|
adelshb
|
# -*- coding: utf-8 -*-
#
# Written by Adel Sohbi, https://github.com/adelshb
#
# 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.
""" Implementation of a QNN for the Titanic dataset
Training script
"""
from argparse import ArgumentParser
from qiskit import Aer, QuantumCircuit
from qiskit.utils import QuantumInstance
from qiskit_machine_learning.neural_networks import CircuitQNN
from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from titanicibmq.titanic_data import *
_available_optimizers = {
"cobyla": COBYLA
}
_available_ansatz = {
"realamplitudes": RealAmplitudes
}
_available_feature_maps = {
"zzfeaturemap": ZZFeatureMap
}
def main(args):
# Load the data
data, __ = titanic()
X_train, y_train, X_test, y_test = parse_data_train_vqc(data, split_ratio=args.split_ratio)
quantum_instance = QuantumInstance(Aer.get_backend('statevector_simulator'), shots=100)
optimizer = COBYLA(maxiter=100)
feature_map = ZZFeatureMap(feature_dimension=X_train.shape[1], reps=1)
ansatz = RealAmplitudes(num_qubits=feature_map._num_qubits, reps=1)
qc = QuantumCircuit(feature_map._num_qubits)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
qnn = CircuitQNN(circuit= qc,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
sparse=False,
sampling=False,
interpret=parity,
output_shape=len(np.unique(y_train, axis=0)),
gradient=None,
quantum_instance=quantum_instance)
cc = NeuralNetworkClassifier(neural_network=qnn,
optimizer=optimizer)
# Train the model
cc.fit(X_train, y_train)
# Model accuracy
acc_train = cc.score(X_train, y_train)
acc_test = cc.score(X_test, y_test)
print("Accuracy on training dataset: {}.".format(acc_train))
print("Accuracy on testing dataset: {}.".format(acc_test))
def parity(x):
return '{:b}'.format(x).count('1') % 2
if __name__ == "__main__":
parser = ArgumentParser()
# Optimizer
parser.add_argument("--optimizer", type=str, default="cobyla", choices=_available_optimizers)
parser.add_argument("--max_iter", type=int, default=1000)
# Ansatz
parser.add_argument("--ansatz", type=str, default="realamplitudes", choices=_available_ansatz)
parser.add_argument("--a_reps", type=int, default=3)
# Feature Map
parser.add_argument("--feature_map", type=str, default="zzfeaturemap", choices=_available_feature_maps)
parser.add_argument("--feature_dim", type=int, default=2)
parser.add_argument("--f_reps", type=int, default=1)
# Backend
parser.add_argument("--backend", type=str, default="qasm_simulator")
parser.add_argument("--shots", type=int, default=1024)
# Data
parser.add_argument("--split_ratio", type=int, default=0.2)
args = parser.parse_args()
main(args)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as drive_sched:
d0 = pulse.drive_channel(0)
a0 = pulse.acquire_channel(0)
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.delay(20, d0)
pulse.shift_phase(3.14/2, d0)
pulse.set_phase(3.14, d0)
pulse.shift_frequency(1e7, d0)
pulse.set_frequency(5e9, d0)
with pulse.build() as temp_sched:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0)
pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0)
pulse.call(temp_sched)
pulse.acquire(30, a0, pulse.MemorySlot(0))
drive_sched.draw()
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.x(1)
qc.draw("mpl")
|
https://github.com/intrinsicvardhan/QuantumComputingAlgos
|
intrinsicvardhan
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import *
from ibm_quantum_widgets import *
# qiskit-ibmq-provider has been deprecated.
# Please see the Migration Guides in https://ibm.biz/provider_migration_guide for more detail.
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options
# Loading your IBM Quantum account(s)
service = QiskitRuntimeService(channel="ibm_quantum")
# Invoke a primitive. For more details see https://docs.quantum.ibm.com/run/primitives
# result = Sampler().run(circuits).result()
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1,0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set(msg).issubset({"0","1"}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1,0)
qc.h(1)
return qc
# Charlie creates the entangled pair between Alice and Bob
qc = create_bell_pair()
# We'll add a barrier for visual separation
qc.barrier()
message = '11'
qc = encode_message(qc, 1, message)
qc.barrier()
# Alice then sends her qubit to Bob.
# After receiving qubit 0, Bob applies the recovery protocol:
qc = decode_message(qc)
# Finally, Bob measures his qubits to read Alice's message
qc.measure_all()
# Draw our output
qc.draw()
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from numpy import pi
qreg_q = QuantumRegister(3, 'q')
creg_c0 = ClassicalRegister(1, 'c0')
creg_c1 = ClassicalRegister(1, 'c1')
creg_c2 = ClassicalRegister(1, 'c2')
circuit = QuantumCircuit(qreg_q, creg_c0, creg_c1, creg_c2)
#quantum teleportation example
circuit.u(0.3, 0.2, 0.1, qreg_q[0])
#creating the first qubit change the values of theta, phi and lambda to create a different qubit
circuit.h(qreg_q[1])
circuit.cx(qreg_q[1], qreg_q[2])
circuit.barrier(qreg_q)
circuit.cx(qreg_q[0], qreg_q[1])
circuit.h(qreg_q[0])
circuit.measure(qreg_q[0], creg_c0[0])
circuit.measure(qreg_q[1], creg_c1[0])
circuit.z(qreg_q[2]).c_if(creg_c0, 1)
circuit.x(qreg_q[2]).c_if(creg_c1, 1)
circuit.measure(qreg_q[2], creg_c2[0])
circuit.draw()
from qiskit_aer import Aer, AerSimulator
from qiskit.compiler import assemble
qc = QuantumCircuit(2)
qc.h(0)
qc.h(1)
qc.cx(0,1)
qc.h(0)
qc.h(1)
display(qc.draw())
qc.save_unitary()
usim = Aer.get_backend('aer_simulator')
qobj = assemble(qc)
unitary = usim.run(qobj).result().get_unitary()
array_to_latex(unitary, prefix="\\text{Circuit = }\n")
qc = QuantumCircuit(2)
qc.cx(1,0)
display(qc.draw())
qc.save_unitary()
qobj = assemble(qc)
unitary = usim.run(qobj).result().get_unitary()
array_to_latex(unitary, prefix="\\text{Circuit = }\n")
qc = QuantumCircuit(2)
qc.cp(pi/4, 0, 1)
display(qc.draw())
# See Results:
qc.save_unitary()
qobj = assemble(qc)
unitary = usim.run(qobj).result().get_unitary()
array_to_latex(unitary, prefix="\\text{Controlled-T} = \n")
|
https://github.com/peiyong-addwater/Hackathon-QNLP
|
peiyong-addwater
|
import re
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import string
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer, SnowballStemmer
from nltk import pos_tag, ne_chunk
from nltk.chunk import tree2conlltags
import os
import seaborn as sns
import matplotlib.pyplot as plt
from collections import Counter
import nltk
nltk.download('stopwords')
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('averaged_perceptron_tagger')
nltk.download('maxent_ne_chunker')
nltk.download('words')
import warnings
warnings.filterwarnings("ignore")
pd.set_option('display.width', 1000)
pd.options.display.max_colwidth=120
print(os.getcwd())
columns = ["Id","Entity","Target","Text"]
data = pd.read_csv("/app/data/twitter_training.csv", names=columns,header=None)
data.head()
df_train = data[["Text","Target"]]
df_train = df_train.loc[(df_train["Target"]=='Positive') | (df_train["Target"]=='Negative')]
df_train.head()
df_train.info()
df_train= df_train.drop_duplicates()
df_train.info()
sns.countplot(x="Target",data=df_train)
data_val = pd.read_csv("/app/data/twitter_validation.csv", names=columns,header=None)
data_val.head()
df_val = data_val[['Text', 'Target']]
df_val = df_val.loc[(df_val['Target'] == 'Positive') | (df_val['Target'] == 'Negative')]
df_val.head()
df_val.info()
sns.countplot(x="Target",data=df_val)
text_cleaning_re = "@\S+|https?:\S+|http?:\S|[^A-Za-z0-9]+"
emoji_pattern = re.compile("["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"\U0001F680-\U0001F6FF" # transport & map symbols
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
"]+", flags=re.UNICODE)
stemmer = SnowballStemmer('english')
def preprocess(text):
text = re.sub(text_cleaning_re, ' ', str(text).lower()).strip()
text = emoji_pattern.sub(r'', text)
tokens = []
for token in text.split():
tokens.append(token)
return " ".join(tokens)
df_train["Text"] = df_train["Text"].apply(preprocess)
df_train["Text"]= df_train["Text"].str.replace("im","i am")
df_train["Text"].head()
df_val["Text"] = df_val["Text"].apply(preprocess)
df_val["Text"]=df_val["Text"].str.replace("im","i am")
df_val["Text"].head()
|
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 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 matplotlib import pyplot as plt
%matplotlib inline
pip install time
pip install qiskit_machine_learning
import numpy as np
import matplotlib.pyplot as plt
from torch import Tensor
from torch.nn import Linear, CrossEntropyLoss, MSELoss
from torch.optim import LBFGS
from qiskit import QuantumCircuit
from qiskit.utils import algorithm_globals
from qiskit.circuit import Parameter
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN
from qiskit_machine_learning.connectors import TorchConnector
# Set seed for random generators
algorithm_globals.random_seed = 12
# Generate random dataset
# Select dataset dimension (num_inputs) and size (num_samples)
num_inputs = 2
num_samples = 20
# Generate random input coordinates (X) and binary labels (y)
X = 2 * algorithm_globals.random.random([num_samples, num_inputs]) - 1
y01 = 1 * (np.sum(X, axis=1) >= 0) # in { 0, 1}, y01 will be used for SamplerQNN example
y = 2 * y01 - 1 # in {-1, +1}, y will be used for EstimatorQNN example
# Convert to torch Tensors
X_ = Tensor(X)
y01_ = Tensor(y01).reshape(len(y)).long()
y_ = Tensor(y).reshape(len(y), 1)
# Plot dataset
for x, y_target in zip(X, y):
if y_target == 1:
plt.plot(x[0], x[1], "bo")
else:
plt.plot(x[0], x[1], "go")
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
pip install pylatexenc
pip install matplotlib --upgrade
pip install MatplotlibDrawer
# Set up a circuit
feature_map = ZZFeatureMap(num_inputs)
ansatz = RealAmplitudes(num_inputs)
qc = QuantumCircuit(num_inputs)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
#qc.draw("mpl")
print(qc)
# Setup QNN
qnn1 = EstimatorQNN(
circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters
)
# Set up PyTorch module
# Note: If we don't explicitly declare the initial weights
# they are chosen uniformly at random from [-1, 1].
initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn1.num_weights) - 1)
model1 = TorchConnector(qnn1, initial_weights=initial_weights)
print("Initial weights: ", initial_weights)
#single input test
model1(X_[0, :])
# Define optimizer and loss
optimizer = LBFGS(model1.parameters())
f_loss = MSELoss(reduction="sum")
# Start training
model1.train() # set model to training mode
# Note from (https://pytorch.org/docs/stable/optim.html):
# Some optimization algorithms such as LBFGS need to
# reevaluate the function multiple times, so you have to
# pass in a closure that allows them to recompute your model.
# The closure should clear the gradients, compute the loss,
# and return it.
def closure():
optimizer.zero_grad() # Initialize/clear gradients
loss = f_loss(model1(X_), y_) # Evaluate loss function
loss.backward() # Backward pass
print(loss.item()) # Print loss
return loss
# Run optimizer step4
optimizer.step(closure)
# Evaluate model and compute accuracy
y_predict = []
for x, y_target in zip(X, y):
output = model1(Tensor(x))
y_predict += [np.sign(output.detach().numpy())[0]]
print("Accuracy:", sum(y_predict == y) / len(y))
# Plot results
# red == wrongly classified
for x, y_target, y_p in zip(X, y, y_predict):
if y_target == 1:
plt.plot(x[0], x[1], "bo")
else:
plt.plot(x[0], x[1], "go")
if y_target != y_p:
plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2)
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
# Define feature map and ansatz
feature_map = ZZFeatureMap(num_inputs)
ansatz = RealAmplitudes(num_inputs, entanglement="linear", reps=1)
# Define quantum circuit of num_qubits = input dim
# Append feature map and ansatz
qc = QuantumCircuit(num_inputs)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
# Define SamplerQNN and initial setup
parity = lambda x: "{:b}".format(x).count("1") % 2 # optional interpret function
output_shape = 2 # parity = 0, 1
qnn2 = SamplerQNN(
circuit=qc,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
interpret=parity,
output_shape=output_shape,
)
# Set up PyTorch module
# Reminder: If we don't explicitly declare the initial weights
# they are chosen uniformly at random from [-1, 1].
initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn2.num_weights) - 1)
print("Initial weights: ", initial_weights)
model2 = TorchConnector(qnn2, initial_weights)
# Define model, optimizer, and loss
optimizer = LBFGS(model2.parameters())
f_loss = CrossEntropyLoss() # Our output will be in the [0,1] range
# Start training
model2.train()
# Define LBFGS closure method (explained in previous section)
def closure():
optimizer.zero_grad(set_to_none=True) # Initialize gradient
loss = f_loss(model2(X_), y01_) # Calculate loss
loss.backward() # Backward pass
print(loss.item()) # Print loss
return loss
# Run optimizer (LBFGS requires closure)
optimizer.step(closure);
# Evaluate model and compute accuracy
y_predict = []
for x in X:
output = model2(Tensor(x))
y_predict += [np.argmax(output.detach().numpy())]
print("Accuracy:", sum(y_predict == y01) / len(y01))
# plot results
# red == wrongly classified
for x, y_target, y_ in zip(X, y01, y_predict):
if y_target == 1:
plt.plot(x[0], x[1], "bo")
else:
plt.plot(x[0], x[1], "go")
if y_target != y_:
plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2)
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
# Additional torch-related imports
import torch
from torch import cat, no_grad, manual_seed
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import torch.optim as optim
from torch.nn import (
Module,
Conv2d,
Linear,
Dropout2d,
NLLLoss,
MaxPool2d,
Flatten,
Sequential,
ReLU,
)
import torch.nn.functional as F
# torchvision API to directly load a subset of the MNIST dataset and define torch DataLoaders (link) for train and test.
# Train Dataset
# -------------
# Set train shuffle seed (for reproducibility)
manual_seed(42)
batch_size = 1
n_samples = 100 # We will concentrate on the first 100 samples
# Use pre-defined torchvision function to load MNIST train data
X_train = datasets.MNIST(
root="./data", train=True, download=True, transform=transforms.Compose([transforms.ToTensor()])
)
# 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]
# Define torch dataloader with filtered data
train_loader = DataLoader(X_train, batch_size=batch_size, shuffle=True)
n_samples_show = 6
data_iter = iter(train_loader)
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
while n_samples_show > 0:
images, targets = data_iter.__next__()
axes[n_samples_show - 1].imshow(images[0, 0].numpy().squeeze(), cmap="gray")
axes[n_samples_show - 1].set_xticks([])
axes[n_samples_show - 1].set_yticks([])
axes[n_samples_show - 1].set_title("Labeled: {}".format(targets[0].item()))
n_samples_show -= 1
# Test Dataset
# -------------
# Set test shuffle seed (for reproducibility)
# manual_seed(5)
n_samples = 50
# Use pre-defined torchvision function to load MNIST test data
X_test = datasets.MNIST(
root="./data", train=False, download=True, transform=transforms.Compose([transforms.ToTensor()])
)
# 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=batch_size, shuffle=True)
#Defining QNN and the Hybrid
# Define and create QNN
def create_qnn():
feature_map = ZZFeatureMap(2)
ansatz = RealAmplitudes(2, reps=1)
qc = QuantumCircuit(2)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
# REMEMBER TO SET input_gradients=True FOR ENABLING HYBRID GRADIENT BACKPROP
qnn = EstimatorQNN(
circuit=qc,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
input_gradients=True,
)
return qnn
qnn4 = create_qnn()
# Define torch NN module
class Net(Module):
def __init__(self, qnn):
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
self.qnn = TorchConnector(qnn) # Apply torch connector, weights chosen
# 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 cat((x, 1 - x), -1)
model4 = Net(qnn4)
# Define model, optimizer, and loss function
optimizer = optim.Adam(model4.parameters(), lr=0.001)
loss_func = NLLLoss()
# Start training
epochs = 10 # Set number of epochs
loss_list = [] # Store loss history
model4.train() # Set model to training mode
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad(set_to_none=True) # Initialize gradient
output = model4(data) # Forward pass
loss = loss_func(output, target) # Calculate loss
loss.backward() # Backward pass
optimizer.step() # Optimize weights
total_loss.append(loss.item()) # Store loss
loss_list.append(sum(total_loss) / len(total_loss))
print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1]))
# Plot loss convergence
plt.plot(loss_list)
plt.title("Hybrid NN Training Convergence")
plt.xlabel("Training Iterations")
plt.ylabel("Neg. Log Likelihood Loss")
plt.show()
torch.save(model4.state_dict(), "model4.pt")
# to execute on real hardware, change the backend
qnn5 = create_qnn()
model5 = Net(qnn5)
model5.load_state_dict(torch.load("model4.pt"))
model5.eval() # set model to evaluation mode
with no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model5(data)
if len(output.shape) == 1:
output = output.reshape(1, *output.shape)
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
)
)
# Plot predicted labels
n_samples_show = 6
count = 0
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
model5.eval()
with no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
if count == n_samples_show:
break
output = model5(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([])
axes[count].set_title("Predicted {}".format(pred.item()))
count += 1
# Define model, optimizer, and loss function
optimizer = optim.Adam(model4.parameters(), lr=0.001)
loss_func = NLLLoss()
# Start training
epochs = 5 # Set number of epochs
loss_list = [] # Store loss history
model4.train() # Set model to training mode
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad(set_to_none=True) # Initialize gradient
output = model4(data) # Forward pass
loss = loss_func(output, target) # Calculate loss
loss.backward() # Backward pass
optimizer.step() # Optimize weights
total_loss.append(loss.item()) # Store loss
loss_list.append(sum(total_loss) / len(total_loss))
print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1]))
# to execute on real hardware, change the backend
qnn5 = create_qnn()
model5 = Net(qnn5)
model5.load_state_dict(torch.load("model4.pt"))
model5.eval() # set model to evaluation mode
with no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model5(data)
if len(output.shape) == 1:
output = output.reshape(1, *output.shape)
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
)
)
# Define model, optimizer, and loss function
optimizer = optim.Adam(model4.parameters(), lr=0.001)
loss_func = NLLLoss()
# Start training
epochs = 5 # Set number of epochs
loss_list = [] # Store loss history
model4.train() # Set model to training mode
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad(set_to_none=True) # Initialize gradient
output = model4(data) # Forward pass
loss = loss_func(output, target) # Calculate loss
loss.backward() # Backward pass
optimizer.step() # Optimize weights
total_loss.append(loss.item()) # Store loss
loss_list.append(sum(total_loss) / len(total_loss))
print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1]))
# to execute on real hardware, change the backend
qnn5 = create_qnn()
model5 = Net(qnn5)
model5.load_state_dict(torch.load("model4.pt"))
model5.eval() # set model to evaluation mode
with no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model5(data)
if len(output.shape) == 1:
output = output.reshape(1, *output.shape)
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
)
)
print(qc)
|
https://github.com/mahabubul-alam/QAOA-Compiler
|
mahabubul-alam
|
"""
################################################################################
############## This library has been created by ######################
############## Md Mahabubul Alam ######################
############## https://mahabubul-alam.github.io/Personal/ ######################
############## Graduate Student (Ph.D.) ######################
############## Department of Electrical Engineering ######################
############## Pennsylvania State University ######################
############## University Park, PA, USA ######################
############## mxa890@psu.edu ######################
################################################################################
"""
import math
import re
import os
from . initial_layout_qaoa import create_initial_layout
from random import shuffle
from qiskit.circuit import Parameter
from qiskit import QuantumCircuit, transpile, Aer, execute
import commentjson as json
import networkx as nx
from qiskit.quantum_info.analysis import hellinger_fidelity
from qiskit.converters import circuit_to_dag
class CompileQAOAQiskit:
"""
This class implements the QAOA-specific compilation policies
described in the following articles
https://ieeexplore.ieee.org/document/9251960
https://ieeexplore.ieee.org/document/9218558
https://ieeexplore.ieee.org/document/9256490
After crating the object, compilation can be performed with the chosen compilation
policies using the following public methods:
run_ip
run_iter_c
run_incr_c
The current implementation only supports compilation with qiskit compiler backend.
Necessary instrcutions are given under __compile_with_backend method docstring
to add support for other compilers (e.g. tket).
"""
def __init__(self, circuit_json = None,
qc_json = None, config_json = None, out_circuit_file_name = 'QAOA.qasm'):
"""
This method initializes necessary config variables.
"""
self.supported_backends = ['qiskit']
self.supported_initial_layout_strategies = ['qaim','vqp','random']
self.__load_config(config_json)
self.output_file_name = out_circuit_file_name
self.__extract_qc_data(qc_json)
self.layer_zz_assignments = {}
self.zz_graph = self.qaoa_zz_graph(circuit_json)
with open(circuit_json) as f:
self.zz_dict = json.loads(f.read())
self.initial_layout = list(range(len(self.zz_graph.nodes())))
self.circuit = None
self.sorted_ops = None
self.cost = 10e10
self.final_map = []
[self.uncompiled_ckt, self.naive_ckt] = self.__naive_compilation()
def __naive_compilation(self):
"""
This method constructs performs a naive compilation with the qiskit backend.
(gates are randomly ordered).
"""
n = len(self.zz_graph.nodes())
qc = QuantumCircuit(n, n)
for node in self.zz_graph.nodes():
qc.h(node)
for p in range(1,self.Target_p+1):
for zz in self.zz_graph.edges():
n1 = zz[0]
n2 = zz[1]
gamma = Parameter('g{}_{}_{}'.format(p, n1, n2))
qc.cx(n1, n2)
qc.rz(gamma, n2)
qc.cx(n1, n2)
beta = Parameter('b{}'.format(p))
for node in self.zz_graph.nodes():
qc.rx(beta,node)
qc.barrier()
qc.measure(range(n), range(n))
trans_ckt = self.__compile_with_backend(ckt_qiskit = qc)
filename = 'uncompiled_' + self.output_file_name
qc.qasm(filename = filename)
self.__fix_param_names(filename)
filename = 'naive_compiled_' + self.output_file_name
trans_ckt.qasm(filename = filename)
self.__fix_param_names(filename)
return [qc, trans_ckt]
def __load_config(self, config_json = None):
"""
This method loads the variables in the config json file.
"""
with open(config_json) as f:
self.config = json.load(f)
if 'Target_p' in self.config.keys():
self.Target_p = int(self.config['Target_p'])
else:
self.Target_p = 1
if 'Packing_Limit' in self.config.keys():
self.Packing_Limit = float(self.config['Packing_Limit'])
else:
self.Packing_Limit = 10e10
if 'Route_Method' in self.config.keys():
self.Route_Method = self.config['Route_Method']
else:
self.Route_Method = 'sabre'
if 'Trans_Seed' in self.config.keys():
self.Trans_Seed = int(self.config['Trans_Seed'])
else:
self.Trans_Seed = 0
if 'Opt_Level' in self.config.keys():
self.Opt_Level = int(self.config['Opt_Level'])
else:
self.Opt_Level = 1
if 'Backend' in self.config.keys():
self.Backend = str(self.config['Backend'])
assert self.Backend in self.supported_backends
else:
self.Backend = 'qiskit'
assert self.Backend in self.supported_backends
def __extract_qc_data(self, qc_file = None):
"""
This method extracts hardware information from the QC json file.
"""
with open(qc_file) as f:
self.qc_data = json.load(f)
try:
self.native_2q = eval(self.qc_data['2Q'].strip('"'))
except:
self.native_2q = self.qc_data['2Q']
try:
self.native_1q = eval(self.qc_data['1Q'].strip('"'))
except:
self.native_1q = self.qc_data['1Q']
self.basis_gates = self.native_2q + self.native_1q
self.coupling_map = []
for key in self.qc_data[str(self.native_2q[0])].keys():
n1, n2 = eval(key)[0], eval(key)[1]
if [n1, n2] not in self.coupling_map:
self.coupling_map.append([n1, n2])
if [n2, n1] not in self.coupling_map:
self.coupling_map.append([n2, n1])
self.__calc_qq_distances()
def __calc_qq_distances(self):
"""
This method calculates pairwise qubit-qubit distances using the floyd_warshall algorithm.
"""
self.unweighted_undirected_coupling_graph = nx.Graph()
self.weighted_undirected_coupling_graph = nx.Graph()
for key, value in self.qc_data[str(self.native_2q[0])].items():
n1, n2, sp = eval(key)[0], eval(key)[1], float(value)
self.unweighted_undirected_coupling_graph.add_edge(n1, n2)
self.weighted_undirected_coupling_graph.add_edge(n1, n2, weight=1/sp)
self.qq_distances = nx.floyd_warshall(self.unweighted_undirected_coupling_graph)
self.noise_aware_qq_distances = nx.floyd_warshall(self.weighted_undirected_coupling_graph)
def __set_iter_c_target(self, target = 'GC_2Q'):
"""
This method can be used to set the target of iterative compilation.
"""
self.iter_c_target = target
def __set_incrc_var_awareness(self, variation_aware = False):
"""
This method can be used to set variation awareness in incremental compilation.
"""
self.incr_c_var_awareness = variation_aware
@staticmethod
def qaoa_zz_graph(circ_json = None):
"""
This method is used to create the MaxCut graph from the json file.
"""
with open(circ_json) as f:
data = json.loads(f.read())
zz_graph = nx.Graph()
for key, val in data.items():
nodes = eval(key)
zz_graph.add_edge(nodes[0], nodes[1])
return zz_graph
def __final_mapping_ic(self, qiskit_ckt_object):
"""
This method finds the output logical-to-physical qubit mapping in a compiled circuit block.
"""
qiskit_ckt_object.qasm(filename='tempfile')
os.system('grep measure tempfile | awk \'{print $2, $4}\' > temp')
qreg_creg_map = open('temp','r').readlines()
fmap = {}
for line in qreg_creg_map:
elements = line.split(' ')
physical_qs = elements[0]
logical_qs = str(elements[1]).split(';')[0]
physical_q = re.search('\[.*\]',physical_qs).group()
physical_q = re.sub('\[|\]','',physical_q)
logical_q = re.search('\[.*\]',logical_qs).group()
logical_q = re.sub('\[|\]','',logical_q)
fmap[logical_q[0:]] = int(physical_q[0:])
final_map = []
for i in range(qiskit_ckt_object.width() - qiskit_ckt_object.num_qubits):
final_map.append(fmap[str(i)])
os.system('rm temp')
os.system('rm tempfile')
self.final_map = final_map
def __set_initial_layout(self, target_layout = None, initial_layout_method = None):
"""
This method is used to set initial layout before starting compilation of any circuit block.
"""
if target_layout:
self.initial_layout = target_layout
elif initial_layout_method:
if initial_layout_method == 'qaim':
self.initial_layout = create_initial_layout(self.weighted_undirected_coupling_graph, self.zz_graph, method = 'qaim')
elif initial_layout_method == 'vqp':
self.initial_layout = create_initial_layout(self.weighted_undirected_coupling_graph, self.zz_graph, method = 'vqp')
elif initial_layout_method == 'random':
self.initial_layout = list(range(len(self.zz_graph.nodes())))
shuffle(self.initial_layout) #default: random
else:
raise ValueError
def __sort_zz_by_qq_distances(self, unsorted_ops = None):
"""
This method sorts the ZZ operations based on the control-target distances for the current mapping.
"""
sorted_ops = []
swap_distances_ops = {}
for op in unsorted_ops:
_physical_q1 = self.initial_layout[op[0]]
_physical_q2 = self.initial_layout[op[1]]
if not self.incr_c_var_awareness:
swap_dist = self.qq_distances[_physical_q1][_physical_q2]
else:
swap_dist = self.noise_aware_qq_distances[_physical_q1][_physical_q2]
swap_distances_ops[op] = swap_dist
for op in unsorted_ops:
if not sorted_ops:
sorted_ops.append(op)
continue
i = 0
for sop in sorted_ops:
if swap_distances_ops[op] < swap_distances_ops[sop]:
sorted_ops.insert(i, op)
break
i = i + 1
if i == len(sorted_ops):
sorted_ops.append(op)
self.sorted_ops = sorted_ops
def __construct_single_layer_ckt_ic(self, p):
"""
This method constructs a single layer of the circuit in incremental compilation.
"""
n = len(self.zz_graph.nodes())
qc = QuantumCircuit(n, n)
for zz in self.layer_zz_assignments['L0']:
n1 = zz[0]
n2 = zz[1]
gamma = Parameter('g{}_{}_{}'.format(p, n1, n2))
qc.cx(n1, n2)
qc.rz(gamma, n2)
qc.cx(n1, n2)
qc.measure(range(n), range(n))
trans_ckt = self.__compile_with_backend(ckt_qiskit = qc)
self.circuit = trans_ckt
def __compile_with_backend(self, ckt_qiskit = None):
"""
This method performs full/partial circuit compilation using the chosen backend.
This method can be extended to support other compilers (e.g. tket).
1) The target backend should support parametric circuit compilation from a given
qiskit QuantumCircuit object with the target basis gates, given initial layout,
and target hardware coupling map.
initial layout format: [1 2 0 ...] (means q0 --> p1, q1 --> p2, q2 --> p0 ...)
qX: logical qubit, pX: physical qubit
coupling map format: [[0,1],[1,0]...] (means the native 2q gate supported between
0 and 1, 1 and 0, ....)
basis gates format: ['x', 'cx' ...]
2) It should be able to recognize CX, RZ(theta), RX(theta), and H operations.
3) It should return the compiled circuit as a qiskit QuantumCircuit object. If it
does not do so, please convert the compiled circuit to a qiskit QuantumCircuit object.
4) If you are adding a new backend, please update the supported_backends variable
under __init__ as well.
5) Use/add config variables in the Config.json (see under examples) file based on the
supported features of the new backend.
6) Update the __load_config method as well if you are adding new variables in Config.json.
"""
assert isinstance(ckt_qiskit, QuantumCircuit)
if self.Backend == 'qiskit':
return transpile(ckt_qiskit, coupling_map = self.coupling_map,
basis_gates = self.basis_gates, initial_layout = self.initial_layout,
optimization_level = self.Opt_Level, seed_transpiler = self.Trans_Seed,
routing_method = self.Route_Method)
def __incremental_compilation(self):
"""
This method is used for incremental compilation.
"""
logical_n = len(self.zz_graph.nodes())
physical_n = len(self.unweighted_undirected_coupling_graph.nodes())
incr_c_qc = QuantumCircuit(physical_n, logical_n)
for i in range(logical_n):
incr_c_qc.h(self.initial_layout[i])
for p in range(1,self.Target_p+1):
remaining_ops = self.zz_graph.edges()
while remaining_ops:
self.__sort_zz_by_qq_distances(unsorted_ops = remaining_ops)
sorted_ops = self.sorted_ops
self.__instruction_parallelization(sorted_ops, single_layer = True)
remaining_ops = self.layer_zz_assignments['R']
self.__construct_single_layer_ckt_ic(p)
new_ckt_segment = self.circuit
self.__final_mapping_ic(qiskit_ckt_object = new_ckt_segment)
final_map = self.final_map
self.__set_initial_layout(final_map)
new_ckt_segment.remove_final_measurements(inplace=True)
incr_c_qc = incr_c_qc + new_ckt_segment
beta = Parameter('b{}'.format(p))
for node in range(logical_n):
incr_c_qc.rx(beta,self.initial_layout[node])
incr_c_qc.barrier()
for i in range(logical_n):
incr_c_qc.measure(self.initial_layout[i], i)
self.circuit = incr_c_qc
def __instruction_parallelization(self, sorted_edges = None, single_layer = False):
"""
This method is used for instruction parallelization.
"""
logical_qubits = self.zz_graph.nodes()
if sorted_edges:
remaining_edges = sorted_edges.copy()
else:
remaining_edges = list(self.zz_graph.edges())
current_layer = 'L0'
layer_occupancy = {current_layer: list()}
for qubit in logical_qubits:
layer_occupancy[current_layer].insert(len(layer_occupancy[current_layer]), [qubit,'FREE'])
self.layer_zz_assignments[current_layer] = list()
while True:
unallocated_edges = list()
allocated_op_count_in_this_layer = 0
for edge in remaining_edges:
if allocated_op_count_in_this_layer >= self.Packing_Limit:
unallocated_edges.insert(len(unallocated_edges), edge)
continue
n1, n2 = edge[0], edge[1]
free_among_the_two = 0
for occupancy_info_list in layer_occupancy[current_layer]:
if occupancy_info_list[0] in edge:
if occupancy_info_list[1] == 'OCCUPIED':
unallocated_edges.insert(len(unallocated_edges), edge)
break
free_among_the_two = free_among_the_two + 1
if free_among_the_two == 2:
n1_indx = layer_occupancy[current_layer].index([n1, 'FREE'])
n2_indx = layer_occupancy[current_layer].index([n2, 'FREE'])
layer_occupancy[current_layer][n1_indx] = [n1, 'OCCUPIED']
layer_occupancy[current_layer][n2_indx] = [n2, 'OCCUPIED']
self.layer_zz_assignments[current_layer].insert(len(layer_occupancy[current_layer]), edge)
allocated_op_count_in_this_layer = allocated_op_count_in_this_layer + 1
break
remaining_edges = unallocated_edges
if single_layer:
#print('Single layer formed!')
self.layer_zz_assignments['R'] = list()
for edge in remaining_edges:
self.layer_zz_assignments['R'].insert(0, edge)
break
elif len(remaining_edges) != 0:
next_layer = int(current_layer[1:]) + 1
current_layer = 'L' + str(next_layer)
layer_occupancy[current_layer] = list()
self.layer_zz_assignments[current_layer] = list()
for qubit in logical_qubits:
layer_occupancy[current_layer].insert(len(layer_occupancy[current_layer]), [qubit,'FREE'])
else:
#print('All layers formed!')
break
def __iterative_compilation(self):
"""
This method is used for iterative compilation.
"""
interchange = []
layer_order = []
for l in self.layer_zz_assignments.keys():
layer_order.append(l)
opt_target = 10e10
opt_ckt = QuantumCircuit()
while True:
for layer_1 in range(len(layer_order)):
for layer_2 in range(layer_1+1, len(layer_order)):
temp = layer_order.copy()
temp[layer_1], temp[layer_2] = temp[layer_2], temp[layer_1]
self.__construct_circuit_iterc(layer_order = temp)
trial_ckt = self.circuit
self.__calc_cost(circ = trial_ckt, target = self.iter_c_target)
trial_target = self.cost
if trial_target < opt_target:
interchange = [layer_1, layer_2]
opt_target = trial_target
opt_ckt = self.circuit
if not interchange:
self.circuit = opt_ckt
break
layer_1 = interchange[0]
layer_2 = interchange[1]
layer_order[layer_1], layer_order[layer_2] = layer_order[layer_2], layer_order[layer_1]
#print('Interchanged: %s, %s, Cost: %s\n' % (layer_1, layer_2, opt_target))
interchange = []
def __calc_cost(self, circ = None, target = 'GC_2Q'):
"""
This method is used to calculate cost of the compiled
circuit in terms of depth/2-qubit gate-count/estimated success probability.
"""
if target == 'GC_2Q':
self.cost = circ.count_ops()[self.native_2q[0]]
elif target == 'D':
self.cost = circ.depth()
elif target == 'ESP':
self.circuit = circ
self.__estimate_sp()
def __estimate_sp(self):
"""
This method estimates the success probability of a compiled circuit.
"""
cir = self.circuit.copy()
ESP = 1
while True:
if cir._data:
k = cir._data.pop()
gate = k[0].__dict__['name']
if gate not in self.basis_gates:
continue
qub = []
for i in range(len(k[1])):
qub.append(k[1][i].index)
if len(qub) == 1:
ESP = ESP*float(self.qc_data[gate][str(qub[0])])
else:
if '({},{})'.format(qub[0],qub[1]) in self.qc_data[gate].keys():
ESP = ESP*float(self.qc_data[gate]['({},{})'.format(qub[0], qub[1])])
elif '({},{})'.format(qub[1],qub[0]) in self.qc_data[gate].keys():
ESP = ESP*float(self.qc_data[gate]['({},{})'.format(qub[1], qub[0])])
else:
print('Please check the device configuration' +
'file for the following qubit-pair data: {}, {}'.format(qub[0], qub[1]))
else:
break
self.cost = -math.log(ESP)
def __construct_circuit_iterc(self, layer_order = None):
"""
This method constructs the circuit for iterative compilation.
"""
n = len(self.zz_graph.nodes())
qc = QuantumCircuit(n, n)
# superposition state applying hadamard to all the qubits
for node in self.zz_graph.nodes():
qc.h(node)
# change based on the mixing and phase separation layer architectures
for p in range(1, self.Target_p+1):
for l in layer_order:
# phase seperation depends on the number of edges
for edge in self.layer_zz_assignments[l]:
n1 = edge[0]
n2 = edge[1]
gamma = Parameter('g{}_{}_{}'.format(p, n1, n2))
qc.cx(n1, n2)
qc.rz(gamma, n2)
qc.cx(n1, n2)
# mixing depends on the number of nodes rx gates
beta = Parameter('b{}'.format(p))
for node in self.zz_graph.nodes():
qc.rx(beta, node)
qc.barrier()
qc.measure(range(n), range(n))
trans_ckt = self.__compile_with_backend(ckt_qiskit = qc)
self.circuit = trans_ckt
def __approximate_equivalence(self, ckt = None):
"""
This method checks (approximate) equivalence of the compiled circuit with the original one
by comparing the output measurements (at a fixed value of all the parameters).
"""
bind_dic1 = {}
bind_dic2 = {}
val = 1
for param in ckt.parameters:
bind_dic1[param] = val
for param in self.uncompiled_ckt.parameters:
bind_dic2[param] = val
ckt1 = ckt.bind_parameters(bind_dic1)
ckt2 = self.uncompiled_ckt.bind_parameters(bind_dic2)
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute([ckt1, ckt2], backend_sim, shots=1000000)
result_sim = job_sim.result()
counts1 = result_sim.get_counts(ckt1)
counts2 = result_sim.get_counts(ckt2)
return hellinger_fidelity(counts1, counts2) > 0.9
def __qasm_note(self, ckt = None, pol = None):
"""
This method prints notes on the compilation.
"""
#optional, will not work for larger circuits due to finite sampling errors
assert self.__approximate_equivalence(ckt)
print('##################### Notes on the Output File #############################')
if ckt:
self.circuit = self.naive_ckt
self.__estimate_sp()
print('(naive) Depth: {}, gate-count(2Q): {}, ESP: {}'.format(self.naive_ckt.depth(),
self.naive_ckt.count_ops()[self.native_2q[0]], math.exp(-self.cost)))
self.circuit = ckt
self.__estimate_sp()
print('({}) Depth: {}, gate-count(2Q): {}, ESP: {}'.format(pol, ckt.depth(),
ckt.count_ops()[self.native_2q[0]], math.exp(-self.cost)))
print('The circuit is written with beta/gamma parameters ' +
'at different p-lavels (https://arxiv.org/pdf/1411.4028.pdf)')
print('bX --> beta parameter at p=X')
print('gX --> gamma parameter at p=X (https://arxiv.org/pdf/1411.4028.pdf)')
else:
print('Compilation Error! Please check the input files.')
print('############################################################################')
def run_ip(self, initial_layout_method = 'qaim'):
"""
This public method runs instruction parallelization and writes the output circuits
in qasm format.
args:
No arguments required.
"""
self.__set_initial_layout(initial_layout_method = initial_layout_method)
self.__instruction_parallelization()
layer_order = self.layer_zz_assignments.keys()
self.__construct_circuit_iterc(layer_order)
ckt = self.circuit
filename = 'IP_' + self.output_file_name
ckt.qasm(filename = filename)
self.__fix_param_names(filename)
print('############################################################################')
print('Instruction Parallelization-only Compilation (IP) completed (initial layout: {})!'.format(initial_layout_method) +
'\nQASM File Written: {}'.format('IP_' + self.output_file_name))
self.__qasm_note(ckt, 'IP')
def run_iter_c(self, target = 'D', initial_layout_method = 'qaim'):
"""
This public method runs iterative compilation and writes the output circuits
in qasm format.
Args:
Target minimization objective: D (depth), GC-2Q (two-qubit gate-count),
ESP (estimated success probability)
"""
self.__set_initial_layout(initial_layout_method = initial_layout_method)
self.__set_iter_c_target(target)
self.__instruction_parallelization()
self.__iterative_compilation()
ckt = self.circuit
filename = 'IterC_' + self.output_file_name
ckt.qasm(filename = filename)
self.__fix_param_names(filename)
print('############################################################################')
print('Iterative Compilation (IterC) completed (initial layout: {})!'.format(initial_layout_method) +
'\nQASM File Written: {}'.format('IterC_' + self.output_file_name))
self.__qasm_note(ckt, 'IterC_' + target)
def run_incr_c(self, variation_aware = False, initial_layout_method = 'qaim'):
"""
This public method runs incremental compilation and writes the output circuits
in qasm format.
Args:
variation_aware (boolean) - False to perform IC and True to perform VIC
"""
self.__set_initial_layout(initial_layout_method = initial_layout_method)
self.__set_incrc_var_awareness(variation_aware)
self.__incremental_compilation()
ckt = self.circuit
print('############################################################################')
if variation_aware:
filename = 'VIC_' + self.output_file_name
ckt.qasm(filename = filename)
self.__fix_param_names(filename)
print('Variation-aware Incremental Compilation (VIC) completed (initial layout: {})!'.format(initial_layout_method) +
'\nQASM File Written: {}'.format('VIC_' + self.output_file_name))
self.__qasm_note(ckt, 'VIC')
else:
filename = 'IC_' + self.output_file_name
ckt.qasm(filename = filename)
self.__fix_param_names(filename)
print('Incremental Compilation (IC) completed (initial layout: {})!'.format(initial_layout_method) +
'\nQASM File Written: {}'.format('IC_' + self.output_file_name))
self.__qasm_note(ckt, 'IC')
def __fix_param_names(self, filename):
all_keys = self.zz_dict.keys()
f = open(filename, 'r').readlines()
out = open('{}_fixed'.format(filename), 'w')
for line in f:
captures = re.search('(g\d+)_(\d+)_(\d+)', line)
if captures:
captures = captures.groups()
g = captures[0]
n1 = captures[1]
n2 = captures[2]
if '({}, {})'.format(n1, n2) in all_keys:
coeff = 2*float(self.zz_dict['({}, {})'.format(n1, n2)])
else:
coeff = 2*float(self.zz_dict['({}, {})'.format(n2, n1)])
line = line.replace('{}_{}_{}'.format(g, n1, n2), str(coeff) + '*' + g)
out.write(line)
out.close()
os.remove(filename)
os.rename(filename + '_fixed', filename)
|
https://github.com/mballarin97/mps_qnn
|
mballarin97
|
import numpy as np
from qiskit.quantum_info import state_fidelity, Statevector
def getStatevector(circuit):
return Statevector(circuit).data
import warnings
warnings.filterwarnings('ignore')
def P_haar(N, F):
if F == 1:
return 0
else:
return (N - 1) * ((1 - F) ** (N - 2))
def KL(P, Q):
epsilon = 1e-8
kl_divergence = 0.0
for p, q in zip(P, Q):
kl_divergence += p * np.log( (p + epsilon) / (q + epsilon) )
return abs(kl_divergence)
def expressibility(qubits, sampler, *, bins=100, epoch=3000, layer=1, encode=False, return_detail=False):
unit = 1 / bins
limits = []
probabilities = np.array([0] * bins)
for i in range(1, bins + 1):
limits.append(unit * i)
for i in range(epoch):
circuit_1 = sampler(layer=layer, qubits=qubits)
circuit_2 = sampler(layer=layer, qubits=qubits)
f = state_fidelity(
getStatevector(circuit_1),
getStatevector(circuit_2)
)
for j in range(bins):
if f <= limits[j]:
probabilities[j] += 1
break
pHaar_vqc = [ P_haar(2 ** qubits, f - (unit/2)) / bins for f in limits]
probabilities = [ p / epoch for p in probabilities ]
if return_detail:
return pHaar_vqc, probabilities
else:
return KL(probabilities, pHaar_vqc)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
import dimod
import neal
import numpy as np
from dwave.system import DWaveSampler, EmbeddingComposite, DWaveCliqueSampler
A_int = np.array([[0,1,2,3,4,1],
[2,1,4,1,0,2],
[1,5,2,3,1,1],
[0,0,1,2,2,0]])
m, n = A_int.shape
vartype = dimod.Vartype.BINARY
c_int = np.array([-1,2,-2,2,1,1])
b = np.array([6,8,5,2])
print(A_int.dot(np.array([2,0,0,0,1,2])))
def get_binary_form(c,bits):
c_bin = []
for c_j in c:
c_bin += [c_j * 2**i for i in range(0,bits)]
return np.array(c_bin)
# represent each x_i as 2 bits to the power of 2
bits = 2
# Set Penalty for Constraints aprox solution
P = max(abs(c_int))*4
c = get_binary_form(c_int,bits)
print(c)
A = np.array([get_binary_form(A_int[i], bits) for i in range(0,m)])
print(A)
# Set up linear and quadratic coefficients
L = c.T - P * 2 * np.matmul(b.T,A)
Q = P * np.matmul(A.T,A)
offset = P * b.T.dot(b) -1
bqm = dimod.as_bqm(L, Q, offset, vartype)
exactSolver = dimod.ExactSolver()
sim = neal.SimulatedAnnealingSampler()
num_reads = 2500
exactSet = exactSolver.sample(bqm)
simSet = sim.sample(bqm, num_reads = num_reads)
def construct_x(sample, bits):
x=[]
for k in range(0,len(sample.keys()),bits):
x += [sum(sample[k+j]* 2**j for j in range(0,bits))]
return np.array(x)
def testSamples(sampleset, bits):
print("Minimum Energy Level found in:",sampleset.first)
X = []
for sample, energy, in sampleset.data(fields=['sample', 'energy']):
x = construct_x(sample,bits)
if all(A_int.dot(x)[i] == b[i] for i in range(0,m)) :
X += [(x,energy)]
return X
solutions_exact = testSamples(exactSet, bits)
for x, energy in solutions_exact :
print("Found solution {} with Energy Level {}".format(x,energy))
solutions_neal = testSamples(simSet, bits)
solutions_unique = { str(x) : energy for x, energy in solutions_neal}
solutions_count = {x:0 for x in solutions_unique.keys()}
for x,energy in solutions_neal:
solutions_count[str(x)]+=1
for x in solutions_unique.keys() :
print("Found solution {} {} times with Energy Level {}".format(x,solutions_count[x],solutions_unique[x]))
i=0
for sample, energy in exactSet.data(['sample','energy']):
print(sample,energy)
i+=1
if i==5: break
samplerComposite = EmbeddingComposite(DWaveSampler())
sampleset = samplerComposite.sample(bqm,num_reads = num_reads) # b2529319-cbc7-461c-a9c6-e4d2576b4a25
sampleset.to_pandas_dataframe()
solutions_real = testSamples(sampleset, bits)
solutions_unique = { str(x) : energy for x, energy in solutions_real}
for x in solutions_unique.keys() :
print("Found solution {} with Energy Level {}".format(x,solutions_unique[x]))
samplerClique = DWaveCliqueSampler()
sampleset = samplerClique.sample(bqm,num_reads = num_reads) # 9263c4dc-9701-462a-bfad-d990ca722c1f
sampleset.to_pandas_dataframe()
solutions_real = testSamples(sampleset, bits)
solutions_unique = { str(x) : energy for x, energy in solutions_real}
for x in solutions_unique.keys() :
print("Found solution {} with Energy Level {}".format(x,solutions_unique[x]))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit.quantumcircuitdata import CircuitInstruction
from qiskit.circuit import Measure
from qiskit.circuit.library import HGate, CXGate
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
instructions = [
CircuitInstruction(HGate(), [qr[0]], []),
CircuitInstruction(CXGate(), [qr[0], qr[1]], []),
CircuitInstruction(Measure(), [qr[0]], [cr[0]]),
CircuitInstruction(Measure(), [qr[1]], [cr[1]]),
]
circuit = QuantumCircuit.from_instructions(instructions)
circuit.draw("mpl")
|
https://github.com/chaitanya-bhargava/QiskitSolutions
|
chaitanya-bhargava
|
## Enter Team ID
import os
os.environ["TEAMID"] = "Excalibur"
from qiskit import QuantumCircuit
def dj_circuit_2q(oracle):
dj_circuit = QuantumCircuit(3,2)
### Your code here
dj_circuit.x(2)
dj_circuit.barrier()
dj_circuit.h(range(3))
dj_circuit.barrier()
dj_circuit.compose(oracle, inplace = True)
dj_circuit.barrier()
dj_circuit.h(range(2))
dj_circuit.measure(range(2), range(2))
### Your code here
return dj_circuit
def test_function_1():
# a constant oracle with f(x)=0 for all inputs
oracle = QuantumCircuit(3)
oracle.id(2)
dj_circuit = dj_circuit_2q(oracle)
return dj_circuit
test_function_1().draw()
from grader.graders.problem_4.grader import grader1
grader1.evaluate(dj_circuit_2q)
def dj_circuit_4q(oracle):
circuit = QuantumCircuit(5, 4)
### Your code here
circuit.x(4)
circuit.barrier()
circuit.h(range(5))
circuit.barrier()
circuit.compose(oracle, inplace = True)
circuit.barrier()
circuit.h(range(4))
circuit.measure(range(4), range(4))
### Your code here
return circuit
def test_function_2():
oracle = QuantumCircuit(5)
oracle.id(4)
dj_circuit = dj_circuit_4q(oracle)
return dj_circuit
test_function_2().draw()
from grader.graders.problem_4.grader import grader2
grader2.evaluate(dj_circuit_4q)
from qiskit import QuantumCircuit
def dj_circuit_general(n, oracle):
dj_circuit = QuantumCircuit(n+1, n)
### Your code here
dj_circuit.x(n)
dj_circuit.barrier()
dj_circuit.h(range(n+1))
dj_circuit.barrier()
dj_circuit.compose(oracle, inplace = True)
dj_circuit.barrier()
dj_circuit.h(range(n))
dj_circuit.measure(range(n), range(n))
### Your code here
return dj_circuit
def test_function_3():
N = 6
# constant oracle with f(x) = 0
oracle = QuantumCircuit(7)
oracle.id(6)
circuit = dj_circuit_general(N, oracle)
return circuit
test_function_3().draw()
from grader.graders.problem_4.grader import grader3
grader3.evaluate(dj_circuit_general)
|
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/Gopal-Dahale/qiskit-qulacs
|
Gopal-Dahale
|
"""Util functions for provider"""
import re
import warnings
from math import log2
from typing import Any, Dict, Iterable, List, Set, Tuple
import numpy as np
import psutil
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter, ParameterExpression
from qiskit.circuit import library as lib
from qiskit.circuit.parametervector import ParameterVectorElement
from qiskit.quantum_info import SparsePauliOp
from scipy.sparse import diags
from sympy import lambdify
import qulacs.gate as qg
from qulacs import Observable, ParametricQuantumCircuit, PauliOperator
_EPS = 1e-10 # global variable used to chop very small numbers to zero
# Available system memory
SYSTEM_MEMORY_GB = psutil.virtual_memory().total / (1024**3)
# Max number of qubits
MAX_QUBITS = int(log2(SYSTEM_MEMORY_GB * (1024**3) / 16))
# Defintions of some gates that are not directly defined in qulacs
# The `args` argument is of the form *qubits, *parameters
# The gates defined below currently support only single parameter only
def qgUnitary(*args):
"""
The function `qgUnitary` takes qubits and parameters as input and returns a dense matrix.
Returns:
The function `qgUnitary` is returning a `qg.DenseMatrix` object created with the provided `qubits`
and `parameters`.
"""
qubits = args[:-1]
parameters = args[-1]
return qg.DenseMatrix(qubits, parameters) # pylint: disable=no-member
IsingXX = lambda *args: qg.ParametricPauliRotation(args[:-1], [1, 1], args[-1].real)
IsingYY = lambda *args: qg.ParametricPauliRotation(args[:-1], [2, 2], args[-1].real)
IsingZZ = lambda *args: qg.ParametricPauliRotation(args[:-1], [3, 3], args[-1].real)
ecr_mat = np.array(
[[0, 1, 0, 1j], [1, 0, -1j, 0], [0, 1j, 0, 1], [-1j, 0, 1, 0]]
) / np.sqrt(2)
qgECR = lambda *args: qg.DenseMatrix(args, matrix=ecr_mat)
# These gates in qulacs have positive rotation directions.
# Angles of these gates need to be multiplied by -1 during conversion.
# https://docs.qulacs.org/en/latest/guide/2.0_python_advanced.html#1-qubit-rotating-gate
neg_gates = {"RXGate", "RYGate", "RZGate", "RXXGate", "RYYGate", "RZZGate"}
# Only these gates support trainable parameters
parametric_gates = neg_gates
# Gate addition type
# based on the type of the, one of these two will be used in the qulacs circuit
gate_addition = ["add_gate", "add_parametric_gate"]
QISKIT_OPERATION_MAP = {
qg.X: lib.XGate,
qg.Y: lib.YGate,
qg.Z: lib.ZGate,
qg.H: lib.HGate,
qg.CNOT: lib.CXGate,
qg.CZ: lib.CZGate,
qg.SWAP: lib.SwapGate,
qg.FREDKIN: lib.CSwapGate,
qg.ParametricRX: lib.RXGate, # -theta
qg.ParametricRY: lib.RYGate, # -theta
qg.ParametricRZ: lib.RZGate, # -theta
qg.Identity: lib.IGate,
qg.TOFFOLI: lib.CCXGate,
qg.U1: lib.U1Gate, # deprecated in qiskit, use p gate
qg.U2: lib.U2Gate, # deprecated in qiskit, use u gate
qg.U3: lib.U3Gate, # deprecated in qiskit, use u gate
IsingXX: lib.RXXGate, # -theta
IsingYY: lib.RYYGate, # -theta
IsingZZ: lib.RZZGate, # -theta
qg.S: lib.SGate,
qg.Sdag: lib.SdgGate,
qg.T: lib.TGate,
qg.Tdag: lib.TdgGate,
qg.sqrtX: lib.SXGate,
qg.sqrtXdag: lib.SXdgGate,
qgUnitary: lib.UnitaryGate,
qgECR: lib.ECRGate,
}
inv_map = {v.__name__: k for k, v in QISKIT_OPERATION_MAP.items()}
# Gates with different names but same operation
duplicate_gates = {"UGate": "U3Gate"}
def convert_qiskit_to_qulacs_circuit(qc: QuantumCircuit):
"""
The function `convert_qiskit_to_qulacs_circuit` converts a Qiskit QuantumCircuit to a Qulacs
ParametricQuantumCircuit while handling parameter mapping and gate operations.
Args:
qc (QuantumCircuit): The `qc` is expected to be a QuantumCircuit object from Qiskit.
Returns:
The `convert_qiskit_to_qulacs_circuit` function returns a nested function `circuit_builder` that
takes an optional `params_values` argument. Inside `circuit_builder`, it constructs a
`ParametricQuantumCircuit` based on the input `QuantumCircuit` `qc` provided to the outer function.
"""
def circuit_builder(params_values=[]) -> Tuple[ParametricQuantumCircuit, Dict]:
"""
The `circuit_builder` function converts a Qiskit quantum circuit into a ParametricQuantumCircuit,
handling parameter mapping and supporting trainable parameters.
Args:
params_values: The `params_values` parameter in the `circuit_builder` function is a list that
contains the values of the parameters that will be used to build a quantum circuit. These values
will be used to replace the symbolic parameters in the quantum circuit with concrete numerical
values during the circuit construction process.
Returns:
The `circuit_builder` function returns a ParametricQuantumCircuit and a dictionary containing
information about parameter mapping and parameter expressions.
"""
circuit = ParametricQuantumCircuit(qc.num_qubits)
# parameter mapping
# dictionary from qiskit's quantum circuit parameters to a two element tuple.
# the tuple has an element params_values and its index
# Currently not supporting qiskit's parameter expression
var_ref_map = dict(
zip(qc.parameters, list(zip(params_values, range(qc.num_parameters)))),
)
# Wires from a qiskit circuit have unique IDs, so their hashes are unique too
qc_wires = [hash(q) for q in qc.qubits]
wire_map = dict(zip(qc_wires, range(len(qc_wires))))
# Holds the indices of parameter as they occur during
# circuit conversion. This is used during circuit gradient computation.
param_mapping = []
param_exprs = []
f_args: List[Any] = []
f_params: List[Any] = []
indices: List[int] = []
f_param_names: Set[Any] = set()
flag = False # indicates whether the instruction is parametric
for instruction, qargs, _ in qc.data:
# the new Singleton classes have different names than the objects they represent,
# but base_class.__name__ still matches
instruction_name = getattr(
instruction, "base_class", instruction.__class__
).__name__
instruction_name = duplicate_gates.get(instruction_name, instruction_name)
sign = 1.0 - 2 * (instruction_name in neg_gates)
operation_wires = [wire_map[hash(qubit)] for qubit in qargs]
operation_params = []
flag = False
for p in instruction.params:
if isinstance(p, ParameterExpression) and p.parameters:
f_args = []
f_params = []
indices = []
# Ensure duplicate subparameters are only appended once.
f_param_names = set()
for subparam in p.parameters:
try:
parameter = subparam
argument, index = var_ref_map.get(subparam)
except:
raise ValueError(
"The number of circuit parameters does not match",
" the number of parameter values passed.",
)
if isinstance(subparam, ParameterVectorElement):
# Unfortunately, the names of parameter vector elements
# include square brackets, making them invalid Python
# identifiers and causing compatibility problems with SymPy.
# To solve this issue, we generate a temporary parameter
# that replaces square bracket by underscores.
subparam_name = re.sub(r"\[|\]", "_", str(subparam))
parameter = Parameter(subparam_name)
argument, index = var_ref_map.get(subparam)
# Update the subparam in `p`
p = p.assign(subparam, parameter)
if parameter.name not in f_param_names:
f_param_names.add(parameter.name)
f_params.append(parameter)
f_args.append(argument)
indices.append(index)
f_expr = getattr(p, "_symbol_expr")
if isinstance(p, Parameter):
# If `p` is an instance of `Parameter` then we can
# we do not need to calculate the expression value
operation_params += list(map(lambda x: x * sign, f_args))
else:
# Calculate the expression value using sympy
f = lambdify(f_params, f_expr)
operation_params += [f(*f_args) * sign]
param_mapping += indices
param_exprs += [(f_params, f_expr)]
flag = True
else:
operation_params.append(p * sign)
operation_class = inv_map.get(instruction_name)
try:
getattr(circuit, gate_addition[flag])(
operation_class(*operation_wires, *operation_params) # type: ignore
)
except:
if flag:
raise ValueError(
f"{__name__}: The {instruction_name} does not support trainable parameter.",
f" Consider decomposing {instruction_name} into {parametric_gates}.",
)
warnings.warn(
f"{__name__}: The {instruction_name} instruction is not supported"
" by Qiskit-Qulacs and has not been added to the circuit.",
UserWarning,
)
if qc.global_phase > _EPS:
# add the gphase_mat to the circuit
circuit.add_gate(
qg.SparseMatrix( # pylint: disable=no-member
list(range(qc.num_qubits)),
diags(np.exp(1j * qc.global_phase) * np.ones(2**qc.num_qubits)),
)
)
return circuit, {
"parameter_mapping": param_mapping,
"parameter_exprs": param_exprs,
}
return circuit_builder
def qiskit_to_qulacs(
circuits: List[QuantumCircuit],
) -> Iterable[ParametricQuantumCircuit]:
"""
The function `qiskit_to_qulacs` converts a list of Qiskit quantum circuits
into a generator of Qulacs circuits.
Args:
circuits (List[QuantumCircuit]): The `circuits` parameter is a list of
`QuantumCircuit` objects.
"""
for circuit in circuits:
yield convert_qiskit_to_qulacs_circuit(circuit)()[0]
def convert_sparse_pauliop_to_qulacs_obs(sparse_pauliop: SparsePauliOp):
"""
The function `convert_sparse_pauliop_to_qulacs_obs` converts a
sparse Pauli operator to a Qulacs observable.
Args:
sparse_pauliop: The `sparse_pauliop` parameter is a sparse
representation of a Pauli operator. It is an object that contains
information about the Pauli terms and their coefficients. Each term is
represented by a `PauliTerm` object, which consists of a list of Pauli
operators and their corresponding
Returns:
a Qulacs Observable object.
"""
qulacs_observable = Observable(sparse_pauliop.num_qubits)
for op in sparse_pauliop:
term, coefficient = str(op.paulis[0])[::-1], op.coeffs[0]
pauli_string = ""
for qubit, pauli in enumerate(term):
pauli_string += f"{pauli} {qubit} "
qulacs_observable.add_operator(PauliOperator(pauli_string, coefficient.real))
return qulacs_observable
|
https://github.com/drobiu/quantum-project
|
drobiu
|
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.providers.aer import QasmSimulator
from qiskit.visualization import plot_histogram
# Use Aer's qasm_simulator
simulator = QasmSimulator()
# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(2, 2)
# Add a H gate on qubit 0
circuit.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(0, 1)
# Map the quantum measurement to the classical bits
circuit.measure([0,1], [0,1])
# compile the circuit down to low-level QASM instructions
# supported by the backend (not needed for simple circuits)
compiled_circuit = transpile(circuit, simulator)
# Execute the circuit on the qasm simulator
job = simulator.run(compiled_circuit, shots=1000)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(compiled_circuit)
# print("\nTotal count for 00 and 11 are:",counts)
# Draw the ci
circuit.draw(output="latex", filename="printing.png")
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for visualization tools."""
import unittest
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Qubit, Clbit
from qiskit.visualization.circuit import _utils
from qiskit.visualization import array_to_latex
from qiskit.test import QiskitTestCase
from qiskit.utils import optionals
class TestVisualizationUtils(QiskitTestCase):
"""Tests for circuit drawer utilities."""
def setUp(self):
super().setUp()
self.qr1 = QuantumRegister(2, "qr1")
self.qr2 = QuantumRegister(2, "qr2")
self.cr1 = ClassicalRegister(2, "cr1")
self.cr2 = ClassicalRegister(2, "cr2")
self.circuit = QuantumCircuit(self.qr1, self.qr2, self.cr1, self.cr2)
self.circuit.cx(self.qr2[0], self.qr2[1])
self.circuit.measure(self.qr2[0], self.cr2[0])
self.circuit.cx(self.qr2[1], self.qr2[0])
self.circuit.measure(self.qr2[1], self.cr2[1])
self.circuit.cx(self.qr1[0], self.qr1[1])
self.circuit.measure(self.qr1[0], self.cr1[0])
self.circuit.cx(self.qr1[1], self.qr1[0])
self.circuit.measure(self.qr1[1], self.cr1[1])
def test_get_layered_instructions(self):
"""_get_layered_instructions without reverse_bits"""
(qregs, cregs, layered_ops) = _utils._get_layered_instructions(self.circuit)
exp = [
[("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())],
[("measure", (self.qr2[0],), (self.cr2[0],))],
[("measure", (self.qr1[0],), (self.cr1[0],))],
[("cx", (self.qr2[1], self.qr2[0]), ()), ("cx", (self.qr1[1], self.qr1[0]), ())],
[("measure", (self.qr2[1],), (self.cr2[1],))],
[("measure", (self.qr1[1],), (self.cr1[1],))],
]
self.assertEqual([self.qr1[0], self.qr1[1], self.qr2[0], self.qr2[1]], qregs)
self.assertEqual([self.cr1[0], self.cr1[1], self.cr2[0], self.cr2[1]], cregs)
self.assertEqual(
exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_reverse_bits(self):
"""_get_layered_instructions with reverse_bits=True"""
(qregs, cregs, layered_ops) = _utils._get_layered_instructions(
self.circuit, reverse_bits=True
)
exp = [
[("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())],
[("measure", (self.qr2[0],), (self.cr2[0],))],
[("measure", (self.qr1[0],), (self.cr1[0],)), ("cx", (self.qr2[1], self.qr2[0]), ())],
[("cx", (self.qr1[1], self.qr1[0]), ())],
[("measure", (self.qr2[1],), (self.cr2[1],))],
[("measure", (self.qr1[1],), (self.cr1[1],))],
]
self.assertEqual([self.qr2[1], self.qr2[0], self.qr1[1], self.qr1[0]], qregs)
self.assertEqual([self.cr2[1], self.cr2[0], self.cr1[1], self.cr1[0]], cregs)
self.assertEqual(
exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_remove_idle_wires(self):
"""_get_layered_instructions with idle_wires=False"""
qr1 = QuantumRegister(3, "qr1")
qr2 = QuantumRegister(3, "qr2")
cr1 = ClassicalRegister(3, "cr1")
cr2 = ClassicalRegister(3, "cr2")
circuit = QuantumCircuit(qr1, qr2, cr1, cr2)
circuit.cx(qr2[0], qr2[1])
circuit.measure(qr2[0], cr2[0])
circuit.cx(qr2[1], qr2[0])
circuit.measure(qr2[1], cr2[1])
circuit.cx(qr1[0], qr1[1])
circuit.measure(qr1[0], cr1[0])
circuit.cx(qr1[1], qr1[0])
circuit.measure(qr1[1], cr1[1])
(qregs, cregs, layered_ops) = _utils._get_layered_instructions(circuit, idle_wires=False)
exp = [
[("cx", (qr2[0], qr2[1]), ()), ("cx", (qr1[0], qr1[1]), ())],
[("measure", (qr2[0],), (cr2[0],))],
[("measure", (qr1[0],), (cr1[0],))],
[("cx", (qr2[1], qr2[0]), ()), ("cx", (qr1[1], qr1[0]), ())],
[("measure", (qr2[1],), (cr2[1],))],
[("measure", (qr1[1],), (cr1[1],))],
]
self.assertEqual([qr1[0], qr1[1], qr2[0], qr2[1]], qregs)
self.assertEqual([cr1[0], cr1[1], cr2[0], cr2[1]], cregs)
self.assertEqual(
exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_left_justification_simple(self):
"""Test _get_layered_instructions left justification simple since #2802
q_0: |0>───────■──
┌───┐ │
q_1: |0>┤ H ├──┼──
├───┤ │
q_2: |0>┤ H ├──┼──
└───┘┌─┴─┐
q_3: |0>─────┤ X ├
└───┘
"""
qc = QuantumCircuit(4)
qc.h(1)
qc.h(2)
qc.cx(0, 3)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left")
l_exp = [
[
("h", (Qubit(QuantumRegister(4, "q"), 1),), ()),
("h", (Qubit(QuantumRegister(4, "q"), 2),), ()),
],
[("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())],
]
self.assertEqual(
l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_right_justification_simple(self):
"""Test _get_layered_instructions right justification simple since #2802
q_0: |0>──■───────
│ ┌───┐
q_1: |0>──┼──┤ H ├
│ ├───┤
q_2: |0>──┼──┤ H ├
┌─┴─┐└───┘
q_3: |0>┤ X ├─────
└───┘
"""
qc = QuantumCircuit(4)
qc.h(1)
qc.h(2)
qc.cx(0, 3)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right")
r_exp = [
[("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())],
[
("h", (Qubit(QuantumRegister(4, "q"), 1),), ()),
("h", (Qubit(QuantumRegister(4, "q"), 2),), ()),
],
]
self.assertEqual(
r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_left_justification_less_simple(self):
"""Test _get_layered_instructions left justification
less simple example since #2802
┌────────────┐┌───┐┌────────────┐ ┌─┐┌────────────┐┌───┐┌────────────┐
q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├──────────────┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├
├────────────┤└─┬─┘├────────────┤┌────────────┐└╥┘└────────────┘└─┬─┘├────────────┤
q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├┤ U2(0,pi/1) ├─╫─────────────────■──┤ U2(0,pi/1) ├
└────────────┘ └────────────┘└────────────┘ ║ └────────────┘
q_2: |0>────────────────────────────────────────────────╫──────────────────────────────────
║
q_3: |0>────────────────────────────────────────────────╫──────────────────────────────────
║
q_4: |0>────────────────────────────────────────────────╫──────────────────────────────────
║
c1_0: 0 ════════════════════════════════════════════════╩══════════════════════════════════
"""
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[5];
creg c1[1];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
u2(0,3.14159265358979) q[1];
measure q[0] -> c1[0];
u2(0,3.14159265358979) q[0];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
"""
qc = QuantumCircuit.from_qasm_str(qasm)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left")
l_exp = [
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("u2", (Qubit(QuantumRegister(5, "q"), 1),), ())],
[
(
"measure",
(Qubit(QuantumRegister(5, "q"), 0),),
(Clbit(ClassicalRegister(1, "c1"), 0),),
)
],
[("u2", (Qubit(QuantumRegister(5, "q"), 0),), ())],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
]
self.assertEqual(
l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_right_justification_less_simple(self):
"""Test _get_layered_instructions right justification
less simple example since #2802
┌────────────┐┌───┐┌────────────┐┌─┐┌────────────┐┌───┐┌────────────┐
q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├
├────────────┤└─┬─┘├────────────┤└╥┘├────────────┤└─┬─┘├────────────┤
q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├─╫─┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├
└────────────┘ └────────────┘ ║ └────────────┘ └────────────┘
q_2: |0>──────────────────────────────────╫──────────────────────────────────
║
q_3: |0>──────────────────────────────────╫──────────────────────────────────
║
q_4: |0>──────────────────────────────────╫──────────────────────────────────
║
c1_0: 0 ══════════════════════════════════╩══════════════════════════════════
"""
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[5];
creg c1[1];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
u2(0,3.14159265358979) q[1];
measure q[0] -> c1[0];
u2(0,3.14159265358979) q[0];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
"""
qc = QuantumCircuit.from_qasm_str(qasm)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right")
r_exp = [
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[
(
"measure",
(Qubit(QuantumRegister(5, "q"), 0),),
(Clbit(ClassicalRegister(1, "c1"), 0),),
)
],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
]
self.assertEqual(
r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_op_with_cargs(self):
"""Test _get_layered_instructions op with cargs right of measure
┌───┐┌─┐
q_0: |0>┤ H ├┤M├─────────────
└───┘└╥┘┌───────────┐
q_1: |0>──────╫─┤0 ├
║ │ add_circ │
c_0: 0 ══════╩═╡0 ╞
└───────────┘
c_1: 0 ═════════════════════
"""
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.measure(0, 0)
qc_2 = QuantumCircuit(1, 1, name="add_circ")
qc_2.h(0).c_if(qc_2.cregs[0], 1)
qc_2.measure(0, 0)
qc.append(qc_2, [1], [0])
(_, _, layered_ops) = _utils._get_layered_instructions(qc)
expected = [
[("h", (Qubit(QuantumRegister(2, "q"), 0),), ())],
[
(
"measure",
(Qubit(QuantumRegister(2, "q"), 0),),
(Clbit(ClassicalRegister(2, "c"), 0),),
)
],
[
(
"add_circ",
(Qubit(QuantumRegister(2, "q"), 1),),
(Clbit(ClassicalRegister(2, "c"), 0),),
)
],
]
self.assertEqual(
expected, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_nomathmode(self):
"""Test generate latex label default."""
self.assertEqual("abc", _utils.generate_latex_label("abc"))
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_nomathmode_utf8char(self):
"""Test generate latex label utf8 characters."""
self.assertEqual(
"{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label("∭X∀Y"),
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_mathmode_utf8char(self):
"""Test generate latex label mathtext with utf8."""
self.assertEqual(
"abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label("$abc_$∭X∀Y"),
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_mathmode_underscore_outside(self):
"""Test generate latex label with underscore outside mathmode."""
self.assertEqual(
"abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label("$abc$_∭X∀Y"),
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_escaped_dollar_signs(self):
"""Test generate latex label with escaped dollarsign."""
self.assertEqual("${\\ensuremath{\\forall}}$", _utils.generate_latex_label(r"\$∀\$"))
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_escaped_dollar_sign_in_mathmode(self):
"""Test generate latex label with escaped dollar sign in mathmode."""
self.assertEqual(
"a$bc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label(r"$a$bc$_∭X∀Y"),
)
def test_array_to_latex(self):
"""Test array_to_latex produces correct latex string"""
matrix = [
[np.sqrt(1 / 2), 1 / 16, 1 / np.sqrt(8) + 3j, -0.5 + 0.5j],
[1 / 3 - 1 / 3j, np.sqrt(1 / 2) * 1j, 34.3210, -9 / 2],
]
matrix = np.array(matrix)
exp_str = (
"\\begin{bmatrix}\\frac{\\sqrt{2}}{2}&\\frac{1}{16}&"
"\\frac{\\sqrt{2}}{4}+3i&-\\frac{1}{2}+\\frac{i}{2}\\\\"
"\\frac{1}{3}+\\frac{i}{3}&\\frac{\\sqrt{2}i}{2}&34.321&-"
"\\frac{9}{2}\\\\\\end{bmatrix}"
)
result = array_to_latex(matrix, source=True).replace(" ", "").replace("\n", "")
self.assertEqual(exp_str, result)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Special data types.
"""
from enum import Enum
from typing import NamedTuple, List, Union, NewType, Tuple, Dict
from qiskit import circuit
ScheduledGate = NamedTuple(
"ScheduledGate",
[
("t0", int),
("operand", circuit.Gate),
("duration", int),
("bits", List[Union[circuit.Qubit, circuit.Clbit]]),
("bit_position", int),
],
)
ScheduledGate.__doc__ = "A gate instruction with embedded time."
ScheduledGate.t0.__doc__ = "Time when the instruction is issued."
ScheduledGate.operand.__doc__ = "Gate object associated with the gate."
ScheduledGate.duration.__doc__ = "Time duration of the instruction."
ScheduledGate.bits.__doc__ = "List of bit associated with the gate."
ScheduledGate.bit_position.__doc__ = "Position of bit associated with this drawing source."
GateLink = NamedTuple(
"GateLink", [("t0", int), ("opname", str), ("bits", List[Union[circuit.Qubit, circuit.Clbit]])]
)
GateLink.__doc__ = "Dedicated object to represent a relationship between instructions."
GateLink.t0.__doc__ = "A position where the link is placed."
GateLink.opname.__doc__ = "Name of gate associated with this link."
GateLink.bits.__doc__ = "List of bit associated with the instruction."
Barrier = NamedTuple(
"Barrier",
[("t0", int), ("bits", List[Union[circuit.Qubit, circuit.Clbit]]), ("bit_position", int)],
)
Barrier.__doc__ = "Dedicated object to represent a barrier instruction."
Barrier.t0.__doc__ = "A position where the barrier is placed."
Barrier.bits.__doc__ = "List of bit associated with the instruction."
Barrier.bit_position.__doc__ = "Position of bit associated with this drawing source."
HorizontalAxis = NamedTuple(
"HorizontalAxis", [("window", Tuple[int, int]), ("axis_map", Dict[int, int]), ("label", str)]
)
HorizontalAxis.__doc__ = "Data to represent configuration of horizontal axis."
HorizontalAxis.window.__doc__ = "Left and right edge of graph."
HorizontalAxis.axis_map.__doc__ = "Mapping of apparent coordinate system and actual location."
HorizontalAxis.label.__doc__ = "Label of horizontal axis."
class BoxType(str, Enum):
"""Box type.
SCHED_GATE: Box that represents occupation time by gate.
DELAY: Box associated with delay.
TIMELINE: Box that represents time slot of a bit.
"""
SCHED_GATE = "Box.ScheduledGate"
DELAY = "Box.Delay"
TIMELINE = "Box.Timeline"
class LineType(str, Enum):
"""Line type.
BARRIER: Line that represents barrier instruction.
GATE_LINK: Line that represents a link among gates.
"""
BARRIER = "Line.Barrier"
GATE_LINK = "Line.GateLink"
class SymbolType(str, Enum):
"""Symbol type.
FRAME: Symbol that represents zero time frame change (Rz) instruction.
"""
FRAME = "Symbol.Frame"
class LabelType(str, Enum):
"""Label type.
GATE_NAME: Label that represents name of gate.
DELAY: Label associated with delay.
GATE_PARAM: Label that represents parameter of gate.
BIT_NAME: Label that represents name of bit.
"""
GATE_NAME = "Label.Gate.Name"
DELAY = "Label.Delay"
GATE_PARAM = "Label.Gate.Param"
BIT_NAME = "Label.Bit.Name"
class AbstractCoordinate(Enum):
"""Abstract coordinate that the exact value depends on the user preference.
RIGHT: The horizontal coordinate at t0 shifted by the left margin.
LEFT: The horizontal coordinate at tf shifted by the right margin.
TOP: The vertical coordinate at the top of the canvas.
BOTTOM: The vertical coordinate at the bottom of the canvas.
"""
RIGHT = "RIGHT"
LEFT = "LEFT"
TOP = "TOP"
BOTTOM = "BOTTOM"
class Plotter(str, Enum):
"""Name of timeline plotter APIs.
MPL: Matplotlib plotter interface. Show timeline in 2D canvas.
"""
MPL = "mpl"
# convenient type to represent union of drawing data
DataTypes = NewType("DataType", Union[BoxType, LabelType, LineType, SymbolType])
# convenient type to represent union of values to represent a coordinate
Coordinate = NewType("Coordinate", Union[float, AbstractCoordinate])
# Valid bit objects
Bits = NewType("Bits", Union[circuit.Qubit, circuit.Clbit])
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
import pandas as pd
from qiskit import Aer
from qiskit import execute
from qiskit.test.mock import FakeVigo
class DatasetGenerator:
def __init__(self, shots=1000, L=3):
"""
Initialize a new DatasetGenerator.
This object provides an interface to generate synthetic quantum-noisy datasets.
The user must prescribe the circuits and noise models.
Some presets are available.
:param shots: number of times to measure each circuit, default: 1000
:param L: maximum circuit length
"""
# Simulator Variables
self.device_backend = FakeVigo()
self.coupling_map = self.device_backend.configuration().coupling_map
self.simulator = Aer.get_backend('qasm_simulator')
self.shots = shots
self.L = L
self.dataset = self.emptyDataset()
"""self.observations = []
self.features = []
self.labels = []"""
def add_observation(self, circuit, noise_model):
"""
Add a new data point - (feature, label) - to the dataset.
:param circuit: circuit, len(circuit) <= self.L
:param noise_model:
:return: none
"""
assert len(circuit) <= self.L
feature = (circuit, noise_model)
label = self.get_counts(circuit, noise_model)
self.dataset.add_data_point(feature, label)
def get_dataset(self):
"""
:return: the dataset (DataFrame)
"""
return self.dataset
def get_counts(self, circuit, noise_model):
"""
Simulate a circuit with a noise_model and return measurement counts
:param circuit:
:param noise_model:
:return: measurement counts (dict {'0':C0, '1':C1})
"""
result = execute(circuit, self.simulator, noise_model=noise_model, coupling_map=self.coupling_map,
basis_gates=noise_model.basis_gates, shots=self.shots).result()
counts = result.get_counts()
return counts
def emptyDataset(self):
"""
Generate an empty Dataset.
Column format:
Gate_1
NM_1
...
...
Expected Value
:return: df: DataFrame
"""
column_names = []
for i in range(self.L):
column_names.append("Gate_{}_theta".format(i))
column_names.append("Gate_{}_phi".format(i))
column_names.append("Gate_{}_lambda".format(i))
column_names.append("NM_{}".format(i))
column_names.append("ExpectedValue")
df = pd.DataFrame(dtype='float64', columns=column_names)
df.loc[0] = pd.Series(dtype='float64')
df.loc[1] = pd.Series(dtype='float64')
df.loc[2] = pd.Series(dtype='float64')
return df
def __repr__(self):
return "I am a dataset generator for quantum noise estimation"
dgen = DatasetGenerator()
ds = dgen.dataset
print("ds.info()")
print(ds.info())
"""
Questions
1. how to encode noise model
2. how to generate data samples
"""
|
https://github.com/ShabaniLab/qiskit-hackaton-2019
|
ShabaniLab
|
import numpy as np
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
from ising_kitaev import initialize_chain, run_adiabatic_zeeman_change, rotate_to_measurement_basis, add_measurement
from ising_kitaev import move_chain, initialize_coupler
zeeman_ferro = 0.01 # value of on-site magnetic field for ferromagnetic domain
zeeman_para = 10 # value of on-site magnetic field for paramagnetic domain
# initial configuration of domains
initial_config = np.array([zeeman_ferro, zeeman_ferro, zeeman_ferro, zeeman_para, zeeman_para, zeeman_para])
# final configuration of domains
final_config = np.array([zeeman_para, zeeman_para, zeeman_para, zeeman_ferro, zeeman_ferro, zeeman_ferro])
qreg = QuantumRegister(7)
creg = ClassicalRegister(3)
qcirc = QuantumCircuit(qreg, creg)
initialize_chain(qcirc, qreg, initial_config, 'logical_zero')
initialize_coupler(qcirc, qreg) # couple the chain to a coupler
qcirc.draw()
# moving ferromagenetic domain to one end
move_chain(qcirc, qreg, initial_config, final_config, 1.4, 0.25, 0.25, 2, 20, method = "both")
# moving back the ferromagnetic domain
move_chain(qcirc, qreg, final_config, initial_config, 1.4, 0.25, 0.25, 2, 20, method = "both")
qcirc.depth()
rotate_to_measurement_basis(qcirc, qreg, [0, 1, 2]) # measurement in logical basis
add_measurement(qcirc, qreg, creg, [0, 1, 2])
from qiskit import Aer, execute
backend = Aer.get_backend('qasm_simulator')
job = execute(qcirc, backend, shots=2000)
job.status()
result = job.result()
result.get_counts()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.drivers import Molecule
from qiskit_nature.drivers.second_quantization import (
ElectronicStructureDriverType,
ElectronicStructureMoleculeDriver,
PySCFDriver,
)
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer
from qiskit_nature.settings import settings
settings.dict_aux_operators = True
molecule = Molecule(
geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]], charge=0, multiplicity=1
)
driver = ElectronicStructureMoleculeDriver(
molecule, basis="sto3g", driver_type=ElectronicStructureDriverType.PYSCF
)
# or equivalently:
driver = PySCFDriver.from_molecule(molecule, basis="sto3g")
transformer = FreezeCoreTransformer()
problem = ElectronicStructureProblem(driver, transformers=[transformer])
# Note: at this point, `driver.run()` has NOT been called yet. We can trigger this indirectly like so:
second_q_ops = problem.second_q_ops()
hamiltonian = second_q_ops["ElectronicEnergy"]
print(hamiltonian)
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo
from qiskit_nature.second_q.transformers import FreezeCoreTransformer
molecule = MoleculeInfo(["H", "H"], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.735)], charge=0, multiplicity=1)
driver = PySCFDriver.from_molecule(molecule, basis="sto3g")
# this is now done explicitly
problem = driver.run()
transformer = FreezeCoreTransformer()
# and you also apply transformers explicitly
problem = transformer.transform(problem)
hamiltonian = problem.hamiltonian.second_q_op()
print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."]))
from qiskit_nature.drivers import Molecule
from qiskit_nature.drivers.second_quantization import PySCFDriver
molecule = Molecule(
geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]], charge=0, multiplicity=1
)
driver = PySCFDriver.from_molecule(molecule)
result = driver.run()
print(type(result))
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo
molecule = MoleculeInfo(["H", "H"], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.735)], charge=0, multiplicity=1)
driver = PySCFDriver.from_molecule(molecule, basis="sto3g")
result = driver.run()
print(type(result))
from qiskit_nature.drivers.second_quantization import FCIDumpDriver
path_to_fcidump = "aux_files/h2.fcidump"
driver = FCIDumpDriver(path_to_fcidump)
result = driver.run()
print(type(result))
from qiskit_nature.second_q.formats.fcidump import FCIDump
path_to_fcidump = "aux_files/h2.fcidump"
fcidump = FCIDump.from_file(path_to_fcidump)
print(type(fcidump))
from qiskit_nature.second_q.formats.fcidump_translator import fcidump_to_problem
problem = fcidump_to_problem(fcidump)
print(type(problem))
from qiskit_nature.drivers.second_quantization import PySCFDriver
from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer
transformer = FreezeCoreTransformer()
driver = PySCFDriver()
transformed_result = transformer.transform(driver.run())
print(type(transformed_result))
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.transformers import FreezeCoreTransformer
transformer = FreezeCoreTransformer()
driver = PySCFDriver()
transformed_result = transformer.transform(driver.run())
print(type(transformed_result))
from qiskit_nature.drivers.second_quantization import PySCFDriver
from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer
driver = PySCFDriver()
transformer = FreezeCoreTransformer()
problem = ElectronicStructureProblem(driver, transformers=[transformer])
# we trigger driver.run() implicitly like so:
second_q_ops = problem.second_q_ops()
hamiltonian_op = second_q_ops.pop("ElectronicEnergy")
aux_ops = second_q_ops
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.transformers import FreezeCoreTransformer
driver = PySCFDriver()
problem = driver.run()
transformer = FreezeCoreTransformer()
problem = transformer.transform(problem)
hamiltonian_op, aux_ops = problem.second_q_ops()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/gustavomirapalheta/Quantum-Computing-with-Qiskit
|
gustavomirapalheta
|
import sympy as sp
f0, f0L, f1, f1L = sp.symbols('f0 f0L f1, f1L');
Or = sp.Matrix([[f0L, f0, 0, 0],
[ f0, f0L, 0, 0],
[ 0, 0, f1L, f1],
[ 0, 0, f1, f1L]])
Or
import sympy as sp
from sympy import kronecker_product as kron
H = sp.Matrix([[1,1],[1,-1]])
I = sp.Matrix([[1,0],[0,1]])
x=sp.Matrix([[1,0]])
y=sp.Matrix([[0,1]])
#ATENÇÃO: |yx> -> <xy| ou |q2q1q0> -> <q0q1q2| (equivalência ket-bra)
#Logo se utilizamos "bras" no lugar de "kets", o Qiskit deve ser lido
#de cima para baixo e da esquerda para a direita.
deustch = kron(x,y)*(kron(H,H))*(Or)*(kron(H,I))
display(deustch.T)
deustch.subs({f0:1, f0L:0, f1:1, f1L:0})
deustch.subs({f0:0, f0L:1, f1:0, f1L:1})
deustch.subs({f0:0, f0L:1, f1:1, f1L:0})
deustch.subs({f0:1, f0L:0, f1:0, f1L:1})
import numpy as np
x = np.array([[1,0]])
y = np.array([[0,1]])
xy = np.kron(x,y); xy
H2 = np.array([[1, 1],
[1,-1]]); H2
I2 = np.array([[1,0],[0,1]]); I2
H2H2 = np.kron(H2,H2); H2H2
print(xy.dot(H2H2))
Or1 = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]); Or1
res1 = xy.dot(H2H2).dot(Or1).dot(H2I2); print(res1)
Or2 = np.array([[0,1,0,0],[1,0,0,0],[0,0,0,1],[0,0,1,0]]); Or2
res2 = xy.dot(H2H2).dot(Or2).dot(H2I2); print(res2)
Or3 = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); Or3
res3 = xy.dot(H2H2).dot(Or3).dot(H2I2); print(res3)
Or4 = np.array([[0,1,0,0],[1,0,0,0],[0,0,1,0],[0,0,0,1]]); Or4
res4 = xy.dot(H2H2).dot(Or4).dot(H2I2); print(res4)
# Setup básico
!pip install qiskit -q
!pip install qiskit[visualization] -q
import qiskit as qk
!pip install qiskit-aer -q
import qiskit_aer as qk_aer
import numpy as np
np.set_printoptions(precision=3, suppress=True)
from matplotlib import pyplot as plt
%matplotlib inline
import pandas as pd
import sklearn as sk
# IMPORTANT NOTE: The readings in Qiskit should be done from bottom up.
# The most significant bit (the leftmost in a table or
# matrix is the one at the BOTTOM. To keep compatibility
# with the sympy and numpy matrices, x will be placed
# BELOW and y on TOP.
import numpy as np
Or1 = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]); display(Or1)
import qiskit as qk
from qiskit.quantum_info.operators import Operator
qrx = qk.QuantumRegister(1,'x')
cr = qk.ClassicalRegister(1,"c")
qry = qk.QuantumRegister(1,'y')
qc = qk.QuantumCircuit(qry,qrx,cr)
qc.barrier()
qc.h(qrx)
qc.x(qry)
qc.h(qry)
qc.barrier()
oracle = Operator(Or1)
qc.append(oracle,[qry,qrx])
qc.barrier()
qc.h(qrx)
qc.measure(qrx,cr)
display(qc.draw('mpl'))
simulator = qk_aer.Aer.get_backend("aer_simulator")
results = simulator.run(qk.transpile(qc,simulator),shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
# IMPORTANT NOTE: The readings in Qiskit should be done from bottom up.
# The most significant bit (the leftmost in a table or
# matrix is the one at the BOTTOM. To keep compatibility
# with the sympy and numpy matrices, x will be placed
# BELOW and y on TOP.
import numpy as np
Or2 = np.array([[0,1,0,0],[1,0,0,0],[0,0,0,1],[0,0,1,0]]); display(Or2)
import qiskit as qk
from qiskit.quantum_info.operators import Operator
qrx = qk.QuantumRegister(1,'x')
cr = qk.ClassicalRegister(1,"c")
qry = qk.QuantumRegister(1,'y')
qc = qk.QuantumCircuit(qry,qrx,cr)
qc.barrier()
qc.h(qrx)
qc.x(qry)
qc.h(qry)
qc.barrier()
oracle = Operator(Or2)
qc.append(oracle,[qry,qrx])
qc.barrier()
qc.h(qrx)
qc.measure(qrx,cr)
display(qc.draw('mpl'))
simulator = qk_aer.Aer.get_backend("aer_simulator")
results = simulator.run(qk.transpile(qc,simulator),shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
# IMPORTANT NOTE: The readings in Qiskit should be done from bottom up.
# The most significant bit (the leftmost in a table or
# matrix is the one at the BOTTOM. To keep compatibility
# with the sympy and numpy matrices, x will be placed
# BELOW and y on TOP. When the function in balanced this
# is essential to get the correct measurement (x=<1|)
import numpy as np
Or3 = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); display(Or3)
import qiskit as qk
from qiskit.quantum_info.operators import Operator
qrx = qk.QuantumRegister(1,'x')
cr = qk.ClassicalRegister(1,"c")
qry = qk.QuantumRegister(1,'y')
qc = qk.QuantumCircuit(qry,qrx,cr)
qc.barrier()
qc.h(qrx)
qc.x(qry)
qc.h(qry)
qc.barrier()
oracle = Operator(Or3)
qc.append(oracle,[qry,qrx])
qc.barrier()
qc.h(qrx)
qc.measure(qrx,cr)
display(qc.draw('mpl'))
simulator = qk_aer.Aer.get_backend("aer_simulator")
results = simulator.run(qk.transpile(qc,simulator),shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
# IMPORTANT NOTE: The readings in Qiskit should be done from bottom up.
# The most significant bit (the leftmost in a table or
# matrix is the one at the BOTTOM. To keep compatibility
# with the sympy and numpy matrices, x will be placed
# BELOW and y on TOP. When the function in balanced this
# is essential to get the correct measurement (x=<1|)
import numpy as np
Or4 = np.array([[0,1,0,0],[1,0,0,0],[0,0,1,0],[0,0,0,1]]); display(Or4)
import qiskit as qk
from qiskit.quantum_info.operators import Operator
qrx = qk.QuantumRegister(1,'x')
cr = qk.ClassicalRegister(1,"c")
qry = qk.QuantumRegister(1,'y')
qc = qk.QuantumCircuit(qry,qrx,cr)
qc.barrier()
qc.h(qrx)
qc.x(qry)
qc.h(qry)
qc.barrier()
oracle = Operator(Or4)
qc.append(oracle,[qry,qrx])
qc.barrier()
qc.h(qrx)
qc.measure(qrx,cr)
display(qc.draw('mpl'))
simulator = qk_aer.Aer.get_backend("aer_simulator")
results = simulator.run(qk.transpile(qc,simulator),shots=10000).result().get_counts()
qk.visualization.plot_histogram(results)
import sympy as sp
f00, f00L, f01, f01L, f10, f10L, f11, f11L = \
sp.symbols('f00 f00L f01, f01L f10 f10L f11, f11L');
Or = sp.Matrix([[f00L, f00 , 0, 0, 0, 0, 0, 0],
[f00 , f00L, 0, 0, 0, 0, 0, 0],
[ 0, 0, f01L, f01 , 0, 0, 0, 0],
[ 0, 0, f01 , f01L, 0, 0, 0, 0],
[ 0, 0, 0, 0, f10L, f10 , 0, 0],
[ 0, 0, 0, 0, f10 , f10L, 0, 0],
[ 0, 0, 0, 0, 0, 0, f11L, f11 ],
[ 0, 0, 0, 0, 0, 0, f11, f11L]])
Or
import sympy as sp
from sympy import kronecker_product as kron
H = sp.Matrix([[1,1],[1,-1]])
I = sp.Matrix([[1,0],[0,1]])
x0=sp.Matrix([[1,0]])
x1=sp.Matrix([[1,0]])
y=sp.Matrix([[0,1]])
#ATENÇÃO: |yx> -> <xy| ou |q2q1q0> -> <q0q1q2| (equivalência ket-bra)
#Logo se utilizamos "bras" no lugar de "kets", o Qiskit deve ser lido
#de cima para baixo e da esquerda para a direita.
josza = kron(x0,kron(x1,y))*(kron(H,kron(H,H)))*(Or)*(kron(H,kron(H,I)))
display(josza.T)
josza.subs({f00:0, f00L:1,
f01:0, f01L:1,
f10:1, f10L:0,
f11:1, f11L:0})
josza.subs({f00:0, f00L:1,
f01:1, f01L:0,
f10:1, f10L:0,
f11:0, f11L:1})
josza.subs({f00:0, f00L:1,
f01:0, f01L:1,
f10:0, f10L:1,
f11:0, f11L:1})
josza.subs({f00:1, f00L:0,
f01:1, f01L:0,
f10:1, f10L:0,
f11:1, f11L:0})
josza.subs({f00:0, f00L:1,
f01:0, f01L:1,
f10:0, f10L:1,
f11:1, f11L:0})
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram
import numpy as np
q = QuantumRegister(1)
c = ClassicalRegister(1)
error = {}
for n in range(1,11):
# Create a blank circuit
qc = QuantumCircuit(q,c)
# Implement an approximate Hadamard
theta = np.pi # here we incorrectly choose theta=pi
for j in range(n):
qc.rx(theta/n,q[0])
qc.rz(theta/n,q[0])
# We need to measure how good the above approximation is. Here's a simple way to do this.
# Step 1: Use a real hadamard to cancel the above approximation.
# For a good approximatuon, the qubit will return to state 0. For a bad one, it will end up as some superposition.
qc.h(q[0])
# Step 2: Run the circuit, and see how many times we get the outcome 1.
# Since it should return 0 with certainty, the fraction of 1s is a measure of the error.
qc.measure(q,c)
shots = 20000
job = execute(qc, Aer.get_backend('qasm_simulator'),shots=shots)
try:
error[n] = (job.result().get_counts()['1']/shots)
except:
pass
plot_histogram(error)
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from sympy import *
init_printing(use_unicode=True)
mu_u = Matrix([[-1],[+1],[+1]]); mu_u
A_R = Matrix([[1,1,-1,-1],[1,-1,1,-1],[1,-1,-1,1]]); A_R
p1,p2,p3,p4 = symbols('p_1 p_2 p_3 p_4')
p4 = 1-p1-p2-p3
cl = A_R[:,0]*p1 + A_R[:,1]*p2 + A_R[:,2]*p3 + A_R[:,3]*p4
mu_u - cl
s1 = Matrix([[0,1],[1,0]])
s2 = Matrix([[0,-1j],[1j,0]])
s1*s2
import numpy as np
a = [] # gera uma lista com com todos os 512 estados ônticos
for j in range(-1,2,2):
for k in range(-1,2,2):
for l in range(-1,2,2):
for m in range(-1,2,2):
for n in range(-1,2,2):
for o in range(-1,2,2):
for p in range(-1,2,2):
for q in range(-1,2,2):
for r in range(-1,2,2):
a.append(np.array([j,k,l,m,n,o,p,q,r]))
a[10], a[10][5], len(a)
mu = [] # gera, a partir dos estados ônticos, uma lista com os 512 vetores de medida, muitos dos quais são iguais
for j in range(0,2**9):
r1 = a[j][0]*a[j][1]*a[j][2]
r2 = a[j][3]*a[j][4]*a[j][5]
r3 = a[j][6]*a[j][7]*a[j][8]
c1 = a[j][0]*a[j][3]*a[j][6]
c2 = a[j][1]*a[j][4]*a[j][7]
c3 = a[j][2]*a[j][5]*a[j][8]
mu.append([r1,r2,r3,c1,c2,c3])
mu[0], len(mu)
mu_ = [] # remove as repeticoes do vetor de medida
for j in range(0,2**6):
if mu[j] not in mu_:
mu_.append(mu[j])
mu_, len(mu_), mu_[1]
A_R = np.zeros((6,16))#; A_R
for j in range(0,16):
A_R[:,j] = mu_[j]
print(A_R)
print(A_R.shape)
def rpv_zhsl(d): # vetor de probabilidades aleatório
rn = np.zeros(d-1)
for j in range(0,d-1):
rn[j] = np.random.random()
rpv = np.zeros(d)
rpv[0] = 1.0 - rn[0]**(1.0/(d-1.0))
norm = rpv[0]
if d > 2:
for j in range(1,d-1):
rpv[j] = (1.0 - rn[j]**(1.0/(d-j-1)))*(1.0-norm)
norm = norm + rpv[j]
rpv[d-1] = 1.0 - norm
return rpv
rpv = rpv_zhsl(16)
print(rpv)
print(np.linalg.norm(rpv))
mu_Q = np.zeros((6,1)); mu_Q = np.array([1,1,1,1,1,-1]); print(mu_Q.shape)
p = np.zeros((16,1)); p = rpv_zhsl(16); print(p.shape)
vec = mu_Q - A_R@p
print(vec)
def objective(x):
mu_Q = np.array([1,1,1,1,1,-1])
vec = mu_Q - A_R@x
return np.linalg.norm(vec)
from scipy.optimize import minimize
# define o vinculo como sendo uma distribuicao de probabilidades
constraints = [{'type': 'eq', 'fun': lambda x: np.sum(x)-1},
{'type':'ineq', 'fun': lambda x: x},
{'type':'ineq', 'fun': lambda x: 1-x}]
# 'eq' quer dizer = 0 e 'ineq' quer dizer >=0
np.random.seed(130000)
x0 = rpv_zhsl(16)
print(x0)
result = minimize(objective, x0, constraints=constraints, method='trust-constr')
print('melhor distribuicao de probabilidades', result.x)
print(objective(result.x))
from qiskit import *
import numpy as np
import math
import qiskit
nshots = 8192
IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_manila')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
#from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
#from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.visualization import plot_histogram
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr,cr)
qc.barrier() # mede XI
qc.h(0)
qc.cx(0,2)
qc.barrier() # mede IX
qc.h(1)
qc.cx(1,2)
qc.barrier() # mede XX
qc.cx(0,2)
qc.cx(1,2)
qc.barrier()
qc.measure(2,0)
qc.draw('mpl')
job_sim = execute(qc, backend=simulator, shots=nshots)
counts_sim = job_sim.result().get_counts(qc)
job_exp = execute(qc, backend=device, shots=nshots)
print(job_exp.job_id())
job_monitor(job_exp)
counts_exp = job_exp.result().get_counts(qc)
counts_exp
plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp'])
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr,cr)
qc.barrier() # mede YI
qc.sdg(0)
qc.h(0)
qc.cx(0,2)
qc.barrier() # mede IY
qc.sdg(1)
qc.h(1)
qc.cx(1,2)
qc.barrier() # mede YY
qc.cx(0,2)
qc.cx(1,2)
qc.barrier()
qc.measure(2,0)
qc.draw('mpl')
job_sim = execute(qc, backend=simulator, shots=nshots)
counts_sim = job_sim.result().get_counts(qc)
job_exp = execute(qc, backend=device, shots=nshots)
print(job_exp.job_id())
job_monitor(job_exp)
counts_exp = job_exp.result().get_counts(qc)
counts_exp
plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp'])
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr,cr)
qc.barrier()
qc.h(0)
qc.cx(0,2) # mede XI
qc.barrier()
qc.sdg(1)
qc.h(1)
qc.cx(1,2) # mede IX
qc.barrier()
qc.cx(0,2); qc.cx(1,2)
qc.barrier()
qc.measure(2,0)
qc.draw('mpl')
job_sim = execute(qc, backend=simulator, shots=nshots)
counts_sim = job_sim.result().get_counts(qc)
job_exp = execute(qc, backend=device, shots=nshots)
print(job_exp.job_id())
job_monitor(job_exp)
counts_exp = job_exp.result().get_counts(qc)
counts_exp
plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp'])
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr,cr)
qc.barrier()
qc.sdg(0)
qc.h(0)
qc.cx(0,2) # mede XI
qc.barrier()
qc.h(1)
qc.cx(1,2) # mede IX
qc.barrier()
qc.cx(0,2); qc.cx(1,2)
qc.barrier()
qc.measure(2,0)
qc.draw('mpl')
job_sim = execute(qc, backend=simulator, shots=nshots)
counts_sim = job_sim.result().get_counts(qc)
job_exp = execute(qc, backend=device, shots=nshots)
print(job_exp.job_id())
job_monitor(job_exp)
counts_exp = job_exp.result().get_counts(qc)
counts_exp
plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp'])
I = Matrix([[1,0],[0,1]]); X = Matrix([[0,1],[1,0]]);
Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]])
I,X,Y,Z
XX = kronecker_product(X,X); XX.eigenvects()
YY = kronecker_product(Y,Y); YY.eigenvects()
ZZ = kronecker_product(Z,Z); ZZ.eigenvects()
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr,cr)
qc.barrier() # mede ZZ
qc.cx(0,2)
qc.cx(1,2)
qc.barrier() # mede XX
qc.h([0,1])
qc.cx(0,2)
qc.cx(1,2)
qc.barrier() # mede YY
qc.h([0,1])
qc.sdg([0,1])
qc.h([0,1])
qc.cx(0,2)
qc.cx(1,2)
qc.barrier()
qc.measure(2,0)
qc.draw('mpl')
job_sim = execute(qc, backend=simulator, shots=nshots)
counts_sim = job_sim.result().get_counts(qc)
job_exp = execute(qc, backend=device, shots=nshots)
print(job_exp.job_id())
job_monitor(job_exp)
counts_exp = job_exp.result().get_counts(qc)
counts_exp
plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp'])
XY = kronecker_product(X,Y); XY.eigenvects()
YX = kronecker_product(Y,X); YX.eigenvects()
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr,cr)
qc.barrier() # mede ZZ
qc.cx(0,2)
qc.cx(1,2)
qc.barrier() # mede XX
qc.sdg(1)
qc.h([0,1])
qc.cx(0,2)
qc.cx(1,2)
qc.barrier() # mede YY
qc.h([0,1])
qc.sdg(0)
qc.s(1)
qc.h([0,1])
qc.cx(0,2)
qc.cx(1,2)
qc.barrier()
qc.measure(2,0)
qc.draw('mpl')
job_sim = execute(qc, backend=simulator, shots=nshots)
counts_sim = job_sim.result().get_counts(qc)
job_exp = execute(qc, backend=device, shots=nshots)
print(job_exp.job_id())
job_monitor(job_exp)
counts_exp = job_exp.result().get_counts(qc)
counts_exp
plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp'])
cr1 = {'0': 7921, '1': 271}
cr2 = {'0': 7944, '1': 248}
cr3 = {'0': 7754, '1': 438}
cc1 = {'0': 7913, '1': 279}
cc2 = {'0': 7940, '1': 252}
cc3 = {'0': 610, '1': 7582}
r1a = (cr1['0']-cr1['1'])/(cr1['0']+cr1['1'])
r2a = (cr2['0']-cr2['1'])/(cr2['0']+cr2['1'])
r3a = (cr3['0']-cr3['1'])/(cr3['0']+cr3['1'])
c1a = (cc1['0']-cc1['1'])/(cc1['0']+cc1['1'])
c2a = (cc2['0']-cc2['1'])/(cc2['0']+cc2['1'])
c3a = (cc3['0']-cc3['1'])/(cc3['0']+cc3['1'])
print(r1a,r2a,r3a,c1a,c2a,c3a)
def objective(x):
mu_Q = np.array([0.93,0.94,0.89,0.93,0.94,-0.85])
vec = mu_Q - A_R@x
return np.linalg.norm(vec)
constraints = [{'type': 'eq', 'fun': lambda x: np.sum(x)-1},
{'type':'ineq', 'fun': lambda x: x},
{'type':'ineq', 'fun': lambda x: 1-x}]
np.random.seed(130000)
x0 = rpv_zhsl(16)
result = minimize(objective, x0, constraints=constraints, method='trust-constr')
print('melhor distribuicao de probabilidades', result.x)
print(objective(result.x))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import json
import time
import warnings
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import clear_output
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.quantum_info import Statevector
from qiskit.utils import algorithm_globals
from qiskit_machine_learning.circuit.library import RawFeatureVector
from qiskit_machine_learning.neural_networks import SamplerQNN
algorithm_globals.random_seed = 42
def ansatz(num_qubits):
return RealAmplitudes(num_qubits, reps=5)
num_qubits = 5
circ = ansatz(num_qubits)
circ.decompose().draw("mpl")
def auto_encoder_circuit(num_latent, num_trash):
qr = QuantumRegister(num_latent + 2 * num_trash + 1, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
circuit.compose(ansatz(num_latent + num_trash), range(0, num_latent + num_trash), inplace=True)
circuit.barrier()
auxiliary_qubit = num_latent + 2 * num_trash
# swap test
circuit.h(auxiliary_qubit)
for i in range(num_trash):
circuit.cswap(auxiliary_qubit, num_latent + i, num_latent + num_trash + i)
circuit.h(auxiliary_qubit)
circuit.measure(auxiliary_qubit, cr[0])
return circuit
num_latent = 3
num_trash = 2
circuit = auto_encoder_circuit(num_latent, num_trash)
circuit.draw("mpl")
def domain_wall(circuit, a, b):
# Here we place the Domain Wall to qubits a - b in our circuit
for i in np.arange(int(b / 2), int(b)):
circuit.x(i)
return circuit
domain_wall_circuit = domain_wall(QuantumCircuit(5), 0, 5)
domain_wall_circuit.draw("mpl")
ae = auto_encoder_circuit(num_latent, num_trash)
qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1)
qc = qc.compose(domain_wall_circuit, range(num_latent + num_trash))
qc = qc.compose(ae)
qc.draw("mpl")
# Here we define our interpret for our SamplerQNN
def identity_interpret(x):
return x
qnn = SamplerQNN(
circuit=qc,
input_params=[],
weight_params=ae.parameters,
interpret=identity_interpret,
output_shape=2,
)
def cost_func_domain(params_values):
probabilities = qnn.forward([], params_values)
# we pick a probability of getting 1 as the output of the network
cost = np.sum(probabilities[:, 1])
# plotting part
clear_output(wait=True)
objective_func_vals.append(cost)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
return cost
opt = COBYLA(maxiter=150)
initial_point = algorithm_globals.random.random(ae.num_parameters)
objective_func_vals = []
# make the plot nicer
plt.rcParams["figure.figsize"] = (12, 6)
start = time.time()
opt_result = opt.minimize(cost_func_domain, initial_point)
elapsed = time.time() - start
print(f"Fit in {elapsed:0.2f} seconds")
test_qc = QuantumCircuit(num_latent + num_trash)
test_qc = test_qc.compose(domain_wall_circuit)
ansatz_qc = ansatz(num_latent + num_trash)
test_qc = test_qc.compose(ansatz_qc)
test_qc.barrier()
test_qc.reset(4)
test_qc.reset(3)
test_qc.barrier()
test_qc = test_qc.compose(ansatz_qc.inverse())
test_qc.draw("mpl")
test_qc = test_qc.assign_parameters(opt_result.x)
domain_wall_state = Statevector(domain_wall_circuit).data
output_state = Statevector(test_qc).data
fidelity = np.sqrt(np.dot(domain_wall_state.conj(), output_state) ** 2)
print("Fidelity of our Output State with our Input State: ", fidelity.real)
def zero_idx(j, i):
# Index for zero pixels
return [
[i, j],
[i - 1, j - 1],
[i - 1, j + 1],
[i - 2, j - 1],
[i - 2, j + 1],
[i - 3, j - 1],
[i - 3, j + 1],
[i - 4, j - 1],
[i - 4, j + 1],
[i - 5, j],
]
def one_idx(i, j):
# Index for one pixels
return [[i, j - 1], [i, j - 2], [i, j - 3], [i, j - 4], [i, j - 5], [i - 1, j - 4], [i, j]]
def get_dataset_digits(num, draw=True):
# Create Dataset containing zero and one
train_images = []
train_labels = []
for i in range(int(num / 2)):
# First we introduce background noise
empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape(
8, 4
)
# Now we insert the pixels for the one
for i, j in one_idx(2, 6):
empty[j][i] = algorithm_globals.random.uniform(0.9, 1)
train_images.append(empty)
train_labels.append(1)
if draw:
plt.title("This is a One")
plt.imshow(train_images[-1])
plt.show()
for i in range(int(num / 2)):
empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape(
8, 4
)
# Now we insert the pixels for the zero
for k, j in zero_idx(2, 6):
empty[k][j] = algorithm_globals.random.uniform(0.9, 1)
train_images.append(empty)
train_labels.append(0)
if draw:
plt.imshow(train_images[-1])
plt.title("This is a Zero")
plt.show()
train_images = np.array(train_images)
train_images = train_images.reshape(len(train_images), 32)
for i in range(len(train_images)):
sum_sq = np.sum(train_images[i] ** 2)
train_images[i] = train_images[i] / np.sqrt(sum_sq)
return train_images, train_labels
train_images, __ = get_dataset_digits(2)
num_latent = 3
num_trash = 2
fm = RawFeatureVector(2 ** (num_latent + num_trash))
ae = auto_encoder_circuit(num_latent, num_trash)
qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1)
qc = qc.compose(fm, range(num_latent + num_trash))
qc = qc.compose(ae)
qc.draw("mpl")
def identity_interpret(x):
return x
qnn = SamplerQNN(
circuit=qc,
input_params=fm.parameters,
weight_params=ae.parameters,
interpret=identity_interpret,
output_shape=2,
)
def cost_func_digits(params_values):
probabilities = qnn.forward(train_images, params_values)
cost = np.sum(probabilities[:, 1]) / train_images.shape[0]
# plotting part
clear_output(wait=True)
objective_func_vals.append(cost)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
return cost
with open("12_qae_initial_point.json", "r") as f:
initial_point = json.load(f)
opt = COBYLA(maxiter=150)
objective_func_vals = []
# make the plot nicer
plt.rcParams["figure.figsize"] = (12, 6)
start = time.time()
opt_result = opt.minimize(fun=cost_func_digits, x0=initial_point)
elapsed = time.time() - start
print(f"Fit in {elapsed:0.2f} seconds")
# Test
test_qc = QuantumCircuit(num_latent + num_trash)
test_qc = test_qc.compose(fm)
ansatz_qc = ansatz(num_latent + num_trash)
test_qc = test_qc.compose(ansatz_qc)
test_qc.barrier()
test_qc.reset(4)
test_qc.reset(3)
test_qc.barrier()
test_qc = test_qc.compose(ansatz_qc.inverse())
# sample new images
test_images, test_labels = get_dataset_digits(2, draw=False)
for image, label in zip(test_images, test_labels):
original_qc = fm.assign_parameters(image)
original_sv = Statevector(original_qc).data
original_sv = np.reshape(np.abs(original_sv) ** 2, (8, 4))
param_values = np.concatenate((image, opt_result.x))
output_qc = test_qc.assign_parameters(param_values)
output_sv = Statevector(output_qc).data
output_sv = np.reshape(np.abs(output_sv) ** 2, (8, 4))
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.imshow(original_sv)
ax1.set_title("Input Data")
ax2.imshow(output_sv)
ax2.set_title("Output Data")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/antontutoveanu/quantum-tic-tac-toe
|
antontutoveanu
|
# Copyright 2019 Cambridge Quantum Computing
#
# 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 itertools
import qiskit
from typing import Tuple, Iterable
from qiskit import IBMQ, QuantumCircuit
from qiskit.compiler import assemble
from qiskit.tools.monitor import job_monitor
from pytket.backends import Backend
from pytket.qiskit import tk_to_qiskit
from pytket._routing import route, Architecture
from pytket._transform import Transform
from pytket._circuit import Circuit
import numpy as np
VALID_BACKEND_GATES = (
qiskit.extensions.standard.u1.U1Gate,
qiskit.extensions.standard.u2.U2Gate,
qiskit.extensions.standard.u3.U3Gate,
qiskit.extensions.standard.cx.CnotGate,
qiskit.circuit.measure.Measure
)
def _qiskit_circ_valid(qc: QuantumCircuit, coupling:Iterable[Tuple[int]] ) -> bool:
valid = True
measure_count = 0
for instruction in qc:
if type(instruction[0]) not in VALID_BACKEND_GATES:
valid = False
break
if isinstance(instruction[0], qiskit.circuit.measure.Measure):
measure_count += 1
if len(instruction[1]) > 1:
control = instruction[1][0][1]
target = instruction[1][1][1]
if [control, target] not in coupling:
valid =False
break
return valid, (measure_count > 0)
def _routed_ibmq_circuit(circuit:Circuit, arc: Architecture) -> QuantumCircuit:
c = circuit.copy()
Transform.RebaseToQiskit().apply(c)
physical_c = route(c, arc)
physical_c.decompose_SWAP_to_CX()
physical_c.redirect_CX_gates(arc)
Transform.OptimisePostRouting().apply(physical_c)
qc = tk_to_qiskit(physical_c)
return qc
def _convert_bin_str(string) :
return [int(b) for b in string.replace(' ', '')][::-1]
class IBMQBackend(Backend) :
def __init__(self, backend_name:str, monitor:bool=True) :
"""A backend for running circuits on remote IBMQ devices.
:param backend_name: name of ibmq device. e.g. `ibmqx4`, `ibmq_16_melbourne`.
:type backend_name: str
:param monitor: Use IBM job monitor, defaults to True
:type monitor: bool, optional
:raises ValueError: If no IBMQ account has been set up.
"""
if len(IBMQ.stored_accounts()) ==0:
raise ValueError('No IBMQ credentials found on disk. Store some first.')
IBMQ.load_accounts()
self._backend = IBMQ.get_backend(backend_name)
self.config = self._backend.configuration()
self.coupling = self.config.coupling_map
self.architecture = Architecture(self.coupling)
self._monitor = monitor
def run(self, circuit:Circuit, shots:int, fit_to_constraints:bool=True) -> np.ndarray :
if fit_to_constraints:
qc = _routed_ibmq_circuit(circuit, self.architecture)
else:
qc = tk_to_qiskit(circuit)
valid, measures = _qiskit_circ_valid(qc, self.coupling)
if not valid:
raise RuntimeWarning("QuantumCircuit does not pass validity test, will likely fail on remote backend.")
if not measures:
raise RuntimeWarning("Measure gates are required for output.")
qobj = assemble(qc, shots=shots, memory=self.config.memory)
job = self._backend.run(qobj)
if self._monitor :
job_monitor(job)
shot_list = []
if self.config.memory:
shot_list = job.result().get_memory(qc)
else:
for string, count in job.result().get_counts().items():
shot_list += [string]*count
return np.asarray([_convert_bin_str(shot) for shot in shot_list])
def get_counts(self, circuit, shots, fit_to_constraints=True) :
"""
Run the circuit on the backend and accumulate the results into a summary of counts
:param circuit: The circuit to run
:param shots: Number of shots (repeats) to run
:param fit_to_constraints: Compile the circuit to meet the constraints of the backend, defaults to True
:param seed: Random seed to for simulator
:return: Dictionary mapping bitvectors of results to number of times that result was observed (zero counts are omitted)
"""
if fit_to_constraints:
qc = _routed_ibmq_circuit(circuit, self.architecture)
else:
qc = tk_to_qiskit(circuit)
valid, measures = _qiskit_circ_valid(qc, self.coupling)
if not valid:
raise RuntimeWarning("QuantumCircuit does not pass validity test, will likely fail on remote backend.")
if not measures:
raise RuntimeWarning("Measure gates are required for output.")
qobj = assemble(qc, shots=shots)
job = self._backend.run(qobj)
counts = job.result().get_counts(qc)
return {tuple(_convert_bin_str(b)) : c for b, c in counts.items()}
|
https://github.com/jaykomarraju/Quantum-Optimization-for-Solar-Farm
|
jaykomarraju
|
import numpy as np
import networkx as nx
from qiskit import Aer
from qiskit.algorithms import QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.algorithms import MinimumEigenOptimizer
num_time_slots = 24
# Define the QUBO problem
qubo = QuadraticProgram()
# Add binary variables for charging (c) and discharging (d) states
for t in range(num_time_slots):
qubo.binary_var(f'c_{t}')
qubo.binary_var(f'd_{t}')
# Define the objective function
# (In practice, you need to calculate Jij and hi based on the solar farm data)
Jij = np.random.rand(num_time_slots, num_time_slots) * 0.5
hi_c = -1 + np.random.rand(num_time_slots)
hi_d = 1 - np.random.rand(num_time_slots)
# Set linear and quadratic terms of the objective function
linear_terms = {}
quadratic_terms = {}
for t in range(num_time_slots):
linear_terms[f'c_{t}'] = hi_c[t]
linear_terms[f'd_{t}'] = hi_d[t]
for s in range(num_time_slots):
if t != s:
quadratic_terms[(f'c_{t}', f'c_{s}')] = Jij[t, s]
quadratic_terms[(f'd_{t}', f'd_{s}')] = Jij[t, s]
qubo.minimize(linear=linear_terms, quadratic=quadratic_terms)
# Set up the quantum instance
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, seed_simulator=42, seed_transpiler=42, shots=10000)
# Set up the QAOA algorithm and optimizer
optimizer = COBYLA(maxiter=500)
qaoa = QAOA(optimizer=optimizer, reps=5, quantum_instance=quantum_instance)
# Set up the minimum eigen optimizer
min_eig_optimizer = MinimumEigenOptimizer(qaoa)
# Solve the problem
result = min_eig_optimizer.solve(qubo)
print("QAOA result:", result)
# Solve the problem using a classical solver (NumPyMinimumEigensolver)
exact_solver = MinimumEigenOptimizer(NumPyMinimumEigensolver())
exact_result = exact_solver.solve(qubo)
print("Classical result:", exact_result)
|
https://github.com/WhenTheyCry96/qiskitHackathon2022
|
WhenTheyCry96
|
import warnings
warnings.filterwarnings('ignore')
from qiskit_metal import designs, MetalGUI
design = designs.DesignPlanar()
design.overwrite_enabled = True
design.chips.main.size_x = '12mm'
design.chips.main.size_y = '10mm'
gui = MetalGUI(design)
from qiskit_metal.qlibrary.qubits.transmon_pocket_cl import TransmonPocketCL
design.delete_all_components()
design_span_x = 5
design_span_y = 3
half_chip_width = design_span_x / 2
half_chip_height = design_span_y / 2
connection_pads_options = dict(
a = dict(loc_W=1, loc_H=-1),
b = dict(loc_W=1, loc_H=1),
c = dict(loc_W=-1, loc_H=-1)
)
connection23_pads_options = dict(
a = dict(loc_W=1, loc_H=-1),
c = dict(loc_W=-1, loc_H=-1)
)
transmons = []
transmons.append(TransmonPocketCL(design, 'Q1',
options=dict(pos_x=f'-{half_chip_width}mm',
pos_y=f'{-half_chip_height}mm',
connection_pads=dict(**connection_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q2',
options=dict(pos_x=f'0mm',
pos_y=f'{half_chip_height}mm',
orientation=-90,
connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection23_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q3',
options=dict(pos_x=f'0mm',
pos_y=f'{-half_chip_height}mm',
orientation=90,
connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection23_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q4',
options=dict(pos_x=f'{half_chip_width}mm',
pos_y=f'{half_chip_height}mm',
orientation=180,
connection_pads=dict(**connection_pads_options))))
gui.rebuild()
gui.autoscale()
from qiskit_metal.qlibrary.tlines.meandered import RouteMeander
from qiskit_metal import Dict
fillet='99.99um'
options = Dict(
meander=Dict(
lead_start='0.1mm',
lead_end='0.1mm',
asymmetry='0 um')
)
def connect(component_name: str, component1: str, pin1: str, component2: str, pin2: str,
length: str,
asymmetry='0 um', start_strght='0 um', end_strght='0 um', flip=False):
"""Connect two pins with a CPW."""
myoptions = Dict(
pin_inputs=Dict(
start_pin=Dict(
component=component1,
pin=pin1),
end_pin=Dict(
component=component2,
pin=pin2)),
lead=Dict(
start_straight=start_strght,
end_straight=end_strght
),
total_length=length,
fillet = '99.9um')
myoptions.update(options)
myoptions.meander.asymmetry = asymmetry
myoptions.meander.lead_direction_inverted = 'true' if flip else 'false'
return RouteMeander(design, component_name, myoptions)
asym_h = 100
asym_v = 100
cpw = []
cpw.append(connect('cpw1', 'Q1', 'b', 'Q2', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw3', 'Q4', 'b', 'Q3', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw4', 'Q3', 'd', 'Q1', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw5', 'Q2', 'd', 'Q4', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm'))
gui.rebuild()
gui.autoscale()
from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled
readouts_lwc = []
control_lwc = []
offset_x = 0
offset_y = 1
#Readouts
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R1',
options = dict(
pos_x = '-5mm',
pos_y = f'-{half_chip_height+offset_y}mm',
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R2',
options = dict(
pos_x = '-1mm',
pos_y = '4mm',
orientation = -90,
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R3',
options = dict(
pos_x = '1mm',
pos_y = '-4mm',
orientation = 90,
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R4',
options = dict(
pos_x = '5mm',
pos_y = f'{half_chip_height+offset_y}mm',
orientation = 180,
lead_length = '30um')))
#Controls
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL1',
options = dict(
pos_x = '-5mm',
pos_y = '2mm',
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL2',
options = dict(
pos_x = '4mm',
pos_y = '4mm',
orientation = -90,
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL3',
options = dict(
pos_x = '-4mm',
pos_y = '-4mm',
orientation = 90,
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL4',
options = dict(
pos_x = '5mm',
pos_y = '-2mm',
orientation = 180,
lead_length = '30um')))
gui.rebuild()
gui.autoscale()
readout_lines = []
asym_14 = 700
asym_23 = 700
options = Dict(
lead=Dict(
start_straight='330um',
end_straight='0um'),
fillet='99.99um')
readout_lines.append(connect('ol1', 'Q1', 'c', 'R1', 'tie', '8 mm', f'{asym_14}um'))
options = Dict(
lead=Dict(
start_straight='430um',
end_straight='0um'),
fillet='99.99um')
readout_lines.append(connect('ol2', 'Q2', 'c', 'R2', 'tie', '8 mm', f'{asym_23}um'))
readout_lines.append(connect('ol3', 'Q3', 'c', 'R3', 'tie', '8 mm', f'{asym_23}um'))
readout_lines.append(connect('ol4', 'Q4', 'c', 'R4', 'tie', '8 mm', f'{asym_14}um'))
gui.rebuild()
gui.autoscale()
from qiskit_metal.qlibrary.tlines.anchored_path import RouteAnchors
from collections import OrderedDict
import numpy as np
control_lines = []
def connectRouteAnchor(name: str,
component1: str, pin1: str, component2: str, pin2: str,
anchor_points: OrderedDict) -> RouteAnchors:
options_line_cl = dict(
pin_inputs = dict(start_pin = dict(component = component1, pin = pin1),
end_pin = dict(component = component2, pin = pin2)),
anchors = anchor_points,
lead = dict(start_straight = '200um',
end_straight = '225um'),
fillet = fillet
)
return RouteAnchors(design, name, options_line_cl)
anchors1c = OrderedDict()
anchors1c[0] = np.array([-4, -1.42])
anchors1c[1] = np.array([-4, 2])
control_lines.append(connectRouteAnchor('line_cl1', 'Q1', 'Charge_Line', 'CL1', 'tie', anchors1c))
anchors2c = OrderedDict()
anchors2c[0] = np.array([0.08, 3.25])
anchors2c[1] = np.array([4, 3.25])
control_lines.append(connectRouteAnchor('line_cl2', 'Q2', 'Charge_Line', 'CL2', 'tie', anchors2c))
anchors3c = OrderedDict()
anchors3c[0] = np.array([-0.08, -3.25])
anchors3c[1] = np.array([-4, -3.25])
control_lines.append(connectRouteAnchor('line_cl3', 'Q3', 'Charge_Line', 'CL3', 'tie', anchors3c))
anchors4c = OrderedDict()
anchors4c[0] = np.array([4, 1.42])
anchors4c[1] = np.array([4, -2])
control_lines.append(connectRouteAnchor('line_cl4', 'Q4', 'Charge_Line', 'CL4', 'tie', anchors4c))
gui.rebuild()
gui.autoscale()
gui.autoscale()
gui.screenshot(name="full_design")
import numpy as np
from scipy.constants import c, h, pi, hbar, e
from qiskit_metal.analyses.em.cpw_calculations import guided_wavelength
# constants:
phi0 = h/(2*e)
varphi0 = phi0/(2*pi)
# project target parameters
f_qList = np.around(np.linspace(5.25, 5.75, 4),2) # GHz
f_rList = f_qList + 1.8 # GHz
L_JJList = np.around(varphi0**2/((f_qList*1e9+300e6)**2/(8*300e6))/h*1e9, 2) # nH
# initial CPW readout lengths
def find_resonator_length(frequency, line_width, line_gap, N):
#frequency in GHz
#line_width/line_gap in um
#N -> 2 for lambda/2, 4 for lambda/4
[lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6,
line_gap*10**-6, 750*10**-6, 200*10**-9)
return str(lambdaG/N*10**3)+" mm"
find_resonator_length(f_rList, 10, 6, 2)
find_resonator_length(np.around(np.linspace(8, 9.2, 4), 2), 10, 6, 2)
transmons[0].options.pad_gap = '40um'
transmons[0].options.pad_width = '550um' # 405
transmons[0].options.pad_height = '120um'
transmons[1].options.pad_gap = '40um'
transmons[1].options.pad_width = '500um' # 405
transmons[1].options.pad_height = '120um'
transmons[2].options.pad_gap = '40um'
transmons[2].options.pad_width = '460um' # 405
transmons[2].options.pad_height = '120um'
transmons[3].options.pad_gap = '40um'
transmons[3].options.pad_width = '440um' # 405
transmons[3].options.pad_height = '120um'
readout_lines[0].options.total_length = '8.63mm'
readout_lines[1].options.total_length = '8.42mm'
readout_lines[2].options.total_length = '8.24mm'
readout_lines[3].options.total_length = '8.06mm'
cpw[0].options.total_length = '7.6mm'
cpw[1].options.total_length = '7.2mm'
cpw[2].options.total_length = '6.9mm'
cpw[3].options.total_length = '6.6mm'
gui.rebuild()
gui.autoscale()
qcomps = design.components # short handle (alias)
qcomps['Q1'].options['hfss_inductance'] = 'Lj1'
qcomps['Q1'].options['hfss_capacitance'] = 'Cj1'
qcomps['Q2'].options['hfss_inductance'] = 'Lj2'
qcomps['Q2'].options['hfss_capacitance'] = 'Cj2'
qcomps['Q3'].options['hfss_inductance'] = 'Lj3'
qcomps['Q3'].options['hfss_capacitance'] = 'Cj3'
qcomps['Q4'].options['hfss_inductance'] = 'Lj4'
qcomps['Q4'].options['hfss_capacitance'] = 'Cj4'
from qiskit_metal.analyses.quantization import EPRanalysis, LOManalysis
c1 = LOManalysis(design, "q3d")
q3d1 = c1.sim.renderer
q3d1.start()
q3d1.activate_ansys_design("full_circuit", 'capacitive')
q3d1.render_design([], [])
q3d1.add_q3d_setup(name="Setup", max_passes=15, min_converged_passes=5,percent_error=0.05)
q3d1.analyze_setup("Setup")
c1.sim.capacitance_matrix, c1.sim.units = q3d1.get_capacitance_matrix()
c1.sim.capacitance_all_passes, _ = q3d1.get_capacitance_all_passes()
c1.sim.capacitance_matrix
Out[17].to_csv("full_original_design_C.txt")
c1 = LOManalysis(design, "q3d")
q3d1 = c1.sim.renderer
q3d1.start()
q3d1.activate_ansys_design("Q1only_busopen", 'capacitive')
q3d1.render_design(['Q1', 'R1', 'cpw1', 'cpw4', 'ol1', 'line_cl1', 'CL1'], [('cpw1', 'end'),('cpw4', 'start')])
q3d1.add_q3d_setup(name="Setup", max_passes=15, min_converged_passes=5,percent_error=0.05)
q3d1.analyze_setup("Setup")
c1.sim.capacitance_matrix, c1.sim.units = q3d1.get_capacitance_matrix()
c1.sim.capacitance_all_passes, _ = q3d1.get_capacitance_all_passes()
c1.sim.capacitance_matrix
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
from math import cos, pi, acos
print("cosine of 90 degrees is zero:",cos(pi/2))
# find the degree of two unit vectors having the dot product of 0.
radian_degree = acos(0)
degree = 360*radian_degree/(2*pi)
print("the degree of two unit vectors having the dot product of 0 is",degree,"degrees")
# include our predefined functions
%run qlatvia.py
# draw the axes
draw_qubit()
#
# your solution is here
#
draw_quantum_state(3/5,4/5,"main")
draw_quantum_state(-4/5,3/5,"ort1")
draw_quantum_state(4/5,-3/5,"ort2")
draw_qubit()
draw_quantum_state(3/5,-4/5,"main")
draw_quantum_state(4/5,3/5,"ort1")
# randomly create a 2-dimensional quantum state
from math import cos, sin, pi
from random import randrange
def random_quantum_state2():
angle_degree = randrange(360)
angle_radian = 2*pi*angle_degree/360
return [cos(angle_radian),sin(angle_radian)]
# finding the angle of a 2-dimensional quantum state
from math import acos, pi
def angle_quantum_state(x,y):
angle_radian = acos(x) # radian of the angle with state |0>
angle_degree = 360*angle_radian/(2*pi) # degree of the angle with state |0>
# if the second amplitude is negative,
# then angle is (-angle_degree)
# or equivalently 360 + (-angle_degree)
if y<0: angle_degree = 360-angle_degree # degree of the angle
# else degree of the angle is the same as degree of the angle with state |0>
return angle_degree
%run qlatvia.py
draw_qubit()
from math import acos, pi
[x1,y1]=random_quantum_state() # randomly pick a quantum state
first_angle = angle_quantum_state(x1,y1)
print("the angle of |u> is",first_angle)
[x2,y2]=random_quantum_state() # randomly pick a quantum state
second_angle = angle_quantum_state(x2,y2)
print("the angle of |c> is",second_angle)
angle_between_1 = first_angle - second_angle
if angle_between_1 < 0: angle_between_1 *= -1
if angle_between_1 >180: angle_between_1 = 360 - angle_between_1
dot_product = x1*x2+y1*y2
print("their dot prouct is",dot_product)
angle_between_radian = acos(dot_product)
angle_between_2 = 360 * angle_between_radian/(2*pi)
print("the angle in between is calculated as",angle_between_1,"and",angle_between_2)
draw_quantum_state(x1,y1,"|u>")
draw_quantum_state(x2,y2,"|v>")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can set a color for all the bars.
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
from qiskit import compiler, BasicAer, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Unroller
def convert_to_basis_gates(circuit):
# unroll the circuit using the basis u1, u2, u3, cx, and id gates
unroller = Unroller(basis=['u1', 'u2', 'u3', 'cx', 'id'])
pm = PassManager(passes=[unroller])
qc = compiler.transpile(circuit, BasicAer.get_backend('qasm_simulator'), pass_manager=pm)
return qc
def is_qubit(qb):
# check if the input is a qubit, which is in the form (QuantumRegister, int)
return isinstance(qb, tuple) and isinstance(qb[0], QuantumRegister) and isinstance(qb[1], int)
def is_qubit_list(qbs):
# check if the input is a list of qubits
for qb in qbs:
if not is_qubit(qb):
return False
return True
def summarize_circuits(circuits):
"""Summarize circuits based on QuantumCircuit, and four metrics are summarized.
Number of qubits and classical bits, and number of operations and depth of circuits.
The average statistic is provided if multiple circuits are inputed.
Args:
circuits (QuantumCircuit or [QuantumCircuit]): the to-be-summarized circuits
"""
if not isinstance(circuits, list):
circuits = [circuits]
ret = ""
ret += "Submitting {} circuits.\n".format(len(circuits))
ret += "============================================================================\n"
stats = np.zeros(4)
for i, circuit in enumerate(circuits):
dag = circuit_to_dag(circuit)
depth = dag.depth()
width = dag.width()
size = dag.size()
classical_bits = dag.num_cbits()
op_counts = dag.count_ops()
stats[0] += width
stats[1] += classical_bits
stats[2] += size
stats[3] += depth
ret = ''.join([ret, "{}-th circuit: {} qubits, {} classical bits and {} operations with depth {}\n op_counts: {}\n".format(
i, width, classical_bits, size, depth, op_counts)])
if len(circuits) > 1:
stats /= len(circuits)
ret = ''.join([ret, "Average: {:.2f} qubits, {:.2f} classical bits and {:.2f} operations with depth {:.2f}\n".format(
stats[0], stats[1], stats[2], stats[3])])
ret += "============================================================================\n"
return ret
|
https://github.com/Fergus-Hayes/qiskit_tools
|
Fergus-Hayes
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ
from qiskit.circuit.library import ExactReciprocal
from qiskit.extensions import HamiltonianGate
from qiskit.quantum_info import random_hermitian
import qiskit_tools as qt
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['mathtext.fontset'] = 'stix'
matplotlib.rcParams['font.family'] = 'STIXGeneral'
width=0.75
color='black'
fontsize=28
ticksize=22
figsize=(10,8)
def HHL(circ, qb, qanc, qtarg, A, t=2.*np.pi, scaling=None, wrap=False, inverse=False, phase=True, label='HHL'):
n = len(qb)
nanc = len(qanc)
if inverse:
wrap = True
if wrap:
qb = QuantumRegister(n, 'b')
qanc = QuantumRegister(nanc, 'anc')
qtarg = QuantumRegister(1, 'targ')
circ = QuantumCircuit(qb, qanc, qtarg)
# Define unitary operator given matrix A and evolution time t
A_gate = HamiltonianGate(A, t)
# Apply phase estimation
qe_gate = qt.PhaseEst(circ, qb, qanc, A_gate, wrap=True, do_swaps=False, reverse_bits=True)
circ.append(qe_gate, [*qb, *qanc]);
# Apply ExactReciprocal to rotate the target qubit proportionally to the given scaling and the inverse of the
# values stored in the computational basis of the ancillary register
rec_gate = ExactReciprocal(nanc, scaling=scaling, neg_vals=phase).to_gate()
circ.append(rec_gate, [*qanc[::-1], qtarg]);
# Apply the inverse phase estimation
qe_gate_inv = qt.PhaseEst(circ, qb, qanc, A_gate, wrap=True, inverse=True, do_swaps=False, reverse_bits=True)
circ.append(qe_gate_inv, [*qb, *qanc]);
if wrap:
circ = circ.to_gate()
circ.label = label
if inverse:
circ = circ.inverse()
circ.label = label+'\dag'
return circ
n = 2
A = random_hermitian(2**n).to_matrix()
print(A)
lambda_min = np.min(np.abs(np.linalg.eigvals(A)))
lambda_max = np.max(np.abs(np.linalg.eigvals(A)))
kappa = np.abs(lambda_max/lambda_min)
print('Minimum eigenvalue, maximum eigenvalue and conditional number of A:', lambda_min, lambda_max, kappa)
phase = True
# Choose a success probability of determining eigenvalue estimation
p_suc = 0.99
# Determine the number of ancillary qubits to ensure the given success probability
nanc = n + int(np.ceil(np.log2(2. + 1./(2.*(1-p_suc)))))
# Calculate the new scale of the relative magnitudes of maximum and minimum eigenvalues
rescale = int((2**(nanc-phase)-1)/kappa)
# Make sure this scaling is not vanishingly small
if rescale < 1.e-7:
rescale = 1
# determine the number of integer qubits required
nint = qt.get_nint(rescale)
# Assert that the number of integer qubits is equal to or greater than the number of ancillary qubits assigned
if nint < nanc - phase:
nint = nanc - phase
# We can determine the scaling of the rotation of step 3 (variable c)
scaling = qt.bin_to_dec(qt.my_binary_repr(rescale, nint=nint, n=nint, phase=False), nint=0, phase=False)
t0 = scaling / (lambda_min * (2**phase))
t = 2 * np.pi * t0
qb = QuantumRegister(n, 'b')
circ = QuantumCircuit(qb)
circ.h(qb);
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
result = job.result()
in_vector = np.asarray(result.get_statevector())
print('The state amplitudes of b are:',in_vector)
targ = np.matmul(np.linalg.inv(A),in_vector)
print('The target state amplitudes of x are:',targ)
qanc = QuantumRegister(nanc, 'anc')
qtarg = QuantumRegister(1, 'targ')
circ.add_register(qanc, qtarg)
circ = HHL(circ, qb, qanc, qtarg, A, t=t, scaling=scaling)
circ.draw('latex')
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
result = job.result()
state_vector = np.asarray(result.get_statevector())
state_v = np.asarray(state_vector).reshape((2**1,2**nanc,2**n))
# 1, nanc, n
print(state_v.shape)
norm_ = np.sqrt(np.sum(np.abs(state_v[1])**2))
print('The target qubit is in the 1 state with probability:',norm_)
state_v = state_v[1,0]
print(state_v)
state_v = np.array(state_v/np.sqrt(np.sum(np.abs(state_v)**2)))
norm = norm_/lambda_min
out = state_v*norm
print('The amplitudes of the resulting states are:', out)
print('Ratio of real part of output to target:',out.real/targ.real)
print('Ratio of imaginary part of output to target:',out.imag/targ.imag)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# 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.
"""
Clifford operator class.
"""
from __future__ import annotations
import functools
import itertools
import re
from typing import Literal
import numpy as np
from qiskit.circuit import Instruction, QuantumCircuit
from qiskit.circuit.library.standard_gates import HGate, IGate, SGate, XGate, YGate, ZGate
from qiskit.circuit.operation import Operation
from qiskit.exceptions import QiskitError
from qiskit.quantum_info.operators.base_operator import BaseOperator
from qiskit.quantum_info.operators.mixins import AdjointMixin, generate_apidocs
from qiskit.quantum_info.operators.operator import Operator
from qiskit.quantum_info.operators.scalar_op import ScalarOp
from qiskit.quantum_info.operators.symplectic.base_pauli import _count_y
from qiskit.utils.deprecation import deprecate_func
from qiskit.synthesis.linear import calc_inverse_matrix
from .base_pauli import BasePauli
from .clifford_circuits import _append_circuit, _append_operation
from .stabilizer_table import StabilizerTable
class Clifford(BaseOperator, AdjointMixin, Operation):
"""An N-qubit unitary operator from the Clifford group.
**Representation**
An *N*-qubit Clifford operator is stored as a length *2N × (2N+1)*
boolean tableau using the convention from reference [1].
* Rows 0 to *N-1* are the *destabilizer* group generators
* Rows *N* to *2N-1* are the *stabilizer* group generators.
The internal boolean tableau for the Clifford
can be accessed using the :attr:`tableau` attribute. The destabilizer or
stabilizer rows can each be accessed as a length-N Stabilizer table using
:attr:`destab` and :attr:`stab` attributes.
A more easily human readable representation of the Clifford operator can
be obtained by calling the :meth:`to_dict` method. This representation is
also used if a Clifford object is printed as in the following example
.. code-block::
from qiskit import QuantumCircuit
from qiskit.quantum_info import Clifford
# Bell state generation circuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
cliff = Clifford(qc)
# Print the Clifford
print(cliff)
# Print the Clifford destabilizer rows
print(cliff.to_labels(mode="D"))
# Print the Clifford stabilizer rows
print(cliff.to_labels(mode="S"))
.. parsed-literal::
Clifford: Stabilizer = ['+XX', '+ZZ'], Destabilizer = ['+IZ', '+XI']
['+IZ', '+XI']
['+XX', '+ZZ']
**Circuit Conversion**
Clifford operators can be initialized from circuits containing *only* the
following Clifford gates: :class:`~qiskit.circuit.library.IGate`,
:class:`~qiskit.circuit.library.XGate`, :class:`~qiskit.circuit.library.YGate`,
:class:`~qiskit.circuit.library.ZGate`, :class:`~qiskit.circuit.library.HGate`,
:class:`~qiskit.circuit.library.SGate`, :class:`~qiskit.circuit.library.SdgGate`,
:class:`~qiskit.circuit.library.SXGate`, :class:`~qiskit.circuit.library.SXdgGate`,
:class:`~qiskit.circuit.library.CXGate`, :class:`~qiskit.circuit.library.CZGate`,
:class:`~qiskit.circuit.library.CYGate`, :class:`~qiskit.circuit.library.DXGate`,
:class:`~qiskit.circuit.library.SwapGate`, :class:`~qiskit.circuit.library.iSwapGate`,
:class:`~qiskit.circuit.library.ECRGate`, :class:`~qiskit.circuit.library.LinearFunction`,
:class:`~qiskit.circuit.library.PermutationGate`.
They can be converted back into a :class:`~qiskit.circuit.QuantumCircuit`,
or :class:`~qiskit.circuit.Gate` object using the :meth:`~Clifford.to_circuit`
or :meth:`~Clifford.to_instruction` methods respectively. Note that this
decomposition is not necessarily optimal in terms of number of gates.
.. note::
A minimally generating set of gates for Clifford circuits is
the :class:`~qiskit.circuit.library.HGate` and
:class:`~qiskit.circuit.library.SGate` gate and *either* the
:class:`~qiskit.circuit.library.CXGate` or
:class:`~qiskit.circuit.library.CZGate` two-qubit gate.
Clifford operators can also be converted to
:class:`~qiskit.quantum_info.Operator` objects using the
:meth:`to_operator` method. This is done via decomposing to a circuit, and then
simulating the circuit as a unitary operator.
References:
1. S. Aaronson, D. Gottesman, *Improved Simulation of Stabilizer Circuits*,
Phys. Rev. A 70, 052328 (2004).
`arXiv:quant-ph/0406196 <https://arxiv.org/abs/quant-ph/0406196>`_
"""
_COMPOSE_PHASE_LOOKUP = None
_COMPOSE_1Q_LOOKUP = None
def __array__(self, dtype=None):
if dtype:
return np.asarray(self.to_matrix(), dtype=dtype)
return self.to_matrix()
def __init__(self, data, validate=True, copy=True):
"""Initialize an operator object."""
# pylint: disable=cyclic-import
from qiskit.circuit.library import LinearFunction, PermutationGate
# Initialize from another Clifford
if isinstance(data, Clifford):
num_qubits = data.num_qubits
self.tableau = data.tableau.copy() if copy else data.tableau
# Initialize from ScalarOp as N-qubit identity discarding any global phase
elif isinstance(data, ScalarOp):
if not data.num_qubits or not data.is_unitary():
raise QiskitError("Can only initialize from N-qubit identity ScalarOp.")
num_qubits = data.num_qubits
self.tableau = np.fromfunction(
lambda i, j: i == j, (2 * num_qubits, 2 * num_qubits + 1)
).astype(bool)
# Initialize from LinearFunction
elif isinstance(data, LinearFunction):
num_qubits = len(data.linear)
self.tableau = self.from_linear_function(data)
# Initialize from PermutationGate
elif isinstance(data, PermutationGate):
num_qubits = len(data.pattern)
self.tableau = self.from_permutation(data)
# Initialize from a QuantumCircuit or Instruction object
elif isinstance(data, (QuantumCircuit, Instruction)):
num_qubits = data.num_qubits
self.tableau = Clifford.from_circuit(data).tableau
# DEPRECATED: data is StabilizerTable
elif isinstance(data, StabilizerTable):
self.tableau = self._stack_table_phase(data.array, data.phase)
num_qubits = data.num_qubits
# Initialize StabilizerTable directly from the data
else:
if isinstance(data, (list, np.ndarray)) and np.asarray(data, dtype=bool).ndim == 2:
data = np.array(data, dtype=bool, copy=copy)
if data.shape[0] == data.shape[1]:
self.tableau = self._stack_table_phase(
data, np.zeros(data.shape[0], dtype=bool)
)
num_qubits = data.shape[0] // 2
elif data.shape[0] + 1 == data.shape[1]:
self.tableau = data
num_qubits = data.shape[0] // 2
else:
raise QiskitError("")
else:
n_paulis = len(data)
symp = self._from_label(data[0])
num_qubits = len(symp) // 2
tableau = np.zeros((n_paulis, len(symp)), dtype=bool)
tableau[0] = symp
for i in range(1, n_paulis):
tableau[i] = self._from_label(data[i])
self.tableau = tableau
# Validate table is a symplectic matrix
if validate and not Clifford._is_symplectic(self.symplectic_matrix):
raise QiskitError(
"Invalid Clifford. Input StabilizerTable is not a valid symplectic matrix."
)
# Initialize BaseOperator
super().__init__(num_qubits=num_qubits)
@property
def name(self):
"""Unique string identifier for operation type."""
return "clifford"
@property
def num_clbits(self):
"""Number of classical bits."""
return 0
def __repr__(self):
return f"Clifford({repr(self.tableau)})"
def __str__(self):
return (
f'Clifford: Stabilizer = {self.to_labels(mode="S")}, '
f'Destabilizer = {self.to_labels(mode="D")}'
)
def __eq__(self, other):
"""Check if two Clifford tables are equal"""
return super().__eq__(other) and (self.tableau == other.tableau).all()
def copy(self):
return type(self)(self, validate=False, copy=True)
# ---------------------------------------------------------------------
# Attributes
# ---------------------------------------------------------------------
# pylint: disable=bad-docstring-quotes
@deprecate_func(
since="0.24.0",
additional_msg="Instead, index or iterate through the Clifford.tableau attribute.",
)
def __getitem__(self, key):
"""Return a stabilizer Pauli row"""
return self.table.__getitem__(key)
@deprecate_func(since="0.24.0", additional_msg="Use Clifford.tableau property instead.")
def __setitem__(self, key, value):
"""Set a stabilizer Pauli row"""
self.tableau.__setitem__(key, self._stack_table_phase(value.array, value.phase))
@property
@deprecate_func(
since="0.24.0",
additional_msg="Use Clifford.stab and Clifford.destab properties instead.",
is_property=True,
)
def table(self):
"""Return StabilizerTable"""
return StabilizerTable(self.symplectic_matrix, phase=self.phase)
@table.setter
@deprecate_func(
since="0.24.0",
additional_msg="Use Clifford.stab and Clifford.destab properties instead.",
is_property=True,
)
def table(self, value):
"""Set the stabilizer table"""
# Note this setter cannot change the size of the Clifford
# It can only replace the contents of the StabilizerTable with
# another StabilizerTable of the same size.
if not isinstance(value, StabilizerTable):
value = StabilizerTable(value)
self.symplectic_matrix = value._table._array
self.phase = value._table._phase
@property
@deprecate_func(
since="0.24.0",
additional_msg="Use Clifford.stab properties instead.",
is_property=True,
)
def stabilizer(self):
"""Return the stabilizer block of the StabilizerTable."""
array = self.tableau[self.num_qubits : 2 * self.num_qubits, :-1]
phase = self.tableau[self.num_qubits : 2 * self.num_qubits, -1].reshape(self.num_qubits)
return StabilizerTable(array, phase)
@stabilizer.setter
@deprecate_func(
since="0.24.0",
additional_msg="Use Clifford.stab properties instead.",
is_property=True,
)
def stabilizer(self, value):
"""Set the value of stabilizer block of the StabilizerTable"""
if not isinstance(value, StabilizerTable):
value = StabilizerTable(value)
self.tableau[self.num_qubits : 2 * self.num_qubits, :-1] = value.array
@property
@deprecate_func(
since="0.24.0",
additional_msg="Use Clifford.destab properties instead.",
is_property=True,
)
def destabilizer(self):
"""Return the destabilizer block of the StabilizerTable."""
array = self.tableau[0 : self.num_qubits, :-1]
phase = self.tableau[0 : self.num_qubits, -1].reshape(self.num_qubits)
return StabilizerTable(array, phase)
@destabilizer.setter
@deprecate_func(
since="0.24.0",
additional_msg="Use Clifford.destab properties instead.",
is_property=True,
)
def destabilizer(self, value):
"""Set the value of destabilizer block of the StabilizerTable"""
if not isinstance(value, StabilizerTable):
value = StabilizerTable(value)
self.tableau[: self.num_qubits, :-1] = value.array
@property
def symplectic_matrix(self):
"""Return boolean symplectic matrix."""
return self.tableau[:, :-1]
@symplectic_matrix.setter
def symplectic_matrix(self, value):
self.tableau[:, :-1] = value
@property
def phase(self):
"""Return phase with boolean representation."""
return self.tableau[:, -1]
@phase.setter
def phase(self, value):
self.tableau[:, -1] = value
@property
def x(self):
"""The x array for the symplectic representation."""
return self.tableau[:, 0 : self.num_qubits]
@x.setter
def x(self, value):
self.tableau[:, 0 : self.num_qubits] = value
@property
def z(self):
"""The z array for the symplectic representation."""
return self.tableau[:, self.num_qubits : 2 * self.num_qubits]
@z.setter
def z(self, value):
self.tableau[:, self.num_qubits : 2 * self.num_qubits] = value
@property
def destab(self):
"""The destabilizer array for the symplectic representation."""
return self.tableau[: self.num_qubits, :]
@destab.setter
def destab(self, value):
self.tableau[: self.num_qubits, :] = value
@property
def destab_x(self):
"""The destabilizer x array for the symplectic representation."""
return self.tableau[: self.num_qubits, : self.num_qubits]
@destab_x.setter
def destab_x(self, value):
self.tableau[: self.num_qubits, : self.num_qubits] = value
@property
def destab_z(self):
"""The destabilizer z array for the symplectic representation."""
return self.tableau[: self.num_qubits, self.num_qubits : 2 * self.num_qubits]
@destab_z.setter
def destab_z(self, value):
self.tableau[: self.num_qubits, self.num_qubits : 2 * self.num_qubits] = value
@property
def destab_phase(self):
"""Return phase of destabilizer with boolean representation."""
return self.tableau[: self.num_qubits, -1]
@destab_phase.setter
def destab_phase(self, value):
self.tableau[: self.num_qubits, -1] = value
@property
def stab(self):
"""The stabilizer array for the symplectic representation."""
return self.tableau[self.num_qubits :, :]
@stab.setter
def stab(self, value):
self.tableau[self.num_qubits :, :] = value
@property
def stab_x(self):
"""The stabilizer x array for the symplectic representation."""
return self.tableau[self.num_qubits :, : self.num_qubits]
@stab_x.setter
def stab_x(self, value):
self.tableau[self.num_qubits :, : self.num_qubits] = value
@property
def stab_z(self):
"""The stabilizer array for the symplectic representation."""
return self.tableau[self.num_qubits :, self.num_qubits : 2 * self.num_qubits]
@stab_z.setter
def stab_z(self, value):
self.tableau[self.num_qubits :, self.num_qubits : 2 * self.num_qubits] = value
@property
def stab_phase(self):
"""Return phase of stabilizer with boolean representation."""
return self.tableau[self.num_qubits :, -1]
@stab_phase.setter
def stab_phase(self, value):
self.tableau[self.num_qubits :, -1] = value
# ---------------------------------------------------------------------
# Utility Operator methods
# ---------------------------------------------------------------------
def is_unitary(self):
"""Return True if the Clifford table is valid."""
# A valid Clifford is always unitary, so this function is really
# checking that the underlying Stabilizer table array is a valid
# Clifford array.
return Clifford._is_symplectic(self.symplectic_matrix)
# ---------------------------------------------------------------------
# BaseOperator Abstract Methods
# ---------------------------------------------------------------------
def conjugate(self):
return Clifford._conjugate_transpose(self, "C")
def adjoint(self):
return Clifford._conjugate_transpose(self, "A")
def transpose(self):
return Clifford._conjugate_transpose(self, "T")
def tensor(self, other: Clifford) -> Clifford:
if not isinstance(other, Clifford):
other = Clifford(other)
return self._tensor(self, other)
def expand(self, other: Clifford) -> Clifford:
if not isinstance(other, Clifford):
other = Clifford(other)
return self._tensor(other, self)
@classmethod
def _tensor(cls, a, b):
n = a.num_qubits + b.num_qubits
tableau = np.zeros((2 * n, 2 * n + 1), dtype=bool)
clifford = cls(tableau, validate=False)
clifford.destab_x[: b.num_qubits, : b.num_qubits] = b.destab_x
clifford.destab_x[b.num_qubits :, b.num_qubits :] = a.destab_x
clifford.destab_z[: b.num_qubits, : b.num_qubits] = b.destab_z
clifford.destab_z[b.num_qubits :, b.num_qubits :] = a.destab_z
clifford.stab_x[: b.num_qubits, : b.num_qubits] = b.stab_x
clifford.stab_x[b.num_qubits :, b.num_qubits :] = a.stab_x
clifford.stab_z[: b.num_qubits, : b.num_qubits] = b.stab_z
clifford.stab_z[b.num_qubits :, b.num_qubits :] = a.stab_z
clifford.phase[: b.num_qubits] = b.destab_phase
clifford.phase[b.num_qubits : n] = a.destab_phase
clifford.phase[n : n + b.num_qubits] = b.stab_phase
clifford.phase[n + b.num_qubits :] = a.stab_phase
return clifford
def compose(
self,
other: Clifford | QuantumCircuit | Instruction,
qargs: list | None = None,
front: bool = False,
) -> Clifford:
if qargs is None:
qargs = getattr(other, "qargs", None)
# If other is a QuantumCircuit we can more efficiently compose
# using the _append_circuit method to update each gate recursively
# to the current Clifford, rather than converting to a Clifford first
# and then doing the composition of tables.
if not front:
if isinstance(other, QuantumCircuit):
return _append_circuit(self.copy(), other, qargs=qargs)
if isinstance(other, Instruction):
return _append_operation(self.copy(), other, qargs=qargs)
if not isinstance(other, Clifford):
# Not copying is safe since we're going to drop our only reference to `other` at the end
# of the function.
other = Clifford(other, copy=False)
# Validate compose dimensions
self._op_shape.compose(other._op_shape, qargs, front)
# Pad other with identities if composing on subsystem
other = self._pad_with_identity(other, qargs)
left, right = (self, other) if front else (other, self)
if self.num_qubits == 1:
return self._compose_1q(left, right)
return self._compose_general(left, right)
@classmethod
def _compose_general(cls, first, second):
# Correcting for phase due to Pauli multiplication. Start with factors of -i from XZ = -iY
# on individual qubits, and then handle multiplication between each qubitwise pair.
ifacts = np.sum(second.x & second.z, axis=1, dtype=int)
x1, z1 = first.x.astype(np.uint8), first.z.astype(np.uint8)
lookup = cls._compose_lookup()
# The loop is over 2*n_qubits entries, and the entire loop is cubic in the number of qubits.
for k, row2 in enumerate(second.symplectic_matrix):
x1_select = x1[row2]
z1_select = z1[row2]
x1_accum = np.logical_xor.accumulate(x1_select, axis=0).astype(np.uint8)
z1_accum = np.logical_xor.accumulate(z1_select, axis=0).astype(np.uint8)
indexer = (x1_select[1:], z1_select[1:], x1_accum[:-1], z1_accum[:-1])
ifacts[k] += np.sum(lookup[indexer])
p = np.mod(ifacts, 4) // 2
phase = (
(np.matmul(second.symplectic_matrix, first.phase, dtype=int) + second.phase + p) % 2
).astype(bool)
data = cls._stack_table_phase(
(np.matmul(second.symplectic_matrix, first.symplectic_matrix, dtype=int) % 2).astype(
bool
),
phase,
)
return Clifford(data, validate=False, copy=False)
@classmethod
def _compose_1q(cls, first, second):
# 1-qubit composition can be done with a simple lookup table; there are 24 elements in the
# 1q Clifford group, so 576 possible combinations, which is small enough to look up.
if cls._COMPOSE_1Q_LOOKUP is None:
# The valid tables for 1q Cliffords.
tables_1q = np.array(
[
[[False, True], [True, False]],
[[False, True], [True, True]],
[[True, False], [False, True]],
[[True, False], [True, True]],
[[True, True], [False, True]],
[[True, True], [True, False]],
]
)
phases_1q = np.array([[False, False], [False, True], [True, False], [True, True]])
# Build the lookup table.
cliffords = [
cls(cls._stack_table_phase(table, phase), validate=False, copy=False)
for table, phase in itertools.product(tables_1q, phases_1q)
]
cls._COMPOSE_1Q_LOOKUP = {
(cls._hash(left), cls._hash(right)): cls._compose_general(left, right)
for left, right in itertools.product(cliffords, repeat=2)
}
return cls._COMPOSE_1Q_LOOKUP[cls._hash(first), cls._hash(second)].copy()
@classmethod
def _compose_lookup(
cls,
):
if cls._COMPOSE_PHASE_LOOKUP is None:
# A lookup table for calculating phases. The indices are
# current_x, current_z, running_x_count, running_z_count
# where all counts taken modulo 2.
lookup = np.zeros((2, 2, 2, 2), dtype=int)
lookup[0, 1, 1, 0] = lookup[1, 0, 1, 1] = lookup[1, 1, 0, 1] = -1
lookup[0, 1, 1, 1] = lookup[1, 0, 0, 1] = lookup[1, 1, 1, 0] = 1
lookup.setflags(write=False)
cls._COMPOSE_PHASE_LOOKUP = lookup
return cls._COMPOSE_PHASE_LOOKUP
# ---------------------------------------------------------------------
# Representation conversions
# ---------------------------------------------------------------------
def to_dict(self):
"""Return dictionary representation of Clifford object."""
return {
"stabilizer": self.to_labels(mode="S"),
"destabilizer": self.to_labels(mode="D"),
}
@classmethod
def from_dict(cls, obj):
"""Load a Clifford from a dictionary"""
labels = obj.get("destabilizer") + obj.get("stabilizer")
n_paulis = len(labels)
symp = cls._from_label(labels[0])
tableau = np.zeros((n_paulis, len(symp)), dtype=bool)
tableau[0] = symp
for i in range(1, n_paulis):
tableau[i] = cls._from_label(labels[i])
return cls(tableau)
def to_matrix(self):
"""Convert operator to Numpy matrix."""
return self.to_operator().data
@classmethod
def from_matrix(cls, matrix: np.ndarray) -> Clifford:
"""Create a Clifford from a unitary matrix.
Note that this function takes exponentially long time w.r.t. the number of qubits.
Args:
matrix (np.array): A unitary matrix representing a Clifford to be converted.
Returns:
Clifford: the Clifford object for the unitary matrix.
Raises:
QiskitError: if the input is not a Clifford matrix.
"""
tableau = cls._unitary_matrix_to_tableau(matrix)
if tableau is None:
raise QiskitError("Non-Clifford matrix is not convertible")
return cls(tableau)
@classmethod
def from_linear_function(cls, linear_function):
"""Create a Clifford from a Linear Function.
If the linear function is represented by a nxn binary invertible matrix A,
then the corresponding Clifford has symplectic matrix [[A^t, 0], [0, A^{-1}]].
Args:
linear_function (LinearFunction): A linear function to be converted.
Returns:
Clifford: the Clifford object for this linear function.
"""
mat = linear_function.linear
mat_t = np.transpose(mat)
mat_i = calc_inverse_matrix(mat)
dim = len(mat)
zero = np.zeros((dim, dim), dtype=int)
symplectic_mat = np.block([[mat_t, zero], [zero, mat_i]])
phase = np.zeros(2 * dim, dtype=int)
tableau = cls._stack_table_phase(symplectic_mat, phase)
return tableau
@classmethod
def from_permutation(cls, permutation_gate):
"""Create a Clifford from a PermutationGate.
Args:
permutation_gate (PermutationGate): A permutation to be converted.
Returns:
Clifford: the Clifford object for this permutation.
"""
pat = permutation_gate.pattern
dim = len(pat)
symplectic_mat = np.zeros((2 * dim, 2 * dim), dtype=int)
for i, j in enumerate(pat):
symplectic_mat[j, i] = True
symplectic_mat[j + dim, i + dim] = True
phase = np.zeros(2 * dim, dtype=bool)
tableau = cls._stack_table_phase(symplectic_mat, phase)
return tableau
def to_operator(self) -> Operator:
"""Convert to an Operator object."""
return Operator(self.to_instruction())
@classmethod
def from_operator(cls, operator: Operator) -> Clifford:
"""Create a Clifford from a operator.
Note that this function takes exponentially long time w.r.t. the number of qubits.
Args:
operator (Operator): An operator representing a Clifford to be converted.
Returns:
Clifford: the Clifford object for the operator.
Raises:
QiskitError: if the input is not a Clifford operator.
"""
tableau = cls._unitary_matrix_to_tableau(operator.to_matrix())
if tableau is None:
raise QiskitError("Non-Clifford operator is not convertible")
return cls(tableau)
def to_circuit(self):
"""Return a QuantumCircuit implementing the Clifford.
For N <= 3 qubits this is based on optimal CX cost decomposition
from reference [1]. For N > 3 qubits this is done using the general
non-optimal compilation routine from reference [2].
Return:
QuantumCircuit: a circuit implementation of the Clifford.
References:
1. S. Bravyi, D. Maslov, *Hadamard-free circuits expose the
structure of the Clifford group*,
`arXiv:2003.09412 [quant-ph] <https://arxiv.org/abs/2003.09412>`_
2. S. Aaronson, D. Gottesman, *Improved Simulation of Stabilizer Circuits*,
Phys. Rev. A 70, 052328 (2004).
`arXiv:quant-ph/0406196 <https://arxiv.org/abs/quant-ph/0406196>`_
"""
from qiskit.synthesis.clifford import synth_clifford_full
return synth_clifford_full(self)
def to_instruction(self):
"""Return a Gate instruction implementing the Clifford."""
return self.to_circuit().to_gate()
@staticmethod
def from_circuit(circuit: QuantumCircuit | Instruction) -> Clifford:
"""Initialize from a QuantumCircuit or Instruction.
Args:
circuit (QuantumCircuit or ~qiskit.circuit.Instruction):
instruction to initialize.
Returns:
Clifford: the Clifford object for the instruction.
Raises:
QiskitError: if the input instruction is non-Clifford or contains
classical register instruction.
"""
if not isinstance(circuit, (QuantumCircuit, Instruction)):
raise QiskitError("Input must be a QuantumCircuit or Instruction")
# Initialize an identity Clifford
clifford = Clifford(np.eye(2 * circuit.num_qubits), validate=False)
if isinstance(circuit, QuantumCircuit):
clifford = _append_circuit(clifford, circuit)
else:
clifford = _append_operation(clifford, circuit)
return clifford
@staticmethod
def from_label(label: str) -> Clifford:
"""Return a tensor product of single-qubit Clifford gates.
Args:
label (string): single-qubit operator string.
Returns:
Clifford: The N-qubit Clifford operator.
Raises:
QiskitError: if the label contains invalid characters.
Additional Information:
The labels correspond to the single-qubit Cliffords are
* - Label
- Stabilizer
- Destabilizer
* - ``"I"``
- +Z
- +X
* - ``"X"``
- -Z
- +X
* - ``"Y"``
- -Z
- -X
* - ``"Z"``
- +Z
- -X
* - ``"H"``
- +X
- +Z
* - ``"S"``
- +Z
- +Y
"""
# Check label is valid
label_gates = {
"I": IGate(),
"X": XGate(),
"Y": YGate(),
"Z": ZGate(),
"H": HGate(),
"S": SGate(),
}
if re.match(r"^[IXYZHS\-+]+$", label) is None:
raise QiskitError("Label contains invalid characters.")
# Initialize an identity matrix and apply each gate
num_qubits = len(label)
op = Clifford(np.eye(2 * num_qubits, dtype=bool))
for qubit, char in enumerate(reversed(label)):
op = _append_operation(op, label_gates[char], qargs=[qubit])
return op
def to_labels(self, array: bool = False, mode: Literal["S", "D", "B"] = "B"):
r"""Convert a Clifford to a list Pauli (de)stabilizer string labels.
For large Clifford converting using the ``array=True``
kwarg will be more efficient since it allocates memory for
the full Numpy array of labels in advance.
.. list-table:: Stabilizer Representations
:header-rows: 1
* - Label
- Phase
- Symplectic
- Matrix
- Pauli
* - ``"+I"``
- 0
- :math:`[0, 0]`
- :math:`\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}`
- :math:`I`
* - ``"-I"``
- 1
- :math:`[0, 0]`
- :math:`\begin{bmatrix} -1 & 0 \\ 0 & -1 \end{bmatrix}`
- :math:`-I`
* - ``"X"``
- 0
- :math:`[1, 0]`
- :math:`\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}`
- :math:`X`
* - ``"-X"``
- 1
- :math:`[1, 0]`
- :math:`\begin{bmatrix} 0 & -1 \\ -1 & 0 \end{bmatrix}`
- :math:`-X`
* - ``"Y"``
- 0
- :math:`[1, 1]`
- :math:`\begin{bmatrix} 0 & 1 \\ -1 & 0 \end{bmatrix}`
- :math:`iY`
* - ``"-Y"``
- 1
- :math:`[1, 1]`
- :math:`\begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix}`
- :math:`-iY`
* - ``"Z"``
- 0
- :math:`[0, 1]`
- :math:`\begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}`
- :math:`Z`
* - ``"-Z"``
- 1
- :math:`[0, 1]`
- :math:`\begin{bmatrix} -1 & 0 \\ 0 & 1 \end{bmatrix}`
- :math:`-Z`
Args:
array (bool): return a Numpy array if True, otherwise
return a list (Default: False).
mode (Literal["S", "D", "B"]): return both stabilizer and destabilizer if "B",
return only stabilizer if "S" and return only destabilizer if "D".
Returns:
list or array: The rows of the StabilizerTable in label form.
Raises:
QiskitError: if stabilizer and destabilizer are both False.
"""
if mode not in ("S", "B", "D"):
raise QiskitError("mode must be B, S, or D.")
size = 2 * self.num_qubits if mode == "B" else self.num_qubits
offset = self.num_qubits if mode == "S" else 0
ret = np.zeros(size, dtype=f"<U{1 + self.num_qubits}")
for i in range(size):
z = self.tableau[i + offset, self.num_qubits : 2 * self.num_qubits]
x = self.tableau[i + offset, 0 : self.num_qubits]
phase = int(self.tableau[i + offset, -1]) * 2
label = BasePauli._to_label(z, x, phase, group_phase=True)
if label[0] != "-":
label = "+" + label
ret[i] = label
if array:
return ret
return ret.tolist()
# ---------------------------------------------------------------------
# Internal helper functions
# ---------------------------------------------------------------------
def _hash(self):
"""Produce a hashable value that is unique for each different Clifford. This should only be
used internally when the classes being hashed are under our control, because classes of this
type are mutable."""
return np.packbits(self.tableau).tobytes()
@staticmethod
def _is_symplectic(mat):
"""Return True if input is symplectic matrix."""
# Condition is
# table.T * [[0, 1], [1, 0]] * table = [[0, 1], [1, 0]]
# where we are block matrix multiplying using symplectic product
dim = len(mat) // 2
if mat.shape != (2 * dim, 2 * dim):
return False
one = np.eye(dim, dtype=int)
zero = np.zeros((dim, dim), dtype=int)
seye = np.block([[zero, one], [one, zero]])
arr = mat.astype(int)
return np.array_equal(np.mod(arr.T.dot(seye).dot(arr), 2), seye)
@staticmethod
def _conjugate_transpose(clifford, method):
"""Return the adjoint, conjugate, or transpose of the Clifford.
Args:
clifford (Clifford): a clifford object.
method (str): what function to apply 'A', 'C', or 'T'.
Returns:
Clifford: the modified clifford.
"""
ret = clifford.copy()
if method in ["A", "T"]:
# Apply inverse
# Update table
tmp = ret.destab_x.copy()
ret.destab_x = ret.stab_z.T
ret.destab_z = ret.destab_z.T
ret.stab_x = ret.stab_x.T
ret.stab_z = tmp.T
# Update phase
ret.phase ^= clifford.dot(ret).phase
if method in ["C", "T"]:
# Apply conjugate
ret.phase ^= np.mod(_count_y(ret.x, ret.z), 2).astype(bool)
return ret
def _pad_with_identity(self, clifford, qargs):
"""Pad Clifford with identities on other subsystems."""
if qargs is None:
return clifford
padded = Clifford(np.eye(2 * self.num_qubits, dtype=bool), validate=False, copy=False)
inds = list(qargs) + [self.num_qubits + i for i in qargs]
# Pad Pauli array
for i, pos in enumerate(qargs):
padded.tableau[inds, pos] = clifford.tableau[:, i]
padded.tableau[inds, self.num_qubits + pos] = clifford.tableau[
:, clifford.num_qubits + i
]
# Pad phase
padded.phase[inds] = clifford.phase
return padded
@staticmethod
def _stack_table_phase(table, phase):
return np.hstack((table, phase.reshape(len(phase), 1)))
@staticmethod
def _from_label(label):
phase = False
if label[0] in ("-", "+"):
phase = label[0] == "-"
label = label[1:]
num_qubits = len(label)
symp = np.zeros(2 * num_qubits + 1, dtype=bool)
xs = symp[0:num_qubits]
zs = symp[num_qubits : 2 * num_qubits]
for i, char in enumerate(label):
if char not in ["I", "X", "Y", "Z"]:
raise QiskitError(
f"Pauli string contains invalid character: {char} not in ['I', 'X', 'Y', 'Z']."
)
if char in ("X", "Y"):
xs[num_qubits - 1 - i] = True
if char in ("Z", "Y"):
zs[num_qubits - 1 - i] = True
symp[-1] = phase
return symp
@staticmethod
def _pauli_matrix_to_row(mat, num_qubits):
"""Generate a binary vector (a row of tableau representation) from a Pauli matrix.
Return None if the non-Pauli matrix is supplied."""
# pylint: disable=too-many-return-statements
def find_one_index(x, decimals=6):
indices = np.where(np.round(np.abs(x), decimals) == 1)
return indices[0][0] if len(indices[0]) == 1 else None
def bitvector(n, num_bits):
return np.array([int(digit) for digit in format(n, f"0{num_bits}b")], dtype=bool)[::-1]
# compute x-bits
xint = find_one_index(mat[0, :])
if xint is None:
return None
xbits = bitvector(xint, num_qubits)
# extract non-zero elements from matrix (rounded to 1, -1, 1j or -1j)
entries = np.empty(len(mat), dtype=complex)
for i, row in enumerate(mat):
index = find_one_index(row)
if index is None:
return None
expected = xint ^ i
if index != expected:
return None
entries[i] = np.round(mat[i, index])
# compute z-bits
zbits = np.empty(num_qubits, dtype=bool)
for k in range(num_qubits):
sign = np.round(entries[2**k] / entries[0])
if sign == 1:
zbits[k] = False
elif sign == -1:
zbits[k] = True
else:
return None
# compute phase
phase = None
num_y = sum(xbits & zbits)
positive_phase = (-1j) ** num_y
if entries[0] == positive_phase:
phase = False
elif entries[0] == -1 * positive_phase:
phase = True
if phase is None:
return None
# validate all non-zero elements
coef = ((-1) ** phase) * positive_phase
ivec, zvec = np.ones(2), np.array([1, -1])
expected = coef * functools.reduce(np.kron, [zvec if z else ivec for z in zbits[::-1]])
if not np.allclose(entries, expected):
return None
return np.hstack([xbits, zbits, phase])
@staticmethod
def _unitary_matrix_to_tableau(matrix):
# pylint: disable=invalid-name
num_qubits = int(np.log2(len(matrix)))
stab = np.empty((num_qubits, 2 * num_qubits + 1), dtype=bool)
for i in range(num_qubits):
label = "I" * (num_qubits - i - 1) + "X" + "I" * i
Xi = Operator.from_label(label).to_matrix()
target = matrix @ Xi @ np.conj(matrix).T
row = Clifford._pauli_matrix_to_row(target, num_qubits)
if row is None:
return None
stab[i] = row
destab = np.empty((num_qubits, 2 * num_qubits + 1), dtype=bool)
for i in range(num_qubits):
label = "I" * (num_qubits - i - 1) + "Z" + "I" * i
Zi = Operator.from_label(label).to_matrix()
target = matrix @ Zi @ np.conj(matrix).T
row = Clifford._pauli_matrix_to_row(target, num_qubits)
if row is None:
return None
destab[i] = row
tableau = np.vstack([stab, destab])
return tableau
# Update docstrings for API docs
generate_apidocs(Clifford)
|
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.
"""Example on how to load a file into a QuantumCircuit."""
from qiskit import QuantumCircuit
from qiskit import execute, BasicAer
circ = QuantumCircuit.from_qasm_file("examples/qasm/entangled_registers.qasm")
print(circ)
# See the backend
sim_backend = BasicAer.get_backend("qasm_simulator")
# Compile and run the Quantum circuit on a local simulator backend
job_sim = execute(circ, sim_backend)
sim_result = job_sim.result()
# Show the results
print("simulation: ", sim_result)
print(sim_result.get_counts(circ))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import IntegerComparator
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
# set problem parameters
n_z = 2
z_max = 2
z_values = np.linspace(-z_max, z_max, 2**n_z)
p_zeros = [0.15, 0.25]
rhos = [0.1, 0.05]
lgd = [1, 2]
K = len(p_zeros)
alpha = 0.05
from qiskit_finance.circuit.library import GaussianConditionalIndependenceModel as GCI
u = GCI(n_z, z_max, p_zeros, rhos)
u.draw()
u_measure = u.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(u_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# analyze uncertainty circuit and determine exact solutions
p_z = np.zeros(2**n_z)
p_default = np.zeros(K)
values = []
probabilities = []
num_qubits = u.num_qubits
for i, prob in binary_probabilities.items():
# extract value of Z and corresponding probability
i_normal = int(i[-n_z:], 2)
p_z[i_normal] += prob
# determine overall default probability for k
loss = 0
for k in range(K):
if i[K - k - 1] == "1":
p_default[k] += prob
loss += lgd[k]
values += [loss]
probabilities += [prob]
values = np.array(values)
probabilities = np.array(probabilities)
expected_loss = np.dot(values, probabilities)
losses = np.sort(np.unique(values))
pdf = np.zeros(len(losses))
for i, v in enumerate(losses):
pdf[i] += sum(probabilities[values == v])
cdf = np.cumsum(pdf)
i_var = np.argmax(cdf >= 1 - alpha)
exact_var = losses[i_var]
exact_cvar = np.dot(pdf[(i_var + 1) :], losses[(i_var + 1) :]) / sum(pdf[(i_var + 1) :])
print("Expected Loss E[L]: %.4f" % expected_loss)
print("Value at Risk VaR[L]: %.4f" % exact_var)
print("P[L <= VaR[L]]: %.4f" % cdf[exact_var])
print("Conditional Value at Risk CVaR[L]: %.4f" % exact_cvar)
# plot loss PDF, expected loss, var, and cvar
plt.bar(losses, pdf)
plt.axvline(expected_loss, color="green", linestyle="--", label="E[L]")
plt.axvline(exact_var, color="orange", linestyle="--", label="VaR(L)")
plt.axvline(exact_cvar, color="red", linestyle="--", label="CVaR(L)")
plt.legend(fontsize=15)
plt.xlabel("Loss L ($)", size=15)
plt.ylabel("probability (%)", size=15)
plt.title("Loss Distribution", size=20)
plt.xticks(size=15)
plt.yticks(size=15)
plt.show()
# plot results for Z
plt.plot(z_values, p_z, "o-", linewidth=3, markersize=8)
plt.grid()
plt.xlabel("Z value", size=15)
plt.ylabel("probability (%)", size=15)
plt.title("Z Distribution", size=20)
plt.xticks(size=15)
plt.yticks(size=15)
plt.show()
# plot results for default probabilities
plt.bar(range(K), p_default)
plt.xlabel("Asset", size=15)
plt.ylabel("probability (%)", size=15)
plt.title("Individual Default Probabilities", size=20)
plt.xticks(range(K), size=15)
plt.yticks(size=15)
plt.grid()
plt.show()
# add Z qubits with weight/loss 0
from qiskit.circuit.library import WeightedAdder
agg = WeightedAdder(n_z + K, [0] * n_z + lgd)
from qiskit.circuit.library import LinearAmplitudeFunction
# define linear objective function
breakpoints = [0]
slopes = [1]
offsets = [0]
f_min = 0
f_max = sum(lgd)
c_approx = 0.25
objective = LinearAmplitudeFunction(
agg.num_sum_qubits,
slope=slopes,
offset=offsets,
# max value that can be reached by the qubit register (will not always be reached)
domain=(0, 2**agg.num_sum_qubits - 1),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
# define the registers for convenience and readability
qr_state = QuantumRegister(u.num_qubits, "state")
qr_sum = QuantumRegister(agg.num_sum_qubits, "sum")
qr_carry = QuantumRegister(agg.num_carry_qubits, "carry")
qr_obj = QuantumRegister(1, "objective")
# define the circuit
state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A")
# load the random variable
state_preparation.append(u.to_gate(), qr_state)
# aggregate
state_preparation.append(agg.to_gate(), qr_state[:] + qr_sum[:] + qr_carry[:])
# linear objective function
state_preparation.append(objective.to_gate(), qr_sum[:] + qr_obj[:])
# uncompute aggregation
state_preparation.append(agg.to_gate().inverse(), qr_state[:] + qr_sum[:] + qr_carry[:])
# draw the circuit
state_preparation.draw()
state_preparation_measure = state_preparation.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(state_preparation_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# evaluate the result
value = 0
for i, prob in binary_probabilities.items():
if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1":
value += prob
print("Exact Expected Loss: %.4f" % expected_loss)
print("Exact Operator Value: %.4f" % value)
print("Mapped Operator value: %.4f" % objective.post_processing(value))
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=state_preparation,
objective_qubits=[len(qr_state)],
post_processing=objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
# print results
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % expected_loss)
print("Estimated value:\t%.4f" % result.estimation_processed)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
# set x value to estimate the CDF
x_eval = 2
comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False)
comparator.draw()
def get_cdf_circuit(x_eval):
# define the registers for convenience and readability
qr_state = QuantumRegister(u.num_qubits, "state")
qr_sum = QuantumRegister(agg.num_sum_qubits, "sum")
qr_carry = QuantumRegister(agg.num_carry_qubits, "carry")
qr_obj = QuantumRegister(1, "objective")
qr_compare = QuantumRegister(1, "compare")
# define the circuit
state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A")
# load the random variable
state_preparation.append(u, qr_state)
# aggregate
state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:])
# comparator objective function
comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False)
state_preparation.append(comparator, qr_sum[:] + qr_obj[:] + qr_carry[:])
# uncompute aggregation
state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:])
return state_preparation
state_preparation = get_cdf_circuit(x_eval)
state_preparation.draw()
state_preparation_measure = state_preparation.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(state_preparation_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# evaluate the result
var_prob = 0
for i, prob in binary_probabilities.items():
if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1":
var_prob += prob
print("Operator CDF(%s)" % x_eval + " = %.4f" % var_prob)
print("Exact CDF(%s)" % x_eval + " = %.4f" % cdf[x_eval])
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_state)])
# construct amplitude estimation
ae_cdf = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_cdf = ae_cdf.estimate(problem)
# print results
conf_int = np.array(result_cdf.confidence_interval)
print("Exact value: \t%.4f" % cdf[x_eval])
print("Estimated value:\t%.4f" % result_cdf.estimation)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
def run_ae_for_cdf(x_eval, epsilon=0.01, alpha=0.05, simulator="aer_simulator"):
# construct amplitude estimation
state_preparation = get_cdf_circuit(x_eval)
problem = EstimationProblem(
state_preparation=state_preparation, objective_qubits=[len(qr_state)]
)
ae_var = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_var = ae_var.estimate(problem)
return result_var.estimation
def bisection_search(
objective, target_value, low_level, high_level, low_value=None, high_value=None
):
"""
Determines the smallest level such that the objective value is still larger than the target
:param objective: objective function
:param target: target value
:param low_level: lowest level to be considered
:param high_level: highest level to be considered
:param low_value: value of lowest level (will be evaluated if set to None)
:param high_value: value of highest level (will be evaluated if set to None)
:return: dictionary with level, value, num_eval
"""
# check whether low and high values are given and evaluated them otherwise
print("--------------------------------------------------------------------")
print("start bisection search for target value %.3f" % target_value)
print("--------------------------------------------------------------------")
num_eval = 0
if low_value is None:
low_value = objective(low_level)
num_eval += 1
if high_value is None:
high_value = objective(high_level)
num_eval += 1
# check if low_value already satisfies the condition
if low_value > target_value:
return {
"level": low_level,
"value": low_value,
"num_eval": num_eval,
"comment": "returned low value",
}
elif low_value == target_value:
return {"level": low_level, "value": low_value, "num_eval": num_eval, "comment": "success"}
# check if high_value is above target
if high_value < target_value:
return {
"level": high_level,
"value": high_value,
"num_eval": num_eval,
"comment": "returned low value",
}
elif high_value == target_value:
return {
"level": high_level,
"value": high_value,
"num_eval": num_eval,
"comment": "success",
}
# perform bisection search until
print("low_level low_value level value high_level high_value")
print("--------------------------------------------------------------------")
while high_level - low_level > 1:
level = int(np.round((high_level + low_level) / 2.0))
num_eval += 1
value = objective(level)
print(
"%2d %.3f %2d %.3f %2d %.3f"
% (low_level, low_value, level, value, high_level, high_value)
)
if value >= target_value:
high_level = level
high_value = value
else:
low_level = level
low_value = value
# return high value after bisection search
print("--------------------------------------------------------------------")
print("finished bisection search")
print("--------------------------------------------------------------------")
return {"level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success"}
# run bisection search to determine VaR
objective = lambda x: run_ae_for_cdf(x)
bisection_result = bisection_search(
objective, 1 - alpha, min(losses) - 1, max(losses), low_value=0, high_value=1
)
var = bisection_result["level"]
print("Estimated Value at Risk: %2d" % var)
print("Exact Value at Risk: %2d" % exact_var)
print("Estimated Probability: %.3f" % bisection_result["value"])
print("Exact Probability: %.3f" % cdf[exact_var])
# define linear objective
breakpoints = [0, var]
slopes = [0, 1]
offsets = [0, 0] # subtract VaR and add it later to the estimate
f_min = 0
f_max = 3 - var
c_approx = 0.25
cvar_objective = LinearAmplitudeFunction(
agg.num_sum_qubits,
slopes,
offsets,
domain=(0, 2**agg.num_sum_qubits - 1),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
cvar_objective.draw()
# define the registers for convenience and readability
qr_state = QuantumRegister(u.num_qubits, "state")
qr_sum = QuantumRegister(agg.num_sum_qubits, "sum")
qr_carry = QuantumRegister(agg.num_carry_qubits, "carry")
qr_obj = QuantumRegister(1, "objective")
qr_work = QuantumRegister(cvar_objective.num_ancillas - len(qr_carry), "work")
# define the circuit
state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, qr_work, name="A")
# load the random variable
state_preparation.append(u, qr_state)
# aggregate
state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:])
# linear objective function
state_preparation.append(cvar_objective, qr_sum[:] + qr_obj[:] + qr_carry[:] + qr_work[:])
# uncompute aggregation
state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:])
state_preparation_measure = state_preparation.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(state_preparation_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# evaluate the result
value = 0
for i, prob in binary_probabilities.items():
if prob > 1e-6 and i[-(len(qr_state) + 1)] == "1":
value += prob
# normalize and add VaR to estimate
value = cvar_objective.post_processing(value)
d = 1.0 - bisection_result["value"]
v = value / d if d != 0 else 0
normalized_value = v + var
print("Estimated CVaR: %.4f" % normalized_value)
print("Exact CVaR: %.4f" % exact_cvar)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=state_preparation,
objective_qubits=[len(qr_state)],
post_processing=cvar_objective.post_processing,
)
# construct amplitude estimation
ae_cvar = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_cvar = ae_cvar.estimate(problem)
# print results
d = 1.0 - bisection_result["value"]
v = result_cvar.estimation_processed / d if d != 0 else 0
print("Exact CVaR: \t%.4f" % exact_cvar)
print("Estimated CVaR:\t%.4f" % (v + var))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/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/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider = IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
device = provider.get_backend('ibm_nairobi')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor
from qiskit.tools.visualization import plot_histogram
q0 = QuantumRegister(1); q1 = QuantumRegister(1); q2 = QuantumRegister(1); q3 = QuantumRegister(1)
c0 = ClassicalRegister(1); c1 = ClassicalRegister(1); c2 = ClassicalRegister(1); c3 = ClassicalRegister(1)
qc = QuantumCircuit(q0,q1,q2,q3,c0,c1,c2,c3)
# q0 e q1 estao com Alice, q2 com Charlies e q3 com Bob
qc.h(q1); qc.cx(q1,q2); qc.cx(q2,q3) # prepara o estado GHZ
qc.barrier()
#qc.sdg(q0); qc.h(q0) # prepara o estado a ser teletransportado (y+)
# prepara o estado |0>
qc.barrier()
qc.cx(q0,q1); qc.h(q0); qc.measure(q0,c0); qc.measure(q1,c1) # Medida de Alice na base de Bell
qc.h(q2); qc.measure(q2,c2) # medida de Charlie na base +,-
qc.barrier()
qc.z(q3).c_if(c0, 1) # acao de Bob condicionada no 1º cbit enviado por Alice
qc.x(q3).c_if(c1, 1) # acao de Bob condicionada no 2º cbit enviado por Alice
qc.z(q3).c_if(c2, 1) # acao de Bob condicionada no cbit enviado por Charlie
qc.barrier()
#qc.sdg(q3); qc.h(q3); qc.measure(q3,c3) # passa da base circular pra computacional
qc.measure(q3,c3) # mede na base computacional
qc.draw(output='mpl')
jobS = execute(qc, backend = simulator, shots = nshots)
plot_histogram(jobS.result().get_counts(qc))
jobE = execute(qc, backend = device, shots = nshots)
job_monitor(jobE)
tqc = transpile(qc, device)
jobE = device.run(tqc)
job_monitor(jobE)
plot_histogram([jobS.result().get_counts(0), jobE.result().get_counts(0)],
bar_labels = False, legend = ['sim', 'exp'])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit import Parameter
from qiskit import QuantumCircuit
theta = Parameter('$\\theta$')
chsh_circuits_no_meas = QuantumCircuit(2)
chsh_circuits_no_meas.h(0)
chsh_circuits_no_meas.cx(0, 1)
chsh_circuits_no_meas.ry(theta, 0)
chsh_circuits_no_meas.draw('mpl')
import numpy as np
number_of_phases = 21
phases = np.linspace(0, 2*np.pi, number_of_phases)
# Phases need to be expressed as list of lists in order to work
individual_phases = [[ph] for ph in phases]
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = "ibmq_qasm_simulator" # use the simulator
from qiskit_ibm_runtime import Estimator, Session
from qiskit.quantum_info import SparsePauliOp
ZZ = SparsePauliOp.from_list([("ZZ", 1)])
ZX = SparsePauliOp.from_list([("ZX", 1)])
XZ = SparsePauliOp.from_list([("XZ", 1)])
XX = SparsePauliOp.from_list([("XX", 1)])
ops = [ZZ, ZX, XZ, XX]
chsh_est_sim = []
# Simulator
with Session(service=service, backend=backend):
estimator = Estimator()
for op in ops:
job = estimator.run(
circuits=[chsh_circuits_no_meas]*len(individual_phases),
observables=[op]*len(individual_phases),
parameter_values=individual_phases)
est_result = job.result()
chsh_est_sim.append(est_result)
# <CHSH1> = <AB> - <Ab> + <aB> + <ab>
chsh1_est_sim = chsh_est_sim[0].values - chsh_est_sim[1].values + chsh_est_sim[2].values + chsh_est_sim[3].values
# <CHSH2> = <AB> + <Ab> - <aB> + <ab>
chsh2_est_sim = chsh_est_sim[0].values + chsh_est_sim[1].values - chsh_est_sim[2].values + chsh_est_sim[3].values
import matplotlib.pyplot as plt
import matplotlib.ticker as tck
fig, ax = plt.subplots(figsize=(10, 6))
# results from a simulator
ax.plot(phases/np.pi, chsh1_est_sim, 'o-', label='CHSH1 Simulation')
ax.plot(phases/np.pi, chsh2_est_sim, 'o-', label='CHSH2 Simulation')
# classical bound +-2
ax.axhline(y=2, color='r', linestyle='--')
ax.axhline(y=-2, color='r', linestyle='--')
# quantum bound, +-2√2
ax.axhline(y=np.sqrt(2)*2, color='b', linestyle='-.')
ax.axhline(y=-np.sqrt(2)*2, color='b', linestyle='-.')
# set x tick labels to the unit of pi
ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$'))
ax.xaxis.set_major_locator(tck.MultipleLocator(base=0.5))
# set title, labels, and legend
plt.title('Violation of CHSH Inequality')
plt.xlabel('Theta')
plt.ylabel('CHSH witness')
plt.legend()
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info import SparsePauliOp
def heisenberg_hamiltonian(
length: int, jx: float = 1.0, jy: float = 0.0, jz: float = 0.0
) -> SparsePauliOp:
terms = []
for i in range(length - 1):
if jx:
terms.append(("XX", [i, i + 1], jx))
if jy:
terms.append(("YY", [i, i + 1], jy))
if jz:
terms.append(("ZZ", [i, i + 1], jz))
return SparsePauliOp.from_sparse_list(terms, num_qubits=length)
def state_prep_circuit(num_qubits: int, layers: int = 1) -> QuantumCircuit:
qubits = QuantumRegister(num_qubits, name="q")
circuit = QuantumCircuit(qubits)
circuit.h(qubits)
for _ in range(layers):
for i in range(0, num_qubits - 1, 2):
circuit.cx(qubits[i], qubits[i + 1])
circuit.ry(0.1, qubits)
for i in range(1, num_qubits - 1, 2):
circuit.cx(qubits[i], qubits[i + 1])
circuit.ry(0.1, qubits)
return circuit
length = 5
hamiltonian = heisenberg_hamiltonian(length, 1.0, 1.0)
circuit = state_prep_circuit(length, layers=2)
print(hamiltonian)
circuit.draw("mpl")
from qiskit_aer.primitives import Estimator
estimator = Estimator(approximation=True)
job = estimator.run(circuit, hamiltonian, shots=None)
result = job.result()
exact_value = result.values[0]
print(f"Exact energy: {exact_value}")
from qiskit_ibm_runtime import QiskitRuntimeService
hub = "ibm-q-internal"
group = "deployed"
project = "default"
service = QiskitRuntimeService(instance=f"{hub}/{group}/{project}")
from qiskit_ibm_runtime import Estimator, Options, Session
from qiskit.transpiler import CouplingMap
backend = service.get_backend("simulator_statevector")
# set simulation options
simulator = {
"basis_gates": ["id", "rz", "sx", "cx", "reset"],
"coupling_map": list(CouplingMap.from_line(length + 1)),
}
shots = 10000
import math
options = Options(
simulator=simulator,
resilience_level=0,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
from qiskit_aer.noise import NoiseModel, ReadoutError
noise_model = NoiseModel()
##### your code here #####
# P(A|B) = [P(A|0), P(A|1)] = [ 1 - q0_01, q0_01 ] = [ 0.8, 0.2 ]
q0_10 = 0.5
q0_01 = 0.2
qn_10 = 0.05
qn_01 = 0.02
re_l = [ReadoutError(
[
[1 - q0_01, q0_01],
[q0_10, 1 - q0_10],
]
)]
n_qubits = 6
for _ in range(n_qubits - 1):
re_l.append(ReadoutError(
[
[1 - qn_01, qn_01],
[qn_10, 1 - qn_10],
]
))
for q in range(n_qubits):
noise_model.add_readout_error(re_l[q], (q, ))
print(noise_model.to_dict())
# Submit your answer
from qc_grader.challenges.qgss_2023 import grade_lab5_ex1
grade_lab5_ex1(noise_model)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=0,
transpilation=dict(initial_layout=list(range(length))),
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=0,
transpilation=dict(initial_layout=list(range(1, length + 1))),
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=1,
transpilation=dict(initial_layout=list(range(1, length + 1))),
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
new_shots: int
##### your code here #####
new_shots = 20000
# Submit your answer
from qc_grader.challenges.qgss_2023 import grade_lab5_ex2
grade_lab5_ex2(new_shots)
from qiskit_aer.noise import depolarizing_error
noise_model = NoiseModel()
##### your code here #####
error = depolarizing_error(0.01, 2)
noise_model.add_all_qubit_quantum_error(error, ['cx'])
print(noise_model)
# Submit your answer
from qc_grader.challenges.qgss_2023 import grade_lab5_ex3
grade_lab5_ex3(noise_model)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=1,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=2,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variances = result.metadata[0]["zne"]["noise_amplification"]["variance"]
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variances: {variances}")
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from scipy.stats import kruskal
import pandas as pd
import numpy as np
#if p value less than alpha reject
qiskit_data = np.full(100000, 0)
print(qiskit_data)
cirq_data = np.full(100000, 0)
qs_data = np.full(100000, 0)
kruskal(qiskit_data, cirq_data, qs_data)
qiskit_data = np.concatenate((np.full(41192, 8), np.full(1555, 9), np.full(7096, 10),
np.full(226, 11), np.full(41044, 12), np.full(1637, 13),
np.full(6961, 14), np.full(289, 15)))
print(qiskit_data)
cirq_data = np.concatenate((np.full(41016, 8), np.full(1163, 9), np.full(7092, 10),
np.full(301, 11), np.full(41024, 12), np.full(1635, 13),
np.full(7017, 14), np.full(282, 15)))
print(cirq_data)
qs_data = np.concatenate((np.full(40973, 8), np.full(1706, 9), np.full(7123, 10),
np.full(314, 11), np.full(40899, 12), np.full(1621, 13),
np.full(7076, 14), np.full(288, 15)))
print(qs_data)
kruskal(qiskit_data, cirq_data, qs_data)
qiskit_data = np.concatenate((np.full(1676, 8), np.full(40877, 9), np.full(285, 10),
np.full(7103, 11), np.full(1610, 12), np.full(41135, 13),
np.full(256, 14), np.full(7058, 15)))
print(qiskit_data)
cirq_data = np.concatenate((np.full(1639, 8), np.full(40954, 9), np.full(285, 10),
np.full(6906, 11), np.full(1582, 12), np.full(41332, 13),
np.full(265, 14), np.full(7037, 15)))
print(cirq_data)
qs_data = np.concatenate((np.full(1656, 8), np.full(41277, 9), np.full(251, 10),
np.full(7103, 11), np.full(1608, 12), np.full(40752, 13),
np.full(271, 14), np.full(7082, 15)))
print(qs_data)
kruskal(qiskit_data, cirq_data, qs_data)
qiskit_data = np.concatenate((np.full(41064, 8), np.full(1645, 9), np.full(7072, 10),
np.full(261, 11), np.full(40850, 12), np.full(1612, 13),
np.full(7223, 14), np.full(273, 15)))
print(qiskit_data)
cirq_data = np.concatenate((np.full(41036, 8), np.full(1582, 9), np.full(7094, 10),
np.full(250, 11), np.full(41178, 12), np.full(1621, 13),
np.full(6967, 14), np.full(272, 15)))
print(cirq_data)
qs_data = np.concatenate((np.full(41120, 8), np.full(1643, 9), np.full(6953, 10),
np.full(251, 11), np.full(41011, 12), np.full(1631, 13),
np.full(7131, 14), np.full(260, 15)))
print(qs_data)
kruskal(qiskit_data, cirq_data, qs_data)
|
https://github.com/Qiskit/feedback
|
Qiskit
|
# Step 1: setup
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
backend = AerSimulator(method="statevector")
# Step 2: conditional initialisation
qc = QuantumCircuit(1, 2)
qc.h(0) # This is just a stand-in for more complex real-world setup.
qc.measure(0, 0)
# Unlike c_if, we can have more than one instruction in the block, and it only
# requires a single evaluation of the condition. That's especially important if
# the bit is written to part way through the block.
with qc.if_test((0, True)):
qc.reset(0)
qc.x(0)
qc.measure(0, 1)
qc.draw()
backend.run(qc).result().get_counts() # {'00': 0.5, '11': 0.5}
# Step 3: repeat until success.
# Previously this wasn't representable in Qiskit at all, because we didn't have
# any concept of a run-time loop.
qc = QuantumCircuit(1, 2)
qc.h(0)
qc.measure(0, 0)
with qc.while_loop((0, False)):
qc.reset(0)
qc.h(0)
qc.measure(0, 0)
qc.measure(0, 1)
qc.draw()
backend.run(qc).result().get_counts() # {'11': 1}
# Step 4: repeat until success, with limits on the number of iterations.
qc = QuantumCircuit(1, 2)
with qc.for_loop(range(2)):
qc.reset(0)
qc.h(0)
qc.measure(0, 0)
with qc.if_test((0, True)):
# 'break' (and 'continue') is also supported by Aer, but won't be part
# of the initial transpiler support for swap routing.
qc.break_loop()
qc.measure(0, 1)
backend.run(qc).result().get_counts() # {'00': 0.25, '11': 0.75}
# Step 5: converting old-style c_if to IfElseOp.
# This transpiler pass is available in Terra 0.22 for backends to use in their
# injected pass-manager stages, so they can begin transitioning to the new forms
# immediately, and can start deprecating support for handling old-style
# `condition`.
from qiskit.transpiler.passes import ConvertConditionsToIfOps
qc = QuantumCircuit(1, 1)
qc.h(0)
qc.measure(0, 0)
qc.x(0).c_if(0, False)
qc.draw()
pass_ = ConvertConditionsToIfOps()
pass_(qc).draw()
# Other things mentioned:
#
# - The `QuantumCircuit.for_loop` context manager returns a `Parameter` object
# that can be used in angle expressions in the loop body's gates. The
# OpenQASM 3 exporter understands this.
#
# - The `QuantumCircuit.if_test` context manager returns a context-manager
# object that can be entered immediately on termination of the "true" body, to
# make an "else" body. For example:
#
# with qc.if_test((0, False)) as else_:
# qc.x(0)
# with else_:
# qc.z(0)
#
# - The OpenQASM 3 exporter supports all these constructs. The easiest path to
# access that is `qiskit.qasm3.dumps`.
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.