repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
---|---|---|
https://github.com/entropicalabs/OpenQAOA-Challenge---Qiskit-Fall-Fest-2022-Mexico
|
entropicalabs
|
%load_ext autoreload
%autoreload 2
from IPython.display import clear_output
import matplotlib.pyplot as plt
import plotly.graph_objects as go
import numpy as np
import networkx as nx
# Design the graph for the maxcut problem
g = nx.Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 3)
g.add_edge(1, 4)
g.add_edge(2, 4)
g.add_edge(3, 4)
#import problem classes from OQ for easy problem creation
from openqaoa.problems.problem import MaximumCut
#import the QAOA workflow model
from openqaoa.workflows.optimizer import QAOA
#import method to specify the device
from openqaoa.devices import create_device
# Import the method to plot the graph
from openqaoa.utilities import plot_graph
plot_graph(g)
#Use the MaximumCut class to instantiate the problem.
maxcut_prob = MaximumCut(g)
# The binary values can be access via the `asdict()` method.
maxcut_qubo = maxcut_prob.get_qubo_problem()
maxcut_qubo.asdict()
# init the object QAOA for default the backend is vectorised
q = QAOA()
q.local_simulators, q.cloud_provider
from openqaoa.devices import create_device
sim = create_device(location='local', name='vectorized')
q.set_device(sim)
q.compile(maxcut_qubo)
q.optimize()
q.results.most_probable_states['solutions_bitstrings']
q.results.most_probable_states['bitstring_energy']
q.results.get_counts(q.results.optimized['optimized measurement outcomes'])
q.results.plot_cost()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
from qiskit import Aer, IBMQ, execute
from qiskit import transpile, assemble
from qiskit.tools.monitor import job_monitor
from qiskit.tools.monitor import job_monitor
import matplotlib.pyplot as plt
from qiskit.visualization import plot_histogram, plot_state_city
"""
Qiskit backends to execute the quantum circuit
"""
def simulator(qc):
"""
Run on local simulator
:param qc: quantum circuit
:return:
"""
backend = Aer.get_backend("qasm_simulator")
shots = 2048
tqc = transpile(qc, backend)
qobj = assemble(tqc, shots=shots)
job_sim = backend.run(qobj)
qc_results = job_sim.result()
return qc_results, shots
def simulator_state_vector(qc):
"""
Select the StatevectorSimulator from the Aer provider
:param qc: quantum circuit
:return:
statevector
"""
simulator = Aer.get_backend('statevector_simulator')
# Execute and get counts
result = execute(qc, simulator).result()
state_vector = result.get_statevector(qc)
return state_vector
def real_quantum_device(qc):
"""
Use the IBMQ essex device
:param qc: quantum circuit
:return:
"""
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_santiago')
shots = 2048
TQC = transpile(qc, backend)
qobj = assemble(TQC, shots=shots)
job_exp = backend.run(qobj)
job_monitor(job_exp)
QC_results = job_exp.result()
return QC_results, shots
def counts(qc_results):
"""
Get counts representing the wave-function amplitudes
:param qc_results:
:return: dict keys are bit_strings and their counting values
"""
return qc_results.get_counts()
def plot_results(qc_results):
"""
Visualizing wave-function amplitudes in a histogram
:param qc_results: quantum circuit
:return:
"""
plt.show(plot_histogram(qc_results.get_counts(), figsize=(8, 6), bar_labels=False))
def plot_state_vector(state_vector):
"""Visualizing state vector in the density matrix representation"""
plt.show(plot_state_city(state_vector))
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# 数値計算モジュールを導入
import numpy as np
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 3量子ビット回路を用意
qr = QuantumRegister(3)
a_0 = ClassicalRegister(1)
a_1 = ClassicalRegister(1)
b_0 = ClassicalRegister(1)
qc = QuantumCircuit(qr,a_0,a_1,b_0)
# Aliceのもつ未知の量子状態ψをRyで作ります。角度はπ/5にしました。
qc.ry(np.pi/5,0)
qc.barrier() #回路を見やすくするために入れます
# EveがEPRペアを作ってq1をAliceにq2をBobに渡します
qc.h(1)
qc.cx(1, 2)
qc.barrier()
# AliceがCNOTとHでψと自分のEPRペアをエンタングルさせ測定します。
qc.cx(0, 1)
qc.h(0)
qc.barrier()
qc.measure(0, a_0)
qc.measure(1, a_1)
#Aliceが測定結果をBobに送り、Bobが結果に合わせて操作します
qc.z(2).c_if(a_0, 1)
qc.x(2).c_if(a_1, 1)
# 回路を描画
qc.draw(output="mpl")
# 3量子ビット回路を用意
qr = QuantumRegister(3)
a_0 = ClassicalRegister(1)
a_1 = ClassicalRegister(1)
b_0 = ClassicalRegister(1)
qc = QuantumCircuit(qr,a_0,a_1,b_0)
# Aliceのもつ未知の量子状態ψをRyで作ります。角度はπ/5にしました。
qc.ry(np.pi/5,0)
qc.barrier() #回路を見やすくするために入れます
# EveがEPRペアを作ってq1をAliceにq2をBobに渡します
qc.h(1)
qc.cx(1, 2)
qc.barrier()
# AliceがCNOTとHでψと自分のEPRペアをエンタングルさせ測定します。
qc.cx(0, 1)
qc.h(0)
qc.barrier()
qc.measure(0, a_0)
qc.measure(1, a_1)
#Aliceが測定結果をBobに送り、Bobが結果に合わせて操作します
qc.z(2).c_if(a_0, 1)
qc.x(2).c_if(a_1, 1)
# 未知の量子状態ψの逆ゲートをかけて0が測定できるか確かめます
qc.ry(-np.pi/5, 2)
qc.measure(2, b_0)
qc.draw(output="mpl")
# qasm_simulatorで実行して確認します
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(qc, backend).result().get_counts()
print(counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
# 3量子ビット、1古典ビットの回路を用意
qc = QuantumCircuit(3,1)
# Aliceのもつ未知の量子状態ψをRyで作ります。角度はπ/5にしました。
qc.ry(np.pi/5,0)
qc.barrier() #回路を見やすくするために入れます
# EveがEPRペアを作ってq1をAliceにq2をBobに渡します
qc.h(1)
qc.cx(1, 2)
qc.barrier()
# AliceがCNOTとHでψと自分のEPRペアをエンタングルさせます。
qc.cx(0, 1)
qc.h(0)
qc.barrier()
# Aliceの状態に合わせてBobが操作します(ここを変えています!)
qc.cz(0,2)
qc.cx(1,2)
# 未知の量子状態ψの逆ゲートをかけて0が測定できるか確かめます
qc.ry(-np.pi/5, 2)
qc.measure(2, 0)
qc.draw(output="mpl")
# 先にシミュレーターでコードが合っているか確認します
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(qc, backend).result().get_counts()
print(counts)
plot_histogram(counts)
# 初めて実デバイスで実行する人はこちらを実行
from qiskit import IBMQ
IBMQ.save_account('MY_API_TOKEN') # ご自分のトークンを入れてください
# アカウント情報をロードして、使える量子デバイスを確認します
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
# 最もすいているバックエンドを選びます
from qiskit.providers.ibmq import least_busy
large_enough_devices = IBMQ.get_provider().backends(filters=lambda x: x.configuration().n_qubits > 3 and not x.configuration().simulator)
print(large_enough_devices)
real_backend = least_busy(large_enough_devices)
print("ベストなバックエンドは " + real_backend.name())
# 上記のバックエンドで実行します
job = execute(qc,real_backend)
# ジョブの実行状態を確認します
from qiskit.tools.monitor import job_monitor
job_monitor(job)
# 結果を確認します
real_result= job.result()
print(real_result.get_counts(qc))
plot_histogram(real_result.get_counts(qc))
|
https://github.com/hotstaff/qc
|
hotstaff
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Quantum Calculator - libqc
Author: Hideto Manjo
Licence: Apache License 2.0
'''
import sys
import re
from datetime import datetime
from qiskit import QuantumProgram, QISKitError, RegisterSizeError
class QC():
'''
class QC
'''
# pylint: disable=too-many-instance-attributes
def __init__(self, backend='local_qasm_simulator', remote=False, qubits=3):
# private member
# __qp
self.__qp = None
# calc phase
self.phase = [
['0', 'initialized.']
]
# config
self.backend = backend
self.remote = remote
self.qubits = qubits
# circuits variable
self.shots = 2
# async
self.wait = False
self.last = ['init', 'None']
self.load()
def load(self, api_info=True):
'''
load
'''
self.__qp = QuantumProgram()
if self.remote:
try:
import Qconfig
self.__qp.set_api(Qconfig.APItoken, Qconfig.config["url"],
hub=Qconfig.config["hub"],
group=Qconfig.config["group"],
project=Qconfig.config["project"])
except ImportError as ex:
msg = 'Error in loading Qconfig.py!. Error = {}\n'.format(ex)
sys.stdout.write(msg)
sys.stdout.flush()
return False
if api_info is True:
api = self.__qp.get_api()
sys.stdout.write('<IBM Quantum Experience API information>\n')
sys.stdout.flush()
sys.stdout.write('Version: {0}\n'.format(api.api_version()))
sys.stdout.write('User jobs (last 5):\n')
jobs = api.get_jobs(limit=500)
def format_date(job_item):
'''
format
'''
return datetime.strptime(job_item['creationDate'],
'%Y-%m-%dT%H:%M:%S.%fZ')
sortedjobs = sorted(jobs,
key=format_date)
sys.stdout.write(' {0:<32} {1:<24} {2:<9} {3}\n'
.format('id',
'creationDate',
'status',
'backend'))
sys.stdout.write('{:-^94}\n'.format(""))
for job in sortedjobs[-5:]:
sys.stdout.write(' {0:<32} {1:<24} {2:<9} {3}\n'
.format(job['id'],
job['creationDate'],
job['status'],
job['backend']['name']))
sys.stdout.write('There are {0} jobs on the server\n'
.format(len(jobs)))
sys.stdout.write('Credits: {0}\n'
.format(api.get_my_credits()))
sys.stdout.flush()
self.backends = self.__qp.available_backends()
status = self.__qp.get_backend_status(self.backend)
if 'available' in status:
if status['available'] is False:
return False
return True
def set_config(self, config=None):
'''
set config
'''
if config is None:
config = {}
if 'backend' in config:
self.backend = str(config['backend'])
if 'local_' in self.backend:
self.remote = False
else:
self.remote = True
if 'remote' in config:
self.remote = config['remote']
if 'qubits' in config:
self.qubits = int(config['qubits'])
return True
def _progress(self, phasename, text):
self.phase.append([str(phasename), str(text)])
text = "Phase {0}: {1}".format(phasename, text)
sys.stdout.write("{}\n".format(text))
sys.stdout.flush()
def _init_circuit(self):
self._progress('1', 'Initialize quantum registers and circuit')
qubits = self.qubits
quantum_registers = [
{"name": "cin", "size": 1},
{"name": "qa", "size": qubits},
{"name": "qb", "size": qubits},
{"name": "cout", "size": 1}
]
classical_registers = [
{"name": "ans", "size": qubits + 1}
]
if 'cin' in self.__qp.get_quantum_register_names():
self.__qp.destroy_quantum_registers(quantum_registers)
self.__qp.destroy_classical_registers(classical_registers)
q_r = self.__qp.create_quantum_registers(quantum_registers)
c_r = self.__qp.create_classical_registers(classical_registers)
self.__qp.create_circuit("qcirc", q_r, c_r)
def _create_circuit_qadd(self):
# quantum ripple-carry adder from Cuccaro et al, quant-ph/0410184
def majority(circuit, q_a, q_b, q_c):
'''
majority
'''
circuit.cx(q_c, q_b)
circuit.cx(q_c, q_a)
circuit.ccx(q_a, q_b, q_c)
def unmaj(circuit, q_a, q_b, q_c):
'''
unmajority
'''
circuit.ccx(q_a, q_b, q_c)
circuit.cx(q_c, q_a)
circuit.cx(q_a, q_b)
def adder(circuit, c_in, q_a, q_b, c_out, qubits):
'''
adder
'''
# pylint: disable=too-many-arguments
majority(circuit, c_in[0], q_b[0], q_a[0])
for i in range(qubits - 1):
majority(circuit, q_a[i], q_b[i + 1], q_a[i + 1])
circuit.cx(q_a[qubits - 1], c_out[0])
for i in range(qubits - 1)[::-1]:
unmaj(circuit, q_a[i], q_b[i + 1], q_a[i + 1])
unmaj(circuit, c_in[0], q_b[0], q_a[0])
if 'add' not in self.__qp.get_circuit_names():
[c_in, q_a, q_b, c_out] = map(self.__qp.get_quantum_register,
["cin", "qa", "qb", "cout"])
ans = self.__qp.get_classical_register('ans')
qadder = self.__qp.create_circuit("qadd",
[c_in, q_a, q_b, c_out],
[ans])
adder(qadder, c_in, q_a, q_b, c_out, self.qubits)
return 'add' in self.__qp.get_circuit_names()
def _create_circuit_qsub(self):
circuit_names = self.__qp.get_circuit_names()
if 'qsub' not in circuit_names:
if 'qadd' not in circuit_names:
self._create_circuit_qadd()
# subtractor circuit
self.__qp.add_circuit('qsub', self.__qp.get_circuit('qadd'))
qsubtractor = self.__qp.get_circuit('qsub')
qsubtractor.reverse()
return 'qsub' in self.__qp.get_circuit_names()
def _qadd(self, input_a, input_b=None, subtract=False, observe=False):
# pylint: disable=too-many-locals
def measure(circuit, q_b, c_out, ans):
'''
measure
'''
circuit.barrier()
for i in range(self.qubits):
circuit.measure(q_b[i], ans[i])
circuit.measure(c_out[0], ans[self.qubits])
def char2q(circuit, cbit, qbit):
'''
char2q
'''
if cbit == '1':
circuit.x(qbit)
elif cbit == 'H':
circuit.h(qbit)
self.shots = 5 * (2**self.qubits)
def input_state(circuit, input_a, input_b=None):
'''
input state
'''
input_a = input_a[::-1]
for i in range(self.qubits):
char2q(circuit, input_a[i], q_a[i])
if input_b is not None:
input_b = input_b[::-1]
for i in range(self.qubits):
char2q(circuit, input_b[i], q_b[i])
def reset_input(circuit, c_in, q_a, c_out):
'''
reset input
'''
circuit.reset(c_in)
circuit.reset(c_out)
for i in range(self.qubits):
circuit.reset(q_a[i])
# get registers
[c_in, q_a, q_b, c_out] = map(self.__qp.get_quantum_register,
["cin", "qa", "qb", "cout"])
ans = self.__qp.get_classical_register('ans')
qcirc = self.__qp.get_circuit('qcirc')
self._progress('2',
'Define input state ({})'
.format('QADD' if subtract is False else 'QSUB'))
if input_b is not None:
if subtract is True:
# subtract
input_state(qcirc, input_b, input_a)
else:
# add
input_state(qcirc, input_a, input_b)
else:
reset_input(qcirc, c_in, q_a, c_out)
input_state(qcirc, input_a)
self._progress('3',
'Define quantum circuit ({})'
.format('QADD' if subtract is False else 'QSUB'))
if subtract is True:
self._create_circuit_qsub()
qcirc.extend(self.__qp.get_circuit('qsub'))
else:
self._create_circuit_qadd()
qcirc.extend(self.__qp.get_circuit('qadd'))
if observe is True:
measure(qcirc, q_b, c_out, ans)
def _qsub(self, input_a, input_b=None, observe=False):
self._qadd(input_a, input_b, subtract=True, observe=observe)
def _qope(self, input_a, operator, input_b=None, observe=False):
if operator == '+':
return self._qadd(input_a, input_b, observe=observe)
elif operator == '-':
return self._qsub(input_a, input_b, observe=observe)
return None
def _compile(self, name, cross_backend=None, print_qasm=False):
self._progress('4', 'Compile quantum circuit')
coupling_map = None
if cross_backend is not None:
backend_conf = self.__qp.get_backend_configuration(cross_backend)
coupling_map = backend_conf.get('coupling_map', None)
if coupling_map is None:
sys.stdout.write('backend: {} coupling_map not found'
.format(cross_backend))
qobj = self.__qp.compile([name],
backend=self.backend,
shots=self.shots,
seed=1,
coupling_map=coupling_map)
if print_qasm is True:
sys.stdout.write(self.__qp.get_compiled_qasm(qobj, 'qcirc'))
sys.stdout.flush()
return qobj
def _run(self, qobj):
self._progress('5', 'Run quantum circuit (wait for answer)')
result = self.__qp.run(qobj, wait=5, timeout=100000)
return result
def _run_async(self, qobj):
'''
_run_async
'''
self._progress('5', 'Run quantum circuit')
self.wait = True
def async_result(result):
'''
async call back
'''
self.wait = False
self.last = self.result_parse(result)
self.__qp.run_async(qobj,
wait=5, timeout=100000, callback=async_result)
def _is_regular_number(self, numstring, base):
'''
returns input binary format string or None.
'''
if base == 'bin':
binstring = numstring
elif base == 'dec':
if numstring == 'H':
binstring = 'H'*self.qubits
else:
binstring = format(int(numstring), "0{}b".format(self.qubits))
if len(binstring) != self.qubits:
return None
return binstring
def get_seq(self, text, base='dec'):
'''
convert seq and check it
if text is invalid, return the list of length 0.
'''
operators = u'(\\+|\\-)'
seq = re.split(operators, text)
# length check
if len(seq) % 2 == 0 or len(seq) == 1:
return []
# regex
if base == 'bin':
regex = re.compile(r'[01H]+')
else:
regex = re.compile(r'(^(?!.H)[0-9]+|H)')
for i in range(0, len(seq), 2):
match = regex.match(seq[i])
if match is None:
return []
num = match.group(0)
seq[i] = self._is_regular_number(num, base)
if seq[i] is None:
return []
return seq
def result_parse(self, result):
'''
result_parse
'''
data = result.get_data("qcirc")
sys.stdout.write("job id: {0}\n".format(result.get_job_id()))
sys.stdout.write("raw result: {0}\n".format(data))
sys.stdout.write("{:=^40}\n".format("answer"))
counts = data['counts']
sortedcounts = sorted(counts.items(),
key=lambda x: -x[1])
sortedans = []
for count in sortedcounts:
if count[0][0] == '1':
ans = 'OR'
else:
ans = str(int(count[0][-self.qubits:], 2))
sortedans.append(ans)
sys.stdout.write('Dec: {0:>2} Bin: {1} Count: {2} \n'
.format(ans, str(count[0]), str(count[1])))
sys.stdout.write('{0:d} answer{1}\n'
.format(len(sortedans),
'' if len(sortedans) == 1 else 's'))
sys.stdout.write("{:=^40}\n".format(""))
if 'time' in data:
sys.stdout.write("time: {0:<3} sec\n".format(data['time']))
sys.stdout.write("All process done.\n")
sys.stdout.flush()
uniqanswer = sorted(set(sortedans), key=sortedans.index)
ans = ",".join(uniqanswer)
return [str(result), ans]
def exec_calc(self, text, base='dec', wait_result=False):
'''
exec_calc
'''
seq = self.get_seq(text, base)
print('QC seq:', seq)
if seq == []:
return ["Syntax error", None]
# fail message
fail_msg = None
try:
self._init_circuit()
numbers = seq[0::2] # slice even index
i = 1
observe = False
for oper in seq[1::2]: # slice odd index
if i == len(numbers) - 1:
observe = True
if i == 1:
self._qope(numbers[0], oper, numbers[1], observe=observe)
else:
self._qope(numbers[i], oper, observe=observe)
i = i + 1
qobj = self._compile('qcirc')
if wait_result is True:
[status, ans] = self.result_parse(self._run(qobj))
else:
self._run_async(qobj)
[status, ans] = [
'Wait. Calculating on {0}'.format(self.backend),
'...'
]
except QISKitError as ex:
fail_msg = ('There was an error in the circuit!. Error = {}\n'
.format(ex))
except RegisterSizeError as ex:
fail_msg = ('Error in the number of registers!. Error = {}\n'
.format(ex))
if fail_msg is not None:
sys.stdout.write(fail_msg)
sys.stdout.flush()
return ["FAIL", None]
return [status, ans]
|
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 the Layout Score pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import CXGate
from qiskit.transpiler.passes import Layout2qDistance
from qiskit.transpiler import CouplingMap, Layout
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.target import Target
from qiskit.test import QiskitTestCase
class TestLayoutScoreError(QiskitTestCase):
"""Test error-ish of Layout Score"""
def test_no_layout(self):
"""No Layout. Empty Circuit CouplingMap map: None. Result: None"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
coupling = CouplingMap()
layout = None
dag = circuit_to_dag(circuit)
pass_ = Layout2qDistance(coupling)
pass_.property_set["layout"] = layout
pass_.run(dag)
self.assertIsNone(pass_.property_set["layout_score"])
class TestTrivialLayoutScore(QiskitTestCase):
"""Trivial layout scenarios"""
def test_no_cx(self):
"""Empty Circuit CouplingMap map: None. Result: 0"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
coupling = CouplingMap()
layout = Layout().generate_trivial_layout(qr)
dag = circuit_to_dag(circuit)
pass_ = Layout2qDistance(coupling)
pass_.property_set["layout"] = layout
pass_.run(dag)
self.assertEqual(pass_.property_set["layout_score"], 0)
def test_swap_mapped_true(self):
"""Mapped circuit. Good Layout
qr0 (0):--(+)---(+)-
| |
qr1 (1):---.-----|--
|
qr2 (2):---------.--
CouplingMap map: [1]--[0]--[2]
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[2])
coupling = CouplingMap([[0, 1], [0, 2]])
layout = Layout().generate_trivial_layout(qr)
dag = circuit_to_dag(circuit)
pass_ = Layout2qDistance(coupling)
pass_.property_set["layout"] = layout
pass_.run(dag)
self.assertEqual(pass_.property_set["layout_score"], 0)
def test_swap_mapped_false(self):
"""Needs [0]-[1] in a [0]--[2]--[1] Result:1
qr0:--(+)--
|
qr1:---.---
CouplingMap map: [0]--[2]--[1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
coupling = CouplingMap([[0, 2], [2, 1]])
layout = Layout().generate_trivial_layout(qr)
dag = circuit_to_dag(circuit)
pass_ = Layout2qDistance(coupling)
pass_.property_set["layout"] = layout
pass_.run(dag)
self.assertEqual(pass_.property_set["layout_score"], 1)
def test_swap_mapped_true_target(self):
"""Mapped circuit. Good Layout
qr0 (0):--(+)---(+)-
| |
qr1 (1):---.-----|--
|
qr2 (2):---------.--
CouplingMap map: [1]--[0]--[2]
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[2])
target = Target()
target.add_instruction(CXGate(), {(0, 1): None, (0, 2): None})
layout = Layout().generate_trivial_layout(qr)
dag = circuit_to_dag(circuit)
pass_ = Layout2qDistance(target)
pass_.property_set["layout"] = layout
pass_.run(dag)
self.assertEqual(pass_.property_set["layout_score"], 0)
def test_swap_mapped_false_target(self):
"""Needs [0]-[1] in a [0]--[2]--[1] Result:1
qr0:--(+)--
|
qr1:---.---
CouplingMap map: [0]--[2]--[1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
target = Target()
target.add_instruction(CXGate(), {(0, 2): None, (2, 1): None})
layout = Layout().generate_trivial_layout(qr)
dag = circuit_to_dag(circuit)
pass_ = Layout2qDistance(target)
pass_.property_set["layout"] = layout
pass_.run(dag)
self.assertEqual(pass_.property_set["layout_score"], 1)
if __name__ == "__main__":
unittest.main()
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
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([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)
### added x gate ###
qc.x(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
### added z gate ###
qc.z(1)
qc.h(1)
return qc
|
https://github.com/quantastica/quantum-circuit
|
quantastica
|
from qiskit import QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram, plot_state_qsphere
# We create a quantum circuit with 2 qubits and 2 classical bits
qc1 = QuantumCircuit(2, 2)
# We apply the Hadamard gate to the first qubit
qc1.h(0)
# We apply the CNOT gate to the first and second qubits
qc1.cx(0, 1)
# We draw the circuit
qc1.draw(output='mpl')
# We execute the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
result = execute(qc1, backend).result()
statevector = result.get_statevector()
# We plot the results
plot_state_qsphere(statevector)
# We create a quantum circuit with 2 qubits and 2 classical bits
qc2 = QuantumCircuit(2, 2)
# We initialize the input state to |01>
qc2.x(0)
qc2.barrier()
# We apply the Hadamard gate to the first qubit
qc2.h(0)
# We apply the CNOT gate to the first and second qubits
qc2.cx(0, 1)
qc2.barrier()
# We draw the circuit
qc2.draw(output='mpl')
# We execute the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
result = execute(qc2, backend).result()
statevector = result.get_statevector()
# We plot the results
plot_state_qsphere(statevector)
# We create a quantum circuit with 2 qubits and 2 classical bits
qc3 = QuantumCircuit(2, 2)
# We initialize the input state to |10>
qc3.x(1)
qc3.barrier()
# We apply the Hadamard gate to the first qubit
qc3.h(0)
# We apply the CNOT gate to the first and second qubits
qc3.cx(0, 1)
qc3.barrier()
# We draw the circuit
qc3.draw(output='mpl')
# We execute the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
result = execute(qc3, backend).result()
statevector = result.get_statevector()
# We plot the results
plot_state_qsphere(statevector)
# We create a quantum circuit with 2 qubits and 2 classical bits
qc4 = QuantumCircuit(2, 2)
# We initialize the input state to |11>
qc4.x(0)
qc4.x(1)
qc4.barrier()
# We apply the Hadamard gate to the first qubit
qc4.h(0)
# We apply the CNOT gate to the first and second qubits
qc4.cx(0, 1)
qc4.barrier()
# We draw the circuit
qc4.draw(output='mpl')
# We execute the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
result = execute(qc4, backend).result()
statevector = result.get_statevector()
# We plot the results
plot_state_qsphere(statevector)
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, IBMQ, QuantumRegister, ClassicalRegister
from qiskit import IBMQ, BasicAer
from IPython.core.display import Image, display
simulator = Aer.get_backend('qasm_simulator')
# Alice prepares the qubits
input_register = QuantumRegister(1, "x")
output_register = QuantumRegister(1, "f(x)")
classical_register = ClassicalRegister(1, "c")
circuit_Deutsch = QuantumCircuit(input_register, output_register, classical_register)
# Prepare the qubit in the output register in the |1> state
circuit_Deutsch.x(output_register[0])
# Hadamard gates applied on input and output registers
circuit_Deutsch.h(input_register[0])
circuit_Deutsch.h(output_register[0])
# Add a barrier
circuit_Deutsch.barrier()
# Draw the circuit
circuit_Deutsch.draw(output="mpl")
# Bob's four functions/circuits
# The first option: constant f(0) = f(1) = 0
circuit_Bob1 = QuantumCircuit(input_register, output_register)
circuit_Bob1.barrier()
# The second option: constant f(0) = f(1) = 1
circuit_Bob2 = QuantumCircuit(input_register, output_register)
circuit_Bob2.cx(input_register[0], output_register)
circuit_Bob2.x(input_register[0])
circuit_Bob2.cx(input_register[0], output_register)
circuit_Bob2.x(input_register[0])
circuit_Bob2.barrier()
# The third option: balanced f(0) = 0 & f(1) = 1
circuit_Bob3 = QuantumCircuit(input_register, output_register)
circuit_Bob3.cx(input_register[0], output_register)
circuit_Bob3.barrier()
# The fourth option: balanced f(0) = 1 & f(1) = 0
circuit_Bob4 = QuantumCircuit(input_register, output_register)
circuit_Bob4.x(input_register[0])
circuit_Bob4.cx(input_register[0], output_register)
circuit_Bob4.x(input_register[0])
circuit_Bob4.barrier()
import random
list_options_Bob = [circuit_Bob2,circuit_Bob2, circuit_Bob3, circuit_Bob4]
circuit_Bob_choice = random.choice(list_options_Bob)
# Add the chosen circuit to the main circuit
circuit_Deutsch += circuit_Bob_choice
# Draw the circuit
print("The circuit with Bob's chosen function")
circuit_Deutsch.draw(output="mpl")
# Alice's final operations
circuit_Deutsch.h(input_register[0])
circuit_Deutsch.measure(input_register[0], classical_register[0])
# Draw the final version of the circuit
print("The final version of the circuit")
circuit_Deutsch.draw(output="mpl")
# The execution of the circuit
counts = execute(circuit_Deutsch, simulator, shots=1).result().get_counts()
# Finding the only key/measurement outcome
measurement_result = list(counts.keys())[0]
print("The results of the measurements: {}".format(counts))
print("The final result is: {}".format(measurement_result))
# From the final measurement result, Alice understands if
# the Bob's chosen function balanced or constant
if measurement_result == '0':
print("Bob's chosen function was constant")
elif measurement_result == '1':
print("Bob's chosen function was balanced")
# Alice: qubit preparation
input_register = QuantumRegister(3, "x")
output_register = QuantumRegister(1, "f(x)")
classical_register = ClassicalRegister(3, "c")
circuit_Deutsch_Jozsa = QuantumCircuit(input_register, output_register, classical_register)
# Prepare the qubit in the output register in the |1> state
circuit_Deutsch_Jozsa.x(output_register[0])
# Hadamard gates on both input and output registers
circuit_Deutsch_Jozsa.h(input_register) # Hadamard gate is applied to all qubits in the input_register
circuit_Deutsch_Jozsa.h(output_register[0])
# Add a barrier
circuit_Deutsch_Jozsa.barrier()
circuit_Deutsch_Jozsa.draw('mpl')
# Circuit for the constant function
circtuit_Deutsch_Jozsa_constant = QuantumCircuit(input_register, output_register, classical_register)
circtuit_Deutsch_Jozsa_constant += circuit_Deutsch_Jozsa
# Implementing the f(x) = 1 constant function
circtuit_Deutsch_Jozsa_constant.x(output_register[0])
# Add a barrier
circtuit_Deutsch_Jozsa_constant.barrier()
# Final Hadamard gates applied on all qubits in the input register
circtuit_Deutsch_Jozsa_constant.h(input_register)
# Measurements executed for all qubits in the input register
circtuit_Deutsch_Jozsa_constant.measure(input_register, classical_register)
# Draw the circuit
circtuit_Deutsch_Jozsa_constant.draw(output="mpl")
# A function that will help Alice to define if
# the chosen function was balanced or constant
def is_balanced_or_constant(circuit, bakend):
# The execution of the circuit
counts = execute(circuit, bakend, shots=1).result().get_counts()
# Finding the only key/measurement outcome
measurement_result = list(counts.keys())[0]
print("The results of the measurements: {}".format(counts))
print("The final result is: {}".format(measurement_result))
# Alice checks if Bob's function was constant or balanced
if '000' in counts:
print("Bob's chosen function was constant")
else:
print("Bob's chosen function was balanced")
# Alice uses is_balanced_or_constant() function
is_balanced_or_constant(circtuit_Deutsch_Jozsa_constant, simulator)
# Circuit for the balanced case
circtuit_Deutsch_Jozsa_balanced = QuantumCircuit(input_register, output_register, classical_register)
circtuit_Deutsch_Jozsa_balanced += circuit_Deutsch_Jozsa
# implementing the balanced function
circtuit_Deutsch_Jozsa_balanced.cx(input_register[0], output_register[0])
circtuit_Deutsch_Jozsa_balanced.cx(input_register[1], output_register[0])
circtuit_Deutsch_Jozsa_balanced.cx(input_register[2], output_register[0])
# add a barrier
circtuit_Deutsch_Jozsa_balanced.barrier()
# final Hadamard gates applied on all qubits in the input register
circtuit_Deutsch_Jozsa_balanced.h(input_register)
# measurements executed for all qubits in the input register
circtuit_Deutsch_Jozsa_balanced.measure(input_register, classical_register)
# draw the circuit
circtuit_Deutsch_Jozsa_balanced.draw(output="mpl")
# Alice uses is_balanced_or_constant() function
simulator = Aer.get_backend('qasm_simulator')
is_balanced_or_constant(circtuit_Deutsch_Jozsa_balanced, simulator)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.compiler import transpile
from qiskit.transpiler import PassManager
circ = QuantumCircuit(3)
circ.ccx(0, 1, 2)
circ.draw(output='mpl')
from qiskit.transpiler.passes import Unroller
pass_ = Unroller(['u1', 'u2', 'u3', 'cx'])
pm = PassManager(pass_)
new_circ = pm.run(circ)
new_circ.draw(output='mpl')
from qiskit.transpiler import passes
[pass_ for pass_ in dir(passes) if pass_[0].isupper()]
from qiskit.transpiler import CouplingMap, Layout
from qiskit.transpiler.passes import BasicSwap, LookaheadSwap, StochasticSwap
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
circuit = QuantumCircuit(7)
circuit.h(3)
circuit.cx(0, 6)
circuit.cx(6, 0)
circuit.cx(0, 1)
circuit.cx(3, 1)
circuit.cx(3, 0)
coupling_map = CouplingMap(couplinglist=coupling)
bs = BasicSwap(coupling_map=coupling_map)
pass_manager = PassManager(bs)
basic_circ = pass_manager.run(circuit)
ls = LookaheadSwap(coupling_map=coupling_map)
pass_manager = PassManager(ls)
lookahead_circ = pass_manager.run(circuit)
ss = StochasticSwap(coupling_map=coupling_map)
pass_manager = PassManager(ss)
stochastic_circ = pass_manager.run(circuit)
circuit.draw(output='mpl')
basic_circ.draw(output='mpl')
lookahead_circ.draw(output='mpl')
stochastic_circ.draw(output='mpl')
import math
from qiskit.providers.fake_provider import FakeTokyo
backend = FakeTokyo() # mimics the tokyo device in terms of coupling map and basis gates
qc = QuantumCircuit(10)
random_state = [
1 / math.sqrt(4) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
0,
0,
0,
0,
0,
0,
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(8) * complex(0, 1),
0,
0,
0,
0,
1 / math.sqrt(4) * complex(1, 0),
1 / math.sqrt(8) * complex(1, 0)]
qc.initialize(random_state, range(4))
qc.draw()
optimized_0 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=0)
print('gates = ', optimized_0.count_ops())
print('depth = ', optimized_0.depth())
optimized_1 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=1)
print('gates = ', optimized_1.count_ops())
print('depth = ', optimized_1.depth())
optimized_2 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=2)
print('gates = ', optimized_2.count_ops())
print('depth = ', optimized_2.depth())
optimized_3 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=3)
print('gates = ', optimized_3.count_ops())
print('depth = ', optimized_3.depth())
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
circ.draw(output='mpl')
from qiskit.converters import circuit_to_dag
from qiskit.tools.visualization import dag_drawer
dag = circuit_to_dag(circ)
dag_drawer(dag)
dag.op_nodes()
node = dag.op_nodes()[3]
print("node name: ", node.name)
print("node op: ", node.op)
print("node qargs: ", node.qargs)
print("node cargs: ", node.cargs)
print("node condition: ", node.op.condition)
from qiskit.circuit.library import HGate
dag.apply_operation_back(HGate(), qargs=[q[0]])
dag_drawer(dag)
from qiskit.circuit.library import CCXGate
dag.apply_operation_front(CCXGate(), qargs=[q[0], q[1], q[2]], cargs=[])
dag_drawer(dag)
from qiskit.circuit.library import CHGate, U2Gate, CXGate
mini_dag = DAGCircuit()
p = QuantumRegister(2, "p")
mini_dag.add_qreg(p)
mini_dag.apply_operation_back(CHGate(), qargs=[p[1], p[0]])
mini_dag.apply_operation_back(U2Gate(0.1, 0.2), qargs=[p[1]])
# substitute the cx node with the above mini-dag
cx_node = dag.op_nodes(op=CXGate).pop()
dag.substitute_node_with_dag(node=cx_node, input_dag=mini_dag, wires=[p[0], p[1]])
dag_drawer(dag)
from qiskit.converters import dag_to_circuit
circuit = dag_to_circuit(dag)
circuit.draw(output='mpl')
from copy import copy
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.transpiler import Layout
from qiskit.circuit.library import SwapGate
class BasicSwap(TransformationPass):
"""Maps (with minimum effort) a DAGCircuit onto a `coupling_map` adding swap gates."""
def __init__(self,
coupling_map,
initial_layout=None):
"""Maps a DAGCircuit onto a `coupling_map` using swap gates.
Args:
coupling_map (CouplingMap): Directed graph represented a coupling map.
initial_layout (Layout): initial layout of qubits in mapping
"""
super().__init__()
self.coupling_map = coupling_map
self.initial_layout = initial_layout
def run(self, dag):
"""Runs the BasicSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
Raises:
TranspilerError: if the coupling map or the layout are not
compatible with the DAG.
"""
new_dag = DAGCircuit()
for qreg in dag.qregs.values():
new_dag.add_qreg(qreg)
for creg in dag.cregs.values():
new_dag.add_creg(creg)
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
if len(dag.qubits) != len(self.initial_layout):
raise TranspilerError('The layout does not match the amount of qubits in the DAG')
if len(self.coupling_map.physical_qubits) != len(self.initial_layout):
raise TranspilerError(
"Mappers require to have the layout to be the same size as the coupling map")
canonical_register = dag.qregs['q']
trivial_layout = Layout.generate_trivial_layout(canonical_register)
current_layout = trivial_layout.copy()
for layer in dag.serial_layers():
subdag = layer['graph']
for gate in subdag.two_qubit_ops():
physical_q0 = current_layout[gate.qargs[0]]
physical_q1 = current_layout[gate.qargs[1]]
if self.coupling_map.distance(physical_q0, physical_q1) != 1:
# Insert a new layer with the SWAP(s).
swap_layer = DAGCircuit()
swap_layer.add_qreg(canonical_register)
path = self.coupling_map.shortest_undirected_path(physical_q0, physical_q1)
for swap in range(len(path) - 2):
connected_wire_1 = path[swap]
connected_wire_2 = path[swap + 1]
qubit_1 = current_layout[connected_wire_1]
qubit_2 = current_layout[connected_wire_2]
# create the swap operation
swap_layer.apply_operation_back(SwapGate(),
qargs=[qubit_1, qubit_2],
cargs=[])
# layer insertion
order = current_layout.reorder_bits(new_dag.qubits)
new_dag.compose(swap_layer, qubits=order)
# update current_layout
for swap in range(len(path) - 2):
current_layout.swap(path[swap], path[swap + 1])
order = current_layout.reorder_bits(new_dag.qubits)
new_dag.compose(subdag, qubits=order)
return new_dag
q = QuantumRegister(7, 'q')
in_circ = QuantumCircuit(q)
in_circ.h(q[0])
in_circ.cx(q[0], q[4])
in_circ.cx(q[2], q[3])
in_circ.cx(q[6], q[1])
in_circ.cx(q[5], q[0])
in_circ.rz(0.1, q[2])
in_circ.cx(q[5], q[0])
from qiskit.transpiler import PassManager
from qiskit.transpiler import CouplingMap
from qiskit import BasicAer
pm = PassManager()
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
coupling_map = CouplingMap(couplinglist=coupling)
pm.append([BasicSwap(coupling_map)])
out_circ = pm.run(in_circ)
in_circ.draw(output='mpl')
out_circ.draw(output='mpl')
import logging
logging.basicConfig(level='DEBUG')
from qiskit.providers.fake_provider import FakeTenerife
log_circ = QuantumCircuit(2, 2)
log_circ.h(0)
log_circ.h(1)
log_circ.h(1)
log_circ.x(1)
log_circ.cx(0, 1)
log_circ.measure([0,1], [0,1])
backend = FakeTenerife()
transpile(log_circ, backend);
logging.getLogger('qiskit.transpiler').setLevel('INFO')
transpile(log_circ, backend);
# Change log level back to DEBUG
logging.getLogger('qiskit.transpiler').setLevel('DEBUG')
# Transpile multiple circuits
circuits = [log_circ, log_circ]
transpile(circuits, backend);
formatter = logging.Formatter('%(name)s - %(processName)-10s - %(levelname)s: %(message)s')
handler = logging.getLogger().handlers[0]
handler.setFormatter(formatter)
transpile(circuits, backend);
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.problems.second_quantization.lattice.lattices import LineLattice
from qiskit_nature.problems.second_quantization.lattice.models import FermiHubbardModel
line = LineLattice(2)
fermi = FermiHubbardModel.uniform_parameters(line, 2.0, 4.0, 3.0)
print(fermi.second_q_ops()) # Note: the trailing `s`
from qiskit_nature.second_q.hamiltonians.lattices import LineLattice
from qiskit_nature.second_q.hamiltonians import FermiHubbardModel
line = LineLattice(2)
fermi = FermiHubbardModel(line.uniform_parameters(2.0, 4.0), 3.0)
print(fermi.second_q_op()) # Note: NO trailing `s`
import numpy as np
from qiskit_nature.problems.second_quantization.lattice.models import FermiHubbardModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
fermi = FermiHubbardModel.from_parameters(interaction, 3.0)
print(fermi.second_q_ops()) # Note: the trailing `s`
import numpy as np
from qiskit_nature.second_q.hamiltonians.lattices import Lattice
from qiskit_nature.second_q.hamiltonians import FermiHubbardModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
lattice = Lattice.from_adjacency_matrix(interaction)
fermi = FermiHubbardModel(lattice, 3.0)
print(fermi.second_q_op()) # Note: NO trailing `s`
from qiskit_nature.problems.second_quantization.lattice.lattices import LineLattice
from qiskit_nature.problems.second_quantization.lattice.models import IsingModel
line = LineLattice(2)
ising = IsingModel.uniform_parameters(line, 2.0, 4.0)
print(ising.second_q_ops()) # Note: the trailing `s`
from qiskit_nature.second_q.hamiltonians.lattices import LineLattice
from qiskit_nature.second_q.hamiltonians import IsingModel
line = LineLattice(2)
ising = IsingModel(line.uniform_parameters(2.0, 4.0))
print(ising.second_q_op()) # Note: NO trailing `s`
import numpy as np
from qiskit_nature.problems.second_quantization.lattice.models import IsingModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
ising = IsingModel.from_parameters(interaction)
print(ising.second_q_ops()) # Note: the trailing `s`
import numpy as np
from qiskit_nature.second_q.hamiltonians.lattices import Lattice
from qiskit_nature.second_q.hamiltonians import IsingModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
lattice = Lattice.from_adjacency_matrix(interaction)
ising = IsingModel(lattice)
print(ising.second_q_op()) # Note: NO trailing `s`
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import HGate
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.h(1)
custom = qc1.to_gate().control(2)
qc2 = QuantumCircuit(4)
qc2.append(custom, [0, 3, 1, 2])
qc2.draw('mpl')
|
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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a Statevector
state = Statevector(qc)
plot_state_city(state)
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2022-2023 Qiskit on IQM developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Testing IQM backend.
"""
from typing import Optional
import pytest
from qiskit import QuantumCircuit
from qiskit.compiler import transpile
from qiskit.providers import Options
from iqm.qiskit_iqm.iqm_backend import IQMBackendBase
class DummyIQMBackend(IQMBackendBase):
"""Dummy implementation for abstract methods of IQMBacked, so that instances can be created
and the rest of functionality tested."""
@classmethod
def _default_options(cls) -> Options:
return Options()
@property
def max_circuits(self) -> Optional[int]:
return None
def run(self, run_input, **options):
...
@pytest.fixture
def backend(linear_architecture_3q):
return DummyIQMBackend(linear_architecture_3q)
def test_qubit_name_to_index_to_qubit_name(adonis_architecture_shuffled_names):
backend = DummyIQMBackend(adonis_architecture_shuffled_names)
correct_idx_name_associations = set(enumerate(['QB1', 'QB2', 'QB3', 'QB4', 'QB5']))
assert all(backend.index_to_qubit_name(idx) == name for idx, name in correct_idx_name_associations)
assert all(backend.qubit_name_to_index(name) == idx for idx, name in correct_idx_name_associations)
assert backend.index_to_qubit_name(7) is None
assert backend.qubit_name_to_index('Alice') is None
def test_transpile(backend):
circuit = QuantumCircuit(3, 3)
circuit.h(0)
circuit.cx(0, 1)
circuit.cx(1, 2)
circuit.cx(2, 0)
circuit_transpiled = transpile(circuit, backend=backend)
cmap = backend.coupling_map.get_edges()
for instruction, qubits, _ in circuit_transpiled.data:
assert instruction.name in ('r', 'cz')
if instruction.name == 'cz':
idx1 = circuit_transpiled.find_bit(qubits[0]).index
idx2 = circuit_transpiled.find_bit(qubits[1]).index
assert ((idx1, idx2) in cmap) or ((idx2, idx1) in cmap)
def test_validate_compatible_architecture(
adonis_architecture, adonis_architecture_shuffled_names, linear_architecture_3q
):
backend = DummyIQMBackend(adonis_architecture)
assert backend.validate_compatible_architecture(adonis_architecture) is True
assert backend.validate_compatible_architecture(adonis_architecture_shuffled_names) is True
assert backend.validate_compatible_architecture(linear_architecture_3q) is False
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import *
qc = QuantumCircuit(2)
qc.h(i)
qc.crz (PI/4, 0, 1)
|
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
|
vandnaChaturvedi
|
from qiskit import QuantumCircuit, Aer, execute, IBMQ
from qiskit.utils import QuantumInstance
import numpy as np
from qiskit.algorithms import Shor
IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here
provider = IBMQ.get_provider(hub='ibm-q')
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1000)
my_shor = Shor(quantum_instance)
result_dict = my_shor.factor(15)
print(result_dict)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# 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 commutation checker class ."""
import unittest
import numpy as np
from qiskit import ClassicalRegister
from qiskit.test import QiskitTestCase
from qiskit.circuit import QuantumRegister, Parameter, Qubit
from qiskit.circuit import CommutationChecker
from qiskit.circuit.library import (
ZGate,
XGate,
CXGate,
CCXGate,
MCXGate,
RZGate,
Measure,
Barrier,
Reset,
LinearFunction,
)
class TestCommutationChecker(QiskitTestCase):
"""Test CommutationChecker class."""
def test_simple_gates(self):
"""Check simple commutation relations between gates, experimenting with
different orders of gates, different orders of qubits, different sets of
qubits over which gates are defined, and so on."""
comm_checker = CommutationChecker()
# should commute
res = comm_checker.commute(ZGate(), [0], [], CXGate(), [0, 1], [])
self.assertTrue(res)
# should not commute
res = comm_checker.commute(ZGate(), [1], [], CXGate(), [0, 1], [])
self.assertFalse(res)
# should not commute
res = comm_checker.commute(XGate(), [0], [], CXGate(), [0, 1], [])
self.assertFalse(res)
# should commute
res = comm_checker.commute(XGate(), [1], [], CXGate(), [0, 1], [])
self.assertTrue(res)
# should not commute
res = comm_checker.commute(XGate(), [1], [], CXGate(), [1, 0], [])
self.assertFalse(res)
# should commute
res = comm_checker.commute(XGate(), [0], [], CXGate(), [1, 0], [])
self.assertTrue(res)
# should commute
res = comm_checker.commute(CXGate(), [1, 0], [], XGate(), [0], [])
self.assertTrue(res)
# should not commute
res = comm_checker.commute(CXGate(), [1, 0], [], XGate(), [1], [])
self.assertFalse(res)
# should commute
res = comm_checker.commute(
CXGate(),
[1, 0],
[],
CXGate(),
[1, 0],
[],
)
self.assertTrue(res)
# should not commute
res = comm_checker.commute(
CXGate(),
[1, 0],
[],
CXGate(),
[0, 1],
[],
)
self.assertFalse(res)
# should commute
res = comm_checker.commute(
CXGate(),
[1, 0],
[],
CXGate(),
[1, 2],
[],
)
self.assertTrue(res)
# should not commute
res = comm_checker.commute(
CXGate(),
[1, 0],
[],
CXGate(),
[2, 1],
[],
)
self.assertFalse(res)
# should commute
res = comm_checker.commute(
CXGate(),
[1, 0],
[],
CXGate(),
[2, 3],
[],
)
self.assertTrue(res)
res = comm_checker.commute(XGate(), [2], [], CCXGate(), [0, 1, 2], [])
self.assertTrue(res)
res = comm_checker.commute(CCXGate(), [0, 1, 2], [], CCXGate(), [0, 2, 1], [])
self.assertFalse(res)
def test_passing_quantum_registers(self):
"""Check that passing QuantumRegisters works correctly."""
comm_checker = CommutationChecker()
qr = QuantumRegister(4)
# should commute
res = comm_checker.commute(CXGate(), [qr[1], qr[0]], [], CXGate(), [qr[1], qr[2]], [])
self.assertTrue(res)
# should not commute
res = comm_checker.commute(CXGate(), [qr[0], qr[1]], [], CXGate(), [qr[1], qr[2]], [])
self.assertFalse(res)
def test_caching_positive_results(self):
"""Check that hashing positive results in commutativity checker works as expected."""
comm_checker = CommutationChecker()
res = comm_checker.commute(ZGate(), [0], [], CXGate(), [0, 1], [])
self.assertTrue(res)
self.assertGreater(len(comm_checker.cache), 0)
def test_caching_negative_results(self):
"""Check that hashing negative results in commutativity checker works as expected."""
comm_checker = CommutationChecker()
res = comm_checker.commute(XGate(), [0], [], CXGate(), [0, 1], [])
self.assertFalse(res)
self.assertGreater(len(comm_checker.cache), 0)
def test_caching_different_qubit_sets(self):
"""Check that hashing same commutativity results over different qubit sets works as expected."""
comm_checker = CommutationChecker()
# All the following should be cached in the same way
# though each relation gets cached twice: (A, B) and (B, A)
comm_checker.commute(XGate(), [0], [], CXGate(), [0, 1], [])
comm_checker.commute(XGate(), [10], [], CXGate(), [10, 20], [])
comm_checker.commute(XGate(), [10], [], CXGate(), [10, 5], [])
comm_checker.commute(XGate(), [5], [], CXGate(), [5, 7], [])
self.assertEqual(len(comm_checker.cache), 2)
def test_gates_with_parameters(self):
"""Check commutativity between (non-parameterized) gates with parameters."""
comm_checker = CommutationChecker()
res = comm_checker.commute(RZGate(0), [0], [], XGate(), [0], [])
self.assertTrue(res)
res = comm_checker.commute(RZGate(np.pi / 2), [0], [], XGate(), [0], [])
self.assertFalse(res)
res = comm_checker.commute(RZGate(np.pi / 2), [0], [], RZGate(0), [0], [])
self.assertTrue(res)
def test_parameterized_gates(self):
"""Check commutativity between parameterized gates, both with free and with
bound parameters."""
comm_checker = CommutationChecker()
# gate that has parameters but is not considered parameterized
rz_gate = RZGate(np.pi / 2)
self.assertEqual(len(rz_gate.params), 1)
self.assertFalse(rz_gate.is_parameterized())
# gate that has parameters and is considered parameterized
rz_gate_theta = RZGate(Parameter("Theta"))
rz_gate_phi = RZGate(Parameter("Phi"))
self.assertEqual(len(rz_gate_theta.params), 1)
self.assertTrue(rz_gate_theta.is_parameterized())
# gate that has no parameters and is not considered parameterized
cx_gate = CXGate()
self.assertEqual(len(cx_gate.params), 0)
self.assertFalse(cx_gate.is_parameterized())
# We should detect that these gates commute
res = comm_checker.commute(rz_gate, [0], [], cx_gate, [0, 1], [])
self.assertTrue(res)
# We should detect that these gates commute
res = comm_checker.commute(rz_gate, [0], [], rz_gate, [0], [])
self.assertTrue(res)
# We should detect that parameterized gates over disjoint qubit subsets commute
res = comm_checker.commute(rz_gate_theta, [0], [], rz_gate_theta, [1], [])
self.assertTrue(res)
# We should detect that parameterized gates over disjoint qubit subsets commute
res = comm_checker.commute(rz_gate_theta, [0], [], rz_gate_phi, [1], [])
self.assertTrue(res)
# We should detect that parameterized gates over disjoint qubit subsets commute
res = comm_checker.commute(rz_gate_theta, [2], [], cx_gate, [1, 3], [])
self.assertTrue(res)
# However, for now commutativity checker should return False when checking
# commutativity between a parameterized gate and some other gate, when
# the two gates are over intersecting qubit subsets.
# This check should be changed if commutativity checker is extended to
# handle parameterized gates better.
res = comm_checker.commute(rz_gate_theta, [0], [], cx_gate, [0, 1], [])
self.assertFalse(res)
res = comm_checker.commute(rz_gate_theta, [0], [], rz_gate, [0], [])
self.assertFalse(res)
def test_measure(self):
"""Check commutativity involving measures."""
comm_checker = CommutationChecker()
# Measure is over qubit 0, while gate is over a disjoint subset of qubits
# We should be able to swap these.
res = comm_checker.commute(Measure(), [0], [0], CXGate(), [1, 2], [])
self.assertTrue(res)
# Measure and gate have intersecting set of qubits
# We should not be able to swap these.
res = comm_checker.commute(Measure(), [0], [0], CXGate(), [0, 2], [])
self.assertFalse(res)
# Measures over different qubits and clbits
res = comm_checker.commute(Measure(), [0], [0], Measure(), [1], [1])
self.assertTrue(res)
# Measures over different qubits but same classical bit
# We should not be able to swap these.
res = comm_checker.commute(Measure(), [0], [0], Measure(), [1], [0])
self.assertFalse(res)
# Measures over same qubits but different classical bit
# ToDo: can we swap these?
# Currently checker takes the safe approach and returns False.
res = comm_checker.commute(Measure(), [0], [0], Measure(), [0], [1])
self.assertFalse(res)
def test_barrier(self):
"""Check commutativity involving barriers."""
comm_checker = CommutationChecker()
# A gate should not commute with a barrier
# (at least if these are over intersecting qubit sets).
res = comm_checker.commute(Barrier(4), [0, 1, 2, 3], [], CXGate(), [1, 2], [])
self.assertFalse(res)
# Does it even make sense to have a barrier over a subset of qubits?
# Though in this case, it probably makes sense to say that barrier and gate can be swapped.
res = comm_checker.commute(Barrier(4), [0, 1, 2, 3], [], CXGate(), [5, 6], [])
self.assertTrue(res)
def test_reset(self):
"""Check commutativity involving resets."""
comm_checker = CommutationChecker()
# A gate should not commute with reset when the qubits intersect.
res = comm_checker.commute(Reset(), [0], [], CXGate(), [0, 2], [])
self.assertFalse(res)
# A gate should commute with reset when the qubits are disjoint.
res = comm_checker.commute(Reset(), [0], [], CXGate(), [1, 2], [])
self.assertTrue(res)
def test_conditional_gates(self):
"""Check commutativity involving conditional gates."""
comm_checker = CommutationChecker()
qr = QuantumRegister(3)
cr = ClassicalRegister(2)
# Currently, in all cases commutativity checker should returns False.
# This is definitely suboptimal.
res = comm_checker.commute(
CXGate().c_if(cr[0], 0), [qr[0], qr[1]], [], XGate(), [qr[2]], []
)
self.assertFalse(res)
res = comm_checker.commute(
CXGate().c_if(cr[0], 0), [qr[0], qr[1]], [], XGate(), [qr[1]], []
)
self.assertFalse(res)
res = comm_checker.commute(
CXGate().c_if(cr[0], 0), [qr[0], qr[1]], [], CXGate().c_if(cr[0], 0), [qr[0], qr[1]], []
)
self.assertFalse(res)
res = comm_checker.commute(
XGate().c_if(cr[0], 0), [qr[0]], [], XGate().c_if(cr[0], 1), [qr[0]], []
)
self.assertFalse(res)
res = comm_checker.commute(XGate().c_if(cr[0], 0), [qr[0]], [], XGate(), [qr[0]], [])
self.assertFalse(res)
def test_complex_gates(self):
"""Check commutativity involving more complex gates."""
comm_checker = CommutationChecker()
lf1 = LinearFunction([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
lf2 = LinearFunction([[1, 0, 0], [0, 0, 1], [0, 1, 0]])
# lf1 is equivalent to swap(0, 1), and lf2 to swap(1, 2).
# These do not commute.
res = comm_checker.commute(lf1, [0, 1, 2], [], lf2, [0, 1, 2], [])
self.assertFalse(res)
lf3 = LinearFunction([[0, 1, 0], [0, 0, 1], [1, 0, 0]])
lf4 = LinearFunction([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
# lf3 is permutation 1->2, 2->3, 3->1.
# lf3 is the inverse permutation 1->3, 2->1, 3->2.
# These commute.
res = comm_checker.commute(lf3, [0, 1, 2], [], lf4, [0, 1, 2], [])
self.assertTrue(res)
def test_c7x_gate(self):
"""Test wide gate works correctly."""
qargs = [Qubit() for _ in [None] * 8]
res = CommutationChecker().commute(XGate(), qargs[:1], [], XGate().control(7), qargs, [])
self.assertFalse(res)
def test_wide_gates_over_nondisjoint_qubits(self):
"""Test that checking wide gates does not lead to memory problems."""
res = CommutationChecker().commute(MCXGate(29), list(range(30)), [], XGate(), [0], [])
self.assertFalse(res)
res = CommutationChecker().commute(XGate(), [0], [], MCXGate(29), list(range(30)), [])
self.assertFalse(res)
def test_wide_gates_over_disjoint_qubits(self):
"""Test that wide gates still commute when they are over disjoint sets of qubits."""
res = CommutationChecker().commute(MCXGate(29), list(range(30)), [], XGate(), [30], [])
self.assertTrue(res)
res = CommutationChecker().commute(XGate(), [30], [], MCXGate(29), list(range(30)), [])
self.assertTrue(res)
if __name__ == "__main__":
unittest.main()
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
from qiskit.aqua.algorithms import NumPyMinimumEigensolver
from qiskit.optimization.algorithms import GroverOptimizer, MinimumEigenOptimizer
from qiskit.optimization.problems import QuadraticProgram
from qiskit import BasicAer
from docplex.mp.model import Model
backend = BasicAer.get_backend('statevector_simulator')
model = Model()
x0 = model.binary_var(name='x0')
x1 = model.binary_var(name='x1')
x2 = model.binary_var(name='x2')
model.minimize(-x0+2*x1-3*x2-2*x0*x2-1*x1*x2)
qp = QuadraticProgram()
qp.from_docplex(model)
print(qp.export_as_lp_string())
grover_optimizer = GroverOptimizer(6, num_iterations=10, quantum_instance=backend)
results = grover_optimizer.solve(qp)
print("x={}".format(results.x))
print("fval={}".format(results.fval))
import matplotlib.pyplot as plt
import matplotlib.axes as axes
%matplotlib inline
import numpy as np
import networkx as nx
from qiskit.aqua import QuantumInstance
from qiskit.optimization.applications.ising import max_cut, tsp
from qiskit.optimization.converters import IsingToQuadraticProgram
n = 4
num_qubits = n ** 2
ins = tsp.random_tsp(n, seed=123)
G = nx.Graph()
G.add_nodes_from(np.arange(0, n, 1))
colors = ['r' for node in G.nodes()]
pos = {k: v for k, v in enumerate(ins.coord)}
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=pos)
print('distance\n', ins.w)
qubitOp, offset = tsp.get_operator(ins)
print('Offset:', offset)
print('Ising Hamiltonian:')
print(qubitOp.print_details())
qp = QuadraticProgram()
qp.from_ising(qubitOp, offset, linear=True)
qp.to_docplex().prettyprint()
grover_optimizer = GroverOptimizer(6, num_iterations=10, quantum_instance=backend)
results = grover_optimizer.solve(qp)
print("x={}".format(results.x))
print("fval={}".format(results.fval))
# Test with classical EigenOptimizer
from qiskit.aqua.algorithms import NumPyMinimumEigensolver
from qiskit.optimization.algorithms import MinimumEigenOptimizer
exact_solver = MinimumEigenOptimizer(NumPyMinimumEigensolver())
exact_result = exact_solver.solve(qp)`
print("x={}".format(exact_result.x))
print("fval={}".format(exact_result.fval))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw, IQXSimple
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial')
draw(qc, style=IQXSimple())
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""
Quantum Tomography Module
Description:
This module contains functions for performing quantum state and quantum
process tomography. This includes:
- Functions for generating a set of circuits to
extract tomographically complete sets of measurement data.
- Functions for generating a tomography data set from the
results after the circuits have been executed on a backend.
- Functions for reconstructing a quantum state, or quantum process
(Choi-matrix) from tomography data sets.
Reconstruction Methods:
Currently implemented reconstruction methods are
- Linear inversion by weighted least-squares fitting.
- Fast maximum likelihood reconstruction using ref [1].
References:
[1] J Smolin, JM Gambetta, G Smith, Phys. Rev. Lett. 108, 070502 (2012).
Open access: arXiv:1106.5458 [quant-ph].
Workflow:
The basic functions for performing state and tomography experiments are:
- `tomography_set`, `state_tomography_set`, and `process_tomography_set`
all generates data structures for tomography experiments.
- `create_tomography_circuits` generates the quantum circuits specified
in a `tomography_set` for performing state tomography of the output
- `tomography_data` extracts the results after executing the tomography
circuits and returns it in a data structure used by fitters for state
reconstruction.
- `fit_tomography_data` reconstructs a density matrix or Choi-matrix from
the a set of tomography data.
"""
import logging
from functools import reduce
from itertools import product
from re import match
import numpy as np
from qiskit import QuantumCircuit
from qiskit.exceptions import QiskitError
from qiskit.tools.qi.qi import vectorize, devectorize, outer
logger = logging.getLogger(__name__)
###############################################################################
# Tomography Bases
###############################################################################
class TomographyBasis(dict):
"""
Dictionary subsclass that includes methods for adding gates to circuits.
A TomographyBasis is a dictionary where the keys index a measurement
and the values are a list of projectors associated to that measurement.
It also includes two optional methods `prep_gate` and `meas_gate`:
- `prep_gate` adds gates to a circuit to prepare the corresponding
basis projector from an initial ground state.
- `meas_gate` adds gates to a circuit to transform the default
Z-measurement into a measurement in the basis.
With the exception of built in bases, these functions do nothing unless
they are specified by the user. They may be set by the data members
`prep_fun` and `meas_fun`. We illustrate this with an example.
Example:
A measurement in the Pauli-X basis has two outcomes corresponding to
the projectors:
`Xp = [[0.5, 0.5], [0.5, 0.5]]`
`Xm = [[0.5, -0.5], [-0.5, 0.5]]`
We can express this as a basis by
`BX = TomographyBasis( {'X': [Xp, Xm]} )`
To specifiy the gates to prepare and measure in this basis we :
```
def BX_prep_fun(circuit, qreg, op):
bas, proj = op
if bas == "X":
if proj == 0:
circuit.u2(0., np.pi, qreg) # apply H
else: # proj == 1
circuit.u2(np.pi, np.pi, qreg) # apply H.X
def BX_prep_fun(circuit, qreg, op):
if op == "X":
circuit.u2(0., np.pi, qreg) # apply H
```
We can then attach these functions to the basis using:
`BX.prep_fun = BX_prep_fun`
`BX.meas_fun = BX_meas_fun`.
Generating function:
A generating function `tomography_basis` exists to create bases in a
single step. Using the above example this can be done by:
```
BX = tomography_basis({'X': [Xp, Xm]},
prep_fun=BX_prep_fun,
meas_fun=BX_meas_fun)
```
"""
prep_fun = None
meas_fun = None
def prep_gate(self, circuit, qreg, op):
"""
Add state preparation gates to a circuit.
Args:
circuit (QuantumCircuit): circuit to add a preparation to.
qreg (tuple(QuantumRegister,int)): quantum register to apply
preparation to.
op (tuple(str, int)): the basis label and index for the
preparation op.
"""
if self.prep_fun is None:
pass
else:
self.prep_fun(circuit, qreg, op)
def meas_gate(self, circuit, qreg, op):
"""
Add measurement gates to a circuit.
Args:
circuit (QuantumCircuit): circuit to add measurement to.
qreg (tuple(QuantumRegister,int)): quantum register being measured.
op (str): the basis label for the measurement.
"""
if self.meas_fun is None:
pass
else:
self.meas_fun(circuit, qreg, op)
def tomography_basis(basis, prep_fun=None, meas_fun=None):
"""
Generate a TomographyBasis object.
See TomographyBasis for further details.abs
Args:
prep_fun (callable) optional: the function which adds preparation
gates to a circuit.
meas_fun (callable) optional: the function which adds measurement
gates to a circuit.
Returns:
TomographyBasis: A tomography basis.
"""
ret = TomographyBasis(basis)
ret.prep_fun = prep_fun
ret.meas_fun = meas_fun
return ret
# PAULI BASIS
# This corresponds to measurements in the X, Y, Z basis where
# Outcomes 0,1 are the +1,-1 eigenstates respectively.
# State preparation is also done in the +1 and -1 eigenstates.
def __pauli_prep_gates(circuit, qreg, op):
"""
Add state preparation gates to a circuit.
"""
bas, proj = op
if bas not in ['X', 'Y', 'Z']:
raise QiskitError("There's no X, Y or Z basis for this Pauli "
"preparation")
if bas == "X":
if proj == 1:
circuit.u2(np.pi, np.pi, qreg) # H.X
else:
circuit.u2(0., np.pi, qreg) # H
elif bas == "Y":
if proj == 1:
circuit.u2(-0.5 * np.pi, np.pi, qreg) # S.H.X
else:
circuit.u2(0.5 * np.pi, np.pi, qreg) # S.H
elif bas == "Z" and proj == 1:
circuit.u3(np.pi, 0., np.pi, qreg) # X
def __pauli_meas_gates(circuit, qreg, op):
"""
Add state measurement gates to a circuit.
"""
if op not in ['X', 'Y', 'Z']:
raise QiskitError("There's no X, Y or Z basis for this Pauli "
"measurement")
if op == "X":
circuit.u2(0., np.pi, qreg) # H
elif op == "Y":
circuit.u2(0., 0.5 * np.pi, qreg) # H.S^*
__PAULI_BASIS_OPS = {
'X':
[np.array([[0.5, 0.5], [0.5, 0.5]]),
np.array([[0.5, -0.5], [-0.5, 0.5]])],
'Y': [
np.array([[0.5, -0.5j], [0.5j, 0.5]]),
np.array([[0.5, 0.5j], [-0.5j, 0.5]])
],
'Z': [np.array([[1, 0], [0, 0]]),
np.array([[0, 0], [0, 1]])]
}
# Create the actual basis
PAULI_BASIS = tomography_basis(
__PAULI_BASIS_OPS,
prep_fun=__pauli_prep_gates,
meas_fun=__pauli_meas_gates)
# SIC-POVM BASIS
def __sic_prep_gates(circuit, qreg, op):
"""
Add state preparation gates to a circuit.
"""
bas, proj = op
if bas != 'S':
raise QiskitError('Not in SIC basis!')
theta = -2 * np.arctan(np.sqrt(2))
if proj == 1:
circuit.u3(theta, np.pi, 0.0, qreg)
elif proj == 2:
circuit.u3(theta, np.pi / 3, 0.0, qreg)
elif proj == 3:
circuit.u3(theta, -np.pi / 3, 0.0, qreg)
__SIC_BASIS_OPS = {
'S': [
np.array([[1, 0], [0, 0]]),
np.array([[1, np.sqrt(2)], [np.sqrt(2), 2]]) / 3,
np.array([[1, np.exp(np.pi * 2j / 3) * np.sqrt(2)],
[np.exp(-np.pi * 2j / 3) * np.sqrt(2), 2]]) / 3,
np.array([[1, np.exp(-np.pi * 2j / 3) * np.sqrt(2)],
[np.exp(np.pi * 2j / 3) * np.sqrt(2), 2]]) / 3
]
}
SIC_BASIS = tomography_basis(__SIC_BASIS_OPS, prep_fun=__sic_prep_gates)
###############################################################################
# Tomography Set and labels
###############################################################################
def tomography_set(meas_qubits,
meas_basis='Pauli',
prep_qubits=None,
prep_basis=None):
"""
Generate a dictionary of tomography experiment configurations.
This returns a data structure that is used by other tomography functions
to generate state and process tomography circuits, and extract tomography
data from results after execution on a backend.
Quantum State Tomography:
Be default it will return a set for performing Quantum State
Tomography where individual qubits are measured in the Pauli basis.
A custom measurement basis may also be used by defining a user
`tomography_basis` and passing this in for the `meas_basis` argument.
Quantum Process Tomography:
A quantum process tomography set is created by specifying a preparation
basis along with a measurement basis. The preparation basis may be a
user defined `tomography_basis`, or one of the two built in basis 'SIC'
or 'Pauli'.
- SIC: Is a minimal symmetric informationally complete preparation
basis for 4 states for each qubit (4 ^ number of qubits total
preparation states). These correspond to the |0> state and the 3
other vertices of a tetrahedron on the Bloch-sphere.
- Pauli: Is a tomographically overcomplete preparation basis of the six
eigenstates of the 3 Pauli operators (6 ^ number of qubits
total preparation states).
Args:
meas_qubits (list): The qubits being measured.
meas_basis (tomography_basis or str): The qubit measurement basis.
The default value is 'Pauli'.
prep_qubits (list or None): The qubits being prepared. If None then
meas_qubits will be used for process tomography experiments.
prep_basis (tomography_basis or None): The optional qubit preparation
basis. If no basis is specified state tomography will be performed
instead of process tomography. A built in basis may be specified by
'SIC' or 'Pauli' (SIC basis recommended for > 2 qubits).
Returns:
dict: A dict of tomography configurations that can be parsed by
`create_tomography_circuits` and `tomography_data` functions
for implementing quantum tomography experiments. This output contains
fields "qubits", "meas_basis", "circuits". It may also optionally
contain a field "prep_basis" for process tomography experiments.
```
{
'qubits': qubits (list[ints]),
'meas_basis': meas_basis (tomography_basis),
'circuit_labels': (list[string]),
'circuits': (list[dict]) # prep and meas configurations
# optionally for process tomography experiments:
'prep_basis': prep_basis (tomography_basis)
}
```
Raises:
QiskitError: if the Qubits argument is not a list.
"""
if not isinstance(meas_qubits, list):
raise QiskitError('Qubits argument must be a list')
num_of_qubits = len(meas_qubits)
if prep_qubits is None:
prep_qubits = meas_qubits
if not isinstance(prep_qubits, list):
raise QiskitError('prep_qubits argument must be a list')
if len(prep_qubits) != len(meas_qubits):
raise QiskitError('meas_qubits and prep_qubitsare different length')
if isinstance(meas_basis, str):
if meas_basis.lower() == 'pauli':
meas_basis = PAULI_BASIS
if isinstance(prep_basis, str):
if prep_basis.lower() == 'pauli':
prep_basis = PAULI_BASIS
elif prep_basis.lower() == 'sic':
prep_basis = SIC_BASIS
circuits = []
circuit_labels = []
# add meas basis configs
if prep_basis is None:
# State Tomography
for meas_product in product(meas_basis.keys(), repeat=num_of_qubits):
meas = dict(zip(meas_qubits, meas_product))
circuits.append({'meas': meas})
# Make label
label = '_meas_'
for qubit, op in meas.items():
label += '%s(%d)' % (op[0], qubit)
circuit_labels.append(label)
return {'qubits': meas_qubits,
'circuits': circuits,
'circuit_labels': circuit_labels,
'meas_basis': meas_basis}
# Process Tomography
num_of_s = len(list(prep_basis.values())[0])
plst_single = [(b, s)
for b in prep_basis.keys()
for s in range(num_of_s)]
for plst_product in product(plst_single, repeat=num_of_qubits):
for meas_product in product(meas_basis.keys(),
repeat=num_of_qubits):
prep = dict(zip(prep_qubits, plst_product))
meas = dict(zip(meas_qubits, meas_product))
circuits.append({'prep': prep, 'meas': meas})
# Make label
label = '_prep_'
for qubit, op in prep.items():
label += '%s%d(%d)' % (op[0], op[1], qubit)
label += '_meas_'
for qubit, op in meas.items():
label += '%s(%d)' % (op[0], qubit)
circuit_labels.append(label)
return {'qubits': meas_qubits,
'circuits': circuits,
'circuit_labels': circuit_labels,
'prep_basis': prep_basis,
'meas_basis': meas_basis}
def state_tomography_set(qubits, meas_basis='Pauli'):
"""
Generate a dictionary of state tomography experiment configurations.
This returns a data structure that is used by other tomography functions
to generate state and process tomography circuits, and extract tomography
data from results after execution on a backend.
Quantum State Tomography:
Be default it will return a set for performing Quantum State
Tomography where individual qubits are measured in the Pauli basis.
A custom measurement basis may also be used by defining a user
`tomography_basis` and passing this in for the `meas_basis` argument.
Quantum Process Tomography:
A quantum process tomography set is created by specifying a preparation
basis along with a measurement basis. The preparation basis may be a
user defined `tomography_basis`, or one of the two built in basis 'SIC'
or 'Pauli'.
- SIC: Is a minimal symmetric informationally complete preparation
basis for 4 states for each qubit (4 ^ number of qubits total
preparation states). These correspond to the |0> state and the 3
other vertices of a tetrahedron on the Bloch-sphere.
- Pauli: Is a tomographically overcomplete preparation basis of the six
eigenstates of the 3 Pauli operators (6 ^ number of qubits
total preparation states).
Args:
qubits (list): The qubits being measured.
meas_basis (tomography_basis or str): The qubit measurement basis.
The default value is 'Pauli'.
Returns:
dict: A dict of tomography configurations that can be parsed by
`create_tomography_circuits` and `tomography_data` functions
for implementing quantum tomography experiments. This output contains
fields "qubits", "meas_basis", "circuits".
```
{
'qubits': qubits (list[ints]),
'meas_basis': meas_basis (tomography_basis),
'circuit_labels': (list[string]),
'circuits': (list[dict]) # prep and meas configurations
}
```
"""
return tomography_set(qubits, meas_basis=meas_basis)
def process_tomography_set(meas_qubits, meas_basis='Pauli',
prep_qubits=None, prep_basis='SIC'):
"""
Generate a dictionary of process tomography experiment configurations.
This returns a data structure that is used by other tomography functions
to generate state and process tomography circuits, and extract tomography
data from results after execution on a backend.
A quantum process tomography set is created by specifying a preparation
basis along with a measurement basis. The preparation basis may be a
user defined `tomography_basis`, or one of the two built in basis 'SIC'
or 'Pauli'.
- SIC: Is a minimal symmetric informationally complete preparation
basis for 4 states for each qubit (4 ^ number of qubits total
preparation states). These correspond to the |0> state and the 3
other vertices of a tetrahedron on the Bloch-sphere.
- Pauli: Is a tomographically overcomplete preparation basis of the six
eigenstates of the 3 Pauli operators (6 ^ number of qubits
total preparation states).
Args:
meas_qubits (list): The qubits being measured.
meas_basis (tomography_basis or str): The qubit measurement basis.
The default value is 'Pauli'.
prep_qubits (list or None): The qubits being prepared. If None then
meas_qubits will be used for process tomography experiments.
prep_basis (tomography_basis or str): The qubit preparation basis.
The default value is 'SIC'.
Returns:
dict: A dict of tomography configurations that can be parsed by
`create_tomography_circuits` and `tomography_data` functions
for implementing quantum tomography experiments. This output contains
fields "qubits", "meas_basis", "prep_basus", circuits".
```
{
'qubits': qubits (list[ints]),
'meas_basis': meas_basis (tomography_basis),
'prep_basis': prep_basis (tomography_basis),
'circuit_labels': (list[string]),
'circuits': (list[dict]) # prep and meas configurations
}
```
"""
return tomography_set(meas_qubits, meas_basis=meas_basis,
prep_qubits=prep_qubits, prep_basis=prep_basis)
def tomography_circuit_names(tomo_set, name=''):
"""
Return a list of tomography circuit names.
The returned list is the same as the one returned by
`create_tomography_circuits` and can be used by a QuantumProgram
to execute tomography circuits and extract measurement results.
Args:
tomo_set (tomography_set): a tomography set generated by
`tomography_set`.
name (str): the name of the base QuantumCircuit used by the
tomography experiment.
Returns:
list: A list of circuit names.
"""
return [name + l for l in tomo_set['circuit_labels']]
###############################################################################
# Tomography circuit generation
###############################################################################
def create_tomography_circuits(circuit, qreg, creg, tomoset):
"""
Add tomography measurement circuits to a QuantumProgram.
The quantum program must contain a circuit 'name', which is treated as a
state preparation circuit for state tomography, or as teh circuit being
measured for process tomography. This function then appends the circuit
with a set of measurements specified by the input `tomography_set`,
optionally it also prepends the circuit with state preparation circuits if
they are specified in the `tomography_set`.
For n-qubit tomography with a tomographically complete set of preparations
and measurements this results in $4^n 3^n$ circuits being added to the
quantum program.
Args:
circuit (QuantumCircuit): The circuit to be appended with tomography
state preparation and/or measurements.
qreg (QuantumRegister): the quantum register containing qubits to be
measured.
creg (ClassicalRegister): the classical register containing bits to
store measurement outcomes.
tomoset (tomography_set): the dict of tomography configurations.
Returns:
list: A list of quantum tomography circuits for the input circuit.
Raises:
QiskitError: if circuit is not a valid QuantumCircuit
Example:
For a tomography set specifying state tomography of qubit-0 prepared
by a circuit 'circ' this would return:
```
['circ_meas_X(0)', 'circ_meas_Y(0)', 'circ_meas_Z(0)']
```
For process tomography of the same circuit with preparation in the
SIC-POVM basis it would return:
```
[
'circ_prep_S0(0)_meas_X(0)', 'circ_prep_S0(0)_meas_Y(0)',
'circ_prep_S0(0)_meas_Z(0)', 'circ_prep_S1(0)_meas_X(0)',
'circ_prep_S1(0)_meas_Y(0)', 'circ_prep_S1(0)_meas_Z(0)',
'circ_prep_S2(0)_meas_X(0)', 'circ_prep_S2(0)_meas_Y(0)',
'circ_prep_S2(0)_meas_Z(0)', 'circ_prep_S3(0)_meas_X(0)',
'circ_prep_S3(0)_meas_Y(0)', 'circ_prep_S3(0)_meas_Z(0)'
]
```
"""
if not isinstance(circuit, QuantumCircuit):
raise QiskitError('Input circuit must be a QuantumCircuit object')
dics = tomoset['circuits']
labels = tomography_circuit_names(tomoset, circuit.name)
tomography_circuits = []
for label, conf in zip(labels, dics):
tmp = circuit
# Add prep circuits
if 'prep' in conf:
prep = QuantumCircuit(qreg, creg, name='tmp_prep')
for qubit, op in conf['prep'].items():
tomoset['prep_basis'].prep_gate(prep, qreg[qubit], op)
prep.barrier(qreg[qubit])
tmp = prep + tmp
# Add measurement circuits
meas = QuantumCircuit(qreg, creg, name='tmp_meas')
for qubit, op in conf['meas'].items():
meas.barrier(qreg[qubit])
tomoset['meas_basis'].meas_gate(meas, qreg[qubit], op)
meas.measure(qreg[qubit], creg[qubit])
tmp = tmp + meas
# Add label to the circuit
tmp.name = label
tomography_circuits.append(tmp)
logger.info('>> created tomography circuits for "%s"', circuit.name)
return tomography_circuits
###############################################################################
# Get results data
###############################################################################
def tomography_data(results, name, tomoset):
"""
Return a results dict for a state or process tomography experiment.
Args:
results (Result): Results from execution of a process tomography
circuits on a backend.
name (string): The name of the circuit being reconstructed.
tomoset (tomography_set): the dict of tomography configurations.
Returns:
list: A list of dicts for the outcome of each process tomography
measurement circuit.
"""
labels = tomography_circuit_names(tomoset, name)
circuits = tomoset['circuits']
data = []
prep = None
for j, _ in enumerate(labels):
counts = marginal_counts(results.get_counts(labels[j]),
tomoset['qubits'])
shots = sum(counts.values())
meas = circuits[j]['meas']
prep = circuits[j].get('prep', None)
meas_qubits = sorted(meas.keys())
if prep:
prep_qubits = sorted(prep.keys())
circuit = {}
for c in counts.keys():
circuit[c] = {}
circuit[c]['meas'] = [(meas[meas_qubits[k]], int(c[-1 - k]))
for k in range(len(meas_qubits))]
if prep:
circuit[c]['prep'] = [prep[prep_qubits[k]]
for k in range(len(prep_qubits))]
data.append({'counts': counts, 'shots': shots, 'circuit': circuit})
ret = {'data': data, 'meas_basis': tomoset['meas_basis']}
if prep:
ret['prep_basis'] = tomoset['prep_basis']
return ret
def marginal_counts(counts, meas_qubits):
"""
Compute the marginal counts for a subset of measured qubits.
Args:
counts (dict): the counts returned from a backend ({str: int}).
meas_qubits (list[int]): the qubits to return the marginal
counts distribution for.
Returns:
dict: A counts dict for the meas_qubits.abs
Example: if `counts = {'00': 10, '01': 5}`
`marginal_counts(counts, [0])` returns `{'0': 15, '1': 0}`.
`marginal_counts(counts, [0])` returns `{'0': 10, '1': 5}`.
"""
# pylint: disable=cell-var-from-loop
# Extract total number of qubits from count keys
num_of_qubits = len(list(counts.keys())[0])
# keys for measured qubits only
qs = sorted(meas_qubits, reverse=True)
meas_keys = count_keys(len(qs))
# get regex match strings for summing outcomes of other qubits
rgx = [
reduce(lambda x, y: (key[qs.index(y)] if y in qs else '\\d') + x,
range(num_of_qubits), '') for key in meas_keys
]
# build the return list
meas_counts = []
for m in rgx:
c = 0
for key, val in counts.items():
if match(m, key):
c += val
meas_counts.append(c)
# return as counts dict on measured qubits only
return dict(zip(meas_keys, meas_counts))
def count_keys(n):
"""Generate outcome bitstrings for n-qubits.
Args:
n (int): the number of qubits.
Returns:
list: A list of bitstrings ordered as follows:
Example: n=2 returns ['00', '01', '10', '11'].
"""
return [bin(j)[2:].zfill(n) for j in range(2**n)]
###############################################################################
# Tomographic Reconstruction functions.
###############################################################################
def fit_tomography_data(tomo_data, method='wizard', options=None):
"""
Reconstruct a density matrix or process-matrix from tomography data.
If the input data is state_tomography_data the returned operator will
be a density matrix. If the input data is process_tomography_data the
returned operator will be a Choi-matrix in the column-vectorization
convention.
Args:
tomo_data (dict): process tomography measurement data.
method (str): the fitting method to use.
Available methods:
- 'wizard' (default)
- 'leastsq'
options (dict or None): additional options for fitting method.
Returns:
numpy.array: The fitted operator.
Available methods:
- 'wizard' (Default): The returned operator will be constrained to be
positive-semidefinite.
Options:
- 'trace': the trace of the returned operator.
The default value is 1.
- 'beta': hedging parameter for computing frequencies from
zero-count data. The default value is 0.50922.
- 'epsilon: threshold for truncating small eigenvalues to zero.
The default value is 0
- 'leastsq': Fitting without positive-semidefinite constraint.
Options:
- 'trace': Same as for 'wizard' method.
- 'beta': Same as for 'wizard' method.
Raises:
Exception: if the `method` parameter is not valid.
"""
if isinstance(method, str) and method.lower() in ['wizard', 'leastsq']:
# get options
trace = __get_option('trace', options)
beta = __get_option('beta', options)
# fit state
rho = __leastsq_fit(tomo_data, trace=trace, beta=beta)
if method == 'wizard':
# Use wizard method to constrain positivity
epsilon = __get_option('epsilon', options)
rho = __wizard(rho, epsilon=epsilon)
return rho
else:
raise Exception('Invalid reconstruction method "%s"' % method)
def __get_option(opt, options):
"""
Return an optional value or None if not found.
"""
if options is not None:
if opt in options:
return options[opt]
return None
###############################################################################
# Fit Method: Linear Inversion
###############################################################################
def __leastsq_fit(tomo_data, weights=None, trace=None, beta=None):
"""
Reconstruct a state from unconstrained least-squares fitting.
Args:
tomo_data (list[dict]): state or process tomography data.
weights (list or array or None): weights to use for least squares
fitting. The default is standard deviation from a binomial
distribution.
trace (float or None): trace of returned operator. The default is 1.
beta (float or None): hedge parameter (>=0) for computing frequencies
from zero-count data. The default value is 0.50922.
Returns:
numpy.array: A numpy array of the reconstructed operator.
"""
if trace is None:
trace = 1. # default to unit trace
data = tomo_data['data']
keys = data[0]['circuit'].keys()
# Get counts and shots
counts = []
shots = []
ops = []
for dat in data:
for key in keys:
counts.append(dat['counts'][key])
shots.append(dat['shots'])
projectors = dat['circuit'][key]
op = __projector(projectors['meas'], tomo_data['meas_basis'])
if 'prep' in projectors:
op_prep = __projector(projectors['prep'],
tomo_data['prep_basis'])
op = np.kron(op_prep.conj(), op)
ops.append(op)
# Convert counts to frequencies
counts = np.array(counts)
shots = np.array(shots)
freqs = counts / shots
# Use hedged frequencies to calculate least squares fitting weights
if weights is None:
if beta is None:
beta = 0.50922
K = len(keys)
freqs_hedged = (counts + beta) / (shots + K * beta)
weights = np.sqrt(shots / (freqs_hedged * (1 - freqs_hedged)))
return __tomo_linear_inv(freqs, ops, weights, trace=trace)
def __projector(op_list, basis):
"""Returns a projectors.
"""
ret = 1
# list is from qubit 0 to 1
for op in op_list:
label, eigenstate = op
ret = np.kron(basis[label][eigenstate], ret)
return ret
def __tomo_linear_inv(freqs, ops, weights=None, trace=None):
"""
Reconstruct a matrix through linear inversion.
Args:
freqs (list[float]): list of observed frequences.
ops (list[np.array]): list of corresponding projectors.
weights (list[float] or array_like):
weights to be used for weighted fitting.
trace (float or None): trace of returned operator.
Returns:
numpy.array: A numpy array of the reconstructed operator.
"""
# get weights matrix
if weights is not None:
W = np.array(weights)
if W.ndim == 1:
W = np.diag(W)
# Get basis S matrix
S = np.array([vectorize(m).conj()
for m in ops]).reshape(len(ops), ops[0].size)
if weights is not None:
S = np.dot(W, S) # W.S
# get frequencies vec
v = np.array(freqs) # |f>
if weights is not None:
v = np.dot(W, freqs) # W.|f>
Sdg = S.T.conj() # S^*.W^*
inv = np.linalg.pinv(np.dot(Sdg, S)) # (S^*.W^*.W.S)^-1
# linear inversion of freqs
ret = devectorize(np.dot(inv, np.dot(Sdg, v)))
# renormalize to input trace value
if trace is not None:
ret = trace * ret / np.trace(ret)
return ret
###############################################################################
# Fit Method: Wizard
###############################################################################
def __wizard(rho, epsilon=None):
"""
Returns the nearest positive semidefinite operator to an operator.
This method is based on reference [1]. It constrains positivity
by setting negative eigenvalues to zero and rescaling the positive
eigenvalues.
Args:
rho (array_like): the input operator.
epsilon(float or None): threshold (>=0) for truncating small
eigenvalues values to zero.
Returns:
numpy.array: A positive semidefinite numpy array.
"""
if epsilon is None:
epsilon = 0. # default value
dim = len(rho)
rho_wizard = np.zeros([dim, dim])
v, w = np.linalg.eigh(rho) # v eigenvecrors v[0] < v[1] <...
for j in range(dim):
if v[j] < epsilon:
tmp = v[j]
v[j] = 0.
# redistribute loop
x = 0.
for k in range(j + 1, dim):
x += tmp / (dim - (j + 1))
v[k] = v[k] + tmp / (dim - (j + 1))
for j in range(dim):
rho_wizard = rho_wizard + v[j] * outer(w[:, j])
return rho_wizard
###############################################################
# Wigner function tomography
###############################################################
def build_wigner_circuits(circuit, phis, thetas, qubits,
qreg, creg):
"""Create the circuits to rotate to points in phase space
Args:
circuit (QuantumCircuit): The circuit to be appended with tomography
state preparation and/or measurements.
phis (np.matrix[[complex]]): phis
thetas (np.matrix[[complex]]): thetas
qubits (list[int]): a list of the qubit indexes of qreg to be measured.
qreg (QuantumRegister): the quantum register containing qubits to be
measured.
creg (ClassicalRegister): the classical register containing bits to
store measurement outcomes.
Returns:
list: A list of names of the added wigner function circuits.
Raises:
QiskitError: if circuit is not a valid QuantumCircuit.
"""
if not isinstance(circuit, QuantumCircuit):
raise QiskitError('Input circuit must be a QuantumCircuit object')
tomography_circuits = []
points = len(phis[0])
for point in range(points):
label = '_wigner_phase_point'
label += str(point)
tmp_circ = QuantumCircuit(qreg, creg, name=label)
for qubit, _ in enumerate(qubits):
tmp_circ.u3(thetas[qubit][point], 0,
phis[qubit][point], qreg[qubits[qubit]])
tmp_circ.measure(qreg[qubits[qubit]], creg[qubits[qubit]])
# Add to original circuit
tmp_circ = circuit + tmp_circ
tmp_circ.name = circuit.name + label
tomography_circuits.append(tmp_circ)
logger.info('>> Created Wigner function circuits for "%s"', circuit.name)
return tomography_circuits
def wigner_data(q_result, meas_qubits, labels, shots=None):
"""Get the value of the Wigner function from measurement results.
Args:
q_result (Result): Results from execution of a state tomography
circuits on a backend.
meas_qubits (list[int]): a list of the qubit indexes measured.
labels (list[str]): a list of names of the circuits
shots (int): number of shots
Returns:
list: The values of the Wigner function at measured points in
phase space
"""
num = len(meas_qubits)
dim = 2**num
p = [0.5 + 0.5 * np.sqrt(3), 0.5 - 0.5 * np.sqrt(3)]
parity = 1
for i in range(num):
parity = np.kron(parity, p)
w = [0] * len(labels)
wpt = 0
counts = [marginal_counts(q_result.get_counts(circ), meas_qubits)
for circ in labels]
for entry in counts:
x = [0] * dim
for i in range(dim):
if bin(i)[2:].zfill(num) in entry:
x[i] = float(entry[bin(i)[2:].zfill(num)])
if shots is None:
shots = np.sum(x)
for i in range(dim):
w[wpt] = w[wpt] + (x[i] / shots) * parity[i]
wpt += 1
return w
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Example use of the initialize gate to prepare arbitrary pure states.
"""
import math
from qiskit import QuantumCircuit, execute, BasicAer
###############################################################
# Make a quantum circuit for state initialization.
###############################################################
circuit = QuantumCircuit(4, 4, name="initializer_circ")
desired_vector = [
1 / math.sqrt(4) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
0,
0,
0,
0,
0,
0,
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(8) * complex(0, 1),
0,
0,
0,
0,
1 / math.sqrt(4) * complex(1, 0),
1 / math.sqrt(8) * complex(1, 0),
]
circuit.initialize(desired_vector, [0, 1, 2, 3])
circuit.measure([0, 1, 2, 3], [0, 1, 2, 3])
print(circuit)
###############################################################
# Execute on a simulator backend.
###############################################################
shots = 10000
# Desired vector
print("Desired probabilities: ")
print([format(abs(x * x), ".3f") for x in desired_vector])
# Initialize on local simulator
sim_backend = BasicAer.get_backend("qasm_simulator")
job = execute(circuit, sim_backend, shots=shots)
result = job.result()
counts = result.get_counts(circuit)
qubit_strings = [format(i, "04b") for i in range(2**4)]
print("Probabilities from simulator: ")
print([format(counts.get(s, 0) / shots, ".3f") for s in qubit_strings])
|
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.
"""Controlled unitary gate."""
from __future__ import annotations
import copy
from typing import Optional, Union
from qiskit.circuit.exceptions import CircuitError
# pylint: disable=cyclic-import
from .quantumcircuit import QuantumCircuit
from .gate import Gate
from .quantumregister import QuantumRegister
from ._utils import _ctrl_state_to_int
class ControlledGate(Gate):
"""Controlled unitary gate."""
def __init__(
self,
name: str,
num_qubits: int,
params: list,
label: Optional[str] = None,
num_ctrl_qubits: Optional[int] = 1,
definition: Optional["QuantumCircuit"] = None,
ctrl_state: Optional[Union[int, str]] = None,
base_gate: Optional[Gate] = None,
):
"""Create a new ControlledGate. In the new gate the first ``num_ctrl_qubits``
of the gate are the controls.
Args:
name: The name of the gate.
num_qubits: The number of qubits the gate acts on.
params: A list of parameters for the gate.
label: An optional label for the gate.
num_ctrl_qubits: Number of control qubits.
definition: A list of gate rules for implementing this gate. The
elements of the list are tuples of (:meth:`~qiskit.circuit.Gate`, [qubit_list],
[clbit_list]).
ctrl_state: The control state in decimal or as
a bitstring (e.g. '111'). If specified as a bitstring the length
must equal num_ctrl_qubits, MSB on left. If None, use
2**num_ctrl_qubits-1.
base_gate: Gate object to be controlled.
Raises:
CircuitError: If ``num_ctrl_qubits`` >= ``num_qubits``.
CircuitError: ctrl_state < 0 or ctrl_state > 2**num_ctrl_qubits.
Examples:
Create a controlled standard gate and apply it to a circuit.
.. plot::
:include-source:
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import HGate
qr = QuantumRegister(3)
qc = QuantumCircuit(qr)
c3h_gate = HGate().control(2)
qc.append(c3h_gate, qr)
qc.draw('mpl')
Create a controlled custom gate and apply it to a circuit.
.. plot::
:include-source:
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import HGate
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.h(1)
custom = qc1.to_gate().control(2)
qc2 = QuantumCircuit(4)
qc2.append(custom, [0, 3, 1, 2])
qc2.draw('mpl')
"""
self.base_gate = None if base_gate is None else base_gate.copy()
super().__init__(name, num_qubits, params, label=label)
self._num_ctrl_qubits = 1
self.num_ctrl_qubits = num_ctrl_qubits
self.definition = copy.deepcopy(definition)
self._ctrl_state = None
self.ctrl_state = ctrl_state
self._name = name
@property
def definition(self) -> QuantumCircuit:
"""Return definition in terms of other basic gates. If the gate has
open controls, as determined from `self.ctrl_state`, the returned
definition is conjugated with X without changing the internal
`_definition`.
"""
if self._open_ctrl:
closed_gate = self.copy()
closed_gate.ctrl_state = None
bit_ctrl_state = bin(self.ctrl_state)[2:].zfill(self.num_ctrl_qubits)
qreg = QuantumRegister(self.num_qubits, "q")
qc_open_ctrl = QuantumCircuit(qreg)
for qind, val in enumerate(bit_ctrl_state[::-1]):
if val == "0":
qc_open_ctrl.x(qind)
qc_open_ctrl.append(closed_gate, qargs=qreg[:])
for qind, val in enumerate(bit_ctrl_state[::-1]):
if val == "0":
qc_open_ctrl.x(qind)
return qc_open_ctrl
else:
return super().definition
@definition.setter
def definition(self, excited_def: "QuantumCircuit"):
"""Set controlled gate definition with closed controls.
Args:
excited_def: The circuit with all closed controls.
"""
self._definition = excited_def
@property
def name(self) -> str:
"""Get name of gate. If the gate has open controls the gate name
will become:
<original_name_o<ctrl_state>
where <original_name> is the gate name for the default case of
closed control qubits and <ctrl_state> is the integer value of
the control state for the gate.
"""
if self._open_ctrl:
return f"{self._name}_o{self.ctrl_state}"
else:
return self._name
@name.setter
def name(self, name_str):
"""Set the name of the gate. Note the reported name may differ
from the set name if the gate has open controls.
"""
self._name = name_str
@property
def num_ctrl_qubits(self):
"""Get number of control qubits.
Returns:
int: The number of control qubits for the gate.
"""
return self._num_ctrl_qubits
@num_ctrl_qubits.setter
def num_ctrl_qubits(self, num_ctrl_qubits):
"""Set the number of control qubits.
Args:
num_ctrl_qubits (int): The number of control qubits.
Raises:
CircuitError: ``num_ctrl_qubits`` is not an integer in ``[1, num_qubits]``.
"""
if num_ctrl_qubits != int(num_ctrl_qubits):
raise CircuitError("The number of control qubits must be an integer.")
num_ctrl_qubits = int(num_ctrl_qubits)
# This is a range rather than an equality limit because some controlled gates represent a
# controlled version of the base gate whose definition also uses auxiliary qubits.
upper_limit = self.num_qubits - getattr(self.base_gate, "num_qubits", 0)
if num_ctrl_qubits < 1 or num_ctrl_qubits > upper_limit:
limit = "num_qubits" if self.base_gate is None else "num_qubits - base_gate.num_qubits"
raise CircuitError(f"The number of control qubits must be in `[1, {limit}]`.")
self._num_ctrl_qubits = num_ctrl_qubits
@property
def ctrl_state(self) -> int:
"""Return the control state of the gate as a decimal integer."""
return self._ctrl_state
@ctrl_state.setter
def ctrl_state(self, ctrl_state: Union[int, str, None]):
"""Set the control state of this gate.
Args:
ctrl_state: The control state of the gate.
Raises:
CircuitError: ctrl_state is invalid.
"""
self._ctrl_state = _ctrl_state_to_int(ctrl_state, self.num_ctrl_qubits)
@property
def params(self):
"""Get parameters from base_gate.
Returns:
list: List of gate parameters.
Raises:
CircuitError: Controlled gate does not define a base gate
"""
if self.base_gate:
return self.base_gate.params
else:
raise CircuitError("Controlled gate does not define base gate for extracting params")
@params.setter
def params(self, parameters):
"""Set base gate parameters.
Args:
parameters (list): The list of parameters to set.
Raises:
CircuitError: If controlled gate does not define a base gate.
"""
if self.base_gate:
self.base_gate.params = parameters
else:
raise CircuitError("Controlled gate does not define base gate for extracting params")
def __deepcopy__(self, _memo=None):
cpy = copy.copy(self)
cpy.base_gate = self.base_gate.copy()
if self._definition:
cpy._definition = copy.deepcopy(self._definition, _memo)
return cpy
@property
def _open_ctrl(self) -> bool:
"""Return whether gate has any open controls"""
return self.ctrl_state < 2**self.num_ctrl_qubits - 1
def __eq__(self, other) -> bool:
return (
isinstance(other, ControlledGate)
and self.num_ctrl_qubits == other.num_ctrl_qubits
and self.ctrl_state == other.ctrl_state
and self.base_gate == other.base_gate
and self.num_qubits == other.num_qubits
and self.num_clbits == other.num_clbits
and self.definition == other.definition
)
def inverse(self) -> "ControlledGate":
"""Invert this gate by calling inverse on the base gate."""
return self.base_gate.inverse().control(self.num_ctrl_qubits, ctrl_state=self.ctrl_state)
|
https://github.com/hkhetawat/QArithmetic
|
hkhetawat
|
# Import the Qiskit SDK
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, Aer
from QArithmetic import cadd
# Input N
N = 4
a = QuantumRegister(N)
b = QuantumRegister(N+1)
c = QuantumRegister(1)
ca = ClassicalRegister(N)
cb = ClassicalRegister(N+1)
cc = ClassicalRegister(1)
qc = QuantumCircuit(a, b, c, ca, cb, cc)
# Input Superposition
# a = 01110
qc.x(a[1])
qc.x(a[2])
qc.x(a[3])
# b = 01011
qc.x(b[0])
qc.x(b[1])
qc.x(b[3])
# c = 0
# qc.x(c)
cadd(qc, c, a, b, N)
qc.measure(a, ca)
qc.measure(b, cb)
qc.measure(c, cc)
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
print(result_sim.get_counts(qc))
|
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/wyqian1027/Qiskit-Fall-Fest-USC-2022
|
wyqian1027
|
!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/abhishekchak52/quantum-computing-course
|
abhishekchak52
|
%matplotlib inline
import hashlib
import numpy as np
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute
from qiskit.circuit import Parameter
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator
from qiskit.visualization import *
from qiskit.quantum_info import *
from qiskit.circuit.library import HGate
success_msg = 'Your answer is correct and has been saved. Please continue to the next section.'
fail_msg = 'Your answer is not correct. Please try again.'
qc1 = QuantumCircuit(1)
# Insert gates below to create the state
qc1.rx(-np.pi/2,0)
# Insert the necessary gates to change to the Hadamard basis below
qc1.h(0)
# Do not change below this line
qc1.measure_all()
qc1.draw('mpl')
basis_gates = ['id', 'x', 'y', 'z', 's', 't', 'sdg', 'tdg', 'h', 'p', 'sx' ,'r', 'rx', 'ry', 'rz', 'u', 'u1', 'u2', 'u3', 'barrier', 'measure']
assert list(qc1.count_ops()) != [], "Circuit cannot be empty"
assert set(qc1.count_ops().keys()).difference(basis_gates) == set(), "Only basic gates are allowed"
job = execute(qc1, backend=QasmSimulator(), shots=1024, seed_simulator=0)
counts = job.result().get_counts()
sv_check = Statevector.from_instruction(qc1.remove_final_measurements(inplace=False)).evolve(HGate()).equiv(Statevector.from_label('r'))
op_check_dict = qc1.count_ops()
_ = op_check_dict.pop('measure', None)
_ = op_check_dict.pop('barrier', None)
op_check = len(op_check_dict) > 1
print(success_msg if (sv_check and op_check) else fail_msg)
answer1 = hashlib.sha256((str(counts)+str(sv_check and op_check)).encode()).hexdigest()
plot_histogram(counts)
from IPython.display import YouTubeVideo, display
polariser_exp = YouTubeVideo('6N3bJ7Uxpp0', end=93, height=405, width=720, modestbranding=1)
display(polariser_exp)
beta = Parameter('β')
qc2 = QuantumCircuit(1)
# Enter your code below this line
qc2.ry(-2*beta, 0)
qc2.measure_all()
# Do not change below this line
qc2.draw(output='mpl')
def theoretical_prob(beta):
'''
Definition of theoretical transmission probability.
The expression for transmitted probability between two polarisers
with a relative angle `beta` given in radians
'''
# Fill in the correct expression for this probability and assign it to the variable tp below
# You may use numpy function like so: np.func_name()
tp = np.cos(-beta)**2
return tp
beta_range = np.linspace(0, np.pi, 50)
num_shots = 1024
basis_gates = ['id', 'x', 'y', 'z', 's', 't', 'sdg', 'tdg', 'h', 'p', 'sx' ,'r', 'rx', 'ry', 'rz', 'u', 'u1', 'u2', 'u3', 'barrier', 'measure']
assert set(qc1.count_ops().keys()).difference(basis_gates) == set(), "Only basic gates are allowed"
job = execute(qc2,
backend=QasmSimulator(),
shots = num_shots,
parameter_binds=[{beta: beta_val} for beta_val in beta_range],
seed_simulator=0) # For consistent results
counts = job.result().get_counts()
# Calculating the probability of photons passing through
probabilities = list(map(lambda c: c.get('0', 0)/num_shots, counts))
pol_checks = [Statevector.from_instruction(qc2.bind_parameters({beta: beta_val})
.remove_final_measurements(inplace=False))
.equiv(Statevector([np.cos(-beta_val), np.sin(-beta_val)]))
for beta_val in beta_range]
print(success_msg if all(pol_checks) else fail_msg)
answer2 = hashlib.sha256((str(probabilities)+str(pol_checks)).encode()).hexdigest()
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111)
ax.plot(beta_range, probabilities, 'o', label='Experimental')
ax.plot(beta_range, theoretical_prob(beta_range), '-', label='Theoretical')
ax.set_xticks([i * np.pi / 4 for i in range(5)])
ax.set_xticklabels(['β', r'$\frac{\pi}{4}$', r'$\frac{\pi}{2}$', r'$\frac{3\pi}{4}$', r'$\pi$'], fontsize=14)
ax.set_xlabel('β', fontsize=14)
ax.set_ylabel('Probability of Transmission', fontsize=14)
ax.legend(fontsize=14)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test pulse builder with backendV2 context utilities."""
import numpy as np
from qiskit import circuit, pulse
from qiskit.pulse import builder, macros
from qiskit.pulse.instructions import directives
from qiskit.pulse.transforms import target_qobj_transform
from qiskit.providers.fake_provider import FakeMumbaiV2
from qiskit.pulse import instructions
from qiskit.test import QiskitTestCase
class TestBuilderV2(QiskitTestCase):
"""Test the pulse builder context with backendV2."""
def setUp(self):
super().setUp()
self.backend = FakeMumbaiV2()
def assertScheduleEqual(self, program, target):
"""Assert an error when two pulse programs are not equal.
.. note:: Two programs are converted into standard execution format then compared.
"""
self.assertEqual(target_qobj_transform(program), target_qobj_transform(target))
class TestContextsV2(TestBuilderV2):
"""Test builder contexts."""
def test_transpiler_settings(self):
"""Test the transpiler settings context.
Tests that two cx gates are optimized away with higher optimization level.
"""
twice_cx_qc = circuit.QuantumCircuit(2)
twice_cx_qc.cx(0, 1)
twice_cx_qc.cx(0, 1)
with pulse.build(self.backend) as schedule:
with pulse.transpiler_settings(optimization_level=0):
builder.call(twice_cx_qc)
self.assertNotEqual(len(schedule.instructions), 0)
with pulse.build(self.backend) as schedule:
with pulse.transpiler_settings(optimization_level=3):
builder.call(twice_cx_qc)
self.assertEqual(len(schedule.instructions), 0)
def test_scheduler_settings(self):
"""Test the circuit scheduler settings context."""
inst_map = pulse.InstructionScheduleMap()
d0 = pulse.DriveChannel(0)
test_x_sched = pulse.Schedule()
test_x_sched += instructions.Delay(10, d0)
inst_map.add("x", (0,), test_x_sched)
ref_sched = pulse.Schedule()
ref_sched += pulse.instructions.Call(test_x_sched)
x_qc = circuit.QuantumCircuit(2)
x_qc.x(0)
with pulse.build(backend=self.backend) as schedule:
with pulse.transpiler_settings(basis_gates=["x"]):
with pulse.circuit_scheduler_settings(inst_map=inst_map):
builder.call(x_qc)
self.assertScheduleEqual(schedule, ref_sched)
def test_phase_compensated_frequency_offset(self):
"""Test that the phase offset context properly compensates for phase
accumulation with backendV2."""
d0 = pulse.DriveChannel(0)
with pulse.build(self.backend) as schedule:
with pulse.frequency_offset(1e9, d0, compensate_phase=True):
pulse.delay(10, d0)
reference = pulse.Schedule()
reference += instructions.ShiftFrequency(1e9, d0)
reference += instructions.Delay(10, d0)
reference += instructions.ShiftPhase(
-2 * np.pi * ((1e9 * 10 * self.backend.target.dt) % 1), d0
)
reference += instructions.ShiftFrequency(-1e9, d0)
self.assertScheduleEqual(schedule, reference)
class TestChannelsV2(TestBuilderV2):
"""Test builder channels."""
def test_drive_channel(self):
"""Text context builder drive channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.drive_channel(0), pulse.DriveChannel(0))
def test_measure_channel(self):
"""Text context builder measure channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.measure_channel(0), pulse.MeasureChannel(0))
def test_acquire_channel(self):
"""Text context builder acquire channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.acquire_channel(0), pulse.AcquireChannel(0))
def test_control_channel(self):
"""Text context builder control channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.control_channels(0, 1)[0], pulse.ControlChannel(0))
class TestDirectivesV2(TestBuilderV2):
"""Test builder directives."""
def test_barrier_on_qubits(self):
"""Test barrier directive on qubits with backendV2.
A part of qubits map of Mumbai
0 -- 1 -- 4 --
|
|
2
"""
with pulse.build(self.backend) as schedule:
pulse.barrier(0, 1)
reference = pulse.ScheduleBlock()
reference += directives.RelativeBarrier(
pulse.DriveChannel(0),
pulse.DriveChannel(1),
pulse.MeasureChannel(0),
pulse.MeasureChannel(1),
pulse.ControlChannel(0),
pulse.ControlChannel(1),
pulse.ControlChannel(2),
pulse.ControlChannel(3),
pulse.ControlChannel(4),
pulse.ControlChannel(8),
pulse.AcquireChannel(0),
pulse.AcquireChannel(1),
)
self.assertEqual(schedule, reference)
class TestUtilitiesV2(TestBuilderV2):
"""Test builder utilities."""
def test_active_backend(self):
"""Test getting active builder backend."""
with pulse.build(self.backend):
self.assertEqual(pulse.active_backend(), self.backend)
def test_qubit_channels(self):
"""Test getting the qubit channels of the active builder's backend."""
with pulse.build(self.backend):
qubit_channels = pulse.qubit_channels(0)
self.assertEqual(
qubit_channels,
{
pulse.DriveChannel(0),
pulse.MeasureChannel(0),
pulse.AcquireChannel(0),
pulse.ControlChannel(0),
pulse.ControlChannel(1),
},
)
def test_active_transpiler_settings(self):
"""Test setting settings of active builder's transpiler."""
with pulse.build(self.backend):
self.assertFalse(pulse.active_transpiler_settings())
with pulse.transpiler_settings(test_setting=1):
self.assertEqual(pulse.active_transpiler_settings()["test_setting"], 1)
def test_active_circuit_scheduler_settings(self):
"""Test setting settings of active builder's circuit scheduler."""
with pulse.build(self.backend):
self.assertFalse(pulse.active_circuit_scheduler_settings())
with pulse.circuit_scheduler_settings(test_setting=1):
self.assertEqual(pulse.active_circuit_scheduler_settings()["test_setting"], 1)
def test_num_qubits(self):
"""Test builder utility to get number of qubits with backendV2."""
with pulse.build(self.backend):
self.assertEqual(pulse.num_qubits(), 27)
def test_samples_to_seconds(self):
"""Test samples to time with backendV2"""
target = self.backend.target
target.dt = 0.1
with pulse.build(self.backend):
time = pulse.samples_to_seconds(100)
self.assertTrue(isinstance(time, float))
self.assertEqual(pulse.samples_to_seconds(100), 10)
def test_samples_to_seconds_array(self):
"""Test samples to time (array format) with backendV2."""
target = self.backend.target
target.dt = 0.1
with pulse.build(self.backend):
samples = np.array([100, 200, 300])
times = pulse.samples_to_seconds(samples)
self.assertTrue(np.issubdtype(times.dtype, np.floating))
np.testing.assert_allclose(times, np.array([10, 20, 30]))
def test_seconds_to_samples(self):
"""Test time to samples with backendV2"""
target = self.backend.target
target.dt = 0.1
with pulse.build(self.backend):
samples = pulse.seconds_to_samples(10)
self.assertTrue(isinstance(samples, int))
self.assertEqual(pulse.seconds_to_samples(10), 100)
def test_seconds_to_samples_array(self):
"""Test time to samples (array format) with backendV2."""
target = self.backend.target
target.dt = 0.1
with pulse.build(self.backend):
times = np.array([10, 20, 30])
samples = pulse.seconds_to_samples(times)
self.assertTrue(np.issubdtype(samples.dtype, np.integer))
np.testing.assert_allclose(pulse.seconds_to_samples(times), np.array([100, 200, 300]))
class TestMacrosV2(TestBuilderV2):
"""Test builder macros with backendV2."""
def test_macro(self):
"""Test builder macro decorator."""
@pulse.macro
def nested(a):
pulse.play(pulse.Gaussian(100, a, 20), pulse.drive_channel(0))
return a * 2
@pulse.macro
def test():
pulse.play(pulse.Constant(100, 1.0), pulse.drive_channel(0))
output = nested(0.5)
return output
with pulse.build(self.backend) as schedule:
output = test()
self.assertEqual(output, 0.5 * 2)
reference = pulse.Schedule()
reference += pulse.Play(pulse.Constant(100, 1.0), pulse.DriveChannel(0))
reference += pulse.Play(pulse.Gaussian(100, 0.5, 20), pulse.DriveChannel(0))
self.assertScheduleEqual(schedule, reference)
def test_measure(self):
"""Test utility function - measure with backendV2."""
with pulse.build(self.backend) as schedule:
reg = pulse.measure(0)
self.assertEqual(reg, pulse.MemorySlot(0))
reference = macros.measure(qubits=[0], backend=self.backend, meas_map=self.backend.meas_map)
self.assertScheduleEqual(schedule, reference)
def test_measure_multi_qubits(self):
"""Test utility function - measure with multi qubits with backendV2."""
with pulse.build(self.backend) as schedule:
regs = pulse.measure([0, 1])
self.assertListEqual(regs, [pulse.MemorySlot(0), pulse.MemorySlot(1)])
reference = macros.measure(
qubits=[0, 1], backend=self.backend, meas_map=self.backend.meas_map
)
self.assertScheduleEqual(schedule, reference)
def test_measure_all(self):
"""Test utility function - measure with backendV2.."""
with pulse.build(self.backend) as schedule:
regs = pulse.measure_all()
self.assertEqual(regs, [pulse.MemorySlot(i) for i in range(self.backend.num_qubits)])
reference = macros.measure_all(self.backend)
self.assertScheduleEqual(schedule, reference)
def test_delay_qubit(self):
"""Test delaying on a qubit macro."""
with pulse.build(self.backend) as schedule:
pulse.delay_qubits(10, 0)
d0 = pulse.DriveChannel(0)
m0 = pulse.MeasureChannel(0)
a0 = pulse.AcquireChannel(0)
u0 = pulse.ControlChannel(0)
u1 = pulse.ControlChannel(1)
reference = pulse.Schedule()
reference += instructions.Delay(10, d0)
reference += instructions.Delay(10, m0)
reference += instructions.Delay(10, a0)
reference += instructions.Delay(10, u0)
reference += instructions.Delay(10, u1)
self.assertScheduleEqual(schedule, reference)
def test_delay_qubits(self):
"""Test delaying on multiple qubits with backendV2 to make sure we don't insert delays twice."""
with pulse.build(self.backend) as schedule:
pulse.delay_qubits(10, 0, 1)
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
m0 = pulse.MeasureChannel(0)
m1 = pulse.MeasureChannel(1)
a0 = pulse.AcquireChannel(0)
a1 = pulse.AcquireChannel(1)
u0 = pulse.ControlChannel(0)
u1 = pulse.ControlChannel(1)
u2 = pulse.ControlChannel(2)
u3 = pulse.ControlChannel(3)
u4 = pulse.ControlChannel(4)
u8 = pulse.ControlChannel(8)
reference = pulse.Schedule()
reference += instructions.Delay(10, d0)
reference += instructions.Delay(10, d1)
reference += instructions.Delay(10, m0)
reference += instructions.Delay(10, m1)
reference += instructions.Delay(10, a0)
reference += instructions.Delay(10, a1)
reference += instructions.Delay(10, u0)
reference += instructions.Delay(10, u1)
reference += instructions.Delay(10, u2)
reference += instructions.Delay(10, u3)
reference += instructions.Delay(10, u4)
reference += instructions.Delay(10, u8)
self.assertScheduleEqual(schedule, reference)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
from qiskit import *
X = Matrix([[0,1],[1,0]]); Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]]); I = Matrix([[1,0],[0,1]])
xa,ya,za,xb,yb,zb = symbols('x_a y_a z_a x_b y_b z_b')
xx,xy,xz,yx,yy,yz,zx,zy,zz = symbols('xx xy xz yx yy yz zx zy zz')
rho_ab = (1/4)*(tp(I,I) + xa*tp(X,I) + ya*tp(Y,I) + za*tp(Z,I) + xb*tp(I,X) + yb*tp(I,Y) + zb*tp(I,Z))
rho_ab += (1/4)*(xx*tp(X,X) + xy*tp(X,Y) + xz*tp(X,Z) + yx*tp(Y,X) + yy*tp(Y,Y) + yz*tp(Y,Z))
rho_ab += (1/4)*(zx*tp(Z,X) + xy*tp(Z,Y) + zz*tp(Z,Z))
rho_ab
trace(rho_ab)
def ptraceA(da, db, rho):
rhoB = zeros(db,db)
for j in range(0, db):
for k in range(0, db):
for l in range(0, da):
rhoB[j,k] += rho[l*db+j,l*db+k]
return rhoB
def ptraceB(da, db, rho):
rhoA = zeros(da,da)
for j in range(0, da):
for k in range(0, da):
for l in range(0, db):
rhoA[j,k] += rho[j*db+l,k*db+l]
return rhoA
rho_a = ptraceB(2, 2, rho_ab); rho_a
rho_b = ptraceA(2, 2, rho_ab); rho_b
# alguns resultados prontos que usare de init.ipynb
cb(2,0), cb(2,1), id(2), pauli(1), proj(cb(2,0)), tp(cb(2,0),cb(2,0))
CX_ab = tp(proj(cb(2,0)),id(2)) + tp(proj(cb(2,1)),pauli(1)); CX_ab
CX_ba = tp(id(2),proj(cb(2,0))) + tp(pauli(1),proj(cb(2,1))); CX_ba
SWAP = CX_ab*CX_ba*CX_ab; SWAP
SWAP = CX_ba*CX_ab*CX_ba; SWAP
# aplica a troca ao estado de 2 qubits
rho_ab_swap = SWAP*rho_ab*SWAP # pois a SWAP é hermitiana
# verificação que a troca ocorreu
rho_a_swap = ptraceB(2, 2, rho_ab_swap); rho_a_swap
rho_b_swap = ptraceA(2, 2, rho_ab_swap); rho_b_swap
def pTraceL_num(dl, dr, rhoLR):
# Returns the left partial trace over the 'left' subsystem of rhoLR
rhoR = np.zeros((dr, dr), dtype=complex)
for j in range(0, dr):
for k in range(j, dr):
for l in range(0, dl):
rhoR[j,k] += rhoLR[l*dr+j,l*dr+k]
if j != k:
rhoR[k,j] = np.conj(rhoR[j,k])
return rhoR
def pTraceR_num(dl, dr, rhoLR):
# Returns the right partial trace over the 'right' subsystem of rhoLR
rhoL = np.zeros((dl, dl), dtype=complex)
for j in range(0, dl):
for k in range(j, dl):
for l in range(0, dr):
rhoL[j,k] += rhoLR[j*dr+l,k*dr+l]
if j != k:
rhoL[k,j] = np.conj(rhoL[j,k])
return rhoL
qr = QuantumRegister(2); qc = QuantumCircuit(qr)
qc.h(qr[1]); qc.s(qr[1]); qc.draw()
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
nshots = 8192
qstc = state_tomography_circuits(qc, [qr[0],qr[1]]); # circuito para TEQ
job = qiskit.execute(qstc, Aer.get_backend('qasm_simulator'), shots=nshots) # executa no simulador
qstf = StateTomographyFitter(job.result(), qstc) # ajusta os dados
rhoBA = qstf.fit(method='lstsq'); rhoBA # extrai o operador densidade
rhoA = pTraceL_num(2, 2, rhoBA); rhoA
rhoB = pTraceR_num(2, 2, rhoBA); rhoB
qc.cx(qr[0],qr[1]); qc.cx(qr[0],qr[1]); qc.draw()
# data contém todas as portas lógicas do cicuito quântico em uma lista (ou dicionário)
data = qc.data; data
# imprime uma componente de qc.data
print( data[3] )
# deleta uma componente de data
data.pop(3)
data.pop(4)
data.pop(3)
# agora o circuit está como queremos
qc.draw()
qc.cx(qr[1],qr[0]); qc.draw()
data = qc.data; data.pop(3)
qc.cx(qr[0],qr[1]); qc.draw()
qstc = state_tomography_circuits(qc, [qr[0],qr[1]]); # circuito para TEQ
job = qiskit.execute(qstc, Aer.get_backend('qasm_simulator'), shots=nshots) # executa no simulador
qstf = StateTomographyFitter(job.result(), qstc) # ajusta os dados
rhoBA = qstf.fit(method='lstsq'); # extrai o operador densidade
rhoA = pTraceL_num(2, 2, rhoBA); rhoA
rhoB = pTraceR_num(2, 2, rhoBA); rhoB
qr = QuantumRegister(2); qc = QuantumCircuit(qr)
qc.h(qr[1]); qc.s(qr[1]); qc.barrier(); qc.draw()
qiskit.IBMQ.load_account();
provider = IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
device = provider.get_backend('ibmq_belem')
from qiskit.tools.monitor import job_monitor
qstc = state_tomography_circuits(qc, [qr[0],qr[1]]); # circuito para TEQ
job = qiskit.execute(qstc, backend = device, shots = nshots)
print(job.job_id()); job_monitor(job)
qstf = StateTomographyFitter(job.result(), qstc) # ajusta os dados
rhoBA = qstf.fit(method='lstsq'); # extrai o operador densidade
rhoA = pTraceL_num(2, 2, rhoBA); rhoA
rhoB = pTraceR_num(2, 2, rhoBA); rhoB
qc.cx(qr[0],qr[1]); qc.cx(qr[1],qr[0]); qc.cx(qr[0],qr[1]);
data = qc.data; data.pop(5)
qc.draw()
qstc = state_tomography_circuits(qc, [qr[0],qr[1]]); # circuito para TEQ
job = qiskit.execute(qstc, backend = device, shots = nshots)
print(job.job_id()); job_monitor(job)
qstf = StateTomographyFitter(job.result(), qstc) # ajusta os dados
rhoBA = qstf.fit(method='lstsq'); # extrai o operador densidade
rhoA = pTraceL_num(2, 2, rhoBA); rhoA
rhoB = pTraceR_num(2, 2, rhoBA); rhoB
def psi(th):
return cos(th/2)*cb(2,0) + sin(th/2)*cb(2,1)
th, ph = symbols('theta phi'); psi(th)
def Psi(th,ph):
return CX_ab*tp(psi(th),psi(ph))
th, ph = symbols('theta phi'); Psi(th,ph)
th, ph = math.pi/3, math.pi/4; Psi(th,ph)
def rhoA(th,ph):
return ptraceB(2, 2, proj(Psi(th,ph)))
th, ph = symbols('theta phi'); simplify(rhoA(th,ph))
th, ph = math.pi/3, math.pi/4; simplify(rhoA(th,ph))
rhoa = rhoA(th,ph); rhoa.eigenvals()
def rhoB(th,ph):
return ptraceA(2, 2, proj(Psi(th,ph)))
th, ph = symbols('theta phi'); simplify(rhoB(th,ph))
th, ph = math.pi/3, math.pi/4; simplify(rhoB(th,ph))
rhob = rhoB(th,ph); rhob.eigenvals()
qr = QuantumRegister(2); qc = QuantumCircuit(qr)
th = math.pi/3; ph = math.pi/4
qc.u(th,0,0,qr[0]); qc.u(ph,0,0,qr[1]); qc.cx(qr[0],qr[1]); qc.barrier();
qc.draw()
data = qc.data; data.pop(1);
qstc = state_tomography_circuits(qc, [qr[0],qr[1]]); # circuito para TEQ
job = qiskit.execute(qstc, Aer.get_backend('qasm_simulator'), shots=nshots) # executa no simulador
qstf = StateTomographyFitter(job.result(), qstc) # ajusta os dados
rhoBA = qstf.fit(method='lstsq'); # extrai o operador densidade
rhoA = pTraceL_num(2, 2, rhoBA); rhoA
rhoB = pTraceR_num(2, 2, rhoBA); rhoB
qstc = state_tomography_circuits(qc, [qr[0],qr[1]]); # circuito para TEQ
job = qiskit.execute(qstc, backend = device, shots = nshots)
print(job.job_id()); job_monitor(job)
rhoA = pTraceL_num(2, 2, rhoBA); rhoA
rhoB = pTraceR_num(2, 2, rhoBA); rhoB
qc.cx(qr[1],qr[0]); qc.cx(qr[0],qr[1]); qc.cx(qr[1],qr[0])
qc.draw()
qstc = state_tomography_circuits(qc, [qr[0],qr[1]]); # circuito para TEQ
job = qiskit.execute(qstc, Aer.get_backend('qasm_simulator'), shots=nshots) # executa no simulador
qstf = StateTomographyFitter(job.result(), qstc) # ajusta os dados
rhoBA = qstf.fit(method='lstsq'); # extrai o operador densidade
rhoA = pTraceL_num(2, 2, rhoBA); rhoA
rhoB = pTraceR_num(2, 2, rhoBA); rhoB
qstc = state_tomography_circuits(qc, [qr[0],qr[1]]); # circuito para TEQ
job = qiskit.execute(qstc, backend = device, shots = nshots)
print(job.job_id()); job_monitor(job)
rhoA = pTraceL_num(2, 2, rhoBA); rhoA
rhoB = pTraceR_num(2, 2, rhoBA); rhoB
|
https://github.com/EusseJhoan/DeutschJosza_algorithm
|
EusseJhoan
|
from qiskit import QuantumCircuit, transpile, Aer
from qiskit.visualization import plot_histogram
import numpy as np
sim = Aer.get_backend('aer_simulator')
def U_f1(qc):
return qc
def U_f2(qc):
qc.x(1) #Compuerta X al segundo qubit
return qc
def U_f3(qc):
qc.cx(0,1) #Compuerta CNOT entre primer y segundo quibit (el primero es el que controla)
return qc
def U_f4(qc):
qc.cx(0,1) #Compuerta CNOT entre primer y segundo quibit (el primero es el que controla)
qc.x(1) #Compuerta X al segundo qubit
return qc
def Deutsch(U_f):
qc=QuantumCircuit(2,1) #Se crea un circuito cuántico con 2 bits cuánticos y 1 canal clásico
qc.x(1) #Compuerta X al segundo qubit (inicializar estado |1>)
qc.h(0) #Compuerta H al primer qubit
qc.h(1) #Compuerta H al segundo qubit
qc.barrier() #Barrera (empieza oráculo)
qc = U_f(qc) #Agregamos el oráculo
qc.barrier() #Barrera (termina oráculo)
qc.h(0) #Compuerta H al primer qubit
qc.measure(0,0) #Medimos el primer qubit y enviamos señal al canal clásico
return qc
qc=Deutsch(U_f1) # definición circuito con oráculo usando f_1(x)
display(qc.draw()) # visualización del circuito
counts = sim.run(qc).result().get_counts() #contando las medidas de simulador cuántico
plot_histogram(counts) #histrograma de resultados
qc=Deutsch(U_f2) #definición circuito con oráculo usando f_2(x)
display(qc.draw()) # visualización del circuito
counts = sim.run(qc).result().get_counts() #contando las medidas del simulador cuántico
plot_histogram(counts) #histrograma de resultados
qc=Deutsch(U_f3) #definición circuito con oráculo usando f_3(x)
display(qc.draw()) # visualización del circuito
counts = sim.run(qc).result().get_counts() #contando las medidas de simulador cuántico
plot_histogram(counts) #histrograma de resultados
qc=Deutsch(U_f4) #definición circuito con oráculo usando f_4(x)
display(qc.draw()) # visualización del circuito
counts = sim.run(qc).result().get_counts() #contando las medidas de simulador cuántico
plot_histogram(counts) #histrograma de resultados
#oráculo para f(x) constante para un número n de bits en el registro
def constant(qc,n):
ran=np.random.randint(2) #selección aleatoria de 0 ó 1
if ran == 1:
qc.x(n) #si el número aleatorio es 1 se pone compuerta X en el objetivo (se induce fase global -1 al registro)
return qc
#oráculo para f(x) balanceado para un número n de bits en el registro
def balanced(qc,n):
for i in range(n):
qc.cx(i,n) #se crea una CNOT entre cada qubit del registro y el objetivo (los qubits del registro controlan)
ran=np.random.randint(2) #selección aleatoria de 0 ó 1
if ran == 1:
qc.x(n) #si el número aleatorio es 1 se pone compuerta X en el objetivo (se induce fase global -1 al registro)
return qc
def D_J(U_f,n):
qc=QuantumCircuit(n+1,n) #Se crea un circuito cuántico con n+1 quibits y n canales clásicos
qc.x(n) #Compuerta X al bit del registro
for i in range(n+1):
qc.h(i) #Compuerta H a todos los bits
qc.barrier() #Barrera (empieza oráculo)
qc = U_f(qc,n) #Agregamos el oráculo
qc.barrier() #Barrera (termina oráculo)
for i in range(n):
qc.h(i) #Compuerta H a los n bits del registro
qc.measure(i,i) #Medición los n bits del registro
return qc
qc=D_J(constant,3) #definición circuito con oráculo constante y 3 bits en registro
display(qc.draw()) #ver circuito
counts = sim.run(qc).result().get_counts() #contando las medidas de simulador cuántico
plot_histogram(counts) #histrograma de resultados
qc=D_J(balanced,3)
display(qc.draw())
counts = sim.run(qc).result().get_counts()
plot_histogram(counts)
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
from qiskit import *
print(qiskit.__version__)
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
from qiskit.providers.aer import QasmSimulator
# use Aer's qasm_simulator
simulator = QasmSimulator()
# create quantum circute 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=1024)
# grad results from the job
result = job.result()
# return counts
counts = result.get_counts(compiled_circuit)
print('total count for 00 and 11 are: ',counts)
# draw circuit
circuit.draw(output='mpl')
# plot histogram
plot_histogram(counts)
from qiskit.circuit import QuantumCircuit, Parameter
from qiskit.providers.aer import AerSimulator
backend = AerSimulator()
circuit = QuantumCircuit(2)
theta = Parameter('theta')
circuit.rx(234, 0)
circuit.draw(output='mpl')
backend = AerSimulator()
circuit = QuantumCircuit(2)
# theta = Parameter('theta')
circuit.rx(20, 0)
circuit.x(0)
circuit.h(1)
result = execute(circuit, backend=backend, shots=1024).result()
# counts=result.get_counts()
# print(counts)
circuit.draw(output='mpl')
|
https://github.com/rickapocalypse/final_paper_qiskit_sat
|
rickapocalypse
|
from qiskit import *
from qiskit.tools.visualization import plot_bloch_multivector
import matplotlib.pyplot as plt
from qiskit.visualization.gate_map import plot_coupling_map, plot_gate_map
from qiskit.visualization.state_visualization import plot_bloch_vector, plot_state_city, plot_state_paulivec
circuit = QuantumCircuit(1,1)
circuit.x(0)
simulator = Aer.get_backend('statevector_simulator')
result = execute(circuit, backend = simulator).result()
statevector = result.get_statevector()
print(statevector)
simulator2 = Aer.get_backend('unitary_simulator')
result = execute(circuit, backend= simulator2).result()
unitary = result.get_unitary()
print(unitary)
|
https://github.com/Ilan-Bondarevsky/qiskit_algorithm
|
Ilan-Bondarevsky
|
from qiskit import QuantumCircuit, QuantumRegister, AncillaRegister
from itertools import combinations
def and_gate(a = 0 , b = 0):
'''Create an AND gate in qiskit\n
The values of "a" and "b" are inisializing the qubits, the values (0/1)'''
qc = QuantumCircuit(QuantumRegister(2), AncillaRegister(1))
if a:
qc.x(0)
if b:
qc.x(1)
qc.mcx([0,1], qc.ancillas)
return qc
def nand_gate(a = 0 , b = 0):
'''Create an NAND gate in qiskit\n
The values of "a" and "b" are inisializing the qubits, the values (0/1)'''
qc = QuantumCircuit(QuantumRegister(2), AncillaRegister(1))
if a:
qc.x(0)
if b:
qc.x(1)
qc.mcx([0,1], qc.ancillas)
qc.x(qc.ancillas)
return qc
def mand_gate(nqubits, values = []):
'''Create an AND gate in qiskit with multiple qubits\n
The values in the list are corresponding to the qubits, the values (0/1)'''
qc = QuantumCircuit(QuantumRegister(nqubits), AncillaRegister(1))
for i, val in enumerate(values):
if val:
qc.x(i)
qc.mcx(list(range(nqubits)), qc.ancillas)
return qc
def xor_gate(a = 0 , b = 0):
'''Create an XOR gate in qiskit\n
The values of "a" and "b" are inisializing the qubits, the values (0/1)'''
qc = QuantumCircuit(QuantumRegister(2), AncillaRegister(1))
if a:
qc.x(0)
if b:
qc.x(1)
qc.cx(0, qc.ancillas)
qc.cx(1, qc.ancillas)
return qc
def xnor_gate(a = 0 , b = 0):
'''Create an XNOR gate in qiskit\n
The values of "a" and "b" are inisializing the qubits, the values (0/1)'''
qc = QuantumCircuit(QuantumRegister(2), AncillaRegister(1))
if a:
qc.x(0)
if b:
qc.x(1)
qc.cx(0, qc.ancillas)
qc.cx(1, qc.ancillas)
qc.x(qc.ancillas)
return qc
def mxor_gate(nqubits, values = []):
'''Create an XOR gate in qiskit with multiple qubits\n
The values in the list are corresponding to the qubits, the values (0/1)'''
qc = QuantumCircuit(QuantumRegister(nqubits), AncillaRegister(1))
for i, val in enumerate(values):
if val:
qc.x(i)
for i in range(nqubits):
qc.cx(i, qc.ancillas)
return qc
def or_gate(a = 0 , b = 0):
'''Create an OR gate in qiskit\n
The values of "a" and "b" are inisializing the qubits, the values (0/1)'''
qc = QuantumCircuit(QuantumRegister(2), AncillaRegister(1))
if a:
qc.x(0)
if b:
qc.x(1)
qc.cx(0, qc.ancillas)
qc.cx(1, qc.ancillas)
qc.mcx([0,1], qc.ancillas)
return qc
def nor_gate(a = 0 , b = 0):
'''Create an NOR gate in qiskit\n
The values of "a" and "b" are inisializing the qubits, the values (0/1)'''
qc = QuantumCircuit(QuantumRegister(2), AncillaRegister(1))
if a:
qc.x(0)
if b:
qc.x(1)
qc.cx(0, qc.ancillas)
qc.cx(1, qc.ancillas)
qc.mcx([0,1], qc.ancillas)
qc.x(qc.ancillas)
return qc
def mor_gate(nqubits, values = []):
'''Create an OR gate in qiskit with multiple qubits\n
The values in the list are corresponding to the qubits, the values (0/1)'''
qc = QuantumCircuit(QuantumRegister(nqubits), AncillaRegister(1))
for i, val in enumerate(values):
if val:
qc.x(i)
or_cirq = []
for i in range(1, nqubits + 1):
or_cirq = or_cirq + list(combinations(list(range(nqubits)), i))
for circ in or_cirq:
qc.mcx(list(circ), qc.ancillas)
return qc
|
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/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.
"""Depth pass testing"""
import unittest
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.passes import CountOps
from qiskit.test import QiskitTestCase
class TestCountOpsPass(QiskitTestCase):
"""Tests for CountOps analysis methods."""
def test_empty_dag(self):
"""Empty DAG has empty counts."""
circuit = QuantumCircuit()
dag = circuit_to_dag(circuit)
pass_ = CountOps()
_ = pass_.run(dag)
self.assertDictEqual(pass_.property_set["count_ops"], {})
def test_just_qubits(self):
"""A dag with 8 operations (6 CXs and 2 Hs)"""
# ┌───┐ ┌───┐┌───┐
# q0_0: ┤ H ├──■────■────■────■──┤ X ├┤ X ├
# ├───┤┌─┴─┐┌─┴─┐┌─┴─┐┌─┴─┐└─┬─┘└─┬─┘
# q0_1: ┤ H ├┤ X ├┤ X ├┤ X ├┤ X ├──■────■──
# └───┘└───┘└───┘└───┘└───┘
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[1], qr[0])
dag = circuit_to_dag(circuit)
pass_ = CountOps()
_ = pass_.run(dag)
self.assertDictEqual(pass_.property_set["count_ops"], {"cx": 6, "h": 2})
if __name__ == "__main__":
unittest.main()
|
https://github.com/zapatacomputing/qe-qiskit
|
zapatacomputing
|
################################################################################
# © Copyright 2021-2022 Zapata Computing Inc.
################################################################################
import hashlib
from typing import Dict, Iterable, List, NamedTuple, Sequence, Tuple, Union
import numpy as np
import qiskit
import sympy
from orquestra.quantum.circuits import (
_builtin_gates,
_circuit,
_gates,
_operations,
_wavefunction_operations,
)
from orquestra.quantum.circuits.symbolic.sympy_expressions import (
SYMPY_DIALECT,
expression_from_sympy,
)
from orquestra.quantum.circuits.symbolic.translations import translate_expression
from ._qiskit_expressions import QISKIT_DIALECT, expression_from_qiskit
QiskitTriplet = Tuple[
qiskit.circuit.Instruction, List[qiskit.circuit.Qubit], List[qiskit.circuit.Clbit]
]
def _import_qiskit_qubit(qubit: qiskit.circuit.Qubit) -> int:
return qubit._index
def _qiskit_expr_from_orquestra(expr):
intermediate = expression_from_sympy(expr)
return translate_expression(intermediate, QISKIT_DIALECT)
def _orquestra_expr_from_qiskit(expr):
intermediate = expression_from_qiskit(expr)
return translate_expression(intermediate, SYMPY_DIALECT)
ORQUESTRA_QISKIT_GATE_MAP = {
_builtin_gates.X: qiskit.circuit.library.XGate,
_builtin_gates.Y: qiskit.circuit.library.YGate,
_builtin_gates.Z: qiskit.circuit.library.ZGate,
_builtin_gates.S: qiskit.circuit.library.SGate,
_builtin_gates.SX: qiskit.circuit.library.SXGate,
_builtin_gates.T: qiskit.circuit.library.TGate,
_builtin_gates.H: qiskit.circuit.library.HGate,
_builtin_gates.I: qiskit.circuit.library.IGate,
_builtin_gates.CNOT: qiskit.circuit.library.CXGate,
_builtin_gates.CZ: qiskit.circuit.library.CZGate,
_builtin_gates.SWAP: qiskit.circuit.library.SwapGate,
_builtin_gates.ISWAP: qiskit.circuit.library.iSwapGate,
_builtin_gates.RX: qiskit.circuit.library.RXGate,
_builtin_gates.RY: qiskit.circuit.library.RYGate,
_builtin_gates.RZ: qiskit.circuit.library.RZGate,
_builtin_gates.PHASE: qiskit.circuit.library.PhaseGate,
_builtin_gates.CPHASE: qiskit.circuit.library.CPhaseGate,
_builtin_gates.XX: qiskit.circuit.library.RXXGate,
_builtin_gates.YY: qiskit.circuit.library.RYYGate,
_builtin_gates.ZZ: qiskit.circuit.library.RZZGate,
_builtin_gates.U3: qiskit.circuit.library.U3Gate,
_builtin_gates.Delay: qiskit.circuit.Delay,
}
def _make_gate_instance(gate_ref, gate_params) -> _gates.Gate:
"""Returns a gate instance that's applicable to qubits.
For non-parametric gate refs like X, returns just the `X`
For parametric gate factories like `RX`, returns the produced gate, like `RX(0.2)`
"""
if _gates.gate_is_parametric(gate_ref, gate_params):
return gate_ref(*gate_params)
else:
return gate_ref
def _make_controlled_gate_prototype(wrapped_gate_ref, num_control_qubits=1):
def _factory(*gate_params):
return _gates.ControlledGate(
_make_gate_instance(wrapped_gate_ref, gate_params), num_control_qubits
)
return _factory
QISKIT_ORQUESTRA_GATE_MAP = {
**{q_cls: z_ref for z_ref, q_cls in ORQUESTRA_QISKIT_GATE_MAP.items()},
qiskit.extensions.SXdgGate: _builtin_gates.SX.dagger,
qiskit.extensions.SdgGate: _builtin_gates.S.dagger,
qiskit.extensions.TdgGate: _builtin_gates.T.dagger,
qiskit.circuit.library.CSwapGate: _builtin_gates.SWAP.controlled(1),
qiskit.circuit.library.CRXGate: _make_controlled_gate_prototype(_builtin_gates.RX),
qiskit.circuit.library.CRYGate: _make_controlled_gate_prototype(_builtin_gates.RY),
qiskit.circuit.library.CRZGate: _make_controlled_gate_prototype(_builtin_gates.RZ),
}
def export_to_qiskit(circuit: _circuit.Circuit) -> qiskit.QuantumCircuit:
q_circuit = qiskit.QuantumCircuit(circuit.n_qubits)
q_register = qiskit.circuit.QuantumRegister(circuit.n_qubits, "q")
gate_op_only_circuit = _circuit.Circuit(
[op for op in circuit.operations if isinstance(op, _gates.GateOperation)]
)
custom_names = {
gate_def.gate_name
for gate_def in gate_op_only_circuit.collect_custom_gate_definitions()
}
q_triplets = []
for gate_op in circuit.operations:
if isinstance(gate_op, _gates.GateOperation):
q_triplet = _export_gate_to_qiskit(
gate_op.gate,
applied_qubit_indices=gate_op.qubit_indices,
q_register=q_register,
custom_names=custom_names,
)
elif isinstance(gate_op, _wavefunction_operations.ResetOperation):
q_triplet = (
qiskit.circuit.library.Reset(),
[q_register[gate_op.qubit_indices[0]]],
[],
)
q_triplets.append(q_triplet)
for q_gate, q_qubits, q_clbits in q_triplets:
q_circuit.append(q_gate, q_qubits, q_clbits)
return q_circuit
def _export_gate_to_qiskit(gate, applied_qubit_indices, q_register, custom_names):
try:
return _export_gate_via_mapping(
gate, applied_qubit_indices, q_register, custom_names
)
except ValueError:
pass
try:
return _export_dagger_gate(
gate, applied_qubit_indices, q_register, custom_names
)
except ValueError:
pass
try:
return _export_controlled_gate(
gate, applied_qubit_indices, q_register, custom_names
)
except ValueError:
pass
try:
return _export_custom_gate(
gate, applied_qubit_indices, q_register, custom_names
)
except ValueError:
pass
raise NotImplementedError(f"Exporting gate {gate} to Qiskit is unsupported")
def _export_gate_via_mapping(gate, applied_qubit_indices, q_register, custom_names):
try:
qiskit_cls = ORQUESTRA_QISKIT_GATE_MAP[
_builtin_gates.builtin_gate_by_name(gate.name)
]
except KeyError:
raise ValueError(f"Can't export gate {gate} to Qiskit via mapping")
qiskit_params = [_qiskit_expr_from_orquestra(param) for param in gate.params]
qiskit_qubits = [q_register[index] for index in applied_qubit_indices]
return qiskit_cls(*qiskit_params), qiskit_qubits, []
def _export_dagger_gate(
gate: _gates.Dagger,
applied_qubit_indices,
q_register,
custom_names,
):
if not isinstance(gate, _gates.Dagger):
# Raising an exception here is redundant to the type hint, but it allows us
# to handle exporting all gates in the same way, regardless of type
raise ValueError(f"Can't export gate {gate} as a dagger gate")
target_gate, qiskit_qubits, qiskit_clbits = _export_gate_to_qiskit(
gate.wrapped_gate,
applied_qubit_indices=applied_qubit_indices,
q_register=q_register,
custom_names=custom_names,
)
return target_gate.inverse(), qiskit_qubits, qiskit_clbits
def _export_controlled_gate(
gate: _gates.ControlledGate,
applied_qubit_indices,
q_register,
custom_names,
):
if not isinstance(gate, _gates.ControlledGate):
# Raising an exception here is redundant to the type hint, but it allows us
# to handle exporting all gates in the same way, regardless of type
raise ValueError(f"Can't export gate {gate} as a controlled gate")
target_indices = applied_qubit_indices[gate.num_control_qubits :]
target_gate, _, _ = _export_gate_to_qiskit(
gate.wrapped_gate,
applied_qubit_indices=target_indices,
q_register=q_register,
custom_names=custom_names,
)
controlled_gate = target_gate.control(gate.num_control_qubits)
qiskit_qubits = [q_register[index] for index in applied_qubit_indices]
return controlled_gate, qiskit_qubits, []
def _export_custom_gate(
gate: _gates.MatrixFactoryGate,
applied_qubit_indices,
q_register,
custom_names,
):
if gate.name not in custom_names:
raise ValueError(
f"Can't export gate {gate} as a custom gate, the circuit is missing its "
"definition"
)
if gate.params:
raise ValueError(
f"Can't export parametrized gate {gate}, Qiskit doesn't support "
"parametrized custom gates"
)
# At that time of writing it Qiskit doesn't support parametrized gates defined with
# a symbolic matrix.
# See https://github.com/Qiskit/qiskit-terra/issues/4751 for more info.
qiskit_qubits = [q_register[index] for index in applied_qubit_indices]
qiskit_matrix = np.array(gate.matrix)
return (
qiskit.extensions.UnitaryGate(qiskit_matrix, label=gate.name),
qiskit_qubits,
[],
)
class AnonGateOperation(NamedTuple):
gate_name: str
matrix: sympy.Matrix
qubit_indices: Tuple[int, ...]
ImportedOperation = Union[_operations.Operation, AnonGateOperation]
def _apply_custom_gate(
anon_op: AnonGateOperation, custom_defs_map: Dict[str, _gates.CustomGateDefinition]
) -> _gates.GateOperation:
gate_def = custom_defs_map[anon_op.gate_name]
# Qiskit doesn't support custom gates with parametrized matrices
# so we can assume empty params list.
gate_params: Tuple[sympy.Symbol, ...] = tuple()
gate = gate_def(*gate_params)
return gate(*anon_op.qubit_indices)
def import_from_qiskit(circuit: qiskit.QuantumCircuit) -> _circuit.Circuit:
q_ops = [_import_qiskit_triplet(triplet) for triplet in circuit.data]
anon_ops = [op for op in q_ops if isinstance(op, AnonGateOperation)]
# Qiskit doesn't support custom gates with parametrized matrices
# so we can assume empty params list.
params_ordering: Tuple[sympy.Symbol, ...] = tuple()
custom_defs = {
anon_op.gate_name: _gates.CustomGateDefinition(
gate_name=anon_op.gate_name,
matrix=anon_op.matrix,
params_ordering=params_ordering,
)
for anon_op in anon_ops
}
imported_ops = [
_apply_custom_gate(op, custom_defs) if isinstance(op, AnonGateOperation) else op
for op in q_ops
]
return _circuit.Circuit(
operations=imported_ops,
n_qubits=circuit.num_qubits,
)
def _import_qiskit_triplet(qiskit_triplet: QiskitTriplet) -> ImportedOperation:
qiskit_op, qiskit_qubits, _ = qiskit_triplet
return _import_qiskit_op(qiskit_op, qiskit_qubits)
def _import_qiskit_op(qiskit_op, qiskit_qubits) -> ImportedOperation:
# We always wanna try importing via mapping to handle complex gate structures
# represented by a single class, like CNOT (Control + X) or CSwap (Control + Swap).
try:
return _import_qiskit_op_via_mapping(qiskit_op, qiskit_qubits)
except ValueError:
pass
try:
return _import_controlled_qiskit_op(qiskit_op, qiskit_qubits)
except ValueError:
pass
try:
return _import_custom_qiskit_gate(qiskit_op, qiskit_qubits)
except AttributeError:
raise ValueError(f"Conversion of {qiskit_op.name} from Qiskit is unsupported.")
def _import_qiskit_op_via_mapping(
qiskit_gate: qiskit.circuit.Instruction,
qiskit_qubits: Iterable[qiskit.circuit.Qubit],
) -> _operations.Operation:
qubit_indices = [_import_qiskit_qubit(qubit) for qubit in qiskit_qubits]
if isinstance(qiskit_gate, qiskit.circuit.library.Reset):
return _wavefunction_operations.ResetOperation(qubit_indices[0])
try:
gate_ref = QISKIT_ORQUESTRA_GATE_MAP[type(qiskit_gate)]
except KeyError:
raise ValueError(f"Conversion of {qiskit_gate} from Qiskit is unsupported.")
# values to consider:
# - gate matrix parameters (only parametric gates)
# - gate application indices (all gates)
orquestra_params = [
_orquestra_expr_from_qiskit(param) for param in qiskit_gate.params
]
gate = _make_gate_instance(gate_ref, orquestra_params)
return _gates.GateOperation(gate=gate, qubit_indices=tuple(qubit_indices))
def _import_controlled_qiskit_op(
qiskit_gate: qiskit.circuit.ControlledGate,
qiskit_qubits: Sequence[qiskit.circuit.Qubit],
) -> _gates.GateOperation:
if not isinstance(qiskit_gate, qiskit.circuit.ControlledGate):
# Raising an exception here is redundant to the type hint, but it allows us
# to handle exporting all gates in the same way, regardless of type
raise ValueError(f"Can't import gate {qiskit_gate} as a controlled gate")
wrapped_qubits = qiskit_qubits[qiskit_gate.num_ctrl_qubits :]
wrapped_op = _import_qiskit_op(qiskit_gate.base_gate, wrapped_qubits)
qubit_indices = map(_import_qiskit_qubit, qiskit_qubits)
if isinstance(wrapped_op, _gates.GateOperation):
return wrapped_op.gate.controlled(qiskit_gate.num_ctrl_qubits)(*qubit_indices)
else:
raise NotImplementedError(
"Importing of controlled anonymous gates not yet supported."
)
def _hash_hex(bytes_):
return hashlib.sha256(bytes_).hexdigest()
def _custom_qiskit_gate_name(gate_label: str, gate_name: str, matrix: np.ndarray):
matrix_hash = _hash_hex(matrix.tobytes())
target_name = gate_label or gate_name
return f"{target_name}.{matrix_hash}"
def _import_custom_qiskit_gate(
qiskit_op: qiskit.circuit.Gate, qiskit_qubits: Iterable[qiskit.circuit.Qubit]
) -> AnonGateOperation:
value_matrix = qiskit_op.to_matrix()
return AnonGateOperation(
gate_name=_custom_qiskit_gate_name(
qiskit_op.label, qiskit_op.name, value_matrix
),
matrix=sympy.Matrix(value_matrix),
qubit_indices=tuple(_import_qiskit_qubit(qubit) for qubit in qiskit_qubits),
)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
simplify(cos(pi/8)), simplify(sin(pi/8))
from qiskit.visualization import plot_bloch_vector
th, ph = pi/4, 0
#plot_bloch_vector([[math.sin(th)*math.cos(ph), math.sin(th)*math.sin(ph), math.cos(th)]])
float(1+1/sqrt(2))/2
X = Matrix([[0,1],[1,0]]); Z = Matrix([[1,0],[0,-1]]); O = (X+Z)/sqrt(2); O.eigenvects()
from qiskit import *
nshots = 8192
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
simulator = Aer.get_backend('qasm_simulator')
device = provider.get_backend('ibmq_belem')
from qiskit.tools.monitor import job_monitor
from qiskit.tools.visualization import plot_histogram
qc = QuantumCircuit(1, 1)
qc.h(0) # preparação do estado
qc.barrier()
# medida de O=H
th = math.pi/4; ph = 0; lb = math.pi - ph; qc.u(th, ph, lb, 0)
qc.measure(0, 0)
qc.draw()
result = execute(qc, backend = simulator, shots = nshots).result()
plot_histogram(result.get_counts(qc))
job = execute(qc, backend = device, shots = nshots)
job_monitor(job)
plot_histogram(job.result().get_counts(qc))
def qc_bb_cb():
qc = QuantumCircuit(2, name = 'BB->CB')
qc.cx(0,1); qc.h(0)#; qc.measure([0,1],[0,1])
return qc
qc_bb_cb_ = qc_bb_cb(); qc_bb_cb_.draw()
qc = QuantumCircuit(2, 2)
qc.x(1); qc.h([0,1]) # preparação do estado |+->
qc.barrier()
qc_bb_cb_ = qc_bb_cb(); qc.append(qc_bb_cb_, [0,1]); qc.measure([0,1],[0,1])
qc.draw()
result = execute(qc, backend = simulator, shots = nshots).result()
plot_histogram(result.get_counts(qc))
job = execute(qc, backend = device, shots = nshots)
job_monitor(job)
plot_histogram(job.result().get_counts(qc))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
import numpy as np
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.primitives import Sampler
from qiskit.utils import algorithm_globals
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder, MinMaxScaler
from qiskit_machine_learning.algorithms.classifiers import VQC
from IPython.display import clear_output
algorithm_globals.random_seed = 42
sampler1 = Sampler()
sampler2 = Sampler()
num_samples = 40
num_features = 2
features = 2 * algorithm_globals.random.random([num_samples, num_features]) - 1
labels = 1 * (np.sum(features, axis=1) >= 0) # in { 0, 1}
features = MinMaxScaler().fit_transform(features)
features.shape
features[0:5, :]
labels = OneHotEncoder(sparse=False).fit_transform(labels.reshape(-1, 1))
labels.shape
labels[0:5, :]
train_features, test_features, train_labels, test_labels = train_test_split(
features, labels, train_size=30, random_state=algorithm_globals.random_seed
)
train_features.shape
def plot_dataset():
plt.scatter(
train_features[np.where(train_labels[:, 0] == 0), 0],
train_features[np.where(train_labels[:, 0] == 0), 1],
marker="o",
color="b",
label="Label 0 train",
)
plt.scatter(
train_features[np.where(train_labels[:, 0] == 1), 0],
train_features[np.where(train_labels[:, 0] == 1), 1],
marker="o",
color="g",
label="Label 1 train",
)
plt.scatter(
test_features[np.where(test_labels[:, 0] == 0), 0],
test_features[np.where(test_labels[:, 0] == 0), 1],
marker="o",
facecolors="w",
edgecolors="b",
label="Label 0 test",
)
plt.scatter(
test_features[np.where(test_labels[:, 0] == 1), 0],
test_features[np.where(test_labels[:, 0] == 1), 1],
marker="o",
facecolors="w",
edgecolors="g",
label="Label 1 test",
)
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.plot([1, 0], [0, 1], "--", color="black")
plot_dataset()
plt.show()
maxiter = 20
objective_values = []
# callback function that draws a live plot when the .fit() method is called
def callback_graph(_, objective_value):
clear_output(wait=True)
objective_values.append(objective_value)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
stage1_len = np.min((len(objective_values), maxiter))
stage1_x = np.linspace(1, stage1_len, stage1_len)
stage1_y = objective_values[:stage1_len]
stage2_len = np.max((0, len(objective_values) - maxiter))
stage2_x = np.linspace(maxiter, maxiter + stage2_len - 1, stage2_len)
stage2_y = objective_values[maxiter : maxiter + stage2_len]
plt.plot(stage1_x, stage1_y, color="orange")
plt.plot(stage2_x, stage2_y, color="purple")
plt.show()
plt.rcParams["figure.figsize"] = (12, 6)
original_optimizer = COBYLA(maxiter=maxiter)
ansatz = RealAmplitudes(num_features)
initial_point = np.asarray([0.5] * ansatz.num_parameters)
original_classifier = VQC(
ansatz=ansatz, optimizer=original_optimizer, callback=callback_graph, sampler=sampler1
)
original_classifier.fit(train_features, train_labels)
print("Train score", original_classifier.score(train_features, train_labels))
print("Test score ", original_classifier.score(test_features, test_labels))
original_classifier.save("vqc_classifier.model")
loaded_classifier = VQC.load("vqc_classifier.model")
loaded_classifier.warm_start = True
loaded_classifier.neural_network.sampler = sampler2
loaded_classifier.optimizer = COBYLA(maxiter=80)
loaded_classifier.fit(train_features, train_labels)
print("Train score", loaded_classifier.score(train_features, train_labels))
print("Test score", loaded_classifier.score(test_features, test_labels))
train_predicts = loaded_classifier.predict(train_features)
test_predicts = loaded_classifier.predict(test_features)
# return plot to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
plot_dataset()
# plot misclassified data points
plt.scatter(
train_features[np.all(train_labels != train_predicts, axis=1), 0],
train_features[np.all(train_labels != train_predicts, axis=1), 1],
s=200,
facecolors="none",
edgecolors="r",
linewidths=2,
)
plt.scatter(
test_features[np.all(test_labels != test_predicts, axis=1), 0],
test_features[np.all(test_labels != test_predicts, axis=1), 1],
s=200,
facecolors="none",
edgecolors="r",
linewidths=2,
)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/rigetti/qiskit-rigetti
|
rigetti
|
##############################################################################
# Copyright 2021 Rigetti 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##############################################################################
import warnings
from collections import Counter
from datetime import datetime
from typing import Optional, Dict, Any, List, Union, Iterator, cast
import numpy as np
from dateutil.tz import tzutc
from pyquil.api import QuantumComputer
from pyquil.api._qpu import QPUExecuteResponse
from pyquil.api._qvm import QVMExecuteResponse
from qiskit import QuantumCircuit
from qiskit.providers import JobStatus, JobV1, Backend
from qiskit.providers.models import QasmBackendConfiguration
from qiskit.qobj import QobjExperimentHeader
from qiskit.result import Result
from qiskit.result.models import ExperimentResult, ExperimentResultData
from .hooks.pre_compilation import PreCompilationHook
from .hooks.pre_execution import PreExecutionHook
Response = Union[QVMExecuteResponse, QPUExecuteResponse]
class RigettiQCSJob(JobV1):
"""
Class for representing execution jobs sent to Rigetti backends.
"""
def __init__(
self,
*,
job_id: str,
circuits: List[QuantumCircuit],
options: Dict[str, Any],
qc: QuantumComputer,
backend: Backend,
configuration: QasmBackendConfiguration,
) -> None:
"""
Args:
job_id: Unique identifier for this job
circuits: List of circuits to execute
options: Execution options (e.g. "shots")
qc: Quantum computer to run against
backend: :class:`RigettiQCSBackend` that created this job
configuration: Configuration from parent backend
"""
super().__init__(backend, job_id)
self._status = JobStatus.INITIALIZING
self._circuits = circuits
self._options = options
self._qc = qc
self._configuration = configuration
self._result: Optional[Result] = None
self._responses: List[Response] = []
self._start()
def submit(self) -> None:
"""
Raises:
NotImplementedError: This class uses the asynchronous pattern, so this method should not be called.
"""
raise NotImplementedError("'submit' is not implemented as this class uses the asynchronous pattern")
def _start(self) -> None:
self._responses = [self._start_circuit(circuit) for circuit in self._circuits]
self._status = JobStatus.RUNNING
def _start_circuit(self, circuit: QuantumCircuit) -> Response:
shots = self._options["shots"]
qasm = circuit.qasm()
qasm = self._handle_barriers(qasm, circuit.num_qubits)
before_compile: List[PreCompilationHook] = self._options.get("before_compile", [])
for fn in before_compile:
qasm = fn(qasm)
program = self._qc.compiler.transpile_qasm_2(qasm)
program = program.wrap_in_numshots_loop(shots)
before_execute: List[PreExecutionHook] = self._options.get("before_execute", [])
for fn in before_execute:
program = fn(program)
if self._options.get("ensure_native_quil") and len(before_execute) > 0:
program = self._qc.compiler.quil_to_native_quil(program)
executable = self._qc.compiler.native_quil_to_executable(program)
# typing: QuantumComputer's inner QAM is generic, so we set the expected type here
return cast(Response, self._qc.qam.execute(executable))
@staticmethod
def _handle_barriers(qasm: str, num_circuit_qubits: int) -> str:
lines = []
for line in qasm.splitlines():
if line.startswith("barrier"):
warnings.warn("barriers are currently omitted during execution on a RigettiQCSBackend")
continue
lines.append(line)
return "\n".join(lines)
def result(self) -> Result:
"""
Wait until the job is complete, then return a result.
Raises:
JobError: If there was a problem running the Job or retrieving the result
"""
if self._result is not None:
return self._result
now = datetime.now(tzutc())
results = []
success = True
for r in self._get_experiment_results():
results.append(r)
success &= r.success
self._result = Result(
backend_name=self._configuration.backend_name,
backend_version=self._configuration.backend_version,
qobj_id="",
job_id=self.job_id(),
success=success,
results=results,
date=now,
execution_duration_microseconds=[r.execution_duration_microseconds for r in results],
)
self._status = JobStatus.DONE if success else JobStatus.ERROR
return self._result
def _get_experiment_results(self) -> Iterator[ExperimentResult]:
shots = self._options["shots"]
for circuit_idx, response in enumerate(self._responses):
execution_result = self._qc.qam.get_result(response)
states = execution_result.readout_data["ro"]
memory = list(map(_to_binary_str, np.array(states)))
success = True
status = "Completed successfully"
circuit = self._circuits[circuit_idx]
yield ExperimentResult(
header=QobjExperimentHeader(name=circuit.name),
shots=shots,
success=success,
status=status,
data=ExperimentResultData(counts=Counter(memory), memory=memory),
execution_duration_microseconds=execution_result.execution_duration_microseconds,
)
def cancel(self) -> None:
"""
Raises:
NotImplementedError: There is currently no way to cancel this job.
"""
raise NotImplementedError("Cancelling jobs is not supported")
def status(self) -> JobStatus:
"""Get the current status of this Job
If this job was RUNNING when you called it, this function will block until the job is complete.
"""
if self._status == JobStatus.RUNNING:
# Wait for results _now_ to finish running, otherwise consuming code might wait forever.
self.result()
return self._status
def _to_binary_str(state: List[int]) -> str:
# NOTE: According to https://arxiv.org/pdf/1809.03452.pdf, this should be a hex string
# but it results in missing leading zeros in the displayed output, and binary strings
# seem to work too. Hex string could be accomplished with:
# hex(int(binary_str, 2))
binary_str = "".join(map(str, state[::-1]))
return binary_str
|
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
|
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()
|
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-docstring,invalid-name,no-member
# pylint: disable=attribute-defined-outside-init
import os
import qiskit
class TranspilerBenchSuite:
def _build_cx_circuit(self):
cx_register = qiskit.QuantumRegister(2)
cx_circuit = qiskit.QuantumCircuit(cx_register)
cx_circuit.h(cx_register[0])
cx_circuit.h(cx_register[0])
cx_circuit.cx(cx_register[0], cx_register[1])
cx_circuit.cx(cx_register[0], cx_register[1])
cx_circuit.cx(cx_register[0], cx_register[1])
cx_circuit.cx(cx_register[0], cx_register[1])
return cx_circuit
def _build_single_gate_circuit(self):
single_register = qiskit.QuantumRegister(1)
single_gate_circuit = qiskit.QuantumCircuit(single_register)
single_gate_circuit.h(single_register[0])
return single_gate_circuit
def setup(self):
self.single_gate_circuit = self._build_single_gate_circuit()
self.cx_circuit = self._build_cx_circuit()
self.qasm_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "qasm"))
large_qasm_path = os.path.join(self.qasm_path, "test_eoh_qasm.qasm")
self.large_qasm = qiskit.QuantumCircuit.from_qasm_file(large_qasm_path)
self.coupling_map = [
[0, 1],
[1, 0],
[1, 2],
[1, 4],
[2, 1],
[2, 3],
[3, 2],
[3, 5],
[4, 1],
[4, 7],
[5, 3],
[5, 8],
[6, 7],
[7, 4],
[7, 6],
[7, 10],
[8, 5],
[8, 9],
[8, 11],
[9, 8],
[10, 7],
[10, 12],
[11, 8],
[11, 14],
[12, 10],
[12, 13],
[12, 15],
[13, 12],
[13, 14],
[14, 11],
[14, 13],
[14, 16],
[15, 12],
[15, 18],
[16, 14],
[16, 19],
[17, 18],
[18, 15],
[18, 17],
[18, 21],
[19, 16],
[19, 20],
[19, 22],
[20, 19],
[21, 18],
[21, 23],
[22, 19],
[22, 25],
[23, 21],
[23, 24],
[24, 23],
[24, 25],
[25, 22],
[25, 24],
[25, 26],
[26, 25],
]
self.basis = ["id", "rz", "sx", "x", "cx", "reset"]
def time_single_gate_compile(self):
circ = qiskit.compiler.transpile(
self.single_gate_circuit,
coupling_map=self.coupling_map,
basis_gates=self.basis,
seed_transpiler=20220125,
)
qiskit.compiler.assemble(circ)
def time_cx_compile(self):
circ = qiskit.compiler.transpile(
self.cx_circuit,
coupling_map=self.coupling_map,
basis_gates=self.basis,
seed_transpiler=20220125,
)
qiskit.compiler.assemble(circ)
def time_compile_from_large_qasm(self):
circ = qiskit.compiler.transpile(
self.large_qasm,
coupling_map=self.coupling_map,
basis_gates=self.basis,
seed_transpiler=20220125,
)
qiskit.compiler.assemble(circ)
|
https://github.com/DavidFitzharris/EmergingTechnologies
|
DavidFitzharris
|
import numpy as np
from qiskit import QuantumCircuit
# Building the circuit
# 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)
# We can visualise the circuit using QuantumCircuit.draw()
circ.draw('mpl')
from qiskit.quantum_info import Statevector
# Set the initial 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 import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Build
#------
# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(2, 2)
# Add a H gate on qubit 0
circuit.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(0, 1)
# Map the quantum measurement to the classical bits
circuit.measure([0,1], [0,1])
# END
# Execute
#--------
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator
job = execute(circuit, simulator, shots=1000)
# Grab results from the job
result = job.result()
# Return counts
counts = result.get_counts(circuit)
print("\nTotal count for 00 and 11 are:",counts)
# END
# Visualize
#----------
# Using QuantumCircuit.draw(), as in previous example
circuit.draw('mpl')
# Analyze
#--------
# Plot a histogram
plot_histogram(counts)
# END
<h3 style="color: rgb(0, 125, 65)"><i>References</i></h3>
https://qiskit.org/documentation/tutorials.html
https://www.youtube.com/watch?v=P5cGeDKOIP0
https://qiskit.org/documentation/tutorials/circuits/01_circuit_basics.html
https://docs.quantum-computing.ibm.com/lab/first-circuit
|
https://github.com/Alice-Bob-SW/qiskit-alice-bob-provider
|
Alice-Bob-SW
|
##############################################################################
# Copyright 2023 Alice & Bob
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##############################################################################
# pylint: disable=unused-argument
from pathlib import Path
from textwrap import dedent
import pytest
from qiskit import QiskitError, QuantumCircuit, execute, transpile
from qiskit.providers import Options
from qiskit.pulse.schedule import Schedule
from qiskit.result import Result
from qiskit.transpiler.exceptions import TranspilerError
from requests_mock.mocker import Mocker
from qiskit_alice_bob_provider.remote.api.client import AliceBobApiException
from qiskit_alice_bob_provider.remote.backend import (
AliceBobRemoteBackend,
_ab_input_params_from_options,
_qiskit_to_qir,
)
from qiskit_alice_bob_provider.remote.provider import AliceBobRemoteProvider
def test_get_backend(mocked_targets) -> None:
provider = AliceBobRemoteProvider(api_key='foo')
backend = provider.get_backend('EMU:1Q:LESCANNE_2020')
assert isinstance(backend, AliceBobRemoteBackend)
assert backend.options['average_nb_photons'] == 4.0 # Default value.
def test_get_backend_with_options(mocked_targets) -> None:
provider = AliceBobRemoteProvider(api_key='foo')
backend = provider.get_backend(
'EMU:1Q:LESCANNE_2020', average_nb_photons=6.0
)
assert isinstance(backend, AliceBobRemoteBackend)
assert backend.options['average_nb_photons'] == 6.0
def test_get_backend_options_validation(mocked_targets) -> None:
provider = AliceBobRemoteProvider(api_key='foo')
with pytest.raises(ValueError):
provider.get_backend('EMU:1Q:LESCANNE_2020', average_nb_photons=40)
with pytest.raises(ValueError):
provider.get_backend('EMU:1Q:LESCANNE_2020', average_nb_photons=-1)
with pytest.raises(ValueError):
provider.get_backend('EMU:1Q:LESCANNE_2020', shots=0)
with pytest.raises(ValueError):
provider.get_backend('EMU:1Q:LESCANNE_2020', shots=1e10)
with pytest.raises(ValueError):
provider.get_backend('EMU:1Q:LESCANNE_2020', bad_option=1)
def test_execute_options_validation(mocked_targets) -> None:
# We are permissive in our options sytem, allowing the user to both
# define options when creating the backend and executing.
# We therefore need to test both behaviors.
c = QuantumCircuit(1, 1)
provider = AliceBobRemoteProvider(api_key='foo')
backend = provider.get_backend('EMU:1Q:LESCANNE_2020')
with pytest.raises(ValueError):
execute(c, backend, average_nb_photons=40)
with pytest.raises(ValueError):
execute(c, backend, average_nb_photons=-1)
with pytest.raises(ValueError):
execute(c, backend, bad_option=1)
with pytest.raises(ValueError):
execute(c, backend, shots=0)
with pytest.raises(ValueError):
execute(c, backend, shots=1e10)
def test_too_many_qubits_clients_side(mocked_targets) -> None:
c = QuantumCircuit(3, 1)
provider = AliceBobRemoteProvider(api_key='foo')
backend = provider.get_backend('EMU:1Q:LESCANNE_2020')
with pytest.raises(TranspilerError):
execute(c, backend)
def test_input_not_quantum_circuit(mocked_targets) -> None:
c1 = QuantumCircuit(1, 1)
c2 = QuantumCircuit(1, 1)
s1 = Schedule()
s2 = Schedule()
provider = AliceBobRemoteProvider(api_key='foo')
backend = provider.get_backend('EMU:1Q:LESCANNE_2020')
with pytest.raises(NotImplementedError):
execute([c1, c2], backend)
with pytest.raises(NotImplementedError):
execute(s1, backend)
with pytest.raises(NotImplementedError):
execute([s1, s2], backend)
def test_counts_ordering(successful_job: Mocker) -> None:
c = QuantumCircuit(1, 2)
c.initialize('+', 0)
c.measure_x(0, 0)
c.measure(0, 1)
provider = AliceBobRemoteProvider(api_key='foo')
backend = provider.get_backend('EMU:1Q:LESCANNE_2020')
job = execute(c, backend)
counts = job.result(wait=0).get_counts()
expected = {'11': 12, '10': 474, '01': 6, '00': 508}
assert counts == expected
counts = job.result(wait=0).get_counts() # testing memoization
assert counts == expected
def test_failed_transpilation(failed_transpilation_job: Mocker) -> None:
c = QuantumCircuit(1, 1)
provider = AliceBobRemoteProvider(api_key='foo')
backend = provider.get_backend('EMU:1Q:LESCANNE_2020')
job = execute(c, backend)
res: Result = job.result(wait=0)
assert res.results[0].data.input_qir is not None
assert res.results[0].data.transpiled_qir is None
res = job.result(wait=0) # testing memoization
assert res.results[0].data.input_qir is not None
assert res.results[0].data.transpiled_qir is None
with pytest.raises(QiskitError):
res.get_counts()
def test_failed_execution(failed_execution_job: Mocker) -> None:
c = QuantumCircuit(1, 1)
provider = AliceBobRemoteProvider(api_key='foo')
backend = provider.get_backend('EMU:1Q:LESCANNE_2020')
job = execute(c, backend)
res: Result = job.result(wait=0)
assert res.results[0].data.input_qir is not None
assert res.results[0].data.transpiled_qir is not None
with pytest.raises(QiskitError):
res.get_counts()
def test_cancel_job(cancellable_job: Mocker) -> None:
c = QuantumCircuit(1, 1)
provider = AliceBobRemoteProvider(api_key='foo')
backend = provider.get_backend('EMU:1Q:LESCANNE_2020')
job = execute(c, backend)
job.cancel()
res: Result = job.result(wait=0)
assert res.results[0].data.input_qir is not None
assert res.results[0].data.transpiled_qir is not None
with pytest.raises(QiskitError):
res.get_counts()
def test_failed_server_side_validation(failed_validation_job: Mocker) -> None:
c = QuantumCircuit(1, 1)
provider = AliceBobRemoteProvider(api_key='foo')
backend = provider.get_backend('EMU:1Q:LESCANNE_2020')
with pytest.raises(AliceBobApiException):
execute(c, backend)
def test_delay_instruction_recognized() -> None:
c = QuantumCircuit(1, 2)
c.initialize('+', 0)
c.measure_x(0, 0)
c.delay(3000, 0, unit='ns')
c.measure(0, 1)
qir = _qiskit_to_qir(c)
delay_call = (
'call void @__quantum__qis__delay__body'
'(double 3.000000e+00, %Qubit* null)'
)
assert delay_call in qir
def test_ab_input_params_from_options() -> None:
options = Options(shots=43, average_nb_photons=3.2, foo_hey='bar')
params = _ab_input_params_from_options(options)
assert params == {'nbShots': 43, 'averageNbPhotons': 3.2, 'fooHey': 'bar'}
def test_translation_plugin_and_qir(mocked_targets) -> None:
provider = AliceBobRemoteProvider(api_key='foo')
backend = provider.get_backend('ALL_INSTRUCTIONS')
c = QuantumCircuit(4, 4)
c.initialize('-01+')
c.measure([0, 1], [2, 3])
c.x(2).c_if(2, 1)
c.measure_x(2, 0)
c.measure_x(3, 1)
transpiled = transpile(c, backend)
qir = _qiskit_to_qir(transpiled)
assert (
dedent(
Path(
'tests/resources/test_translation_plugin_and_qir.ll'
).read_text(encoding='utf-8')
)
in qir
)
def test_determine_translation_plugin(mocked_targets) -> None:
p = AliceBobRemoteProvider(api_key='foo')
# Rotations available
assert (
p.get_backend('ALL_INSTRUCTIONS').get_translation_stage_plugin()
== 'state_preparation'
)
# H and T missing
assert (
p.get_backend('EMU:1Q:LESCANNE_2020').get_translation_stage_plugin()
== 'state_preparation'
)
# T missing
assert (
p.get_backend('H').get_translation_stage_plugin()
== 'state_preparation'
)
# ok
assert (
p.get_backend('H_T').get_translation_stage_plugin() == 'sk_synthesis'
)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# 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.
"""Test dynamical decoupling insertion pass."""
import unittest
import numpy as np
from numpy import pi
from ddt import ddt, data
from qiskit.circuit import QuantumCircuit, Delay, Measure, Reset, Parameter
from qiskit.circuit.library import XGate, YGate, RXGate, UGate, CXGate, HGate
from qiskit.quantum_info import Operator
from qiskit.transpiler.instruction_durations import InstructionDurations
from qiskit.transpiler.passes import (
ASAPScheduleAnalysis,
ALAPScheduleAnalysis,
PadDynamicalDecoupling,
)
from qiskit.transpiler.passmanager import PassManager
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.target import Target, InstructionProperties
from qiskit import pulse
from qiskit.test import QiskitTestCase
@ddt
class TestPadDynamicalDecoupling(QiskitTestCase):
"""Tests PadDynamicalDecoupling pass."""
def setUp(self):
"""Circuits to test DD on.
┌───┐
q_0: ┤ H ├──■────────────
└───┘┌─┴─┐
q_1: ─────┤ X ├──■───────
└───┘┌─┴─┐
q_2: ──────────┤ X ├──■──
└───┘┌─┴─┐
q_3: ───────────────┤ X ├
└───┘
┌──────────┐
q_0: ──■──┤ U(π,0,π) ├──────────■──
┌─┴─┐└──────────┘ ┌─┴─┐
q_1: ┤ X ├─────■───────────■──┤ X ├
└───┘ ┌─┴─┐ ┌─┐┌─┴─┐└───┘
q_2: ────────┤ X ├────┤M├┤ X ├─────
└───┘ └╥┘└───┘
c: 1/══════════════════╩═══════════
0
"""
super().setUp()
self.ghz4 = QuantumCircuit(4)
self.ghz4.h(0)
self.ghz4.cx(0, 1)
self.ghz4.cx(1, 2)
self.ghz4.cx(2, 3)
self.midmeas = QuantumCircuit(3, 1)
self.midmeas.cx(0, 1)
self.midmeas.cx(1, 2)
self.midmeas.u(pi, 0, pi, 0)
self.midmeas.measure(2, 0)
self.midmeas.cx(1, 2)
self.midmeas.cx(0, 1)
self.durations = InstructionDurations(
[
("h", 0, 50),
("cx", [0, 1], 700),
("cx", [1, 2], 200),
("cx", [2, 3], 300),
("x", None, 50),
("y", None, 50),
("u", None, 100),
("rx", None, 100),
("measure", None, 1000),
("reset", None, 1500),
]
)
def test_insert_dd_ghz(self):
"""Test DD gates are inserted in correct spots.
┌───┐ ┌────────────────┐ ┌───┐ »
q_0: ──────┤ H ├─────────■──┤ Delay(100[dt]) ├──────┤ X ├──────»
┌─────┴───┴─────┐ ┌─┴─┐└────────────────┘┌─────┴───┴─────┐»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■─────────┤ Delay(50[dt]) ├»
├───────────────┴┐└───┘ ┌─┴─┐ └───────────────┘»
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├───────────────■────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├─────────────────────────────┤ X ├──────»
└────────────────┘ └───┘ »
« ┌────────────────┐ ┌───┐ ┌────────────────┐
«q_0: ┤ Delay(200[dt]) ├──────┤ X ├───────┤ Delay(100[dt]) ├─────────────────
« └─────┬───┬──────┘┌─────┴───┴──────┐└─────┬───┬──────┘┌───────────────┐
«q_1: ──────┤ X ├───────┤ Delay(100[dt]) ├──────┤ X ├───────┤ Delay(50[dt]) ├
« └───┘ └────────────────┘ └───┘ └───────────────┘
«q_2: ───────────────────────────────────────────────────────────────────────
«
«q_3: ───────────────────────────────────────────────────────────────────────
«
"""
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(100), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(200), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(100), [0])
expected = expected.compose(Delay(50), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(100), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(50), [1])
self.assertEqual(ghz4_dd, expected)
def test_insert_dd_ghz_with_target(self):
"""Test DD gates are inserted in correct spots.
┌───┐ ┌────────────────┐ ┌───┐ »
q_0: ──────┤ H ├─────────■──┤ Delay(100[dt]) ├──────┤ X ├──────»
┌─────┴───┴─────┐ ┌─┴─┐└────────────────┘┌─────┴───┴─────┐»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■─────────┤ Delay(50[dt]) ├»
├───────────────┴┐└───┘ ┌─┴─┐ └───────────────┘»
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├───────────────■────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├─────────────────────────────┤ X ├──────»
└────────────────┘ └───┘ »
« ┌────────────────┐ ┌───┐ ┌────────────────┐
«q_0: ┤ Delay(200[dt]) ├──────┤ X ├───────┤ Delay(100[dt]) ├─────────────────
« └─────┬───┬──────┘┌─────┴───┴──────┐└─────┬───┬──────┘┌───────────────┐
«q_1: ──────┤ X ├───────┤ Delay(100[dt]) ├──────┤ X ├───────┤ Delay(50[dt]) ├
« └───┘ └────────────────┘ └───┘ └───────────────┘
«q_2: ───────────────────────────────────────────────────────────────────────
«
«q_3: ───────────────────────────────────────────────────────────────────────
«
"""
target = Target(num_qubits=4, dt=1)
target.add_instruction(HGate(), {(0,): InstructionProperties(duration=50)})
target.add_instruction(
CXGate(),
{
(0, 1): InstructionProperties(duration=700),
(1, 2): InstructionProperties(duration=200),
(2, 3): InstructionProperties(duration=300),
},
)
target.add_instruction(
XGate(), {(x,): InstructionProperties(duration=50) for x in range(4)}
)
target.add_instruction(
YGate(), {(x,): InstructionProperties(duration=50) for x in range(4)}
)
target.add_instruction(
UGate(Parameter("theta"), Parameter("phi"), Parameter("lambda")),
{(x,): InstructionProperties(duration=100) for x in range(4)},
)
target.add_instruction(
RXGate(Parameter("theta")),
{(x,): InstructionProperties(duration=100) for x in range(4)},
)
target.add_instruction(
Measure(), {(x,): InstructionProperties(duration=1000) for x in range(4)}
)
target.add_instruction(
Reset(), {(x,): InstructionProperties(duration=1500) for x in range(4)}
)
target.add_instruction(Delay(Parameter("t")), {(x,): None for x in range(4)})
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(target=target),
PadDynamicalDecoupling(target=target, dd_sequence=dd_sequence),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(100), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(200), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(100), [0])
expected = expected.compose(Delay(50), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(100), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(50), [1])
self.assertEqual(ghz4_dd, expected)
def test_insert_dd_ghz_one_qubit(self):
"""Test DD gates are inserted on only one qubit.
┌───┐ ┌────────────────┐ ┌───┐ »
q_0: ──────┤ H ├─────────■──┤ Delay(100[dt]) ├──────┤ X ├───────»
┌─────┴───┴─────┐ ┌─┴─┐└────────────────┘┌─────┴───┴──────┐»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■─────────┤ Delay(300[dt]) ├»
├───────────────┴┐└───┘ ┌─┴─┐ └────────────────┘»
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├───────────────■─────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├─────────────────────────────┤ X ├───────»
└────────────────┘ └───┘ »
meas: 4/═══════════════════════════════════════════════════════════»
»
« ┌────────────────┐┌───┐┌────────────────┐ ░ ┌─┐
« q_0: ┤ Delay(200[dt]) ├┤ X ├┤ Delay(100[dt]) ├─░─┤M├─────────
« └────────────────┘└───┘└────────────────┘ ░ └╥┘┌─┐
« q_1: ──────────────────────────────────────────░──╫─┤M├──────
« ░ ║ └╥┘┌─┐
« q_2: ──────────────────────────────────────────░──╫──╫─┤M├───
« ░ ║ ║ └╥┘┌─┐
« q_3: ──────────────────────────────────────────░──╫──╫──╫─┤M├
« ░ ║ ║ ║ └╥┘
«meas: 4/═════════════════════════════════════════════╩══╩══╩══╩═
« 0 1 2 3
"""
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[0]),
]
)
ghz4_dd = pm.run(self.ghz4.measure_all(inplace=False))
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(100), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(200), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(100), [0])
expected = expected.compose(Delay(300), [1])
expected.measure_all()
self.assertEqual(ghz4_dd, expected)
def test_insert_dd_ghz_everywhere(self):
"""Test DD gates even on initial idle spots.
┌───┐ ┌────────────────┐┌───┐┌────────────────┐┌───┐»
q_0: ──────┤ H ├─────────■──┤ Delay(100[dt]) ├┤ Y ├┤ Delay(200[dt]) ├┤ Y ├»
┌─────┴───┴─────┐ ┌─┴─┐└────────────────┘└───┘└────────────────┘└───┘»
q_1: ┤ Delay(50[dt]) ├─┤ X ├───────────────────────────────────────────■──»
├───────────────┴┐├───┤┌────────────────┐┌───┐┌────────────────┐┌─┴─┐»
q_2: ┤ Delay(162[dt]) ├┤ Y ├┤ Delay(326[dt]) ├┤ Y ├┤ Delay(162[dt]) ├┤ X ├»
├────────────────┤├───┤├────────────────┤├───┤├────────────────┤└───┘»
q_3: ┤ Delay(212[dt]) ├┤ Y ├┤ Delay(426[dt]) ├┤ Y ├┤ Delay(212[dt]) ├─────»
└────────────────┘└───┘└────────────────┘└───┘└────────────────┘ »
« ┌────────────────┐
«q_0: ┤ Delay(100[dt]) ├─────────────────────────────────────────────
« ├───────────────┬┘┌───┐┌────────────────┐┌───┐┌───────────────┐
«q_1: ┤ Delay(50[dt]) ├─┤ Y ├┤ Delay(100[dt]) ├┤ Y ├┤ Delay(50[dt]) ├
« └───────────────┘ └───┘└────────────────┘└───┘└───────────────┘
«q_2: ────────■──────────────────────────────────────────────────────
« ┌─┴─┐
«q_3: ──────┤ X ├────────────────────────────────────────────────────
« └───┘
"""
dd_sequence = [YGate(), YGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, skip_reset_qubits=False),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(162), [2], front=True)
expected = expected.compose(YGate(), [2], front=True)
expected = expected.compose(Delay(326), [2], front=True)
expected = expected.compose(YGate(), [2], front=True)
expected = expected.compose(Delay(162), [2], front=True)
expected = expected.compose(Delay(212), [3], front=True)
expected = expected.compose(YGate(), [3], front=True)
expected = expected.compose(Delay(426), [3], front=True)
expected = expected.compose(YGate(), [3], front=True)
expected = expected.compose(Delay(212), [3], front=True)
expected = expected.compose(Delay(100), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(200), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(100), [0])
expected = expected.compose(Delay(50), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(100), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(50), [1])
self.assertEqual(ghz4_dd, expected)
def test_insert_dd_ghz_xy4(self):
"""Test XY4 sequence of DD gates.
┌───┐ ┌───────────────┐ ┌───┐ ┌───────────────┐»
q_0: ──────┤ H ├─────────■──┤ Delay(37[dt]) ├──────┤ X ├──────┤ Delay(75[dt]) ├»
┌─────┴───┴─────┐ ┌─┴─┐└───────────────┘┌─────┴───┴─────┐└─────┬───┬─────┘»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■────────┤ Delay(12[dt]) ├──────┤ X ├──────»
├───────────────┴┐└───┘ ┌─┴─┐ └───────────────┘ └───┘ »
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├──────────────■─────────────────────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├────────────────────────────┤ X ├───────────────────────»
└────────────────┘ └───┘ »
« ┌───┐ ┌───────────────┐ ┌───┐ ┌───────────────┐»
«q_0: ──────┤ Y ├──────┤ Delay(76[dt]) ├──────┤ X ├──────┤ Delay(75[dt]) ├»
« ┌─────┴───┴─────┐└─────┬───┬─────┘┌─────┴───┴─────┐└─────┬───┬─────┘»
«q_1: ┤ Delay(25[dt]) ├──────┤ Y ├──────┤ Delay(26[dt]) ├──────┤ X ├──────»
« └───────────────┘ └───┘ └───────────────┘ └───┘ »
«q_2: ────────────────────────────────────────────────────────────────────»
« »
«q_3: ────────────────────────────────────────────────────────────────────»
« »
« ┌───┐ ┌───────────────┐
«q_0: ──────┤ Y ├──────┤ Delay(37[dt]) ├─────────────────
« ┌─────┴───┴─────┐└─────┬───┬─────┘┌───────────────┐
«q_1: ┤ Delay(25[dt]) ├──────┤ Y ├──────┤ Delay(12[dt]) ├
« └───────────────┘ └───┘ └───────────────┘
«q_2: ───────────────────────────────────────────────────
«
«q_3: ───────────────────────────────────────────────────
"""
dd_sequence = [XGate(), YGate(), XGate(), YGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(37), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(75), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(76), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(75), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(37), [0])
expected = expected.compose(Delay(12), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(25), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(26), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(25), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(12), [1])
self.assertEqual(ghz4_dd, expected)
def test_insert_midmeas_hahn_alap(self):
"""Test a single X gate as Hahn echo can absorb in the downstream circuit.
global phase: 3π/2
┌────────────────┐ ┌───┐ ┌────────────────┐»
q_0: ────────■─────────┤ Delay(625[dt]) ├───────┤ X ├───────┤ Delay(625[dt]) ├»
┌─┴─┐ └────────────────┘┌──────┴───┴──────┐└────────────────┘»
q_1: ──────┤ X ├───────────────■─────────┤ Delay(1000[dt]) ├────────■─────────»
┌─────┴───┴──────┐ ┌─┴─┐ └───────┬─┬───────┘ ┌─┴─┐ »
q_2: ┤ Delay(700[dt]) ├──────┤ X ├───────────────┤M├──────────────┤ X ├───────»
└────────────────┘ └───┘ └╥┘ └───┘ »
c: 1/═════════════════════════════════════════════╩═══════════════════════════»
0 »
« ┌───────────────┐
«q_0: ┤ U(0,π/2,-π/2) ├───■──
« └───────────────┘ ┌─┴─┐
«q_1: ──────────────────┤ X ├
« ┌────────────────┐└───┘
«q_2: ┤ Delay(700[dt]) ├─────
« └────────────────┘
«c: 1/═══════════════════════
"""
dd_sequence = [XGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
midmeas_dd = pm.run(self.midmeas)
combined_u = UGate(0, -pi / 2, pi / 2)
expected = QuantumCircuit(3, 1)
expected.cx(0, 1)
expected.delay(625, 0)
expected.x(0)
expected.delay(625, 0)
expected.compose(combined_u, [0], inplace=True)
expected.delay(700, 2)
expected.cx(1, 2)
expected.delay(1000, 1)
expected.measure(2, 0)
expected.cx(1, 2)
expected.cx(0, 1)
expected.delay(700, 2)
expected.global_phase = pi / 2
self.assertEqual(midmeas_dd, expected)
# check the absorption into U was done correctly
self.assertEqual(Operator(combined_u), Operator(XGate()) & Operator(XGate()))
def test_insert_midmeas_hahn_asap(self):
"""Test a single X gate as Hahn echo can absorb in the upstream circuit.
┌──────────────────┐ ┌────────────────┐┌─────────┐»
q_0: ────────■─────────┤ U(3π/4,-π/2,π/2) ├─┤ Delay(600[dt]) ├┤ Rx(π/4) ├»
┌─┴─┐ └──────────────────┘┌┴────────────────┤└─────────┘»
q_1: ──────┤ X ├────────────────■──────────┤ Delay(1000[dt]) ├─────■─────»
┌─────┴───┴──────┐ ┌─┴─┐ └───────┬─┬───────┘ ┌─┴─┐ »
q_2: ┤ Delay(700[dt]) ├───────┤ X ├────────────────┤M├───────────┤ X ├───»
└────────────────┘ └───┘ └╥┘ └───┘ »
c: 1/═══════════════════════════════════════════════╩════════════════════»
0 »
« ┌────────────────┐
«q_0: ┤ Delay(600[dt]) ├──■──
« └────────────────┘┌─┴─┐
«q_1: ──────────────────┤ X ├
« ┌────────────────┐└───┘
«q_2: ┤ Delay(700[dt]) ├─────
« └────────────────┘
«c: 1/═══════════════════════
«
"""
dd_sequence = [RXGate(pi / 4)]
pm = PassManager(
[
ASAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
midmeas_dd = pm.run(self.midmeas)
combined_u = UGate(3 * pi / 4, -pi / 2, pi / 2)
expected = QuantumCircuit(3, 1)
expected.cx(0, 1)
expected.compose(combined_u, [0], inplace=True)
expected.delay(600, 0)
expected.rx(pi / 4, 0)
expected.delay(600, 0)
expected.delay(700, 2)
expected.cx(1, 2)
expected.delay(1000, 1)
expected.measure(2, 0)
expected.cx(1, 2)
expected.cx(0, 1)
expected.delay(700, 2)
self.assertEqual(midmeas_dd, expected)
# check the absorption into U was done correctly
self.assertTrue(
Operator(XGate()).equiv(
Operator(UGate(3 * pi / 4, -pi / 2, pi / 2)) & Operator(RXGate(pi / 4))
)
)
def test_insert_ghz_uhrig(self):
"""Test custom spacing (following Uhrig DD [1]).
[1] Uhrig, G. "Keeping a quantum bit alive by optimized π-pulse sequences."
Physical Review Letters 98.10 (2007): 100504.
┌───┐ ┌──────────────┐ ┌───┐ ┌──────────────┐┌───┐»
q_0: ──────┤ H ├─────────■──┤ Delay(3[dt]) ├──────┤ X ├───────┤ Delay(8[dt]) ├┤ X ├»
┌─────┴───┴─────┐ ┌─┴─┐└──────────────┘┌─────┴───┴──────┐└──────────────┘└───┘»
q_1: ┤ Delay(50[dt]) ├─┤ X ├───────■────────┤ Delay(300[dt]) ├─────────────────────»
├───────────────┴┐└───┘ ┌─┴─┐ └────────────────┘ »
q_2: ┤ Delay(750[dt]) ├──────────┤ X ├──────────────■──────────────────────────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├───────────────────────────┤ X ├────────────────────────────»
└────────────────┘ └───┘ »
« ┌───────────────┐┌───┐┌───────────────┐┌───┐┌───────────────┐┌───┐┌───────────────┐»
«q_0: ┤ Delay(13[dt]) ├┤ X ├┤ Delay(16[dt]) ├┤ X ├┤ Delay(20[dt]) ├┤ X ├┤ Delay(16[dt]) ├»
« └───────────────┘└───┘└───────────────┘└───┘└───────────────┘└───┘└───────────────┘»
«q_1: ───────────────────────────────────────────────────────────────────────────────────»
« »
«q_2: ───────────────────────────────────────────────────────────────────────────────────»
« »
«q_3: ───────────────────────────────────────────────────────────────────────────────────»
« »
« ┌───┐┌───────────────┐┌───┐┌──────────────┐┌───┐┌──────────────┐
«q_0: ┤ X ├┤ Delay(13[dt]) ├┤ X ├┤ Delay(8[dt]) ├┤ X ├┤ Delay(3[dt]) ├
« └───┘└───────────────┘└───┘└──────────────┘└───┘└──────────────┘
«q_1: ────────────────────────────────────────────────────────────────
«
«q_2: ────────────────────────────────────────────────────────────────
«
«q_3: ────────────────────────────────────────────────────────────────
«
"""
n = 8
dd_sequence = [XGate()] * n
# uhrig specifies the location of the k'th pulse
def uhrig(k):
return np.sin(np.pi * (k + 1) / (2 * n + 2)) ** 2
# convert that to spacing between pulses (whatever finite duration pulses have)
spacing = []
for k in range(n):
spacing.append(uhrig(k) - sum(spacing))
spacing.append(1 - sum(spacing))
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[0], spacing=spacing),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(3), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(8), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(13), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(16), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(20), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(16), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(13), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(8), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(3), [0])
expected = expected.compose(Delay(300), [1])
self.assertEqual(ghz4_dd, expected)
def test_asymmetric_xy4_in_t2(self):
"""Test insertion of XY4 sequence with unbalanced spacing.
global phase: π
┌───┐┌───┐┌────────────────┐┌───┐┌────────────────┐┌───┐┌────────────────┐»
q_0: ┤ H ├┤ X ├┤ Delay(450[dt]) ├┤ Y ├┤ Delay(450[dt]) ├┤ X ├┤ Delay(450[dt]) ├»
└───┘└───┘└────────────────┘└───┘└────────────────┘└───┘└────────────────┘»
« ┌───┐┌────────────────┐┌───┐
«q_0: ┤ Y ├┤ Delay(450[dt]) ├┤ H ├
« └───┘└────────────────┘└───┘
"""
dd_sequence = [XGate(), YGate()] * 2
spacing = [0] + [1 / 4] * 4
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, spacing=spacing),
]
)
t2 = QuantumCircuit(1)
t2.h(0)
t2.delay(2000, 0)
t2.h(0)
expected = QuantumCircuit(1)
expected.h(0)
expected.x(0)
expected.delay(450, 0)
expected.y(0)
expected.delay(450, 0)
expected.x(0)
expected.delay(450, 0)
expected.y(0)
expected.delay(450, 0)
expected.h(0)
expected.global_phase = pi
t2_dd = pm.run(t2)
self.assertEqual(t2_dd, expected)
# check global phase is correct
self.assertEqual(Operator(t2), Operator(expected))
def test_dd_after_reset(self):
"""Test skip_reset_qubits option works.
┌─────────────────┐┌───┐┌────────────────┐┌───┐┌─────────────────┐»
q_0: ─|0>─┤ Delay(1000[dt]) ├┤ H ├┤ Delay(190[dt]) ├┤ X ├┤ Delay(1710[dt]) ├»
└─────────────────┘└───┘└────────────────┘└───┘└─────────────────┘»
« ┌───┐┌───┐
«q_0: ┤ X ├┤ H ├
« └───┘└───┘
"""
dd_sequence = [XGate(), XGate()]
spacing = [0.1, 0.9]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(
self.durations, dd_sequence, spacing=spacing, skip_reset_qubits=True
),
]
)
t2 = QuantumCircuit(1)
t2.reset(0)
t2.delay(1000)
t2.h(0)
t2.delay(2000, 0)
t2.h(0)
expected = QuantumCircuit(1)
expected.reset(0)
expected.delay(1000)
expected.h(0)
expected.delay(190, 0)
expected.x(0)
expected.delay(1710, 0)
expected.x(0)
expected.h(0)
t2_dd = pm.run(t2)
self.assertEqual(t2_dd, expected)
def test_insert_dd_bad_sequence(self):
"""Test DD raises when non-identity sequence is inserted."""
dd_sequence = [XGate(), YGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
with self.assertRaises(TranspilerError):
pm.run(self.ghz4)
@data(0.5, 1.5)
def test_dd_with_calibrations_with_parameters(self, param_value):
"""Check that calibrations in a circuit with parameters work fine."""
circ = QuantumCircuit(2)
circ.x(0)
circ.cx(0, 1)
circ.rx(param_value, 1)
rx_duration = int(param_value * 1000)
with pulse.build() as rx:
pulse.play(pulse.Gaussian(rx_duration, 0.1, rx_duration // 4), pulse.DriveChannel(1))
circ.add_calibration("rx", (1,), rx, params=[param_value])
durations = InstructionDurations([("x", None, 100), ("cx", None, 300)])
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[ALAPScheduleAnalysis(durations), PadDynamicalDecoupling(durations, dd_sequence)]
)
self.assertEqual(pm.run(circ).duration, rx_duration + 100 + 300)
def test_insert_dd_ghz_xy4_with_alignment(self):
"""Test DD with pulse alignment constraints.
┌───┐ ┌───────────────┐ ┌───┐ ┌───────────────┐»
q_0: ──────┤ H ├─────────■──┤ Delay(40[dt]) ├──────┤ X ├──────┤ Delay(70[dt]) ├»
┌─────┴───┴─────┐ ┌─┴─┐└───────────────┘┌─────┴───┴─────┐└─────┬───┬─────┘»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■────────┤ Delay(20[dt]) ├──────┤ X ├──────»
├───────────────┴┐└───┘ ┌─┴─┐ └───────────────┘ └───┘ »
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├──────────────■─────────────────────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├────────────────────────────┤ X ├───────────────────────»
└────────────────┘ └───┘ »
« ┌───┐ ┌───────────────┐ ┌───┐ ┌───────────────┐»
«q_0: ──────┤ Y ├──────┤ Delay(70[dt]) ├──────┤ X ├──────┤ Delay(70[dt]) ├»
« ┌─────┴───┴─────┐└─────┬───┬─────┘┌─────┴───┴─────┐└─────┬───┬─────┘»
«q_1: ┤ Delay(20[dt]) ├──────┤ Y ├──────┤ Delay(20[dt]) ├──────┤ X ├──────»
« └───────────────┘ └───┘ └───────────────┘ └───┘ »
«q_2: ────────────────────────────────────────────────────────────────────»
« »
«q_3: ────────────────────────────────────────────────────────────────────»
« »
« ┌───┐ ┌───────────────┐
«q_0: ──────┤ Y ├──────┤ Delay(50[dt]) ├─────────────────
« ┌─────┴───┴─────┐└─────┬───┬─────┘┌───────────────┐
«q_1: ┤ Delay(20[dt]) ├──────┤ Y ├──────┤ Delay(20[dt]) ├
« └───────────────┘ └───┘ └───────────────┘
«q_2: ───────────────────────────────────────────────────
«
«q_3: ───────────────────────────────────────────────────
«
"""
dd_sequence = [XGate(), YGate(), XGate(), YGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(
self.durations,
dd_sequence,
pulse_alignment=10,
extra_slack_distribution="edges",
),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(40), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(70), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(70), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(70), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(50), [0])
expected = expected.compose(Delay(20), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(20), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(20), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(20), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(20), [1])
self.assertEqual(ghz4_dd, expected)
def test_dd_can_sequentially_called(self):
"""Test if sequentially called DD pass can output the same circuit.
This test verifies:
- if global phase is properly propagated from the previous padding node.
- if node_start_time property is properly updated for new dag circuit.
"""
dd_sequence = [XGate(), YGate(), XGate(), YGate()]
pm1 = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[0]),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[1]),
]
)
circ1 = pm1.run(self.ghz4)
pm2 = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[0, 1]),
]
)
circ2 = pm2.run(self.ghz4)
self.assertEqual(circ1, circ2)
def test_respect_target_instruction_constraints(self):
"""Test if DD pass does not pad delays for qubits that do not support delay instructions
and does not insert DD gates for qubits that do not support necessary gates.
See: https://github.com/Qiskit/qiskit-terra/issues/9993
"""
qc = QuantumCircuit(3)
qc.cx(0, 1)
qc.cx(1, 2)
target = Target(dt=1)
# Y is partially supported (not supported on qubit 2)
target.add_instruction(
XGate(), {(q,): InstructionProperties(duration=100) for q in range(2)}
)
target.add_instruction(
CXGate(),
{
(0, 1): InstructionProperties(duration=1000),
(1, 2): InstructionProperties(duration=1000),
},
)
# delays are not supported
# No DD instructions nor delays are padded due to no delay support in the target
pm_xx = PassManager(
[
ALAPScheduleAnalysis(target=target),
PadDynamicalDecoupling(dd_sequence=[XGate(), XGate()], target=target),
]
)
scheduled = pm_xx.run(qc)
self.assertEqual(qc, scheduled)
# Fails since Y is not supported in the target
with self.assertRaises(TranspilerError):
PassManager(
[
ALAPScheduleAnalysis(target=target),
PadDynamicalDecoupling(
dd_sequence=[XGate(), YGate(), XGate(), YGate()], target=target
),
]
)
# Add delay support to the target
target.add_instruction(Delay(Parameter("t")), {(q,): None for q in range(3)})
# No error but no DD on qubit 2 (just delay is padded) since X is not supported on it
scheduled = pm_xx.run(qc)
expected = QuantumCircuit(3)
expected.delay(1000, [2])
expected.cx(0, 1)
expected.cx(1, 2)
expected.delay(200, [0])
expected.x([0])
expected.delay(400, [0])
expected.x([0])
expected.delay(200, [0])
self.assertEqual(expected, scheduled)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeManilaV2
from qiskit import transpile
from qiskit.tools.visualization import plot_histogram
# Get a fake backend from the fake provider
backend = FakeManilaV2()
# Create a simple circuit
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0,1)
circuit.cx(0,2)
circuit.measure_all()
circuit.draw('mpl')
# Transpile the ideal circuit to a circuit that can be directly executed by the backend
transpiled_circuit = transpile(circuit, backend)
transpiled_circuit.draw('mpl')
# Run the transpiled circuit using the simulated fake backend
job = backend.run(transpiled_circuit)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
import qiskit_alt
qiskit_alt.project.ensure_init(calljulia="pyjulia", compile=False, depot=True)
julia = qiskit_alt.project.julia
julia.Main.zeros(10)
from qiskit_nature.drivers import UnitsType, Molecule
from qiskit_nature.drivers.second_quantization import ElectronicStructureDriverType, ElectronicStructureMoleculeDriver
# Specify the geometry of the H_2 molecule
geometry = [['H', [0., 0., 0.]],
['H', [0., 0., 0.735]]]
basis = 'sto3g'
molecule = Molecule(geometry=geometry,
charge=0, multiplicity=1)
driver = ElectronicStructureMoleculeDriver(molecule, basis=basis, driver_type=ElectronicStructureDriverType.PYSCF)
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
es_problem = ElectronicStructureProblem(driver)
second_q_op = es_problem.second_q_ops()
fermionic_hamiltonian = second_q_op[0]
qubit_converter = QubitConverter(mapper=JordanWignerMapper())
nature_qubit_op = qubit_converter.convert(fermionic_hamiltonian)
nature_qubit_op.primitive
import qiskit_alt.electronic_structure
fermi_op = qiskit_alt.electronic_structure.fermionic_hamiltonian(geometry, basis)
pauli_op = qiskit_alt.electronic_structure.jordan_wigner(fermi_op)
pauli_op.simplify() # The Julia Pauli operators use a different sorting convention; we sort again for comparison.
%run ../bench/jordan_wigner_nature_time.py
nature_times
%run ../bench/jordan_wigner_alt_time.py
alt_times
[t_nature / t_qk_alt for t_nature, t_qk_alt in zip(nature_times, alt_times)]
%run ../bench/fermionic_nature_time.py
nature_times
%run ../bench/fermionic_alt_time.py
alt_times
[t_nature / t_qk_alt for t_nature, t_qk_alt in zip(nature_times, alt_times)]
from qiskit_alt.pauli_operators import QuantumOps, PauliSum_to_SparsePauliOp
import numpy as np
m = np.random.rand(2**3, 2**3) # 3-qubit operator
pauli_sum = QuantumOps.PauliSum(m) # This is a wrapped Julia object
PauliSum_to_SparsePauliOp(pauli_sum) # Convert to qiskit.quantum_info.SparsePauliOp
%run ../bench/from_matrix_quantum_info.py
%run ../bench/from_matrix_alt.py
[t_pyqk / t_qk_alt for t_pyqk, t_qk_alt in zip(pyqk_times, qk_alt_times)]
%run ../bench/pauli_from_list_qinfo.py
%run ../bench/pauli_from_list_alt.py
[x / y for x,y in zip(quantum_info_times, qkalt_times)]
%load_ext julia.magic
%julia using Random: randstring
%julia pauli_strings = [randstring("IXYZ", 10) for _ in 1:1000]
None;
%julia import Pkg; Pkg.add("BenchmarkTools")
%julia using BenchmarkTools: @btime
%julia @btime QuantumOps.PauliSum($pauli_strings)
None;
%julia pauli_sum = QuantumOps.PauliSum(pauli_strings);
%julia println(length(pauli_sum))
%julia println(pauli_sum[1])
6.9 * 2.29 / .343 # Ratio of time to construct PauliSum via qiskit_alt to time in pure Julia
import qiskit.tools.jupyter
d = qiskit.__qiskit_version__._version_dict
d['qiskit_alt'] = qiskit_alt.__version__
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate
from qiskit.converters import dag_to_circuit
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
dag = circuit_to_dag(circ)
circuit = dag_to_circuit(dag)
circuit.draw('mpl')
|
https://github.com/COFAlumni-USB/qiskit-fall-2022
|
COFAlumni-USB
|
import numpy as np
import math
import qiskit as qiskit
from numpy import sqrt
from random import randint
from qiskit import *
from qiskit import Aer, QuantumCircuit, IBMQ, execute, quantum_info, transpile
from qiskit.visualization import plot_state_city, plot_bloch_multivector
from qiskit.visualization import plot_histogram
from qiskit.tools import job_monitor
from qiskit.providers.fake_provider import FakeOpenPulse2Q, FakeOpenPulse3Q, FakeManila, FakeValencia, FakeHanoi
from qiskit import pulse, transpile
from qiskit.pulse.library import Gaussian
#Compuertas personalizadas
from qiskit.circuit import Gate
from qiskit import QiskitError
#informacion
import qiskit.tools.jupyter
provider = IBMQ.load_account()
belem = provider.get_backend('ibmq_belem')
print('se ha ejecutado correctamente')
def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
return qc
def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
return qc
def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_1)
return qc
def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
qc.x(x_qubit_1)
return qc
def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit):
rand=randint(0,3)
if rand==3:
SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==2:
SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==1:
SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit)
else:
SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit)
return qc
def Grover_Iteration(qc, x_qubit_0,x_qubit_1):
qc.h(range(2))
qc.x(range(2))
qc.h(x_qubit_1)
qc.cx(x_qubit_0,x_qubit_1)
qc.h(x_qubit_1)
qc.x(range(2))
qc.h(range(2))
return qc
print('se ha ejecutado correctamente')
#Simulador de prueba FakeManila
backend = FakeManila()
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
result = execute(circ, backend=FakeManila()).result();
job = backend.run(circ)
counts = job.result().get_counts()
plot_histogram(counts)
backend = FakeManila();
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0))
h_q0.draw()
backend = FakeManila();
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=33.33), pulse.drive_channel(0))
h_q0.draw()
circ.add_calibration( 'h', [0], h_q0)
circ.add_calibration( 'x', [0], h_q0)
circ.add_calibration( 'cx',[0], h_q0)
circ.add_calibration( 'sx',[0], h_q0)
circ.add_calibration( 'id',[0], h_q0)
circ.add_calibration( 'rz',[0], h_q0)
circ.add_calibration( 'reset',[0], h_q0)
backend = FakeManila()
circ1 = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ1.draw('mpl', idle_wires=False)
result = execute(circ1, backend=FakeManila()).result();
job = backend.run(circ1)
counts = job.result().get_counts()
plot_histogram(counts)
def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
return qc
def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
return qc
def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_1)
return qc
def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
qc.x(x_qubit_1)
return qc
def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit):
rand=randint(0,3)
if rand==3:
SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==2:
SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==1:
SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit)
else:
SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit)
return qc
def Grover_Iteration(qc, x_qubit_0,x_qubit_1):
qc.h(range(2))
qc.x(range(2))
qc.h(x_qubit_1)
qc.cx(x_qubit_0,x_qubit_1)
qc.h(x_qubit_1)
qc.x(range(2))
qc.h(range(2))
return qc
print('se ha ejecutado correctamente')
#Simulador de prueba FakeOpenPulse3Q
backend = FakeOpenPulse3Q()
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
result = execute(circ, backend=FakeOpenPulse3Q()).result();
job = backend.run(circ)
counts = job.result().get_counts()
plot_histogram(counts)
backend = FakeOpenPulse3Q();
with pulse.build(backend, name='hadamard') as h_q1:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0))
h_q1.draw()
backend = FakeOpenPulse3Q();
with pulse.build(backend, name='hadamard') as h_q1:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=33.33), pulse.drive_channel(0))
h_q1.draw()
circ.add_calibration( 'h', [0], h_q1)
circ.add_calibration( 'x', [0], h_q1)
circ.add_calibration( 'cx',[0], h_q1)
circ.add_calibration( 'sx',[0], h_q1)
circ.add_calibration( 'id',[0], h_q1)
circ.add_calibration( 'rz',[0], h_q1)
circ.add_calibration( 'reset',[0], h_q1)
backend = FakeOpenPulse3Q()
circ2 = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ2.draw('mpl', idle_wires=False)
result = execute(circ2, backend=FakeOpenPulse3Q()).result();
job = backend.run(circ2)
counts = job.result().get_counts()
plot_histogram(counts)
def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
return qc
def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
return qc
def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_1)
return qc
def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
qc.x(x_qubit_1)
return qc
def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit):
rand=randint(0,3)
if rand==3:
SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==2:
SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==1:
SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit)
else:
SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit)
return qc
def Grover_Iteration(qc, x_qubit_0,x_qubit_1):
qc.h(range(2))
qc.x(range(2))
qc.h(x_qubit_1)
qc.cx(x_qubit_0,x_qubit_1)
qc.h(x_qubit_1)
qc.x(range(2))
qc.h(range(2))
return qc
print('se ha ejecutado correctamente')
#Simulador de prueba FakeManila
backend = FakeManila()
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
result = execute(circ, backend=FakeManila()).result();
job = backend.run(circ)
counts = job.result().get_counts()
plot_histogram(counts)
backend = FakeManila();
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0))
h_q0.draw()
backend = FakeManila();
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=50, amp=0.1, sigma=16.66), pulse.drive_channel(0))
h_q0.draw()
circ.add_calibration( 'h', [0], h_q0)
circ.add_calibration( 'x', [0], h_q0)
circ.add_calibration( 'cx',[0], h_q0)
circ.add_calibration( 'sx',[0], h_q0)
circ.add_calibration( 'id',[0], h_q0)
circ.add_calibration( 'rz',[0], h_q0)
circ.add_calibration( 'reset',[0], h_q0)
backend = FakeManila()
circ1 = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ1.draw('mpl', idle_wires=False)
result = execute(circ1, backend=FakeManila()).result();
job = backend.run(circ1)
counts = job.result().get_counts()
plot_histogram(counts)
def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
return qc
def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
return qc
def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_1)
return qc
def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
qc.x(x_qubit_1)
return qc
def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit):
rand=randint(0,3)
if rand==3:
SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==2:
SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==1:
SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit)
else:
SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit)
return qc
def Grover_Iteration(qc, x_qubit_0,x_qubit_1):
qc.h(range(2))
qc.x(range(2))
qc.h(x_qubit_1)
qc.cx(x_qubit_0,x_qubit_1)
qc.h(x_qubit_1)
qc.x(range(2))
qc.h(range(2))
return qc
print('se ha ejecutado correctamente')
#Simulador de prueba FakeOpenPulse3Q
backend = FakeOpenPulse3Q()
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
result = execute(circ, backend=FakeOpenPulse3Q()).result();
job = backend.run(circ)
counts = job.result().get_counts()
plot_histogram(counts)
backend = FakeOpenPulse3Q();
with pulse.build(backend, name='hadamard') as h_q1:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0))
h_q1.draw()
backend = FakeOpenPulse3Q();
with pulse.build(backend, name='hadamard') as h_q1:
pulse.play(Gaussian(duration=50, amp=0.1, sigma=16.66), pulse.drive_channel(0))
h_q1.draw()
circ.add_calibration( 'h', [0], h_q1)
circ.add_calibration( 'x', [0], h_q1)
circ.add_calibration( 'cx',[0], h_q1)
circ.add_calibration( 'sx',[0], h_q1)
circ.add_calibration( 'id',[0], h_q1)
circ.add_calibration( 'rz',[0], h_q1)
circ.add_calibration( 'reset',[0], h_q1)
backend = FakeOpenPulse3Q()
circ2 = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ2.draw('mpl', idle_wires=False)
result = execute(circ2, backend=FakeOpenPulse3Q()).result();
job = backend.run(circ2)
counts = job.result().get_counts()
plot_histogram(counts)
def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
return qc
def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
return qc
def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_1)
return qc
def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
qc.x(x_qubit_1)
return qc
def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit):
rand=randint(0,3)
if rand==3:
SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==2:
SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==1:
SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit)
else:
SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit)
return qc
def Grover_Iteration(qc, x_qubit_0,x_qubit_1):
qc.h(range(2))
qc.x(range(2))
qc.h(x_qubit_1)
qc.cx(x_qubit_0,x_qubit_1)
qc.h(x_qubit_1)
qc.x(range(2))
qc.h(range(2))
return qc
print('se ha ejecutado correctamente')
#Simulador de prueba FakeManila
backend = FakeManila()
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
result = execute(circ, backend=FakeManila()).result();
job = backend.run(circ)
counts = job.result().get_counts()
plot_histogram(counts)
backend = FakeManila();
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0))
h_q0.draw()
backend = FakeManila();
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=10, amp=0.1, sigma=3.33), pulse.drive_channel(0))
h_q0.draw()
circ.add_calibration( 'h', [0], h_q0)
circ.add_calibration( 'x', [0], h_q0)
circ.add_calibration( 'cx',[0], h_q0)
circ.add_calibration( 'sx',[0], h_q0)
circ.add_calibration( 'id',[0], h_q0)
circ.add_calibration( 'rz',[0], h_q0)
circ.add_calibration( 'reset',[0], h_q0)
backend = FakeManila()
circ1 = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ1.draw('mpl', idle_wires=False)
result = execute(circ1, backend=FakeManila()).result();
job = backend.run(circ1)
counts = job.result().get_counts()
plot_histogram(counts)
def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
return qc
def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
return qc
def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_1)
return qc
def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
qc.x(x_qubit_1)
return qc
def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit):
rand=randint(0,3)
if rand==3:
SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==2:
SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==1:
SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit)
else:
SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit)
return qc
def Grover_Iteration(qc, x_qubit_0,x_qubit_1):
qc.h(range(2))
qc.x(range(2))
qc.h(x_qubit_1)
qc.cx(x_qubit_0,x_qubit_1)
qc.h(x_qubit_1)
qc.x(range(2))
qc.h(range(2))
return qc
print('se ha ejecutado correctamente')
#Simulador de prueba FakeOpenPulse3Q
backend = FakeOpenPulse3Q()
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
result = execute(circ, backend=FakeOpenPulse3Q()).result();
job = backend.run(circ)
counts = job.result().get_counts()
plot_histogram(counts)
backend = FakeOpenPulse3Q();
with pulse.build(backend, name='hadamard') as h_q1:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0))
h_q1.draw()
backend = FakeOpenPulse3Q();
with pulse.build(backend, name='hadamard') as h_q1:
pulse.play(Gaussian(duration=10, amp=1, sigma=3.33), pulse.drive_channel(0))
h_q1.draw()
circ.add_calibration( 'h', [0], h_q1)
circ.add_calibration( 'x', [0], h_q1)
circ.add_calibration( 'cx',[0], h_q1)
circ.add_calibration( 'sx',[0], h_q1)
circ.add_calibration( 'id',[0], h_q1)
circ.add_calibration( 'rz',[0], h_q1)
circ.add_calibration( 'reset',[0], h_q1)
backend = FakeOpenPulse3Q()
circ2 = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ2.draw('mpl', idle_wires=False)
result = execute(circ2, backend=FakeOpenPulse3Q()).result();
job = backend.run(circ2)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/kaelynj/Qiskit-HubbardModel
|
kaelynj
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer, QuantumRegister, ClassicalRegister
from qiskit.compiler import transpile, assemble
from qiskit.quantum_info import Operator
from qiskit.tools.monitor import job_monitor
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import random as rand
import scipy.linalg as la
provider = IBMQ.load_account()
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
from matplotlib import rcParams
rcParams['text.usetex'] = True
def reverse_list(s):
temp_list = list(s)
temp_list.reverse()
return ''.join(temp_list)
#Useful tool for converting an integer to a binary bit string
def get_bin(x, n=0):
"""
Get the binary representation of x.
Parameters: x (int), n (int, number of digits)"""
binry = format(x, 'b').zfill(n)
sup = list( reversed( binry[0:int(len(binry)/2)] ) )
sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) )
return format(x, 'b').zfill(n)
#return ''.join(sup)+''.join(sdn)
'''The task here is now to define a function which will either update a given circuit with a time-step
or return a single gate which contains all the necessary components of a time-step'''
#==========Needed Functions=============#
#Function to apply a full set of time evolution gates to a given circuit
def qc_evolve(qc, numsite, time, hop, U, trotter_steps):
#Compute angles for the onsite and hopping gates
# based on the model parameters t, U, and dt
theta = hop*time/(2*trotter_slices)
phi = U*time/(trotter_slices)
numq = 2*numsite
y_hop = Operator([[np.cos(theta), 0, 0, -1j*np.sin(theta)],
[0, np.cos(theta), 1j*np.sin(theta), 0],
[0, 1j*np.sin(theta), np.cos(theta), 0],
[-1j*np.sin(theta), 0, 0, np.cos(theta)]])
x_hop = Operator([[np.cos(theta), 0, 0, 1j*np.sin(theta)],
[0, np.cos(theta), 1j*np.sin(theta), 0],
[0, 1j*np.sin(theta), np.cos(theta), 0],
[1j*np.sin(theta), 0, 0, np.cos(theta)]])
z_onsite = Operator([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, np.exp(1j*phi)]])
#Loop over each time step needed and apply onsite and hopping gates
for trot in range(trotter_steps):
#Onsite Terms
for i in range(0, numsite):
qc.unitary(z_onsite, [i,i+numsite], label="Z_Onsite")
#Add barrier to separate onsite from hopping terms
qc.barrier()
#Hopping terms
for i in range(0,numsite-1):
#Spin-up chain
qc.unitary(y_hop, [i,i+1], label="YHop")
qc.unitary(x_hop, [i,i+1], label="Xhop")
#Spin-down chain
qc.unitary(y_hop, [i+numsite, i+1+numsite], label="Xhop")
qc.unitary(x_hop, [i+numsite, i+1+numsite], label="Xhop")
#Add barrier after finishing the time step
qc.barrier()
#Measure the circuit
for i in range(numq):
qc.measure(i, i)
#Function to run the circuit and store the counts for an evolution with
# num_steps number of time steps.
def sys_evolve(nsites, excitations, total_time, dt, hop, U, trotter_steps):
#Check for correct data types
if not isinstance(nsites, int):
raise TypeError("Number of sites should be int")
if np.isscalar(excitations):
raise TypeError("Initial state should be list or numpy array")
if not np.isscalar(total_time):
raise TypeError("Evolution time should be scalar")
if not np.isscalar(dt):
raise TypeError("Time step should be scalar")
if not np.isscalar(hop):
raise TypeError("Hopping term should be scalar")
if not np.isscalar(U):
raise TypeError("Repulsion term should be scalar")
if not isinstance(trotter_steps, int):
raise TypeError("Number of trotter slices should be int")
numq = 2*nsites
num_steps = int(total_time/dt)
print('Num Steps: ',num_steps)
print('Total Time: ', total_time)
data = np.zeros((2**numq, num_steps))
for t_step in range(0, num_steps):
#Create circuit with t_step number of steps
q = QuantumRegister(numq)
c = ClassicalRegister(numq)
qcirc = QuantumCircuit(q,c)
#=========USE THIS REGION TO SET YOUR INITIAL STATE==============
#Initialize circuit by setting the occupation to
# a spin up and down electron in the middle site
#qcirc.x(int(nsites/2))
#qcirc.x(nsites+int(nsites/2))
for flip in excitations:
qcirc.x(flip)
#if nsites==3:
#Half-filling
#qcirc.x(1)
# qcirc.x(4)
# qcirc.x(0)
# qcirc.x(2)
#1 electron
# qcirc.x(1)
#===============================================================
qcirc.barrier()
#Append circuit with Trotter steps needed
qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps)
#Choose provider and backend
provider = IBMQ.get_provider()
#backend = Aer.get_backend('statevector_simulator')
backend = Aer.get_backend('qasm_simulator')
#backend = provider.get_backend('ibmq_qasm_simulator')
#backend = provider.get_backend('ibmqx4')
#backend = provider.get_backend('ibmqx2')
#backend = provider.get_backend('ibmq_16_melbourne')
shots = 8192
max_credits = 10 #Max number of credits to spend on execution
job_exp = execute(qcirc, backend=backend, shots=shots, max_credits=max_credits)
job_monitor(job_exp)
result = job_exp.result()
counts = result.get_counts(qcirc)
print(result.get_counts(qcirc))
print("Job: ",t_step+1, " of ", num_steps," complete.")
#Store results in data array and normalize them
for i in range(2**numq):
if counts.get(get_bin(i,numq)) is None:
dat = 0
else:
dat = counts.get(get_bin(i,numq))
data[i,t_step] = dat/shots
return data
#==========Set Parameters of the System=============#
dt = 0.25 #Delta t
T = 4.5
time_steps = int(T/dt)
t = 1.0 #Hopping parameter
U = 2. #On-Site repulsion
#time_steps = 10
nsites = 3
trotter_slices = 5
initial_state = np.array([1,4])
#Run simulation
run_results = sys_evolve(nsites, initial_state, T, dt, t, U, trotter_slices)
#print(True if np.isscalar(initial_state) else False)
#Process and plot data
'''The procedure here is, for each fermionic mode, add the probability of every state containing
that mode (at a given time step), and renormalize the data based on the total occupation of each mode.
Afterwards, plot the data as a function of time step for each mode.'''
proc_data = np.zeros((2*nsites, time_steps))
timesq = np.arange(0.,time_steps*dt, dt)
#Sum over time steps
for t in range(time_steps):
#Sum over all possible states of computer
for i in range(2**(2*nsites)):
#num = get_bin(i, 2*nsite)
num = ''.join( list( reversed(get_bin(i,2*nsites)) ) )
#For each state, check which mode(s) it contains and add them
for mode in range(len(num)):
if num[mode]=='1':
proc_data[mode,t] += run_results[i,t]
#Renormalize these sums so that the total occupation of the modes is 1
norm = 0.0
for mode in range(len(num)):
norm += proc_data[mode,t]
proc_data[:,t] = proc_data[:,t] / norm
'''
At this point, proc_data is a 2d array containing the occupation
of each mode, for every time step
'''
#Create plots of the processed data
fig2, ax2 = plt.subplots(figsize=(20,10))
colors = list(mcolors.TABLEAU_COLORS.keys())
for i in range(nsites):
#Create string label
strup = "Site "+str(i+1)+r'$\uparrow$'
strdwn = "Site "+str(i+1)+r'$\downarrow$'
ax2.plot(timesq, proc_data[i,:], marker="^", color=str(colors[i]), label=strup)
ax2.plot(timesq, proc_data[i+nsites,:], marker="v", color=str(colors[i]), label=strdwn)
#ax2.set_ylim(0, 0.55)
ax2.set_xlim(0, time_steps*dt+dt/2.)
#ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2))
#ax2.set_yticks(np.arange(0,0.55, 0.05))
ax2.tick_params(labelsize=16)
ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22)
ax2.set_xlabel('Time', fontsize=24)
ax2.set_ylabel('Probability', fontsize=24)
ax2.legend(fontsize=20)
#Plot the raw data as a colormap
xticks = np.arange(2**(nsite*2))
xlabels=[]
print("Time Steps: ",time_steps, " Step Size: ",dt)
for i in range(2**(nsite*2)):
xlabels.append(get_bin(i,6))
fig, ax = plt.subplots(figsize=(10,20))
c = ax.pcolor(run_results, cmap='binary')
ax.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22)
plt.yticks(xticks, xlabels, size=18)
ax.set_xlabel('Time Step', fontsize=22)
ax.set_ylabel('State', fontsize=26)
plt.show()
#Try by constructing the matrix and finding the eigenvalues
N = 3
Nup = 2
Ndwn = N - Nup
t = 1.0
U = 2.
#Check if two states are different by a single hop
def hop(psii, psij):
#Check spin down
hopp = 0
if psii[0]==psij[0]:
#Create array of indices with nonzero values
indi = np.nonzero(psii[1])[0]
indj = np.nonzero(psij[1])[0]
for i in range(len(indi)):
if abs(indi[i]-indj[i])==1:
hopp = -t
return hopp
#Check spin up
if psii[1]==psij[1]:
indi = np.nonzero(psii[0])[0]
indj = np.nonzero(psij[0])[0]
for i in range(len(indi)):
if abs(indi[i]-indj[i])==1:
hopp = -t
return hopp
return hopp
#On-site terms
def repel(l,state):
if state[0][l]==1 and state[1][l]==1:
return state
else:
return []
#States for 3 electrons with net spin up
'''
states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]],
[[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]],
[[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ]
#States for 2 electrons in singlet state
'''
states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]],
[[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]],
[[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ]
#'''
#States for a single electron
#states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ]
#'''
H = np.zeros((len(states),len(states)) )
#Construct Hamiltonian matrix
for i in range(len(states)):
psi_i = states[i]
for j in range(len(states)):
psi_j = states[j]
if j==i:
for l in range(0,N):
if psi_i == repel(l,psi_j):
H[i,j] = U
break
else:
H[i,j] = hop(psi_i, psi_j)
print(H)
results = la.eig(H)
print()
for i in range(len(results[0])):
print('Eigenvalue: ',results[0][i])
print('Eigenvector: \n',results[1][i])
print()
dens_ops = []
eigs = []
for vec in results[1]:
dens_ops.append(np.outer(results[1][i],results[1][i]))
eigs.append(results[0][i])
print(dens_ops)
dt = 0.1
tsteps = 50
times = np.arange(0., tsteps*dt, dt)
t_op = la.expm(-1j*H*dt)
#print(np.subtract(np.identity(len(H)), dt*H*1j))
#print(t_op)
#wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] #Half-filling initial state
wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state
#wfk = [0., 1., 0.] #1 electron initial state
evolve = np.zeros([tsteps, len(wfk)])
mode_evolve = np.zeros([tsteps, 6])
evolve[0] = wfk
#Figure out how to generalize this later
#'''
mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]) /2.
mode_evolve[0][1] = (evolve[0][3]+evolve[0][4]+evolve[0][5]) /2.
mode_evolve[0][2] = (evolve[0][6]+evolve[0][7]+evolve[0][8]) /2.
mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /2.
mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /2.
mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /2.
'''
mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][3]+evolve[0][4]+evolve[0][5]) /3.
mode_evolve[0][1] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3.
mode_evolve[0][2] = (evolve[0][3]+evolve[0][4]+evolve[0][5]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3.
mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /3.
mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /3.
mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /3.
#'''
print(mode_evolve[0])
#Define density matrices
for t in range(1, tsteps):
#t_op = la.expm(-1j*H*t)
wfk = np.dot(t_op, wfk)
evolve[t] = np.multiply(np.conj(wfk), wfk)
norm = np.sum(evolve[t])
#print(evolve[t])
#Store data in modes rather than basis defined in 'states' variable
#Procedure for two electrons
mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]) / (2)
mode_evolve[t][1] = (evolve[t][3]+evolve[t][4]+evolve[t][5]) / (2)
mode_evolve[t][2] = (evolve[t][6]+evolve[t][7]+evolve[t][8]) / (2)
mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) / (2)
mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) / (2)
mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) / (2)
''' #Procedure for half-filling
mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][3]+evolve[t][4]+evolve[t][5]) /3.
mode_evolve[t][1] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3.
mode_evolve[t][2] = (evolve[t][3]+evolve[t][4]+evolve[t][5]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3.
mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) /3.
mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) /3.
mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) /3.
#'''
print(mode_evolve[t])
#print(np.linalg.norm(evolve[t]))
#print(len(evolve[:,0]) )
#print(len(times))
#print(evolve[:,0])
#print(min(evolve[:,0]))
#Create plots of the processed data
fig2, ax2 = plt.subplots(figsize=(20,10))
colors = list(mcolors.TABLEAU_COLORS.keys())
sit1 = "Exact Site "+str(1)+r'$\uparrow$'
sit2 = "Exact Site "+str(2)+r'$\uparrow$'
sit3 = "Exact Site "+str(3)+r'$\uparrow$'
#ax2.plot(times, evolve[:,0], linestyle='--', color=colors[0], linewidth=2.5, label=sit1)
#ax2.plot(times, evolve[:,1], linestyle='--', color=str(colors[1]), linewidth=2.5, label=sit2)
#ax2.plot(times, evolve[:,2], linestyle='--', color=str(colors[2]), linewidth=2., label=sit3)
#ax2.plot(times, np.zeros(len(times)))
for i in range(nsites):
#Create string label
strupq = "Quantum Site "+str(i+1)+r'$\uparrow$'
strdwnq = "Quantum Site "+str(i+1)+r'$\downarrow$'
strup = "Numerical Site "+str(i+1)+r'$\uparrow$'
strdwn = "Numerical Site "+str(i+1)+r'$\downarrow$'
ax2.scatter(timesq, proc_data[i,:], marker="*", color=str(colors[i]), label=strupq)
#ax2.scatter(timesq, proc_data[i+nsite,:], marker="v", color=str(colors[i]), label=strdwnq)
ax2.plot(times, mode_evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup)
ax2.plot(times, mode_evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn)
#ax2.plot(times, evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup)
#ax2.plot(times, evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn)
ax2.set_ylim(0, .51)
ax2.set_xlim(0, tsteps*dt+dt/2.)
#ax2.set_xticks(np.arange(0,tsteps*dt+dt, 2*dt))
#ax2.set_yticks(np.arange(0,0.5, 0.05))
ax2.tick_params(labelsize=16)
ax2.set_title('Time Evolution of 2 Electrons in 3 Site Chain', fontsize=22)
ax2.set_xlabel('Time', fontsize=24)
ax2.set_ylabel('Probability', fontsize=24)
#ax2.legend(fontsize=20)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub="ibm-q", group="open", project="main")
program_id = "qaoa"
qaoa_program = provider.runtime.program(program_id)
print(f"Program name: {qaoa_program.name}, Program id: {qaoa_program.program_id}")
print(qaoa_program.parameters())
import numpy as np
from qiskit.tools import job_monitor
from qiskit.opflow import PauliSumOp, Z, I
from qiskit.algorithms.optimizers import SPSA
# Define the cost operator to run.
op = (
(Z ^ Z ^ I ^ I ^ I)
- (I ^ I ^ Z ^ Z ^ I)
+ (I ^ I ^ Z ^ I ^ Z)
- (Z ^ I ^ Z ^ I ^ I)
- (I ^ Z ^ Z ^ I ^ I)
+ (I ^ Z ^ I ^ Z ^ I)
+ (I ^ I ^ I ^ Z ^ Z)
)
# SPSA helps deal with noisy environments.
optimizer = SPSA(maxiter=100)
# We will run a depth two QAOA.
reps = 2
# The initial point for the optimization, chosen at random.
initial_point = np.random.random(2 * reps)
# The backend that will run the programm.
options = {"backend_name": "ibmq_qasm_simulator"}
# The inputs of the program as described above.
runtime_inputs = {
"operator": op,
"reps": reps,
"optimizer": optimizer,
"initial_point": initial_point,
"shots": 2**13,
# Set to True when running on real backends to reduce circuit
# depth by leveraging swap strategies. If False the
# given optimization_level (default is 1) will be used.
"use_swap_strategies": False,
# Set to True when optimizing sparse problems.
"use_initial_mapping": False,
# Set to true when using echoed-cross-resonance hardware.
"use_pulse_efficient": False,
}
job = provider.runtime.run(
program_id=program_id,
options=options,
inputs=runtime_inputs,
)
job_monitor(job)
print(f"Job id: {job.job_id()}")
print(f"Job status: {job.status()}")
result = job.result()
from collections import defaultdict
def op_adj_mat(op: PauliSumOp) -> np.array:
"""Extract the adjacency matrix from the op."""
adj_mat = np.zeros((op.num_qubits, op.num_qubits))
for pauli, coeff in op.primitive.to_list():
idx = tuple([i for i, c in enumerate(pauli[::-1]) if c == "Z"]) # index of Z
adj_mat[idx[0], idx[1]], adj_mat[idx[1], idx[0]] = np.real(coeff), np.real(coeff)
return adj_mat
def get_cost(bit_str: str, adj_mat: np.array) -> float:
"""Return the cut value of the bit string."""
n, x = len(bit_str), [int(bit) for bit in bit_str[::-1]]
cost = 0
for i in range(n):
for j in range(n):
cost += adj_mat[i, j] * x[i] * (1 - x[j])
return cost
def get_cut_distribution(result) -> dict:
"""Extract the cut distribution from the result.
Returns:
A dict of cut value: probability.
"""
adj_mat = op_adj_mat(PauliSumOp.from_list(result["inputs"]["operator"]))
state_results = []
for bit_str, amp in result["eigenstate"].items():
state_results.append((bit_str, get_cost(bit_str, adj_mat), amp**2 * 100))
vals = defaultdict(int)
for res in state_results:
vals[res[1]] += res[2]
return dict(vals)
import matplotlib.pyplot as plt
cut_vals = get_cut_distribution(result)
fig, axs = plt.subplots(1, 2, figsize=(14, 5))
axs[0].plot(result["optimizer_history"]["energy"])
axs[1].bar(list(cut_vals.keys()), list(cut_vals.values()))
axs[0].set_xlabel("Energy evaluation number")
axs[0].set_ylabel("Energy")
axs[1].set_xlabel("Cut value")
axs[1].set_ylabel("Probability")
from qiskit_optimization.runtime import QAOAClient
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization import QuadraticProgram
qubo = QuadraticProgram()
qubo.binary_var("x")
qubo.binary_var("y")
qubo.binary_var("z")
qubo.minimize(linear=[1, -2, 3], quadratic={("x", "y"): 1, ("x", "z"): -1, ("y", "z"): 2})
print(qubo.prettyprint())
qaoa_mes = QAOAClient(
provider=provider, backend=provider.get_backend("ibmq_qasm_simulator"), reps=2, alpha=0.75
)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(qubo)
print(result.prettyprint())
from qiskit.transpiler import PassManager
from qiskit.circuit.library.standard_gates.equivalence_library import (
StandardEquivalenceLibrary as std_eqlib,
)
from qiskit.transpiler.passes import (
Collect2qBlocks,
ConsolidateBlocks,
UnrollCustomDefinitions,
BasisTranslator,
Optimize1qGatesDecomposition,
)
from qiskit.transpiler.passes.calibration.builders import RZXCalibrationBuilderNoEcho
from qiskit.transpiler.passes.optimization.echo_rzx_weyl_decomposition import (
EchoRZXWeylDecomposition,
)
from qiskit.test.mock import FakeBelem
backend = FakeBelem()
inst_map = backend.defaults().instruction_schedule_map
channel_map = backend.configuration().qubit_channel_mapping
rzx_basis = ["rzx", "rz", "x", "sx"]
pulse_efficient = PassManager(
[
# Consolidate consecutive two-qubit operations.
Collect2qBlocks(),
ConsolidateBlocks(basis_gates=["rz", "sx", "x", "rxx"]),
# Rewrite circuit in terms of Weyl-decomposed echoed RZX gates.
EchoRZXWeylDecomposition(backend.defaults().instruction_schedule_map),
# Attach scaled CR pulse schedules to the RZX gates.
RZXCalibrationBuilderNoEcho(
instruction_schedule_map=inst_map, qubit_channel_mapping=channel_map
),
# Simplify single-qubit gates.
UnrollCustomDefinitions(std_eqlib, rzx_basis),
BasisTranslator(std_eqlib, rzx_basis),
Optimize1qGatesDecomposition(rzx_basis),
]
)
from qiskit import QuantumCircuit
circ = QuantumCircuit(3)
circ.h([0, 1, 2])
circ.rzx(0.5, 0, 1)
circ.swap(0, 1)
circ.cx(2, 1)
circ.rz(0.4, 1)
circ.cx(2, 1)
circ.rx(1.23, 2)
circ.cx(2, 1)
circ.draw("mpl")
pulse_efficient.run(circ).draw("mpl", fold=False)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# define a quantum register with one qubit
qreg1 = QuantumRegister(1)
# define a classical register with one bit
# it stores the measurement result of the quantum part
creg1 = ClassicalRegister(1)
# define our quantum circuit
mycircuit1 = QuantumCircuit(qreg1,creg1)
# apply h-gate (Hadamard: quantum coin-flipping) to the first qubit
mycircuit1.h(qreg1[0])
# measure the first qubit, and store the result in the first classical bit
mycircuit1.measure(qreg1,creg1)
print("Everything looks fine, let's continue ...")
# draw the circuit by using ASCII art
mycircuit1.draw()
# draw the circuit by using matplotlib
mycircuit1.draw(output='mpl',reverse_bits=True)
# reexecute this cell if you DO NOT see the circuit diagram
# execute the circuit 10000 times in the local simulator
job = execute(mycircuit1,Aer.get_backend('qasm_simulator'),shots=10000)
counts1 = job.result().get_counts(mycircuit1)
print(counts1) # print the outcomes
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# define a quantum register with one qubit
qreg2 = QuantumRegister(1)
# define a classical register with one bit
# it stores the measurement result of the quantum part
creg2 = ClassicalRegister(1)
# define our quantum circuit
mycircuit2 = QuantumCircuit(qreg2,creg2)
# apply h-gate (Hadamard: quantum coin-flipping) to the first qubit
mycircuit2.h(qreg2[0])
# apply h-gate (Hadamard: quantum coin-flipping) to the first qubit once more
mycircuit2.h(qreg2[0])
# measure the first qubit, and store the result in the first classical bit
mycircuit2.measure(qreg2,creg2)
print("Everything looks fine, let's continue ...")
# draw the circuit by using matplotlib
mycircuit2.draw(output='mpl',reverse_bits=True)
# reexecute me if you DO NOT see the circuit diagram
# execute the circuit 10000 times in the local simulator
job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=10000)
counts2 = job.result().get_counts(mycircuit2)
print(counts2)
#
# your solution is here
#
# start with 1 do the same experiment
# define a quantum register with one qubit
qreg1 = QuantumRegister(1)
# define a classical register with one bit
# it stores the measurement result of the quantum part
creg1 = ClassicalRegister(1)
# define our quantum circuit
mycircuit1 = QuantumCircuit(qreg1,creg1)
# reverse the bit
mycircuit1.x(qreg1[0])
# apply h-gate (Hadamard: quantum coin-flipping) to the first qubit
mycircuit1.h(qreg1[0])
# measure the first qubit, and store the result in the first classical bit
mycircuit1.measure(qreg1,creg1)
# get the numbers
job = execute(mycircuit1,Aer.get_backend('qasm_simulator'),shots=10000)
counts1 = job.result().get_counts(mycircuit1)
print(counts1) # print the outcomes
# draw the circuit by using ASCII art
mycircuit1.draw()
mycircuit1.draw(output='mpl',reverse_bits=True)
# reexecute this cell if you DO NOT see the circuit diagram
# 2nd experiment with the resersed bit
# define a quantum register with one qubit
qreg2 = QuantumRegister(1)
# define a classical register with one bit
# it stores the measurement result of the quantum part
creg2 = ClassicalRegister(1)
# define our quantum circuit
mycircuit2 = QuantumCircuit(qreg2,creg2)
# reverse the bit start with 1
mycircuit2.x(qreg2[0])
# apply h-gate (Hadamard: quantum coin-flipping) to the first qubit
mycircuit2.h(qreg2[0])
# apply h-gate (Hadamard: quantum coin-flipping) to the first qubit once more
mycircuit2.h(qreg2[0])
# measure the first qubit, and store the result in the first classical bit
mycircuit2.measure(qreg2,creg2)
job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=10000)
counts2 = job.result().get_counts(mycircuit2)
print(counts2)
mycircuit2.draw(output='mpl',reverse_bits=True)
# reexecute this cell if you DO NOT see the circuit diagram
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.problems import BaseProblem
dummy_hamiltonian = None
base_problem = BaseProblem(dummy_hamiltonian)
print(base_problem.properties)
from qiskit_nature.second_q.properties import AngularMomentum
print("AngularMomentum is in problem.properties:", AngularMomentum in base_problem.properties)
print("Adding AngularMomentum to problem.properties...")
base_problem.properties.add(AngularMomentum(2))
print("AngularMomentum is in problem.properties:", AngularMomentum in base_problem.properties)
print("Discarding AngularMomentum from problem.properties...")
base_problem.properties.discard(AngularMomentum)
print("AngularMomentum is in problem.properties:", AngularMomentum in base_problem.properties)
from qiskit_nature.second_q.drivers import PySCFDriver
es_problem = PySCFDriver().run()
print(es_problem.properties.particle_number)
print(es_problem.properties.angular_momentum)
print(es_problem.properties.magnetization)
print(es_problem.properties.electronic_dipole_moment)
print(es_problem.properties.electronic_density)
from qiskit_nature.second_q.properties import ElectronicDensity
density = ElectronicDensity.from_orbital_occupation(
es_problem.orbital_occupations,
es_problem.orbital_occupations_b,
)
es_problem.properties.electronic_density = density
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/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)
retrieved_jobs = jobs
retrieved_cal_job = cal_job
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)))
|
https://github.com/abbarreto/qiskit3
|
abbarreto
| |
https://github.com/ichen17/Learning-Qiskit
|
ichen17
|
# initialization
import numpy as np
import matplotlib
# importing Qiskit
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer, assemble, transpile
from qiskit.quantum_info import Statevector
# import basic plot tools
from qiskit.visualization import plot_bloch_multivector,plot_bloch_vector, plot_histogram
style = {'backgroundcolor': 'lightyellow'} # Style of the circuits
# set the length of the n-bit input string.
n = 3
# set the length of the n-bit input string.
n = 3
const_oracle = QuantumCircuit(n+1)
output = np.random.randint(2)
if output == 1:
const_oracle.x(n)
const_oracle.draw(output='mpl', style=style)
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
balanced_oracle.draw(output='mpl', style=style)
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
balanced_oracle.draw(output='mpl', style=style)
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Show oracle
balanced_oracle.draw(output='mpl', style=style)
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
dj_circuit.draw(output='mpl', style=style)
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit += balanced_oracle
dj_circuit.draw(output='mpl', style=style)
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit += balanced_oracle
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i)
# Display circuit
dj_circuit.draw(output='mpl', style=style)
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(dj_circuit, aer_sim)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
def dj_oracle(case, n):
# We need to make a QuantumCircuit object to return
# This circuit has n+1 qubits: the size of the input,
# plus one output qubit
oracle_qc = QuantumCircuit(n+1)
# First, let's deal with the case in which oracle is balanced
if case == "balanced":
# First generate a random number that tells us which CNOTs to
# wrap in X-gates:
b = np.random.randint(1,2**n)
print(b)
print(str(n))
b=7
# Next, format 'b' as a binary string of length 'n', padded with zeros:
b_str = format(b, '0'+str(n)+'b')
print(b_str)
# Next, we place the first X-gates. Each digit in our binary string
# corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
# we apply an X-gate to that qubit:
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Do the controlled-NOT gates for each qubit, using the output qubit
# as the target:
for qubit in range(n):
oracle_qc.cx(qubit, n)
# Next, place the final X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Case in which oracle is constant
if case == "constant":
# First decide what the fixed output of the oracle will be
# (either always 0 or always 1)
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle" # To show when we display the circuit
return oracle_gate
def dj_algorithm(oracle, n):
dj_circuit = QuantumCircuit(n+1, n)
# Set up the output qubit:
dj_circuit.x(n)
dj_circuit.h(n)
# And set up the input register:
for qubit in range(n):
dj_circuit.h(qubit)
# Let's append the oracle gate to our circuit:
dj_circuit.append(oracle, range(n+1))
# Finally, perform the H-gates again and measure:
for qubit in range(n):
dj_circuit.h(qubit)
for i in range(n):
dj_circuit.measure(i, i)
return dj_circuit
n = 4
oracle_gate = dj_oracle('balanced', n)
dj_circuit = dj_algorithm(oracle_gate, n)
dj_circuit.draw(output='mpl', style=style)
transpiled_dj_circuit = transpile(dj_circuit, aer_sim)
qobj = assemble(transpiled_dj_circuit)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.mappers import ParityMapper
from qiskit_nature.second_q.properties import ParticleNumber
from qiskit_nature.second_q.transformers import ActiveSpaceTransformer
bond_distance = 2.5 # in Angstrom
# specify driver
driver = PySCFDriver(
atom=f"Li 0 0 0; H 0 0 {bond_distance}",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
problem = driver.run()
# specify active space transformation
active_space_trafo = ActiveSpaceTransformer(
num_electrons=problem.num_particles, num_spatial_orbitals=3
)
# transform the electronic structure problem
problem = active_space_trafo.transform(problem)
# construct the parity mapper with 2-qubit reduction
qubit_mapper = ParityMapper(num_particles=problem.num_particles)
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_nature.second_q.algorithms.ground_state_solvers import GroundStateEigensolver
np_solver = NumPyMinimumEigensolver()
np_groundstate_solver = GroundStateEigensolver(qubit_mapper, np_solver)
np_result = np_groundstate_solver.solve(problem)
target_energy = np_result.total_energies[0]
print(np_result)
from qiskit.circuit.library import EfficientSU2
ansatz = EfficientSU2(num_qubits=4, reps=1, entanglement="linear", insert_barriers=True)
ansatz.decompose().draw("mpl", style="iqx")
import numpy as np
from qiskit.utils import algorithm_globals
# fix random seeds for reproducibility
np.random.seed(5)
algorithm_globals.random_seed = 5
from qiskit.algorithms.optimizers import SPSA
optimizer = SPSA(maxiter=100)
initial_point = np.random.random(ansatz.num_parameters)
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.primitives import Estimator
estimator = Estimator()
local_vqe = VQE(
estimator,
ansatz,
optimizer,
initial_point=initial_point,
)
local_vqe_groundstate_solver = GroundStateEigensolver(qubit_mapper, local_vqe)
local_vqe_result = local_vqe_groundstate_solver.solve(problem)
print(local_vqe_result)
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(group="open") # replace by your runtime provider
backend = provider.get_backend("ibmq_qasm_simulator") # select a backend that supports the runtime
from qiskit_nature.runtime import VQEClient
runtime_vqe = VQEClient(
ansatz=ansatz,
optimizer=optimizer,
initial_point=initial_point,
provider=provider,
backend=backend,
shots=1024,
measurement_error_mitigation=True,
) # use a complete measurement fitter for error mitigation
runtime_vqe_groundstate_solver = GroundStateEigensolver(qubit_mapper, runtime_vqe)
runtime_vqe_result = runtime_vqe_groundstate_solver.solve(problem)
print(runtime_vqe_result)
runtime_result = runtime_vqe_result.raw_result
history = runtime_result.optimizer_history
loss = history["energy"]
import matplotlib.pyplot as plt
plt.rcParams["font.size"] = 14
# plot loss and reference value
plt.figure(figsize=(12, 6))
plt.plot(loss + runtime_vqe_result.nuclear_repulsion_energy, label="Runtime VQE")
plt.axhline(y=target_energy + 0.2, color="tab:red", ls=":", label="Target + 200mH")
plt.axhline(y=target_energy, color="tab:red", ls="--", label="Target")
plt.legend(loc="best")
plt.xlabel("Iteration")
plt.ylabel("Energy [H]")
plt.title("VQE energy");
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Pitt-JonesLab/mirror-gates
|
Pitt-JonesLab
|
from qiskit import transpile
from qiskit.circuit.library import CZGate, iSwapGate
from qiskit.quantum_info import Operator
from qiskit import QuantumCircuit
import numpy as np
qc = QuantumCircuit(2)
qc.cz(0, 1)
qc.swap(0, 1)
qc2 = QuantumCircuit(2)
qc2.rz(-np.pi / 2, 0)
qc2.rz(-np.pi / 2, 1)
qc2.iswap(0, 1)
Operator(qc).equiv(qc2)
qc2.draw("mpl")
from qiskit.circuit.library import QuantumVolume, EfficientSU2, TwoLocal, QFT
from qiskit import QuantumCircuit
from qiskit.circuit.library.standard_gates import iSwapGate, CXGate
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeQuitoV2
from qiskit.transpiler.coupling import CouplingMap
from qiskit.extensions import UnitaryGate
from weylchamber import canonical_gate
from mirror_gates.pass_managers import Mirage, QiskitLevel3
from transpile_benchy.metrics.gate_counts import (
DepthMetric,
TotalMetric,
TotalSwaps,
)
from transpile_benchy.metrics.timer import TimeMetric
from mirror_gates.fast_unitary import FastConsolidateBlocks
from qiskit.transpiler.passes import (
Collect2qBlocks,
Unroll3qOrMore,
ConsolidateBlocks,
)
from qiskit.transpiler import PassManager
import numpy as np
from mirror_gates.logging import transpile_benchy_logger
N = 8
# coupling_map = FakeQuitoV2().target.build_coupling_map()
# coupling_map = CouplingMap.from_grid(4,4)
coupling_map = CouplingMap.from_line(N)
# coupling_map = CouplingMap.from_heavy_hex(5)
# coupling_map.draw()
from transpile_benchy.interfaces.mqt_interface import MQTBench
from transpile_benchy.interfaces.qasm_interface import QASMBench
from transpile_benchy.library import CircuitLibrary
lib = CircuitLibrary(circuit_list=[])
qc = lib.get_circuit("qft_n4")
qc = qc.decompose()
display(qc.draw("mpl"))
# qc.remove_final_measurements()
# qc.save_density_matrix()
# qc.draw("mpl")
# # Create an empty noise model
# from qiskit_aer.noise import (
# NoiseModel,
# QuantumError,
# ReadoutError,
# pauli_error,
# depolarizing_error,
# thermal_relaxation_error,
# )
# # Error probabilities
# prob_1 = 0.001 # 1-qubit gate
# prob_2 = 0.01 # 2-qubit gate
# # Depolarizing quantum errors
# error_1 = depolarizing_error(prob_1, 1)
# error_2 = depolarizing_error(prob_2, 2)
# # Add errors to noise model
# noise_model = NoiseModel()
# noise_model.add_all_qubit_quantum_error(error_1, ["u1", "u2", "u3"])
# noise_model.add_all_qubit_quantum_error(error_2, ["cx"])
# print(noise_model)
runner = Mirage(
coupling_map,
cx_basis=0,
parallel=0,
logger=transpile_benchy_logger,
cost_function="depth",
# cost_function="basic",
anneal_routing=True,
layout_trials=20,
fb_iters=4,
# layout_trials=20,
# fb_iters=4,
# fixed_aggression=0
# cost_function="basic",
use_fast_settings=1,
)
runner.seed = 0
metric = DepthMetric(consolidate=False)
runner._append_metric_pass(metric)
metric = TotalMetric(consolidate=False)
runner._append_metric_pass(metric)
metric = TotalSwaps(consolidate=False)
runner._append_metric_pass(metric)
# metric = TimeMetric()
# runner._append_metric_pass(metric)
transp = runner.run(qc)
# print(runner.property_set["accepted_subs"])
print(runner.property_set["monodromy_depth"])
print(runner.property_set["monodromy_total"])
print(runner.property_set["total_swaps"])
display(runner.property_set["mid"].draw("mpl", fold=-1))
# display(runner.property_set["post0"].draw("mpl"))
# display(transp.draw(output="mpl", fold=-1))
transpile(transp, basis_gates=["cx", "u"]).draw("mpl")
from qiskit import transpile
mirage_qc = transpile(
qc,
optimization_level=3,
coupling_map=coupling_map,
# basis_gates=["u", "xx_plus_yy", "id"],
basis_gates=["u", "cx"],
routing_method="mirage",
layout_method="sabre_layout_v2",
)
mirage_qc.draw(output="mpl")
runner = QiskitLevel3(coupling_map, cx_basis=0)
metric = DepthMetric(consolidate=False)
runner._append_metric_pass(metric)
metric = TotalSwaps(consolidate=False)
runner._append_metric_pass(metric)
transp = runner.run(qc)
print(runner.property_set["monodromy_depth"])
print(runner.property_set["total_swaps"])
# print(runner.property_set["monodromy_total"])
display(transp.draw(output="mpl", fold=-1))
# display(runner.property_set["post0"].draw("mpl"))
# from qiskit import Aer, transpile
# from qiskit.quantum_info import state_fidelity
# from qiskit_aer import AerSimulator
# simulator = Aer.get_backend("aer_simulator")
# circ = transpile(qc, simulator)
# result = simulator.run(circ).result()
# perfect_density_matrix = result.data()["density_matrix"]
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main')
device = provider.get_backend('ibmq_bogota')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from qiskit.quantum_info import state_fidelity
cos(pi/8), sin(pi/8)
U = (1/sqrt(2))*Matrix([[1,1],[1,-1]]); V1 = Matrix([[1,0],[0,1]]); V2 = V1
D1 = Matrix([[cos(pi/8),0],[0,cos(pi/8)]]); D2 = Matrix([[sin(pi/8),0],[0,sin(pi/8)]])
U, U*U.T, D1, D2
M1 = V1*D1*U; M2 = V2*D2*U; M1, M2
M1*M1, M2*M2, M1*M1 + M2*M2 # não são projetores, mas são operadores de medida
2*float((1/4)*(1+1/sqrt(2))), 2*float((1/4)*(1-1/sqrt(2)))
qr = QuantumRegister(2); cr = ClassicalRegister(1); qc = QuantumCircuit(qr, cr)
qc.h(qr[0]); qc.x(qr[0]); qc.cry(math.pi/4, 0, 1); qc.x(qr[0]); qc.cry(math.pi/4, 0, 1)
# V1=V2=I
qc.measure(1,0)
qc.draw(output = 'mpl')
job_sim = execute(qc, backend = simulator, shots = nshots)
job_exp = execute(qc, backend = device, shots = nshots)
job_monitor(job_exp)
plot_histogram([job_sim.result().get_counts(), job_exp.result().get_counts()],
legend = ['sim', 'exp'])
def U(xi, et, ga):
return Matrix([[(cos(xi)+1j*sin(xi))*cos(ga), (cos(et)+1j*sin(et))*sin(ga)],
[-(cos(et)-1j*sin(et))*sin(ga), (cos(xi)-1j*sin(xi))*cos(ga)]])
xi, et, ga = symbols('xi eta gamma'); U(xi, et, ga)
def D1(th, ph):
return Matrix([[cos(th/2),0],[0,cos(ph/2)]])
def D2(th, ph):
return Matrix([[sin(th/2),0],[0,sin(ph/2)]])
th,ph = symbols('theta phi'); D1(th, ph), D2(th, ph)
xi1,et1,ga1,xi2,et2,ga2,xi3,et3,ga3 = symbols('xi_1 eta_1 gamma_1 xi_2 eta_2 gamma_2 xi_3 eta_3 gamma_3')
simplify(U(xi1,et1,ga1)*D1(th,ph)*U(xi2,et2,ga2) - (1/2)*sqrt(1+1/sqrt(2))*Matrix([[1,1],[1,-1]]))
simplify(U(xi3,et3,ga3)*D2(th,ph)*U(xi2,et2,ga2) - (1/2)*sqrt(1+1/sqrt(2))*Matrix([[1,1],[1,-1]]))
cos(pi/3), sin(pi/3), cos(2*pi/3), sin(2*pi/3)
M1 = sqrt(2/3)*Matrix([[1,0],[0,0]])
M2 = (1/(4*sqrt(6)))*Matrix([[1,sqrt(3)],[sqrt(3),3]])
M3 = (1/(4*sqrt(6)))*Matrix([[1,-sqrt(3)],[-sqrt(3),3]])
M1,M2,M3
M1.T*M1 + M2.T*M2 + M3.T*M3
M1 = sqrt(2/3.)*Matrix([[1,0],[0,0]]); M2 = sqrt(2/3.)*(1/4)*Matrix([[1,sqrt(3.)],[sqrt(3.),3]])
M3 = sqrt(2/3.)*(1/4)*Matrix([[1,-sqrt(3.)],[-sqrt(3.),3]])
M1, M2, M3
M1.T*M1 + M2.T*M2 + M3.T*M3
2/3, 1/6, 2/3+2*(1/6)
#th1 = acos(sqrt(2/3)); ph1 = pi; th2 = pi/2; ph2 = pi/2
D11 = Matrix([[sqrt(2/3),0],[0,0]])
D21 = Matrix([[sqrt(1/3),0],[0,1]])
D12 = Matrix([[1/sqrt(2),0],[0,1/sqrt(2)]])
D22 = Matrix([[1/sqrt(2),0],[0,1/sqrt(2)]])
U = Matrix([[1,0],[0,1]])
V11 = Matrix([[1,0],[0,1]])
V21 = (1/sqrt(2))*Matrix([[1,1],[-1,1]])
V12 = (1/2)*Matrix([[1,-sqrt(3)],[sqrt(3),1]])
V22 = -(1/2)*Matrix([[sqrt(3),-1],[1,sqrt(3)]])
M1 = V11*D11*U
np.array(M1).astype(np.float64), np.array(Matrix([[sqrt(2/3),0],[0,0]])).astype(np.float64)
M2 = V12*D12*V21*D21*U
np.array(M2).astype(np.float64), np.array((1/4)*sqrt(2/3)*Matrix([[1,sqrt(3)],[sqrt(3),3]])).astype(np.float64)
# não é o resultado que precisamos
M3 = V22*D22*V21*D21*U
np.array(M3).astype(np.float64), np.array((1/4)*sqrt(2/3)*Matrix([[1,-sqrt(3)],[-sqrt(3),3]])).astype(np.float64)
# não é o resultado que precisamos
np.array(M1.T*M1 + M2.T*M2 + M3.T*M3).astype(np.float64) # esta ok a relacao de completeza
cos(pi/3), sin(pi/3), cos(pi/6)
def qc_ry(th):
qr = QuantumRegister(1); qc = QuantumCircuit(qr, name = 'RY')
qc.ry(th, 0)
return qc
def qc_u(th,ph,lb):
qr = QuantumRegister(1); qc = QuantumCircuit(qr, name = 'U')
qc.u(th,ph,lb, 0)
return qc
qr = QuantumRegister(3); cr = ClassicalRegister(2); qc = QuantumCircuit(qr, cr)
# U = I
qc.x(qr[0]); qc.cry(math.acos(math.sqrt(2/3)), 0, 1); qc.x(qr[0]); qc.cry(math.pi/2, 0, 1)
# V11 = I
qc.cu(math.pi/2,math.pi,math.pi,0, 1,0)
qc.barrier()
qc_ry_ = qc_ry(0); ccry = qc_ry_.to_gate().control(2) # cria a ctrl-ctrl-RY
qc.x(0); qc.append(ccry, [0,1,2]); qc.x(0)
qc_ry_ = qc_ry(math.pi/2); ccry = qc_ry_.to_gate().control(2)
qc.append(ccry, [0,1,2]) # os primeiros sao o controle, os ultimos sao o target
qc.x(2)
qc_u_ = qc_u(2*math.pi/3,0,0); ccu = qc_u_.to_gate().control(2)
qc.append(ccu, [1,2,0])
qc.x(2)
qc_u_ = qc_u(4*math.pi/3,0,0); ccu = qc_u_.to_gate().control(2)
qc.append(ccu, [1,2,0])
qc.barrier()
qc.measure(1,0); qc.measure(2,1)
qc.draw(output = 'mpl')
qc.decompose().draw(output = 'mpl')
job_sim = execute(qc, backend = simulator, shots = nshots)
job_exp = execute(qc, backend = device, shots = nshots)
job_monitor(job_exp)
plot_histogram([job_sim.result().get_counts(), job_exp.result().get_counts()],
legend = ['sim', 'exp'])
# sequencia: 000 001 010 011 100 101 110 111 = 0 1 2 3 4 5 6 7
Phi_ACD = [math.sqrt(2/3), (1/4)*math.sqrt(2/3), (1/4)*math.sqrt(2/3), 0,
0, (1/4)*math.sqrt(2), -(1/4)*math.sqrt(2), 0]
qr = QuantumRegister(3); cr = ClassicalRegister(2); qc = QuantumCircuit(qr,cr)
qc.initialize(Phi_ACD, [qr[2],qr[1],qr[0]])
qc.draw(output='mpl')
backend = BasicAer.get_backend('statevector_simulator')
job = backend.run(transpile(qc, backend))
qc_state = job.result().get_statevector(qc)
qc_state
sqrt(2/3), 0.25*sqrt(2/3), 0.25*sqrt(2.)
state_fidelity(Phi_ACD,qc_state)
qc.measure([1,2],[0,1])
qc.draw(output='mpl')
job_sim = execute(qc, backend = simulator, shots = nshots)
job_exp = execute(qc, backend = device, shots = nshots)
job_monitor(job_exp)
# tava dando errado o resultado. Me parece que na inicializacao a ordem dos qubits foi trocada
plot_histogram([job_sim.result().get_counts(), job_exp.result().get_counts()],
legend = ['sim', 'exp'])
# sequencia: 000 001 010 011 100 101 110 111 = 0 1 2 3 4 5 6 7
Phi_ACD = [1/math.sqrt(2), 1/(2*math.sqrt(2)), 0, 1/(2*math.sqrt(2)),
0, 1/(2*math.sqrt(2)), 0, -1/(2*math.sqrt(2))]
qr = QuantumRegister(3); cr = ClassicalRegister(2); qc = QuantumCircuit(qr,cr)
qc.initialize(Phi_ACD, [qr[2],qr[1],qr[0]])
qc.measure([1,2],[0,1])
qc.draw(output='mpl')
qc.decompose().decompose().decompose().decompose().decompose().draw(output='mpl')
job_sim = execute(qc, backend = simulator, shots = nshots)
job_exp = execute(qc, backend = device, shots = nshots)
job_monitor(job_exp)
plot_histogram([job_sim.result().get_counts(), job_exp.result().get_counts()],
legend = ['sim', 'exp'])
qr = QuantumRegister(4); cr = ClassicalRegister(3); qc = QuantumCircuit(qr, cr)
# U = I
qc.x(qr[0]); qc.cry(math.acos(math.sqrt(2/3)), 0, 1); qc.x(qr[0]); qc.cry(math.pi/2, 0, 1)
# V11 = I
qc.cu(math.pi/2,math.pi,math.pi,0, 1,0)
qc.barrier()
qc_ry_ = qc_ry(0); ccry = qc_ry_.to_gate().control(2) # cria a ctrl-ctrl-RY
qc.x(0); qc.append(ccry, [0,1,2]); qc.x(0)
qc_ry_ = qc_ry(math.pi/2); ccry = qc_ry_.to_gate().control(2)
qc.append(ccry, [0,1,2]) # os primeiros sao o controle, os ultimos sao o target
qc.x(2)
qc_u_ = qc_u(2*math.pi/3,0,0); ccu = qc_u_.to_gate().control(2)
qc.append(ccu, [1,2,0])
qc.x(2)
qc_u_ = qc_u(4*math.pi/3,0,0); ccu = qc_u_.to_gate().control(2)
qc.append(ccu, [1,2,0])
qc.barrier()
qc_ry_ = qc_ry(math.pi); cccry = qc_ry_.to_gate().control(3) # cria a ctrl-ctrl-ctrl-RY
qc.x(0); qc.append(cccry, [0,1,2,3]); qc.x(0)
qc_ry_ = qc_ry(math.pi/2); cccry = qc_ry_.to_gate().control(3)
qc.append(cccry, [0,1,2,3])
qc_u_ = qc_u(math.pi,0,0); cccu = qc_u_.to_gate().control(3)
qc.x(3); qc.append(cccu, [3,2,1,0]); qc.x(3)
qc.append(cccu, [3,2,1,0])
qc_u_ = qc_u(math.pi/3,0,0); cccu = qc_u_.to_gate().control(3)
qc.barrier()
qc.measure(1,0); qc.measure(2,1); qc.measure(3,2)
qc.draw(output = 'mpl')
qc.decompose().draw(output = 'mpl')
%run init.ipynb
# 2 element 1-qubit povm (Yordanov)
M1 = (1/2)*Matrix([[1,0],[0,sqrt(3)]]); M2 = M1
M1, M2
M1.T*M1 + M2.T*M2
# 3 element 1-qubit povm (Yordanov)
M1 = sqrt(2/3)*Matrix([[1,0],[0,0]])
M2 = (1/(4*sqrt(6)))*Matrix([[1,sqrt(3)],[sqrt(3),1]])
M3 = (1/(4*sqrt(6)))*Matrix([[1,-sqrt(3)],[-sqrt(3),1]])
M1,M2,M3
M1.T*M1 + M2.T*M2 + M3.T*M3
# 2-element 1-qubit POVM (Douglas)
M1 = (1/(2*sqrt(2)))*Matrix([[1,0],[sqrt(3),2]])
M2 = (1/(2*sqrt(2)))*Matrix([[1,0],[-sqrt(3),2]])
M1,M2
M1.T*M1 + M2.T*M2
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, execute
from qiskit.providers.fake_provider import FakeVigoV2
from qiskit.visualization import plot_gate_map
backend = FakeVigoV2()
plot_gate_map(backend)
|
https://github.com/abbarreto/qiskit3
|
abbarreto
| |
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
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()
|
https://github.com/DavidFitzharris/EmergingTechnologies
|
DavidFitzharris
|
# initialization
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer
from qiskit import QuantumCircuit, transpile
# import basic plot tools
from qiskit.visualization import plot_histogram
# set the length of the n-bit input string.
n = 3
# Constant Oracle
const_oracle = QuantumCircuit(n+1)
# Random output
output = np.random.randint(2)
if output == 1:
const_oracle.x(n)
const_oracle.draw()
# Balanced Oracle
balanced_oracle = QuantumCircuit(n+1)
# Binary string length
b_str = "101"
# For each qubit in our circuit
# we place an X-gate if the corresponding digit in b_str is 1
# or do nothing if the digit is 0
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
balanced_oracle.draw()
# Creating the controlled-NOT gates
# using each input qubit as a control
# and the output as a target
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
# Wrapping the controls in X-gates
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Show oracle
balanced_oracle.draw()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit = dj_circuit.compose(balanced_oracle)
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i)
# Display circuit
dj_circuit.draw()
# Viewing the output
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
results = aer_sim.run(dj_circuit).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/usamisaori/Grover
|
usamisaori
|
import qiskit
from qiskit import QuantumCircuit
from qiskit.visualization import plot_histogram
from qiskit.quantum_info import Operator
import numpy as np
from qiskit import execute, Aer
simulator = Aer.get_backend('qasm_simulator')
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
def createYouneInitCircuit():
circuit = QuantumCircuit(3, 2)
circuit.h(0)
circuit.h(1)
circuit.barrier()
return circuit
youneInitCircuit = createYouneInitCircuit()
youneInitCircuit.draw(output='mpl')
def createYouneOracle():
circuit = QuantumCircuit(3, 2)
circuit.x(0)
circuit.x(1)
circuit.ccx(0, 1, 2)
circuit.x(0)
circuit.x(1)
circuit.barrier()
circuit.x(0)
circuit.ccx(0, 1, 2)
circuit.x(0)
circuit.barrier()
return circuit
youneOracle = createYouneOracle()
youneOracle.draw(output='mpl')
def createYouneDiffuser():
circuit = QuantumCircuit(3, 2)
circuit.h(0)
circuit.h(1)
circuit.barrier(2)
circuit.x(2)
circuit.x(0)
circuit.x(1)
circuit.h(2)
circuit.ccx(0, 1, 2)
circuit.barrier(0)
circuit.barrier(1)
circuit.h(2)
circuit.x(2)
circuit.x(0)
circuit.x(1)
circuit.h(0)
circuit.h(1)
# circuit.h(2)
circuit.barrier()
return circuit
youneDiffuser = createYouneDiffuser()
youneDiffuser.draw(output='mpl')
youneGroverIteration = createYouneOracle().compose(createYouneDiffuser())
grover_youne = createYouneInitCircuit().compose(youneGroverIteration.copy())
grover_youne.draw(output='mpl')
grover_youne.measure([0, 1], [0, 1])
job = execute(grover_youne, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_youne)
print(counts)
plot_histogram(counts, figsize=(4, 5), color="#0099CC", title="youne grover - find evens")
def createYouneOracle2():
circuit = QuantumCircuit(3, 2)
circuit.x(0)
circuit.cx(0, 2)
circuit.x(0)
circuit.barrier()
return circuit
youneOracle2 = createYouneOracle2()
youneOracle2.draw(output='mpl')
# 0 => 4 2 => 6
Operator(youneOracle2).data
youneGroverIteration2 = createYouneOracle2().compose(createYouneDiffuser())
grover_youne2 = createYouneInitCircuit().compose(youneGroverIteration2.copy())
grover_youne2.draw(output='mpl')
grover_youne2.measure([0, 1], [0, 1])
job = execute(grover_youne2, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_youne2)
print(counts)
plot_histogram(counts, figsize=(4, 5), color="#66CCFF", title="youne grover(using another Oracle) - find evens")
|
https://github.com/CQCL/pytket-qiskit
|
CQCL
|
# Copyright 2020-2024 Quantinuum
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Optional, List, Union, Any
from qiskit.circuit.quantumcircuit import QuantumCircuit # type: ignore
from qiskit.providers.backend import BackendV1 # type: ignore
from qiskit.providers.models import QasmBackendConfiguration # type: ignore
from qiskit.providers import Options # type: ignore
from pytket.extensions.qiskit import AerStateBackend, AerUnitaryBackend
from pytket.extensions.qiskit.qiskit_convert import qiskit_to_tk, _gate_str_2_optype_rev
from pytket.extensions.qiskit.tket_job import TketJob, JobInfo
from pytket.backends import Backend
from pytket.passes import BasePass
from pytket.predicates import (
NoClassicalControlPredicate,
GateSetPredicate,
CompilationUnit,
)
from pytket.architecture import FullyConnected
def _extract_basis_gates(backend: Backend) -> List[str]:
for pred in backend.required_predicates:
if type(pred) == GateSetPredicate:
return [
_gate_str_2_optype_rev[optype]
for optype in pred.gate_set
if optype in _gate_str_2_optype_rev.keys()
]
return []
class TketBackend(BackendV1):
"""Wraps a :py:class:`Backend` as a :py:class:`qiskit.providers.BaseBackend` for use
within the Qiskit software stack.
Each :py:class:`qiskit.circuit.quantumcircuit.QuantumCircuit` passed in will be
converted to a :py:class:`Circuit` object. If a :py:class:`BasePass` is provided for
``comp_pass``, this is applied to the :py:class:`Circuit`. Then it is processed by
the :py:class:`Backend`, wrapping the :py:class:`ResultHandle` s in a
:py:class:`TketJob`, retrieving the results when called on the job object. The
required predicates of the :py:class:`Backend` are presented to the Qiskit
transpiler to enable it to perform the compilation in many cases. This may not
always be possible due to unsupported gatesets or additional constraints that cannot
be captured in Qiskit's transpiler, in which case a custom
:py:class:`qiskit.transpiler.TranspilationPass` should be used to map into a tket-
compatible gateset and set ``comp_pass`` to compile for the backend. To compile with
tket only, set ``comp_pass`` and just use Qiskit to map into a tket-compatible
gateset. In Qiskit Aqua, you should wrap the :py:class:`TketBackend` in a
:py:class:`qiskit.aqua.QuantumInstance`, providing a custom
:py:class:`qiskit.transpiler.PassManager` with a
:py:class:`qiskit.transpiler.passes.Unroller`. For examples, see the `user manual
<https://tket.quantinuum.com/user-manual/manual_backend.html#embedding-into-
qiskit>`_ or the `Qiskit integration example <ht
tps://github.com/CQCL/pytket/blob/main/examples/qiskit_integration. ipynb>`_.
"""
def __init__(self, backend: Backend, comp_pass: Optional[BasePass] = None):
"""Create a new :py:class:`TketBackend` from a :py:class:`Backend`.
:param backend: The device or simulator to wrap up
:type backend: Backend
:param comp_pass: The (optional) tket compilation pass to apply to each circuit
before submitting to the :py:class:`Backend`, defaults to None
:type comp_pass: Optional[BasePass], optional
"""
arch = backend.backend_info.architecture if backend.backend_info else None
coupling: Optional[List[List[Any]]]
if isinstance(arch, FullyConnected):
coupling = [
[n1.index[0], n2.index[0]]
for n1 in arch.nodes
for n2 in arch.nodes
if n1 != n2
]
else:
coupling = (
[[n.index[0], m.index[0]] for n, m in arch.coupling] if arch else None
)
config = QasmBackendConfiguration(
backend_name=("statevector_" if backend.supports_state else "")
+ "pytket/"
+ str(type(backend)),
backend_version="0.0.1",
n_qubits=len(arch.nodes) if arch and arch.nodes else 40,
basis_gates=_extract_basis_gates(backend),
gates=[],
local=False,
simulator=False,
conditional=not any(
(
type(pred) == NoClassicalControlPredicate
for pred in backend.required_predicates
)
),
open_pulse=False,
memory=backend.supports_shots,
max_shots=10000,
coupling_map=coupling,
max_experiments=10000,
)
super().__init__(configuration=config, provider=None)
self._backend = backend
self._comp_pass = comp_pass
@classmethod
def _default_options(cls) -> Options:
return Options(shots=None, memory=False)
def run(
self, run_input: Union[QuantumCircuit, List[QuantumCircuit]], **options: Any
) -> TketJob:
if isinstance(run_input, QuantumCircuit):
run_input = [run_input]
n_shots = options.get("shots", None)
circ_list = []
jobinfos = []
for qc in run_input:
tk_circ = qiskit_to_tk(qc)
if isinstance(self._backend, (AerStateBackend, AerUnitaryBackend)):
tk_circ.remove_blank_wires()
circ_list.append(tk_circ)
jobinfos.append(JobInfo(qc.name, tk_circ.qubits, tk_circ.bits, n_shots))
if self._comp_pass:
final_maps = []
compiled_list = []
for c in circ_list:
cu = CompilationUnit(c)
self._comp_pass.apply(cu)
compiled_list.append(cu.circuit)
final_maps.append(cu.final_map)
circ_list = compiled_list
else:
final_maps = [None] * len(circ_list) # type: ignore
handles = self._backend.process_circuits(circ_list, n_shots=n_shots)
return TketJob(self, handles, jobinfos, final_maps)
|
https://github.com/Juan-Varela11/BNL_2020_Summer_Internship
|
Juan-Varela11
|
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.aqua.components.initial_states import Zero
from qiskit.aqua.components.variational_forms import RY
from qiskit import BasicAer
from qiskit.aqua.algorithms.classical import ExactEigensolver
import matplotlib.pyplot as plt
pauli_dict = {
'paulis': [{"coeff": {"imag": 0.0, "real": -1.052373245772859}, "label": "II"},
{"coeff": {"imag": 0.0, "real": 0.39793742484318045}, "label": "ZI"},
{"coeff": {"imag": 0.0, "real": -0.39793742484318045}, "label": "IZ"},
{"coeff": {"imag": 0.0, "real": -0.01128010425623538}, "label": "ZZ"},
{"coeff": {"imag": 0.0, "real": 0.18093119978423156}, "label": "XX"}
]
}
qubit_op = WeightedPauliOperator.from_dict(pauli_dict)
num_qubits = qubit_op.num_qubits
print('Number of qubits: {}'.format(num_qubits))
init_state = Zero(num_qubits)
var_form = RY(num_qubits, initial_state=init_state)
backend = BasicAer.get_backend('statevector_simulator')
from qiskit.aqua.components.optimizers import COBYLA, L_BFGS_B, SLSQP
import numpy as np
from qiskit.aqua import QuantumInstance, aqua_globals
from qiskit.aqua.algorithms.adaptive import VQE
optimizers = [COBYLA, L_BFGS_B, SLSQP]
converge_cnts = np.empty([len(optimizers)], dtype=object)
converge_vals = np.empty([len(optimizers)], dtype=object)
param_vals = np.empty([len(optimizers)], dtype=object)
num_qubits = qubit_op.num_qubits
for i in range(len(optimizers)):
aqua_globals.random_seed = 250
optimizer = optimizers[i]()
print('\rOptimizer: {} '.format(type(optimizer).__name__), end='')
counts = []
values = []
params = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
params.append(parameters)
algo = VQE(qubit_op, var_form, optimizer, callback=store_intermediate_result)
quantum_instance = QuantumInstance(backend=backend)
algo_result = algo.run(quantum_instance)
converge_cnts[i] = np.asarray(counts)
converge_vals[i] = np.asarray(values)
param_vals[i] = np.asarray(params)
print('\rOptimization complete ');
ee = ExactEigensolver(qubit_op)
result = ee.run()
ref = result['energy']
print('Reference value: {}'.format(ref))
plt.figure(figsize=(10,5))
for i in range(len(optimizers)):
plt.plot(converge_cnts[i], abs(ref - converge_vals[i]), label=optimizers[i].__name__)
plt.xlabel('Eval count')
plt.ylabel('Energy difference from solution reference value')
plt.title('Energy convergence for various optimizers')
plt.yscale('log')
plt.legend(loc='upper right')
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
# Checking the version of PYTHON; we only support > 3.5
import sys
if sys.version_info < (3,5):
raise Exception('Please use Python version 3.5 or greater.')
from qiskit import QuantumProgram
import math
#import Qconfig
#Define a QuantumProgram object
Q_program = QuantumProgram()
#Q_program.set_api(Qconfig.APItoken, Qconfig.config['url'])
pi = math.pi
def solve_linear_sys():
#Q_program.set_api(Qconfig.APItoken, Qconfig.config['url'])
# create Quantum Register called "qr" with 4 qubits
qr = Q_program.create_quantum_register("qr", 4)
# create Quantum Register called "cr" with 4 qubits
cr = Q_program.create_classical_register("cr", 4)
# Creating Quantum Circuit called "qc" involving your Quantum Register "qr"
# and your Classical Register "cr"
qc = Q_program.create_circuit("solve_linear_sys", [qr], [cr])
# Initialize times that we get the result vector
n0 = 0
n1 = 0
for i in range(10):
#Set the input|b> state"
qc.x(qr[2])
#Set the phase estimation circuit
qc.h(qr[0])
qc.h(qr[1])
qc.u1(pi, qr[0])
qc.u1(pi/2, qr[1])
qc.cx(qr[1], qr[2])
#The quantum inverse Fourier transform
qc.h(qr[0])
qc.cu1(-pi/2, qr[0], qr[1])
qc.h(qr[1])
#R(lamda^-1) Rotation
qc.x(qr[1])
qc.cu3(pi/16, 0, 0, qr[0], qr[3])
qc.cu3(pi/8, 0, 0, qr[1], qr[3])
#Uncomputation
qc.x(qr[1])
qc.h(qr[1])
qc.cu1(pi/2, qr[0], qr[1])
qc.h(qr[0])
qc.cx(qr[1], qr[2])
qc.u1(-pi/2, qr[1])
qc.u1(-pi, qr[0])
qc.h(qr[1])
qc.h(qr[0])
# To measure the whole quantum register
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
qc.measure(qr[2], cr[2])
qc.measure(qr[3], cr[3])
result = Q_program.execute("solve_linear_sys", shots=8192, backend='local_qasm_simulator')
# Get the sum og all results
n0 = n0 + result.get_data("solve_linear_sys")['counts']['1000']
n1 = n1 + result.get_data("solve_linear_sys")['counts']['1100']
# print the result
print(result)
print(result.get_data("solve_linear_sys"))
# Reset the circuit
qc.reset(qr)
# calculate the scale of the elements in result vectot and print it.
p = n0/n1
print(n0)
print(n1)
print(p)
# The test function
if __name__ == "__main__":
solve_linear_sys()
%run "../version.ipynb"
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
#!pip install pylatexenc # para desenhar os circuitos quânticos
from qiskit import QuantumCircuit
qc = QuantumCircuit(1,1)
qc.barrier()
qc.measure(0,0)
qc.draw('mpl') # Para medidas de Z
# Para medidas de X
qc = QuantumCircuit(1,1)
qc.barrier()
qc.h(0)
qc.measure(0,0)
qc.draw('mpl')
# Para medidas de Y
qc = QuantumCircuit(1,1)
qc.barrier()
qc.sdg(0)
qc.h(0)
qc.measure(0,0)
qc.draw('mpl')
# Calculo da inversa da matrix de Hadamard
from sympy import Matrix
H2 = Matrix([[1,1],[1,-1]]); H2
H2.inv()
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import SamplerV2 as Sampler
import numpy as np
def tomo_rho_1qb_sim(nqb, qbt, qct, nshots, backend):
# qct = quantum circuit for tomography
# nqb = number of qubits
# qbt = qubit to be tomographed
sampler = Sampler(backend=backend)
avgs = []
for j in range(0,3):
qc_list = []
qc = QuantumCircuit(nqb,1)
qc.append(qct,list(range(nqb)))
if j == 0: # medida de X
qc.h(qbt)
elif j == 1: # medida de Y
qc.sdg(qbt)
qc.h(qbt)
qc.measure(qbt,0)
qc_list.append(qc.decompose())
job = sampler.run(qc_list, shots=nshots)
counts = job.result()[0].data.c.get_counts()
if '0' in counts:
avg = counts['0']
if '1' in counts:
avg -= counts['1']
avg = avg/nshots
avgs.append(avg)
s0 = np.array([[1,0],[0,1]]); s1 = np.array([[0,1],[1,0]])
s2 = np.array([[0,-1j],[1j,0]]); s3 = np.array([[1,0],[0,-1]])
rho_1qb = 0.5*(s0 + avgs[0]*s1 + avgs[1]*s2 + avgs[2]*s3)
return rho_1qb
nqb = 2; qbt = 0
qct = QuantumCircuit(nqb)
qct.h(0)
qct.cx(0,1)
nshots = 2**13
backend = AerSimulator()
rho = tomo_rho_1qb(nqb, qbt, qct, nshots, backend)
print(rho)
from sympy.physics.quantum import TensorProduct as tp
H4 = tp(H2,H2); H4
H4i = H4.inv(); H4i
def hadarmard_inv():
return (1/4)*np.array([[1,1,1,1],[1,-1,1,-1],[1,1,-1,-1],[1,-1,-1,1]])
#hadarmard_inv()
def tomo_rho_2qb(nqb, qbt, qct, nshots, backend):
# qct = quantum circuit for tomography
# nqb = number of qubits
# qbt = list with the 2 qubits to be tomographed
sampler = Sampler(backend=backend)
avgs = []
for j in range(1,4):
for k in range(1,4):
qc_list = []
qc = QuantumCircuit(nqb,2)
qc.append(qct,list(range(nqb)))
if j == 1: # medida de X_0
qc.h(qbt[0])
elif j == 2: # medida de Y_0
qc.sdg(qbt[0])
qc.h(qbt[0])
if k == 1: # medida de X_1
qc.h(qbt[1])
elif k == 2: # medida de Y_1
qc.sdg(qbt[1])
qc.h(qbt[1])
qc.measure(qbt,[0,1]) # medida de ZZ
qc_list.append(qc.decompose())
job = sampler.run(qc_list, shots=nshots)
counts = job.result()[0].data.c.get_counts()
labels = ['00','01','10','11']
probs = np.zeros(4)
for l in range(0,4):
if labels[l] in counts:
probs[l] = counts[labels[l]]/nshots
print(probs)
s0 = np.array([[1,0],[0,1]]); s1 = np.array([[0,1],[1,0]])
s2 = np.array([[0,-1j],[1j,0]]); s3 = np.array([[1,0],[0,-1]])
rho_2qb = 0.5*(s0 + avgs[0]*s1 + avgs[1]*s2 + avgs[2]*s3)
return rho_2qb
def tomo_2qb(avgs):
# avgs e uma lista com 16 valores medios na seguinte ordem [II,IX,IY,IZ,XI,XX,XY,XZ,YI,YX,YY,YZ,ZI,ZX,ZY,ZZ]
import numpy as np
s0 = np.array([[1,0],[0,1]]); s1 = np.array([[0,1],[1,0]])
s2 = np.array([[0,-1j],[1j,0]]); s3 = np.array([[1,0],[0,-1]])
paulis = [s0,s1,s2,s3] # lista com as matrizes de Pauli
rho = np.zeros([4,4],dtype=complex)
l = 0
for j in range(0,3):
for k in range(0,3):
l += 1
rho += avgs[l]*tp(paulis[j],paulis[k])
return 0.25*rho
nqb = 2; qbt = [0,1]
qct = QuantumCircuit(nqb)
qct.h(0)
qct.cx(0,1)
nshots = 2**13
backend = AerSimulator()
rho = tomo_rho_2qb(nqb, qbt, qct, nshots, backend)
print(rho)
print(np.zeros(4))
def tomo_2qb(avgs):
# avgs e uma lista com 16 valores medios na seguinte ordem [II,IX,IY,IZ,XI,XX,XY,XZ,YI,YX,YY,YZ,ZI,ZX,ZY,ZZ]
import numpy as np
s0 = np.array([[1,0],[0,1]]); s1 = np.array([[0,1],[1,0]])
s2 = np.array([[0,-1j],[1j,0]]); s3 = np.array([[1,0],[0,-1]])
paulis = [s0,s1,s2,s3] # lista com as matrizes de Pauli
rho = np.zeros([4,4],dtype=complex)
l = 0
for j in range(0,3):
for k in range(0,3):
l += 1
rho += avgs[l]*tp(paulis[j],paulis[k])
return 0.25*rho
avgs = [1,0.1,0,0,0.1,0.3,0,0,0.3,0,0.2,0,0,0.1,0,0.5] #[II,IX,IY,IZ,XI,XX,XY,XZ,YI,YX,YY,YZ,ZI,ZX,ZY,ZZ]
rho = tomo_2qb(avgs); rho
# Inversa da matriz de Hadamard 4x4 (sem o multiplo 1/4)
H4i = np.array([[1,1,1,1],[1,-1,1,-1],[1,1,-1,-1],[1,-1,-1,1]]); H4i
def qc_test_2qb():
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, name='qc2qb')
qc.h(0); qc.cx(0,1)
return qc
def tomo_2qb(avgs):
# avgs e uma lista com 64 valores medios na seguinte ordem [III,IIX,IIY,IIZ,IXI,IXX,IXY,IXZ,...]
import numpy as np
s0 = np.array([[1,0],[0,1]]); s1 = np.array([[0,1],[1,0]])
s2 = np.array([[0,-1j],[1j,0]]); s3 = np.array([[1,0],[0,-1]])
paulis = [s0,s1,s2,s3]
rho = np.zeros([4,4],dtype=complex)
m = 0
for j in range(0,4):
for k in range(0,4):
for l in range(0,4):
rho += avgs[m]*np.kron(np.kron(paulis[j],paulis[k]),paulis[l])
m += 1
return 0.25*rho
from qiskit import QuantumCircuit, execute
from qiskit import Aer
simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13
qct = qc_test_2qb() # circuito quantico principal
# medida de XX
qc = QuantumCircuit(2,2); qc.append(qct,[0,1]); qc.h([0,1]); qc.measure([0,1],[0,1]); qcxx = qc
job = execute(qc, backend = simulator, shots = nshots); counts_xx = job.result().get_counts()
pr_xx = np.zeros(4); cb2_labels = ['00','10','01','11']
for j in range(0,4):
if cb2_labels[j] in counts_xx:
pr_xx[j] = counts_xx[cb2_labels[j]]/nshots
print('counts_xx=',counts_xx, pr_xx)
XX_vec = np.matmul(H4i,pr_xx); print('XX_vec=',XX_vec) # =[II,IX,XI,XX]
qcxx.draw('mpl')
ss_vecs = [] # list with the averages of the observables
obs = ['x','y','z']
for j in range(0,3):
lo = obs[j] # left observable
for k in range(0,3):
ro = obs[k] # right observable
qc = QuantumCircuit(2,2)
qc.append(qct,[0,1]) # the quantum circuit for preparing psi
if lo == 'x' and ro = 'x':
qc.h([0,1])
elif lo == 'x' and ro = 'y':
qc.sdg(1); qc.h([0,1])
elif lo == 'y' and ro = 'x':
qc.sdg(0); qc.h([0,1])
elif lo == 'y' and ro = 'y':
qc.sdg([0,1]); qc.h([0,1])
qc.measure([0,1],[0,1])
job = execute(qc, backend = simulator, shots = nshots)
counts = job.result().get_counts()
pr = np.zeros(4); cb2_labels = ['00','10','01','11']
for j in range(0,4):
if cb2_labels[j] in counts_xx:
pr_xx[j] = counts_xx[cb2_labels[j]]/nshots
ss_vec = np.matmul(H4i,pr)
ss_vecs.append(ss_vec)
# matriz de Hadamard
H8 = tp(H2,H4); H8
H8i = H8.inv(); H8i
from sympy import symbols
f000,f001,f010,f011,f100,f101,f110,f111 = symbols('f_{000},f_{001},f_{010},f_{011},f_{100},f_{101},f_{110},f_{111}')
f = Matrix([[f000],[f001],[f010],[f011],[f100],[f101],[f110],[f111]])
f.T
al = 8*H8i*f; al
import numpy as np
s0 = np.array([[1,0],[0,1]]); s1 = np.array([[0,1],[1,0]]); s2 = np.array([[0,-1j],[1j,0]]); s3 = np.array([[1,0],[0,-1]])
paulis = [s0,s1,s2,s3] # lista com as matrizes de Pauli
list_avgs = []
m = 0
for j in range(0,4):
for k in range(0,4):
for l in range(0,4):
list_avgs.append((j,k,l))
m += 1
|
https://github.com/BoschSamuel/QizGloria
|
BoschSamuel
|
# -- coding: utf-8 --
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import torch
from torch.autograd import Function
import torch.optim as optim
from qiskit import QuantumRegister,QuantumCircuit,ClassicalRegister,execute
from qiskit.circuit import Parameter
from qiskit import Aer
import numpy as np
from tqdm import tqdm
from matplotlib import pyplot as plt
%matplotlib inline
np.random.seed = 42
def to_numbers(tensor_list):
num_list = []
for tensor in tensor_list:
num_list += [tensor.item()]
return num_list
class QiskitCircuit():
def __init__(self,shots):
self.theta = Parameter('Theta')
self.phi = Parameter('Phi')
self.lam = Parameter('Lambda')
self.shots = shots
def create_circuit():
qr = QuantumRegister(1,'q')
cr = ClassicalRegister(1,'c')
ckt = QuantumCircuit(qr,cr)
ckt.h(qr[0])
ckt.barrier()
ckt.u3(self.theta,self.phi,self.lam,qr[0])
ckt.barrier()
ckt.measure(qr,cr)
return ckt
self.circuit = create_circuit()
def N_qubit_expectation_Z(self,counts, shots, nr_qubits):
expects = np.zeros(nr_qubits)
for key in counts.keys():
perc = counts[key]/shots
check = np.array([(float(key[i])-1/2)*2*perc for i in range(nr_qubits)])
expects += check
return expects
def bind(self, parameters):
[self.theta,self.phi,self.lam] = to_numbers(parameters)
self.circuit.data[2][0]._params = to_numbers(parameters)
def run(self, i):
self.bind(i)
backend = Aer.get_backend('qasm_simulator')
job_sim = execute(self.circuit,backend,shots=self.shots)
result_sim = job_sim.result()
counts = result_sim.get_counts(self.circuit)
return self.N_qubit_expectation_Z(counts,self.shots,1)
class TorchCircuit(Function):
@staticmethod
def forward(ctx, i):
if not hasattr(ctx, 'QiskitCirc'):
ctx.QiskitCirc = QiskitCircuit(shots=10000)
exp_value = ctx.QiskitCirc.run(i[0])
result = torch.tensor([exp_value])
ctx.save_for_backward(result, i)
return result
@staticmethod
def backward(ctx, grad_output):
eps = 0.01
forward_tensor, i = ctx.saved_tensors
input_numbers = to_numbers(i[0])
gradient = [0,0,0]
for k in range(len(input_numbers)):
input_eps = input_numbers
input_eps[k] = input_numbers[k] + eps
exp_value = ctx.QiskitCirc.run(torch.tensor(input_eps))[0]
result_eps = torch.tensor([exp_value])
gradient_result = (exp_value - forward_tensor[0][0].item())/eps
gradient[k] = gradient_result
# print(gradient)
result = torch.tensor([gradient])
# print(result)
return result.float() * grad_output.float()
torch.manual_seed(42)
# x = torch.tensor([np.pi/4, np.pi/4, np.pi/4], requires_grad=True)
x = torch.tensor([[0.0, 0.0, 0.0]], requires_grad=True)
qc = TorchCircuit.apply
y1 = qc(x)
y1.backward()
print(x.grad)
qc = TorchCircuit.apply
def cost(x):
target = -1
expval = qc(x)
return torch.abs(qc(x) - target) ** 2, expval
x = torch.tensor([[np.pi/4, np.pi/4, np.pi/4]], requires_grad=True)
opt = torch.optim.Adam([x], lr=0.1)
num_epoch = 100
loss_list = []
expval_list = []
for i in tqdm(range(num_epoch)):
# for i in range(num_epoch):
opt.zero_grad()
loss, expval = cost(x)
loss.backward()
opt.step()
loss_list.append(loss.item())
expval_list.append(expval.item())
# print(loss.item())
plt.plot(loss_list)
# print(circuit(phi, theta))
# print(cost(x))
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import torchvision
from torchvision import datasets, transforms
batch_size_train = 1
batch_size_test = 1
learning_rate = 0.01
momentum = 0.5
log_interval = 10
torch.backends.cudnn.enabled = False
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor()])
mnist_trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
labels = mnist_trainset.targets #get labels
labels = labels.numpy()
idx1 = np.where(labels == 0) #search all zeros
idx2 = np.where(labels == 1) # search all ones
idx = np.concatenate((idx1[0][0:10],idx2[0][0:10])) # concatenate their indices
mnist_trainset.targets = labels[idx]
mnist_trainset.data = mnist_trainset.data[idx]
print(mnist_trainset)
train_loader = torch.utils.data.DataLoader(mnist_trainset, batch_size=batch_size_train, shuffle=True)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 3)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(-1, 320)
x = F.relu(self.fc1(x))
x = F.dropout(x, training=self.training)
x = self.fc2(x)
# x = np.pi*F.tanh(x)
print(x)
x = qc(x)
# print(x)
x = (x+1)/2
x = torch.cat((x, 1-x), -1)
return x
# return F.softmax(x)
network = Net()
optimizer = optim.SGD(network.parameters(), lr=learning_rate,
momentum=momentum)
epochs = 100
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
# print(batch_idx)
optimizer.zero_grad()
output = network(data)
loss = F.nll_loss(output, target)
# print(output)
# print(output[0][1].item(), target.item())
loss.backward()
optimizer.step()
total_loss.append(loss.item())
print(sum(total_loss)/len(total_loss))
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
'''
(C) 2023 Renata Wong
Electronic structure problem with classical shadows, as presented in https://arxiv.org/abs/2103.07510
This code uses Qiskit as platform.
The shadow is constructed based on derandomized Hamiltonian.
The molecules tested are: H2 (6-31s basis), LiH (sto3g basis), BeH2 (sto3g), H2O (sto3g), and NH3 (sto3g).
The coordinates for NH3 were taken from 'Algorithms for Computer Detection of Symmetry Elementsin Molecular Systems'.
'''
import time
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute
from qiskit_aer.primitives import Estimator as AerEstimator
from qiskit_aer import QasmSimulator
from qiskit.quantum_info import SparsePauliOp
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper, JordanWignerMapper, ParityMapper
from qiskit_nature.second_q.circuit.library import UCCSD, HartreeFock
from qiskit_nature.second_q.algorithms import VQEUCCFactory
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
# Estimator primitive is based on the Statevector construct = algebraic simulation
from qiskit.primitives import Estimator
from qiskit.utils import algorithm_globals
from modified_derandomization import modified_derandomized_classical_shadow
from predicting_quantum_properties.data_acquisition_shadow import derandomized_classical_shadow
from predicting_quantum_properties.prediction_shadow import estimate_exp
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
'''
DEFINING DRIVERS FOR THE MOLECULES
'''
H2_driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="6-31g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
LiH_driver = PySCFDriver(
atom="Li 0 0 0; H 0 0 1.599",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
BeH2_driver = PySCFDriver(
atom="Be 0 0 0; H 0 0 1.3264; H 0 0 -1.3264",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
H2O_driver = PySCFDriver(
atom="O 0.0 0.0 0.0; H 0.757 0.586 0.0; H -0.757 0.586 0.0",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
NH3_driver = PySCFDriver(
atom="N 0 0 0; H 0 0 1.008000; H 0.950353 0 -0.336000; H -0.475176 -0.823029 -0.336000",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
'''
FORMATTING HAMILTONIAN
'''
def process_hamiltonian(hamiltonian, derandomize = False):
hamiltonian_observables = []
hamiltonian_coefficients = []
for observable in hamiltonian.paulis:
op_list = []
for op_index, pauli_op in enumerate(observable):
pauli_op = str(pauli_op)
if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z':
op_list.append((pauli_op, op_index))
hamiltonian_observables.append(op_list)
hamiltonian_coefficients = hamiltonian.coeffs.real
system_size = len(hamiltonian_observables[0])
# removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left
# these observables are needed for estimate_exp()
observables_xyze = []
for observable in hamiltonian_observables:
XYZE = []
for pauli in observable:
if pauli[0] != 'I':
XYZE.append(pauli)
observables_xyze.append(XYZE)
# derandomisation procedure requires that coefficients are non-negative
if derandomize == True:
absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients]
# removing the empty list as well
# these observables are needed for derandomisation procedure
observables_xyz = []
for idx, observable in enumerate(observables_xyze):
if observable:
observables_xyz.append(observable)
else:
absolute_coefficients.pop(idx)
return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients
return system_size, observables_xyze, hamiltonian_coefficients
'''
COST FUNCTION AND HELPER FUNCTIONS
'''
def basis_change_circuit(pauli_op):
# Generating circuit with just the basis change operators
#
# pauli_op: n-qubit Pauli operator
basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits)
for idx, op in enumerate(pauli_op):
if op == 'X':
basis_change.h(idx)
if op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def ground_state_energy_from_shadow(operators, params):
backend = QasmSimulator(method='statevector', shots=1)
pauli_op_dict = Counter(tuple(x) for x in operators)
shadow = []
for pauli_op in pauli_op_dict:
qc = ansatz.bind_parameters(params)
qc = qc.compose(basis_change_circuit(pauli_op))
qc.measure(reversed(range(system_size)), range(system_size))
result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result()
counts = result.get_counts() # given in order q0 q1 ... qn-1 after register reversal in qc.measure
for count in counts:
for _ in range(counts[count]): # number of repeated measurement values
output_str = list(count)
output = [int(i) for i in output_str]
eigenvals = [x+1 if x == 0 else x-2 for x in output]
snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)]
shadow.append(snapshot)
expectation_value = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
expectation_value += (weight * sum_product / match_count)
return expectation_value
'''
EXPERIMENTS
'''
start_time = time.time()
all_molecules_rmse_errors = []
# CALCULATING FERMIONIC HAMILTONIAN AND CONVERTING TO QUBIT HAMILTONIAN
MOLECULES = ['H2']
for molecule in MOLECULES:
rmse_errors = []
if molecule == 'H2':
problem = H2_driver.run()
if molecule == 'LiH':
problem = LiH_driver.run()
if molecule == 'BeH2':
problem = BeH2_driver.run()
if molecule == 'H2O':
problem = H2O_driver.run()
if molecule == 'NH3':
problem = NH3_driver.run()
hamiltonian = problem.hamiltonian
second_q_op = hamiltonian.second_q_op()
bk_mapper = BravyiKitaevMapper() #(num_particles=problem.num_particles) #BravyiKitaevMapper()
bkencoded_hamiltonian = bk_mapper.map(second_q_op)
#print('Qubit Hamiltonian in Bravyi-Kitaev encoding', bkencoded_hamiltonian)
# process the Hamiltonian to obtain properly formatted data
hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = True)
system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients = hamiltonian_data
'''
VARIATIONAL ANSATZ
'''
ansatz = UCCSD(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
initial_state=HartreeFock(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
),
)
'''
Running VQE on the Hamiltonian obtained from PySCFDriver using Statevector simulator (Estimator primitive)
'''
#estimator = Estimator()
# If shots = None, it calculates the exact expectation values. Otherwise, it samples from normal distributions
# with standard errors as standard deviations using normal distribution approximation.
#estimator.set_options(shots = None)
#estimator = AerEstimator()
#estimator.set_options(approximation=False, shots=None)
#vqe_solver = VQE(estimator, ansatz, SLSQP())
vqe_solver = VQE(Estimator(), ansatz, SLSQP())
vqe_solver.initial_point = np.zeros(ansatz.num_parameters)
calc = GroundStateEigensolver(bk_mapper, vqe_solver)
result = calc.solve(problem)
print(result.raw_result)
#print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50, 250, 500, 750, 1000, 1250, 1500, 1750]
for num_operators in measurement_range:
derandomized_hamiltonian = derandomized_classical_shadow(observables_xyz, 50,
system_size, weight=absolute_coefficients)
tuples = (tuple(pauli) for pauli in derandomized_hamiltonian)
counts = Counter(tuples)
print('Original derandomized Hamiltonian', counts)
# derandomized classical shadow will usually either undergenerate or overgenerate derandomized operators
# adjusting for this issue:
while sum(counts.values()) != num_operators:
for key, value in zip(counts.keys(), counts.values()):
sum_counts = sum(counts.values())
if sum_counts == num_operators:
break
if sum_counts < num_operators:
# generate additional operators from the existing ones by increasing the number of counts
counts[key] += 1
if sum_counts > num_operators:
# remove the element with highest count
max_element_key = [k for k, v in counts.items() if v == max(counts.values())][0]
counts[max_element_key] -= 1
print('Size-adjusted derandomized Hamiltonian', counts)
# translate the Counter to a set of derandomized operators
new_derandomized_hamiltonian = []
for key, value in counts.items():
for _ in range(value):
new_derandomized_hamiltonian.append(list(key))
#print('Size-adjusted derandomized Hamiltonian', new_derandomized_hamiltonian)
expectation_values = []
num_experiments = 10
for iteration in range(num_experiments):
expectation_value = ground_state_energy_from_shadow(new_derandomized_hamiltonian, result.raw_result.optimal_point)
expectation_values.append(expectation_value)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, expectation_value))
rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - result.raw_result.optimal_value)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_derandomised_cs)
print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs))
all_molecules_rmse_errors.append(rmse_errors)
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
import matplotlib.pyplot as plt
points = [50, 250, 500, 750, 1000, 1250, 1500, 1750]
num_points = len(points)
rmse_errors = [0.1069869635064184, 0.07725001066018326, 0.05225116371481676, 0.042165636875291464,
0.051653435360326294, 0.03145057406737202, 0.03650841505283894, 0.03864886899799828]
plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='derandomized classical shadow')
plt.xlabel('Number of measurements')
plt.ylabel('Average RMSE error')
plt.legend(loc=1)
|
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/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test ObservablesArray"""
import itertools as it
import ddt
import numpy as np
import qiskit.quantum_info as qi
from qiskit.primitives.containers.observables_array import ObservablesArray
from test import QiskitTestCase # pylint: disable=wrong-import-order
@ddt.ddt
class ObservablesArrayTestCase(QiskitTestCase):
"""Test the ObservablesArray class"""
@ddt.data(0, 1, 2)
def test_coerce_observable_str(self, num_qubits):
"""Test coerce_observable for allowed basis str input"""
for chars in it.permutations(ObservablesArray.ALLOWED_BASIS, num_qubits):
label = "".join(chars)
obs = ObservablesArray.coerce_observable(label)
self.assertEqual(obs, {label: 1})
def test_coerce_observable_custom_basis(self):
"""Test coerce_observable for custom al flowed basis"""
class PauliArray(ObservablesArray):
"""Custom array allowing only Paulis, not projectors"""
ALLOWED_BASIS = "IXYZ"
with self.assertRaises(ValueError):
PauliArray.coerce_observable("0101")
for p in qi.pauli_basis(1):
obs = PauliArray.coerce_observable(p)
self.assertEqual(obs, {p.to_label(): 1})
@ddt.data("iXX", "012", "+/-")
def test_coerce_observable_invalid_str(self, basis):
"""Test coerce_observable for Pauli input"""
with self.assertRaises(ValueError):
ObservablesArray.coerce_observable(basis)
@ddt.data(1, 2, 3)
def test_coerce_observable_pauli(self, num_qubits):
"""Test coerce_observable for Pauli input"""
for p in qi.pauli_basis(num_qubits):
obs = ObservablesArray.coerce_observable(p)
self.assertEqual(obs, {p.to_label(): 1})
@ddt.data(0, 1, 2, 3)
def test_coerce_observable_phased_pauli(self, phase):
"""Test coerce_observable for phased Pauli input"""
pauli = qi.Pauli("IXYZ")
pauli.phase = phase
coeff = (-1j) ** phase
if phase % 2:
with self.assertRaises(ValueError):
ObservablesArray.coerce_observable(pauli)
else:
obs = ObservablesArray.coerce_observable(pauli)
self.assertIsInstance(obs, dict)
self.assertEqual(list(obs.keys()), ["IXYZ"])
np.testing.assert_allclose(
list(obs.values()), [coeff], err_msg=f"Wrong value for Pauli {pauli}"
)
@ddt.data("+IXYZ", "-IXYZ", "iIXYZ", "+iIXYZ", "-IXYZ")
def test_coerce_observable_phased_pauli_str(self, pauli):
"""Test coerce_observable for phased Pauli input"""
pauli = qi.Pauli(pauli)
coeff = (-1j) ** pauli.phase
if pauli.phase % 2:
with self.assertRaises(ValueError):
ObservablesArray.coerce_observable(pauli)
else:
obs = ObservablesArray.coerce_observable(pauli)
self.assertIsInstance(obs, dict)
self.assertEqual(list(obs.keys()), ["IXYZ"])
np.testing.assert_allclose(
list(obs.values()), [coeff], err_msg=f"Wrong value for Pauli {pauli}"
)
def test_coerce_observable_signed_sparse_pauli_op(self):
"""Test coerce_observable for SparsePauliOp input with phase paulis"""
op = qi.SparsePauliOp(["+I", "-X", "Y", "-Z"], [1, 2, 3, 4])
obs = ObservablesArray.coerce_observable(op)
self.assertIsInstance(obs, dict)
self.assertEqual(len(obs), 4)
self.assertEqual(sorted(obs.keys()), sorted(["I", "X", "Y", "Z"]))
np.testing.assert_allclose([obs[i] for i in ["I", "X", "Y", "Z"]], [1, -2, 3, -4])
def test_coerce_observable_zero_sparse_pauli_op(self):
"""Test coerce_observable for SparsePauliOp input with zero val coeffs"""
op = qi.SparsePauliOp(["I", "X", "Y", "Z"], [0, 0, 0, 1])
obs = ObservablesArray.coerce_observable(op)
self.assertIsInstance(obs, dict)
self.assertEqual(len(obs), 1)
self.assertEqual(sorted(obs.keys()), ["Z"])
self.assertEqual(obs["Z"], 1)
def test_coerce_observable_duplicate_sparse_pauli_op(self):
"""Test coerce_observable for SparsePauliOp wiht duplicate paulis"""
op = qi.SparsePauliOp(["XX", "-XX", "XX", "-XX"], [2, 1, 3, 2])
obs = ObservablesArray.coerce_observable(op)
self.assertIsInstance(obs, dict)
self.assertEqual(len(obs), 1)
self.assertEqual(list(obs.keys()), ["XX"])
self.assertEqual(obs["XX"], 2)
def test_coerce_observable_pauli_mapping(self):
"""Test coerce_observable for pauli-keyed Mapping input"""
mapping = dict(zip(qi.pauli_basis(1), range(1, 5)))
obs = ObservablesArray.coerce_observable(mapping)
target = {key.to_label(): val for key, val in mapping.items()}
self.assertEqual(obs, target)
def test_coerce_0d(self):
"""Test the coerce() method with 0-d input."""
obs = ObservablesArray.coerce("X")
self.assertEqual(obs.shape, ())
self.assertDictAlmostEqual(obs[()], {"X": 1})
obs = ObservablesArray.coerce({"I": 2})
self.assertEqual(obs.shape, ())
self.assertDictAlmostEqual(obs[()], {"I": 2})
obs = ObservablesArray.coerce(qi.SparsePauliOp(["X", "Y"], [1, 3]))
self.assertEqual(obs.shape, ())
self.assertDictAlmostEqual(obs[()], {"X": 1, "Y": 3})
def test_format_invalid_mapping_qubits(self):
"""Test an error is raised when different qubits in mapping keys"""
mapping = {"IX": 1, "XXX": 2}
with self.assertRaises(ValueError):
ObservablesArray.coerce_observable(mapping)
def test_format_invalid_mapping_basis(self):
"""Test an error is raised when keys contain invalid characters"""
mapping = {"XX": 1, "0Z": 2, "02": 3}
with self.assertRaises(ValueError):
ObservablesArray.coerce_observable(mapping)
def test_init_nested_list_str(self):
"""Test init with nested lists of str"""
obj = [["X", "Y", "Z"], ["0", "1", "+"]]
obs = ObservablesArray(obj)
self.assertEqual(obs.size, 6)
self.assertEqual(obs.shape, (2, 3))
def test_init_nested_list_sparse_pauli_op(self):
"""Test init with nested lists of SparsePauliOp"""
obj = [
[qi.SparsePauliOp(qi.random_pauli_list(2, 3, phase=False)) for _ in range(3)]
for _ in range(5)
]
obs = ObservablesArray(obj)
self.assertEqual(obs.size, 15)
self.assertEqual(obs.shape, (5, 3))
def test_init_single_sparse_pauli_op(self):
"""Test init with single SparsePauliOps"""
obj = qi.SparsePauliOp(qi.random_pauli_list(2, 3, phase=False))
obs = ObservablesArray(obj)
self.assertEqual(obs.size, 1)
self.assertEqual(obs.shape, ())
def test_init_pauli_list(self):
"""Test init with PauliList"""
obs = ObservablesArray(qi.pauli_basis(2))
self.assertEqual(obs.size, 16)
self.assertEqual(obs.shape, (16,))
def test_init_nested_pauli_list(self):
"""Test init with nested PauliList"""
obj = [qi.random_pauli_list(2, 3, phase=False) for _ in range(5)]
obs = ObservablesArray(obj)
self.assertEqual(obs.size, 15)
self.assertEqual(obs.shape, (5, 3))
def test_init_ragged_array(self):
"""Test init with ragged input"""
obj = [["X", "Y"], ["X", "Y", "Z"]]
with self.assertRaises(ValueError):
ObservablesArray(obj)
def test_init_validate_false(self):
"""Test init validate kwarg"""
obj = [["A", "B", "C"], ["D", "E", "F"]]
obs = ObservablesArray(obj, validate=False)
self.assertEqual(obs.shape, (2, 3))
self.assertEqual(obs.size, 6)
for i in range(2):
for j in range(3):
self.assertEqual(obs[i, j], obj[i][j])
def test_init_validate_true(self):
"""Test init validate kwarg"""
obj = [["A", "B", "C"], ["D", "E", "F"]]
with self.assertRaises(ValueError):
ObservablesArray(obj, validate=True)
@ddt.data(0, 1, 2, 3)
def test_size_and_shape_single(self, ndim):
"""Test size and shape method for size=1 array"""
obs = {"XX": 1}
for _ in range(ndim):
obs = [obs]
arr = ObservablesArray(obs, validate=False)
self.assertEqual(arr.size, 1, msg="Incorrect ObservablesArray.size")
self.assertEqual(arr.shape, (1,) * ndim, msg="Incorrect ObservablesArray.shape")
@ddt.data(0, 1, 2, 3)
def test_tolist_single(self, ndim):
"""Test tolist method for size=1 array"""
obs = {"XX": 1}
for _ in range(ndim):
obs = [obs]
arr = ObservablesArray(obs, validate=False)
ls = arr.tolist()
self.assertEqual(ls, obs)
@ddt.data(0, 1, 2, 3)
def test_array_single(self, ndim):
"""Test __array__ method for size=1 array"""
obs = {"XX": 1}
for _ in range(ndim):
obs = [obs]
arr = ObservablesArray(obs, validate=False)
nparr = np.array(arr)
self.assertEqual(nparr.dtype, object)
self.assertEqual(nparr.shape, arr.shape)
self.assertEqual(nparr.size, arr.size)
self.assertTrue(np.all(nparr == np.array(obs)))
@ddt.data(0, 1, 2, 3)
def test_getitem_single(self, ndim):
"""Test __getitem__ method for size=1 array"""
base_obs = {"XX": 1}
obs = base_obs
for _ in range(ndim):
obs = [obs]
arr = ObservablesArray(obs, validate=False)
idx = ndim * (0,)
item = arr[idx]
self.assertEqual(item, base_obs)
def test_tolist_1d(self):
"""Test tolist method"""
obj = ["A", "B", "C", "D"]
obs = ObservablesArray(obj, validate=False)
self.assertEqual(obs.tolist(), obj)
def test_tolist_2d(self):
"""Test tolist method"""
obj = [["A", "B", "C"], ["D", "E", "F"]]
obs = ObservablesArray(obj, validate=False)
self.assertEqual(obs.tolist(), obj)
def test_array_1d(self):
"""Test __array__ dunder method"""
obj = np.array(["A", "B", "C", "D"], dtype=object)
obs = ObservablesArray(obj, validate=False)
self.assertTrue(np.all(np.array(obs) == obj))
def test_array_2d(self):
"""Test __array__ dunder method"""
obj = np.array([["A", "B", "C"], ["D", "E", "F"]], dtype=object)
obs = ObservablesArray(obj, validate=False)
self.assertTrue(np.all(np.array(obs) == obj))
def test_getitem_1d(self):
"""Test __getitem__ for 1D array"""
obj = np.array(["A", "B", "C", "D"], dtype=object)
obs = ObservablesArray(obj, validate=False)
for i in range(obj.size):
self.assertEqual(obs[i], obj[i])
def test_getitem_2d(self):
"""Test __getitem__ for 2D array"""
obj = np.array([["A", "B", "C"], ["D", "E", "F"]], dtype=object)
obs = ObservablesArray(obj, validate=False)
for i in range(obj.shape[0]):
row = obs[i]
self.assertIsInstance(row, ObservablesArray)
self.assertEqual(row.shape, (3,))
self.assertTrue(np.all(np.array(row) == obj[i]))
def test_ravel(self):
"""Test ravel method"""
bases_flat = qi.pauli_basis(2).to_labels()
bases = [bases_flat[4 * i : 4 * (i + 1)] for i in range(4)]
obs = ObservablesArray(bases)
flat = obs.ravel()
self.assertEqual(flat.ndim, 1)
self.assertEqual(flat.shape, (16,))
self.assertEqual(flat.size, 16)
for (
i,
label,
) in enumerate(bases_flat):
self.assertEqual(flat[i], {label: 1})
def test_reshape(self):
"""Test reshape method"""
bases = qi.pauli_basis(2)
labels = np.array(bases.to_labels(), dtype=object)
obs = ObservablesArray(qi.pauli_basis(2))
def various_formats(shape):
# call reshape with a single argument
yield [shape]
yield [(-1,) + shape[1:]]
yield [np.array(shape)]
yield [list(shape)]
yield [list(map(np.int64, shape))]
yield [tuple(map(np.int64, shape))]
# call reshape with multiple arguments
yield shape
yield np.array(shape)
yield list(shape)
yield list(map(np.int64, shape))
yield tuple(map(np.int64, shape))
for shape in [(16,), (4, 4), (2, 4, 2), (2, 2, 2, 2), (1, 8, 1, 2)]:
with self.subTest(shape):
for input_shape in various_formats(shape):
obs_rs = obs.reshape(*input_shape)
self.assertEqual(obs_rs.shape, shape)
labels_rs = labels.reshape(shape)
for idx in np.ndindex(shape):
self.assertEqual(
obs_rs[idx],
{labels_rs[idx]: 1},
msg=f"failed for shape {shape} with input format {input_shape}",
)
def test_validate(self):
"""Test the validate method"""
ObservablesArray({"XX": 1}).validate()
ObservablesArray([{"XX": 1}] * 5).validate()
ObservablesArray([{"XX": 1}] * 15).reshape((3, 5)).validate()
obs = ObservablesArray([{"XX": 1}, {"XYZ": 1}], validate=False)
with self.assertRaisesRegex(ValueError, "number of qubits must be the same"):
obs.validate()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 12345
from qiskit_machine_learning.datasets import ad_hoc_data
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=20,
test_size=5,
n=adhoc_dimension,
gap=0.3,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
import matplotlib.pyplot as plt
import numpy as np
def plot_features(ax, features, labels, class_label, marker, face, edge, label):
# A train plot
ax.scatter(
# x coordinate of labels where class is class_label
features[np.where(labels[:] == class_label), 0],
# y coordinate of labels where class is class_label
features[np.where(labels[:] == class_label), 1],
marker=marker,
facecolors=face,
edgecolors=edge,
label=label,
)
def plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total):
plt.figure(figsize=(5, 5))
plt.ylim(0, 2 * np.pi)
plt.xlim(0, 2 * np.pi)
plt.imshow(
np.asmatrix(adhoc_total).T,
interpolation="nearest",
origin="lower",
cmap="RdBu",
extent=[0, 2 * np.pi, 0, 2 * np.pi],
)
# A train plot
plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "A train")
# B train plot
plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B train")
# A test plot
plot_features(plt, test_features, test_labels, 0, "s", "b", "w", "A test")
# B test plot
plot_features(plt, test_features, test_labels, 1, "o", "r", "w", "B test")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset")
plt.show()
plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total)
from qiskit.circuit.library import ZZFeatureMap
from qiskit.primitives import Sampler
from qiskit.algorithms.state_fidelities import ComputeUncompute
from qiskit_machine_learning.kernels import FidelityQuantumKernel
adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")
sampler = Sampler()
fidelity = ComputeUncompute(sampler=sampler)
adhoc_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=adhoc_feature_map)
from sklearn.svm import SVC
adhoc_svc = SVC(kernel=adhoc_kernel.evaluate)
adhoc_svc.fit(train_features, train_labels)
adhoc_score_callable_function = adhoc_svc.score(test_features, test_labels)
print(f"Callable kernel classification test score: {adhoc_score_callable_function}")
adhoc_matrix_train = adhoc_kernel.evaluate(x_vec=train_features)
adhoc_matrix_test = adhoc_kernel.evaluate(x_vec=test_features, y_vec=train_features)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(
np.asmatrix(adhoc_matrix_train), interpolation="nearest", origin="upper", cmap="Blues"
)
axs[0].set_title("Ad hoc training kernel matrix")
axs[1].imshow(np.asmatrix(adhoc_matrix_test), interpolation="nearest", origin="upper", cmap="Reds")
axs[1].set_title("Ad hoc testing kernel matrix")
plt.show()
adhoc_svc = SVC(kernel="precomputed")
adhoc_svc.fit(adhoc_matrix_train, train_labels)
adhoc_score_precomputed_kernel = adhoc_svc.score(adhoc_matrix_test, test_labels)
print(f"Precomputed kernel classification test score: {adhoc_score_precomputed_kernel}")
from qiskit_machine_learning.algorithms import QSVC
qsvc = QSVC(quantum_kernel=adhoc_kernel)
qsvc.fit(train_features, train_labels)
qsvc_score = qsvc.score(test_features, test_labels)
print(f"QSVC classification test score: {qsvc_score}")
print(f"Classification Model | Accuracy Score")
print(f"---------------------------------------------------------")
print(f"SVC using kernel as a callable function | {adhoc_score_callable_function:10.2f}")
print(f"SVC using precomputed kernel matrix | {adhoc_score_precomputed_kernel:10.2f}")
print(f"QSVC | {qsvc_score:10.2f}")
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=25,
test_size=0,
n=adhoc_dimension,
gap=0.6,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
plt.figure(figsize=(5, 5))
plt.ylim(0, 2 * np.pi)
plt.xlim(0, 2 * np.pi)
plt.imshow(
np.asmatrix(adhoc_total).T,
interpolation="nearest",
origin="lower",
cmap="RdBu",
extent=[0, 2 * np.pi, 0, 2 * np.pi],
)
# A label plot
plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "B")
# B label plot
plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset for clustering")
plt.show()
adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")
adhoc_kernel = FidelityQuantumKernel(feature_map=adhoc_feature_map)
adhoc_matrix = adhoc_kernel.evaluate(x_vec=train_features)
plt.figure(figsize=(5, 5))
plt.imshow(np.asmatrix(adhoc_matrix), interpolation="nearest", origin="upper", cmap="Greens")
plt.title("Ad hoc clustering kernel matrix")
plt.show()
from sklearn.cluster import SpectralClustering
from sklearn.metrics import normalized_mutual_info_score
adhoc_spectral = SpectralClustering(2, affinity="precomputed")
cluster_labels = adhoc_spectral.fit_predict(adhoc_matrix)
cluster_score = normalized_mutual_info_score(cluster_labels, train_labels)
print(f"Clustering score: {cluster_score}")
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=25,
test_size=10,
n=adhoc_dimension,
gap=0.6,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total)
feature_map = ZZFeatureMap(feature_dimension=2, reps=2, entanglement="linear")
qpca_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=feature_map)
matrix_train = qpca_kernel.evaluate(x_vec=train_features)
matrix_test = qpca_kernel.evaluate(x_vec=test_features, y_vec=test_features)
from sklearn.decomposition import KernelPCA
kernel_pca_rbf = KernelPCA(n_components=2, kernel="rbf")
kernel_pca_rbf.fit(train_features)
train_features_rbf = kernel_pca_rbf.transform(train_features)
test_features_rbf = kernel_pca_rbf.transform(test_features)
kernel_pca_q = KernelPCA(n_components=2, kernel="precomputed")
train_features_q = kernel_pca_q.fit_transform(matrix_train)
test_features_q = kernel_pca_q.fit_transform(matrix_test)
from sklearn.linear_model import LogisticRegression
logistic_regression = LogisticRegression()
logistic_regression.fit(train_features_q, train_labels)
logistic_score = logistic_regression.score(test_features_q, test_labels)
print(f"Logistic regression score: {logistic_score}")
fig, (q_ax, rbf_ax) = plt.subplots(1, 2, figsize=(10, 5))
plot_features(q_ax, train_features_q, train_labels, 0, "s", "w", "b", "A train")
plot_features(q_ax, train_features_q, train_labels, 1, "o", "w", "r", "B train")
plot_features(q_ax, test_features_q, test_labels, 0, "s", "b", "w", "A test")
plot_features(q_ax, test_features_q, test_labels, 1, "o", "r", "w", "A test")
q_ax.set_ylabel("Principal component #1")
q_ax.set_xlabel("Principal component #0")
q_ax.set_title("Projection of training and test data\n using KPCA with Quantum Kernel")
# Plotting the linear separation
h = 0.01 # step size in the mesh
# create a mesh to plot in
x_min, x_max = train_features_q[:, 0].min() - 1, train_features_q[:, 0].max() + 1
y_min, y_max = train_features_q[:, 1].min() - 1, train_features_q[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
predictions = logistic_regression.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
predictions = predictions.reshape(xx.shape)
q_ax.contourf(xx, yy, predictions, cmap=plt.cm.RdBu, alpha=0.2)
plot_features(rbf_ax, train_features_rbf, train_labels, 0, "s", "w", "b", "A train")
plot_features(rbf_ax, train_features_rbf, train_labels, 1, "o", "w", "r", "B train")
plot_features(rbf_ax, test_features_rbf, test_labels, 0, "s", "b", "w", "A test")
plot_features(rbf_ax, test_features_rbf, test_labels, 1, "o", "r", "w", "A test")
rbf_ax.set_ylabel("Principal component #1")
rbf_ax.set_xlabel("Principal component #0")
rbf_ax.set_title("Projection of training data\n using KernelPCA")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/TheGupta2012/QPE-Algorithms
|
TheGupta2012
|
from qiskit import IBMQ
from qiskit import QuantumCircuit, execute, transpile, Aer
from qiskit.extensions import UnitaryGate, Initialize
from qiskit.quantum_info import Statevector
from qiskit.compiler import assemble
from qiskit.circuit.random import random_circuit
from qiskit.tools.visualization import plot_bloch_vector
from qiskit.tools.visualization import plot_histogram, plot_bloch_multivector
import numpy as np
from time import sleep
import sys
import os
from scipy.stats import unitary_group
import matplotlib.pyplot as plt
%matplotlib inline
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-education')
simulator = Aer.get_backend('qasm_simulator')
athens = provider.get_backend('ibmq_athens')
class SPEA():
def __init__(self, unitary, resolution=50, error=3, max_iters=20):
# handle resolution
if not isinstance(resolution, int):
raise TypeError(
"Please enter the number of intervals as an integer value")
if resolution < 10 or resolution > 1e6:
raise ValueError(
"Resolution needs to be atleast 0.1 and greater than 0.000001")
self.resolution = resolution
# handle unitary
if not isinstance(unitary, np.ndarray) and not isinstance(unitary, QuantumCircuit)\
and not isinstance(unitary, UnitaryGate):
raise TypeError(
"A numpy array or Quantum Circuit or UnitaryGate needs to be passed as the unitary matrix")
# convert circuit to numpy array for uniformity
if isinstance(unitary, UnitaryGate):
U = unitary.to_matrix()
else: # both QC and ndarray type
U = unitary
# note - the unitary here is not just a single qubit unitary
if isinstance(U, np.ndarray):
self.dims = U.shape[0]
else:
self.dims = 2**(U.num_qubits)
if isinstance(U, np.ndarray):
self.c_unitary_gate = UnitaryGate(data=U).control(
num_ctrl_qubits=1, label='CU', ctrl_state='1')
else:
self.c_unitary_gate = U.control(
num_ctrl_qubits=1, label='CU', ctrl_state='1')
# handle error
if not isinstance(error, int):
raise TypeError(
"The allowable error should be provided as an int. Interpreted as 10**(-error)")
if error <= 0:
raise ValueError(
"The error threshold must be finite and greater than 0.")
self.error = error
# handle max_iters
if not isinstance(max_iters, int):
raise TypeError("Max iterations must be of integer type")
if max_iters <= 0 and max_iters > 1e5:
raise ValueError(
"Max iterations should be atleast 1 and less than 1e5")
self.iterations = max_iters
self.basis = []
def get_basis_vectors(self, randomize=True):
# get the d dimensional basis for the unitary provided
if randomize == True:
UR = unitary_group.rvs(self.dims)
else:
UR = np.identity(self.dims)
basis = []
for k in UR:
basis.append(np.array(k, dtype=complex))
return basis
def get_unitary_circuit(self, backend):
'''Return the pretranspiled circuit '''
if backend is None:
backend = Aer.get_backend('qasm_simulator')
qc = QuantumCircuit(1 + int(np.log2(self.dims)))
# make the circuit
qc.h(0)
qc = qc.compose(self.c_unitary_gate, qubits=range(
1+int(np.log2(self.dims))))
qc.barrier()
qc = transpile(qc,backend=backend,optimization_level = 3)
return qc
def get_circuit(self, state, backend, angle=None):
'''Given an initial state ,
return the circuit that is generated with
inverse rotation '''
# all theta values are iterated over for the same state
phi = Initialize(state)
shots = 512
qc1 = QuantumCircuit(1 + int(np.log2(self.dims)), 1)
# initialize the circuit
qc1 = qc1.compose(phi, qubits=list(
range(1, int(np.log2(self.dims))+1)))
qc1 = transpile(qc1, backend=backend,optimization_level=1)
# get the circuit2
qc2 = self.unitary_circuit
qc3 = QuantumCircuit(1 + int(np.log2(self.dims)), 1)
if angle is not None:
# add inverse rotation on the first qubit
qc3.p(-2*np.pi*angle, 0)
# add hadamard
qc3.h(0)
qc3 = transpile(qc3, backend=backend,optimization_level=1)
# make final circuit
qc = qc1 + qc2 + qc3
# measure
qc.measure([0], [0])
return qc
def get_standard_cost(self, angles, state, backend,shots):
'''Given an initial state and a set of angles,
return the best cost and the associated angle
state is a normalized state in ndarray form'''
result = {'cost': -1, 'theta': -1}
# all theta values are iterated over for the same state
phi = Initialize(state)
circuits = []
for theta in angles:
qc = self.get_circuit(state,backend,theta)
circuits.append(qc)
circuits = assemble(circuits)
# execute only once...
counts = backend.run(circuits, shots=shots).result().get_counts()
# get the cost for this theta
for k, theta in zip(counts, angles):
# for all experiments you ran
try:
C_val = (k['0'])/shots
except:
C_val = 0
if C_val > result['cost']:
# means this is a better theta value
result['theta'] = theta
result['cost'] = C_val
return result
def get_alternate_cost(self, angles, state, backend,shots):
'''Given an initial state and a set of angles,
return the best cost and the associated angle
state is a normalized state in ndarray form'''
result = {'cost': -1, 'theta': -1}
# all theta values are iterated over for the same state
phi = Initialize(state)
qc = self.get_circuit(state,backend)
qc = assemble(qc)
# execute only once...
counts = backend.run(qc, shots=shots).result().get_counts()
# generate experimental probabilities
try:
p0 = counts['0']/shots
except:
p0 = 0
try:
p1 = counts['1']/shots
except:
p1 = 0
# now, find the best theta as specified by the
# alternate method classically
min_s = 1e5
for theta in angles:
# generate theoretical probabilities
c0 = (np.cos(np.pi*theta))**2
c1 = (np.sin(np.pi*theta))**2
# generate s value
s = (p0-c0)**2 + (p1-c1)**2
if s < min_s:
result['theta'] = theta
min_s = s
# now , we have the best theta stored in phi
# run circuit once again to get the value of C*
qc = self.get_circuit(state, backend, result['theta'])
qc = assemble(qc)
counts = backend.run(qc, shots=shots).result().get_counts()
try:
result['cost'] = counts['0']/shots
except:
result['cost'] = 0
# no 0 counts presenta
# return the result
return result
def get_eigen_pair(self, backend, algo='alternate', progress=False, randomize=True, target_cost=None
, basis = None, basis_ind = None,shots=512):
'''Finding the eigenstate pair for the unitary'''
# handle algorithm...
self.unitary_circuit = self.get_unitary_circuit(backend)
if not isinstance(algo, str):
raise TypeError(
"Algorithm must be mentioned as a string from the values {alternate,standard}")
elif algo not in ['alternate', 'standard']:
raise ValueError(
"Algorithm must be specified as 'alternate' or 'standard' ")
if not isinstance(progress, bool):
raise TypeError("Progress must be a boolean variable")
if not isinstance(randomize, bool):
raise Exception("Randomize must be a boolean variable")
if target_cost is not None:
if not isinstance(target_cost, float):
raise TypeError("Target cost must be a float")
if (target_cost <= 0 or target_cost >= 1):
raise ValueError(
"Target cost must be a float value between 0 and 1")
results = dict()
# first initialize the state phi
if basis is None:
self.basis = self.get_basis_vectors(randomize)
else:
# is basis is specified, given as array of vectors...
self.basis = basis
# choose a random index
if basis_ind is None:
ind = np.random.choice(self.dims)
else:
# choose the index given in that basis
ind = basis_ind
phi = self.basis[ind]
# doing the method 1 of our algorithm
# define resolution of angles and precision
if target_cost == None:
precision = 1/10**self.error
else:
precision = 1 - target_cost
samples = self.resolution
# initialization of range
left, right = 0, 1
# generate the angles
angles = np.linspace(left, right, samples)
# iterate once
if algo == 'alternate':
result = self.get_alternate_cost(angles, phi, backend,shots)
else:
result = self.get_standard_cost(angles, phi, backend,shots)
# get initial estimates
cost = result['cost']
theta_max = result['theta']
# the range upto which theta extends iin each iteration
angle_range = 0.5
# a parameter
a = 1
# start algorithm
iters = 0
best_phi = phi
found = True
while 1 - cost >= precision:
# get angles, note if theta didn't change, then we need to
# again generate the same range again
right = min(1, theta_max + angle_range/2)
left = max(0, theta_max - angle_range/2)
if progress:
print("Right :", right)
print("Left :", left)
# generate the angles only if the theta has been updated
if found == True:
angles = np.linspace(left, right, samples)
found = False # for this iteration
if progress:
print("ITERATION NUMBER", iters+1, "...")
for i in range((2*self.dims)):
# everyone is supplied with the same range of theta in one iteration
# define z
if i < self.dims:
z = 1
else:
z = 1j
# alter and normalise phi
curr_phi = best_phi + z*a*(1 - cost)*self.basis[i % self.dims]
curr_phi = curr_phi / np.linalg.norm(curr_phi)
# iterate (angles would be same until theta is changed)
if algo == 'alternate':
res = self.get_alternate_cost(angles, curr_phi, backend,shots)
else:
res = self.get_standard_cost(angles, curr_phi, backend,shots)
curr_cost = res['cost']
curr_theta = res['theta']
# at this point I have the best Cost for the state PHI and the
#
# print(curr_phi)
if curr_cost > cost:
theta_max = float(curr_theta)
cost = float(curr_cost)
best_phi = curr_phi
found = True
if progress:
sys.stdout.write('\r')
sys.stdout.write("%f %%completed" %
(100*(i+1)/(2*self.dims)))
sys.stdout.flush()
sleep(0.2)
# iteration completes
if found == False:
# phi was not updated , change a
a = a/2
if progress:
print("\nNo change, updating a...")
else:
angle_range /= 2 # updated phi and thus theta too -> refine theta range
iters += 1
if progress:
print("\nCOST :", cost)
print("THETA :", theta_max)
if iters >= self.iterations:
print(
"Maximum iterations reached for the estimation.\nTerminating algorithm...")
break
# add the warning that iters maxed out
# add cost, eigenvector and theta to the dict
results['cost'] = cost
results['theta'] = theta_max
results['state'] = best_phi
return results
simulator = Aer.get_backend('qasm_simulator')
U = random_circuit(num_qubits=4,depth=1)
U.draw('mpl')
spe = SPEA(U, resolution=40, error=3, max_iters=13)
result = spe.get_eigen_pair(
progress=False, algo='alternate', backend=athens,shots=512)
result
U = QuantumCircuit(4)
U.cp(2*np.pi*(1/2), 1, 2)
display(U.draw('mpl'))
errors = []
eigvals = np.array([0.0, 0.5, 1.0])
for resolution in range(10, 80, 10):
spe = SPEA(U, resolution=resolution, error=4, max_iters=15)
res = spe.get_eigen_pair(backend=simulator, algo='alternate')
theta = res['theta']
min_error = 1e5
# get percentage error
for e in eigvals:
error = abs(e-theta)
if error < min_error:
min_error = error
if e != 0:
perc_error = (error/e)*100
else:
perc_error = error*100
errors.append(perc_error)
plt.title(
"Eigenphase estimation for theta = 1/2, 0, 1 (4-qubit unitary)", fontsize=15)
plt.grid()
plt.plot(list(range(10, 80, 10)), errors, marker='o',
color='brown', label='Estimates', alpha=0.7)
# plt.plot([10,80],[0.25,0.25],color='black',label = "True")
# plt.plot([10,80],[0,0],color='black',label = "True")
# plt.plot([10,80],[1,1],color='black',label = "True")
plt.legend()
plt.xlabel("Resolution of theta ")
plt.ylabel("Percentage errors from closest eigenvalues")
plt.savefig("Alternate_SPE_PLOT_original_algo.jpg", dpi=200)
U = QuantumCircuit(2)
U.cp(2*np.pi*(1/6), 0, 1)
U.draw('mpl')
eigvals = np.array([0.0, 1/6, 1.0])
errors = []
for resolution in range(10, 80, 10):
spe = SPEA(U, resolution=resolution, error=3, max_iters=12)
# run 5 experiments of this
p_errors = []
for exp in range(4):
res = spe.get_eigen_pair(
progress=False, algo='alternate', backend=simulator)
theta = res['theta']
min_error = 1e5
min_val = -1
# get min error
for e in eigvals:
error = abs(e-theta)
if error < min_error:
min_error = error
min_val = e
# percent error in this experiment
if min_val != 0:
p_errors.append((min_error/min_val)*100)
else:
p_errors.append((min_error)*100)
print("Percentage Errors in current iteration:", p_errors)
errors.append(np.average(p_errors))
print("Errors :", errors)
plt.title(
"Eigenphase estimation for theta = 1/6, 0, 1 (2-qubit unitary)", fontsize=15)
plt.grid()
plt.plot(list(range(10, 80, 10)), errors, marker='o',
color='magenta', label='Estimates', alpha=0.6)
# plt.plot([10,80],[0.25,0.25],color='black',label = "True")
# plt.plot([10,80],[0,0],color='black',label = "True")
# plt.plot([10,80],[1,1],color='black',label = "True")
plt.legend()
plt.xlabel("Resolution of theta ")
plt.ylabel("Percentage Errors from closest eigenvalues")
plt.savefig("Alternate_SPE_PLOT_2_original_algo.jpg", dpi=200)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeBoeblingen
backend = FakeBoeblingen()
ghz = QuantumCircuit(5)
ghz.h(0)
ghz.cx(0,range(1,5))
circ = transpile(ghz, backend, scheduling_method="asap")
circ.draw(output='mpl')
|
https://github.com/KathrinKoenig/QuantumTopologicalDataAnalysis
|
KathrinKoenig
|
import numpy as np
import qtda_module as qtda
from qiskit.visualization import plot_histogram
from qiskit import IBMQ
from qiskit import execute, QuantumRegister, QuantumCircuit, ClassicalRegister, Aer
from qiskit.compiler import transpile
provider = IBMQ.load_account()
accountProvider = IBMQ.get_provider(hub='ibm-q-fraunhofer',group = 'fhg-all',project = 'ticket')
backend = accountProvider.get_backend('ibmq_brooklyn')
n_vertices = 3 # number of vertices
num_eval_qubits = 3 # number of evaluation qubits
S0 = [(0,0,1),(0,1,0), (1,0,0)] # points
S1 = [(1,0,1),(0,1,1),(1,1,0)] # lines
S2 = []
state_dict = {0: S0, 1: S1, 2: S2}
k = 1 # order of the combinatorial Laplacian
qc = qtda.QTDAalgorithm(num_eval_qubits, k, state_dict)
qc.add_register(ClassicalRegister(num_eval_qubits)) # adding a classical register for measuring
for q in qc.eval_qubits: # measure all evaluation qubits
qc.measure(q,q)
qc.draw('mpl')
qcc = transpile(qc, basis_gates=['id', 'rz', 'sx', 'x', 'cx'], layout_method='sabre',optimization_level=3)
qa = transpile(qc, backend=backend, basis_gates=['id', 'rz', 'sx', 'x', 'cx'],layout_method='sabre',optimization_level=3)
qa.depth() # depth of ibmq_brooklyn
qcc.depth() # depth of an arbitrary backend
shots = 8192
job = execute(qa, backend, shots=shots)
counts = job.result().get_counts(qa)
dim = len(state_dict[1]) # dimension of 1-simplex space
prob = counts.get("0"*num_eval_qubits)/shots # probability of eigenvalue 0
print('The number of 1-holes is', dim * prob)
plot_histogram(counts)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/levchCode/RSA-breaker
|
levchCode
|
#
# This is a toy RSA encryption breaker using Shor's algorithm (params: a = 2, N = 85)
# To use your custom alphabet, please change alphabet var
#
from qiskit import QuantumProgram
from fractions import gcd
from math import pi
qp = QuantumProgram()
qr = qp.create_quantum_register('qr', 8)
cr = qp.create_classical_register('cr', 4)
qc = qp.create_circuit('Shor',[qr],[cr])
def Oracle():
qc.cx(qr[2], qr[6])
qc.cx(qr[3], qr[7])
def findPQ(a, N):
qc.h(qr[0])
qc.h(qr[1])
qc.h(qr[2])
qc.h(qr[3])
Oracle()
qc.h(qr[0])
qc.cu1(pi/2, qr[0], qr[1])
qc.h(qr[1])
qc.cu1(pi/4, qr[0], qr[2])
qc.cu1(pi/2, qr[1], qr[2])
qc.h(qr[2])
qc.cu1(pi/8, qr[0], qr[3])
qc.cu1(pi/4, qr[1], qr[3])
qc.cu1(pi/2, qr[2], qr[3])
qc.h(qr[3])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
qc.measure(qr[2], cr[2])
qc.measure(qr[3], cr[3])
result = qp.execute(['Shor'])#, backend='ibmqx_qasm_simulator', shots=1024, wait=5, timeout=1200)
res = result.get_counts('Shor')
mult_list = []
for k in res.keys():
p = int(k, 2)
if p % 2 == 0:
k1 = a**(p/2) - 1
k2 = a**(p/2) + 1
mult_list.append((gcd(k1, N), gcd(k2, N)))
else:
print("Period is odd, skipping")
print("mult_list: {}".format(mult_list))
return mult_list
def decrypt(public_key, message):
m_list = findPQ(2, public_key[1])
#alphabet84 = " !(),-./0123456789:?АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
#alphabet50 = " !(),-.0123456789:?АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"
alphabet = " !(),-./0123456789:?АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
message = [alphabet.find(i) for i in message]
for m in m_list:
fi = (m[0]-1)*(m[1]-1)
if(fi == 0):
print("N = N * 1, skipping")
else:
d = 0
while True:
rem = (d*public_key[0]) % fi
if rem == 1:
break
else:
d = d + 1
text = ''
for i in message:
text += alphabet[i**d % public_key[1]]
print("The message is: {}".format(text))
if __name__ == '__main__':
decrypt((11, 85), "Ы97 3хД7УЙ НЖ3 Жл2Ж, Н9ще7 НЖ?32Ж Дхнх9лЖ,д")
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# 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.
"""
Engine for the Quantum Subspace Expansion algorithm
"""
import time
import logging
import itertools
from typing import List
import numpy as np
from multiprocessing import Pool, cpu_count
from _pickle import PicklingError
from qiskit import QuantumCircuit, ClassicalRegister
from pytket.chemistry.aqua.qse_subs import QseMatrices
from qiskit.aqua import QuantumAlgorithm, AquaError, Operator
from qiskit.aqua.components.variational_forms import VariationalForm
logger = logging.getLogger(__name__)
logger = logging.getLogger('qiskit.aqua')
class QSE(QuantumAlgorithm):
"""
:py:class:`qiskit.aqua.QuantumAlgorithm` implementation for Quantum Subspace Expansion (QSE)
[See Phys. Rev. A 95, 042308 (2017)].
"""
CONFIGURATION = {
'name': 'QSE',
'description': 'QSE Algorithm',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'qse_schema',
'type': 'object',
'properties': {
'operator_mode': {
'type': 'string',
'default': 'matrix',
'oneOf': [
{'enum': ['matrix', 'paulis', 'grouped_paulis']}
]
},
'initial_point': {
'type': ['array', 'null'],
"items": {
"type": "number"
},
'default': None
}
},
'additionalProperties': False
},
'problems': ['energy', 'ising'],
'depends': ['variational_form', 'initial_state'],
'defaults': {
'variational_form': {
'name': 'UCCSD'
},
'initial_state': {
'name': 'ZERO'
}
}
}
def __init__(self, qse_operators:QseMatrices, operator_mode:str, var_form:VariationalForm,
opt_init_point:np.ndarray=None, aux_operators:List[Operator]=[]):
"""
:param qse_operators: Qubit operator generator
:param operator_mode: Operator mode to be used for evaluation of the operator
:param var_form: Parametrized variational form
:param opt_init_point: Initial point for the optimisation
:param aux_operators: Auxiliary operators to be evaluated at each eigenvalue
"""
super().__init__()
self._qse_operators = qse_operators
self._operator = None
self._operator_mode = operator_mode
self._var_form = var_form
self.opt_var_params = opt_init_point
self._aux_operators = aux_operators
self._ret = {}
self._eval_count = 0
self._eval_time = 0
if opt_init_point is None:
self.opt_var_params = var_form.preferred_init_points
else:
self.opt_circuit = self._var_form.construct_circuit(self.opt_var_params)
self._quantum_state = None
@property
def setting(self):
ret = "Algorithm: {}\n".format(self._configuration['name'])
params = ""
for key, value in self.__dict__.items():
if key != "_configuration" and key[0] == "_":
if "opt_init_point" in key and value is None:
params += "-- {}: {}\n".format(key[1:], "Random seed")
else:
params += "-- {}: {}\n".format(key[1:], value)
ret += "{}".format(params)
return ret
def print_setting(self) -> str:
"""
Presents the QSE settings as a string.
:return: The formatted settings of the QSE instance
"""
ret = "\n"
ret += "==================== Setting of {} ============================\n".format(self.configuration['name'])
ret += "{}".format(self.setting)
ret += "===============================================================\n"
ret += "{}".format(self._var_form.setting)
ret += "===============================================================\n"
return ret
def _energy_evaluation(self, operator):
"""
Evaluate the energy of the current input circuit with respect to the given operator.
:param operator: Hamiltonian of the system
:return: Energy of the Hamiltonian
"""
if self._quantum_state is not None:
input_circuit = self._quantum_state
else:
input_circuit = [self.opt_circuit]
if operator._paulis:
mean_energy, std_energy = operator.evaluate_with_result(self._operator_mode, input_circuit,
self._quantum_instance.backend, self.ret)
else:
mean_energy = 0.0
std_energy = 0.0
operator.disable_summarize_circuits()
logger.debug('Energy evaluation {} returned {}'.format(self._eval_count, np.real(mean_energy)))
return np.real(mean_energy), np.real(std_energy)
def _h_qse_finder(self, pair):
i, j = pair
term = self._qse_operators.hamiltonian_term(i, j)
term.chop(1e-10)
result, std_ij = self._energy_evaluation(term)
return result
#Measure elements of the overlap matrix
def _s_qse_finder(self, pair):
i, j = pair
term = self._qse_operators.overlap_term(i, j)
result, std_ij = self._energy_evaluation(term)
return result
def _linear_compute(self, terms, _n_qubits):
matrix = np.zeros((_n_qubits**2, _n_qubits**2), dtype=np.float)
pairs = filter(lambda x: x[1]>=x[0], itertools.product(range(_n_qubits**2), repeat=2))
completed = 0
total = _n_qubits**4
for pair, term in zip(pairs, terms):
i, j = pair
result, std = self._energy_evaluation(term)
matrix[[i,j], [j,i]] = result
completed += 2
if completed % 1 ==0:
logger.info("Matrix Filled: {0:.2%}".format(completed/total))
return matrix
def _parallel_compute(self, terms, _n_qubits):
matrix = np.zeros((_n_qubits**2, _n_qubits**2), dtype=np.float)
N_CORES = cpu_count()
pairs = filter(lambda x: x[1]>=x[0], itertools.product(range(_n_qubits**2), repeat=2))
n_calcs = N_CORES*5
next_terms = list(itertools.islice(terms, n_calcs))
next_pairs = list(itertools.islice(pairs, n_calcs))
completed = 0
total = _n_qubits**4
with Pool(N_CORES) as p:
while next_terms:
start = time.time()
results, stdev = zip(*p.map(self._energy_evaluation, next_terms))
i_s, j_s = zip(*next_pairs)
results = np.array(list(results))
matrix[i_s, j_s] = results
matrix[j_s, i_s] = results
next_terms = list(itertools.islice(terms, n_calcs))
next_pairs = list(itertools.islice(pairs, n_calcs))
completed += n_calcs*2
logger.debug("{} calculations in {}".format(n_calcs, time.time() - start))
logger.info("Matrix Filled: {0:.2%}".format(completed/total))
return matrix
def _generate_terms(self):
n_qubits = self._qse_operators.n_qubits
pairs = list(filter(lambda x: x[1]>=x[0], itertools.product(range(n_qubits**2), repeat=2)))
def chop(term):
term.chop(1e-10)
return term
h_terms = (chop(term) for term in(self._qse_operators.hamiltonian_term(i, j) for i, j in pairs))
s_terms = (self._qse_operators.overlap_term(i, j) for i, j in pairs)
return h_terms, s_terms
def _solve(self, parallel=True):
h_terms, s_terms = self._generate_terms()
n_qubits = self._qse_operators.n_qubits
if parallel:
h_qse_matrix = self._parallel_compute(h_terms, n_qubits)
s_qse_matrix = self._parallel_compute(s_terms, n_qubits)
else:
h_qse_matrix = self._linear_compute(h_terms, n_qubits)
s_qse_matrix = self._linear_compute(s_terms, n_qubits)
eigvals, vectors = np.linalg.eig(np.matmul(np.linalg.pinv(s_qse_matrix),h_qse_matrix))
eigvals = np.real(eigvals)
eigvals.sort()
self._ret['eigvals'] = eigvals
def _eval_aux_ops(self, threshold=1e-12):
wavefn_circuit = self._var_form.construct_circuit(self._ret['opt_params'])
values = []
for operator in self._aux_operators:
mean, std = 0.0, 0.0
if not operator.is_empty():
mean, std = operator.eval(self._operator_mode, wavefn_circuit,
self._backend, self._execute_config, self._qjob_config)
mean = mean.real if abs(mean.real) > threshold else 0.0
std = std.real if abs(std.real) > threshold else 0.0
values.append((mean, std))
if len(values) > 0:
aux_op_vals = np.empty([1, len(self._aux_operators), 2])
aux_op_vals[0, :] = np.asarray(values)
self._ret['aux_ops'] = aux_op_vals
def _run(self) -> dict:
"""
Runs the QSE algorithm to compute the eigenvalues of the Hamiltonian.
:return: Dictionary of results
"""
if not self._quantum_instance.is_statevector:
raise AquaError("Can only calculate state for QSE with statevector backends")
ret = self._quantum_instance.execute(self.opt_circuit)
self.ret = ret
self._eval_count = 0
self._solve()
self._ret['eval_count'] = self._eval_count
self._ret['eval_time'] = self._eval_time
return self._ret
|
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/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/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
# Importing standard Qiskit libraries
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import Aer, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector, plot_state_qsphere, plot_state_city, plot_state_paulivec, plot_state_hinton
# Ignore warnings
import warnings
warnings.filterwarnings('ignore')
# Define backend
sim = Aer.get_backend('aer_simulator')
def createBellStates(inp1, inp2):
qc = QuantumCircuit(2)
qc.reset(range(2))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
qc.h(0)
qc.cx(0,1)
qc.save_statevector()
qobj = assemble(qc)
result = sim.run(qobj).result()
state = result.get_statevector()
return qc, state, result
print('Note: Since these qubits are in entangled state, their state cannot be written as two separate qubit states. This also means that we lose information when we try to plot our state on separate Bloch spheres as seen below.\n')
inp1 = 0
inp2 = 1
qc, state, result = createBellStates(inp1, inp2)
display(plot_bloch_multivector(state))
# Uncomment below code in order to explore other states
#for inp2 in ['0', '1']:
#for inp1 in ['0', '1']:
#qc, state, result = createBellStates(inp1, inp2)
#print('For inputs',inp2,inp1,'Representation of Entangled States are:')
# Uncomment any of the below functions to visualize the resulting quantum states
# Draw the quantum circuit
#display(qc.draw())
# Plot states on QSphere
#display(plot_state_qsphere(state))
# Plot states on Bloch Multivector
#display(plot_bloch_multivector(state))
# Plot histogram
#display(plot_histogram(result.get_counts()))
# Plot state matrix like a city
#display(plot_state_city(state))
# Represent state matix using Pauli operators as the basis
#display(plot_state_paulivec(state))
# Plot state matrix as Hinton representation
#display(plot_state_hinton(state))
#print('\n')'''
from qiskit import IBMQ, execute
from qiskit.providers.ibmq import least_busy
from qiskit.tools import job_monitor
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
and not x.configuration().simulator
and x.status().operational==True))
def createBSRealDevice(inp1, inp2):
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.reset(range(2))
if inp1 == 1:
qc.x(0)
if inp2 == 1:
qc.x(1)
qc.barrier()
qc.h(0)
qc.cx(0,1)
qc.measure(qr, cr)
job = execute(qc, backend=backend, shots=100)
job_monitor(job)
result = job.result()
return qc, result
inp1 = 0
inp2 = 0
print('For inputs',inp2,inp1,'Representation of Entangled States are,')
#first results
qc, first_result = createBSRealDevice(inp1, inp2)
first_counts = first_result.get_counts()
# Draw the quantum circuit
display(qc.draw())
#second results
qc, second_result = createBSRealDevice(inp1, inp2)
second_counts = second_result.get_counts()
# Plot results on histogram with legend
legend = ['First execution', 'Second execution']
plot_histogram([first_counts, second_counts], legend=legend)
def ghzCircuit(inp1, inp2, inp3):
qc = QuantumCircuit(3)
qc.reset(range(3))
if inp1 == 1:
qc.x(0)
if inp2 == 1:
qc.x(1)
if inp3 == 1:
qc.x(2)
qc.barrier()
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
qc.save_statevector()
qobj = assemble(qc)
result = sim.run(qobj).result()
state = result.get_statevector()
return qc, state, result
print('Note: Since these qubits are in entangled state, their state cannot be written as two separate qubit states. This also means that we lose information when we try to plot our state on separate Bloch spheres as seen below.\n')
inp1 = 0
inp2 = 1
inp3 = 1
qc, state, result = ghzCircuit(inp1, inp2, inp3)
display(plot_bloch_multivector(state))
# Uncomment below code in order to explore other states
#for inp3 in ['0','1']:
#for inp2 in ['0','1']:
#for inp1 in ['0','1']:
#qc, state, result = ghzCircuit(inp1, inp2, inp3)
#print('For inputs',inp3,inp2,inp1,'Representation of GHZ States are:')
# Uncomment any of the below functions to visualize the resulting quantum states
# Draw the quantum circuit
#display(qc.draw())
# Plot states on QSphere
#display(plot_state_qsphere(state))
# Plot states on Bloch Multivector
#display(plot_bloch_multivector(state))
# Plot histogram
#display(plot_histogram(result.get_counts()))
# Plot state matrix like a city
#display(plot_state_city(state))
# Represent state matix using Pauli operators as the basis
#display(plot_state_paulivec(state))
# Plot state matrix as Hinton representation
#display(plot_state_hinton(state))
#print('\n')
def ghz5QCircuit(inp1, inp2, inp3, inp4, inp5):
qc = QuantumCircuit(5)
#qc.reset(range(5))
if inp1 == 1:
qc.x(0)
if inp2 == 1:
qc.x(1)
if inp3 == 1:
qc.x(2)
if inp4 == 1:
qc.x(3)
if inp5 == 1:
qc.x(4)
qc.barrier()
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
qc.cx(0,3)
qc.cx(0,4)
qc.save_statevector()
qobj = assemble(qc)
result = sim.run(qobj).result()
state = result.get_statevector()
return qc, state, result
# Explore GHZ States for input 00010. Note: the input has been stated in little-endian format.
inp1 = 0
inp2 = 1
inp3 = 0
inp4 = 0
inp5 = 0
qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5)
print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:')
display(plot_state_qsphere(state))
print('\n')
# Explore GHZ States for input 11001. Note: the input has been stated in little-endian format.
inp1 = 1
inp2 = 0
inp3 = 0
inp4 = 1
inp5 = 1
qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5)
print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:')
display(plot_state_qsphere(state))
print('\n')
# Explore GHZ States for input 01010. Note: the input has been stated in little-endian format.
inp1 = 0
inp2 = 1
inp3 = 0
inp4 = 1
inp5 = 0
qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5)
print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:')
display(plot_state_qsphere(state))
print('\n')
# Uncomment below code in order to explore other states
#for inp5 in ['0','1']:
#for inp4 in ['0','1']:
#for inp3 in ['0','1']:
#for inp2 in ['0','1']:
#for inp1 in ['0','1']:
#qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5)
#print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:')
# Uncomment any of the below functions to visualize the resulting quantum states
# Draw the quantum circuit
#display(qc.draw())
# Plot states on QSphere
#display(plot_state_qsphere(state))
# Plot states on Bloch Multivector
#display(plot_bloch_multivector(state))
# Plot histogram
#display(plot_histogram(result.get_counts()))
# Plot state matrix like a city
#display(plot_state_city(state))
# Represent state matix using Pauli operators as the basis
#display(plot_state_paulivec(state))
# Plot state matrix as Hinton representation
#display(plot_state_hinton(state))
#print('\n')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 5
and not x.configuration().simulator
and x.status().operational==True))
def create5QGHZRealDevice(inp1, inp2, inp3, inp4, inp5):
qr = QuantumRegister(5)
cr = ClassicalRegister(5)
qc = QuantumCircuit(qr, cr)
qc.reset(range(5))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
if inp3=='1':
qc.x(1)
if inp4=='1':
qc.x(1)
if inp5=='1':
qc.x(1)
qc.barrier()
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
qc.cx(0,3)
qc.cx(0,4)
qc.measure(qr, cr)
job = execute(qc, backend=backend, shots=1000)
job_monitor(job)
result = job.result()
return qc, result
inp1 = 0
inp2 = 0
inp3 = 0
inp4 = 0
inp5 = 0
#first results
qc, first_result = create5QGHZRealDevice(inp1, inp2, inp3, inp4, inp5)
first_counts = first_result.get_counts()
# Draw the quantum circuit
display(qc.draw())
#second results
qc, second_result = create5QGHZRealDevice(inp1, inp2, inp3, inp4, inp5)
second_counts = second_result.get_counts()
print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ circuit states are,')
# Plot results on histogram with legend
legend = ['First execution', 'Second execution']
plot_histogram([first_counts, second_counts], legend=legend)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
|
SaashaJoshi
|
!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/2lambda123/Qiskit-qiskit
|
2lambda123
|
# 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.
"""Testing legacy instruction alignment pass."""
from qiskit import QuantumCircuit, pulse
from qiskit.test import QiskitTestCase
from qiskit.transpiler import InstructionDurations
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.passes import (
AlignMeasures,
ValidatePulseGates,
ALAPSchedule,
TimeUnitConversion,
)
class TestAlignMeasures(QiskitTestCase):
"""A test for measurement alignment pass."""
def setUp(self):
super().setUp()
instruction_durations = InstructionDurations()
instruction_durations.update(
[
("rz", (0,), 0),
("rz", (1,), 0),
("x", (0,), 160),
("x", (1,), 160),
("sx", (0,), 160),
("sx", (1,), 160),
("cx", (0, 1), 800),
("cx", (1, 0), 800),
("measure", None, 1600),
]
)
self.time_conversion_pass = TimeUnitConversion(inst_durations=instruction_durations)
# reproduce old behavior of 0.20.0 before #7655
# currently default write latency is 0
self.scheduling_pass = ALAPSchedule(
durations=instruction_durations,
clbit_write_latency=1600,
conditional_latency=0,
)
self.align_measure_pass = AlignMeasures(alignment=16)
def test_t1_experiment_type(self):
"""Test T1 experiment type circuit.
(input)
┌───┐┌────────────────┐┌─┐
q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├
└───┘└────────────────┘└╥┘
c: 1/════════════════════════╩═
0
(aligned)
┌───┐┌────────────────┐┌─┐
q_0: ┤ X ├┤ Delay(112[dt]) ├┤M├
└───┘└────────────────┘└╥┘
c: 1/════════════════════════╩═
0
This type of experiment slightly changes delay duration of interest.
However the quantization error should be less than alignment * dt.
"""
circuit = QuantumCircuit(1, 1)
circuit.x(0)
circuit.delay(100, 0, unit="dt")
circuit.measure(0, 0)
timed_circuit = self.time_conversion_pass(circuit)
scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"})
aligned_circuit = self.align_measure_pass(
scheduled_circuit, property_set={"time_unit": "dt"}
)
ref_circuit = QuantumCircuit(1, 1)
ref_circuit.x(0)
ref_circuit.delay(112, 0, unit="dt")
ref_circuit.measure(0, 0)
self.assertEqual(aligned_circuit, ref_circuit)
def test_hanh_echo_experiment_type(self):
"""Test Hahn echo experiment type circuit.
(input)
┌────┐┌────────────────┐┌───┐┌────────────────┐┌────┐┌─┐
q_0: ┤ √X ├┤ Delay(100[dt]) ├┤ X ├┤ Delay(100[dt]) ├┤ √X ├┤M├
└────┘└────────────────┘└───┘└────────────────┘└────┘└╥┘
c: 1/══════════════════════════════════════════════════════╩═
0
(output)
┌────┐┌────────────────┐┌───┐┌────────────────┐┌────┐┌──────────────┐┌─┐
q_0: ┤ √X ├┤ Delay(100[dt]) ├┤ X ├┤ Delay(100[dt]) ├┤ √X ├┤ Delay(8[dt]) ├┤M├
└────┘└────────────────┘└───┘└────────────────┘└────┘└──────────────┘└╥┘
c: 1/══════════════════════════════════════════════════════════════════════╩═
0
This type of experiment doesn't change duration of interest (two in the middle).
However induces slight delay less than alignment * dt before measurement.
This might induce extra amplitude damping error.
"""
circuit = QuantumCircuit(1, 1)
circuit.sx(0)
circuit.delay(100, 0, unit="dt")
circuit.x(0)
circuit.delay(100, 0, unit="dt")
circuit.sx(0)
circuit.measure(0, 0)
timed_circuit = self.time_conversion_pass(circuit)
scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"})
aligned_circuit = self.align_measure_pass(
scheduled_circuit, property_set={"time_unit": "dt"}
)
ref_circuit = QuantumCircuit(1, 1)
ref_circuit.sx(0)
ref_circuit.delay(100, 0, unit="dt")
ref_circuit.x(0)
ref_circuit.delay(100, 0, unit="dt")
ref_circuit.sx(0)
ref_circuit.delay(8, 0, unit="dt")
ref_circuit.measure(0, 0)
self.assertEqual(aligned_circuit, ref_circuit)
def test_mid_circuit_measure(self):
"""Test circuit with mid circuit measurement.
(input)
┌───┐┌────────────────┐┌─┐┌───────────────┐┌───┐┌────────────────┐┌─┐
q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├┤ Delay(10[dt]) ├┤ X ├┤ Delay(120[dt]) ├┤M├
└───┘└────────────────┘└╥┘└───────────────┘└───┘└────────────────┘└╥┘
c: 2/════════════════════════╩══════════════════════════════════════════╩═
0 1
(output)
┌───┐┌────────────────┐┌─┐┌───────────────┐┌───┐┌────────────────┐┌─┐
q_0: ┤ X ├┤ Delay(112[dt]) ├┤M├┤ Delay(10[dt]) ├┤ X ├┤ Delay(134[dt]) ├┤M├
└───┘└────────────────┘└╥┘└───────────────┘└───┘└────────────────┘└╥┘
c: 2/════════════════════════╩══════════════════════════════════════════╩═
0 1
Extra delay is always added to the existing delay right before the measurement.
Delay after measurement is unchanged.
"""
circuit = QuantumCircuit(1, 2)
circuit.x(0)
circuit.delay(100, 0, unit="dt")
circuit.measure(0, 0)
circuit.delay(10, 0, unit="dt")
circuit.x(0)
circuit.delay(120, 0, unit="dt")
circuit.measure(0, 1)
timed_circuit = self.time_conversion_pass(circuit)
scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"})
aligned_circuit = self.align_measure_pass(
scheduled_circuit, property_set={"time_unit": "dt"}
)
ref_circuit = QuantumCircuit(1, 2)
ref_circuit.x(0)
ref_circuit.delay(112, 0, unit="dt")
ref_circuit.measure(0, 0)
ref_circuit.delay(10, 0, unit="dt")
ref_circuit.x(0)
ref_circuit.delay(134, 0, unit="dt")
ref_circuit.measure(0, 1)
self.assertEqual(aligned_circuit, ref_circuit)
def test_mid_circuit_multiq_gates(self):
"""Test circuit with mid circuit measurement and multi qubit gates.
(input)
┌───┐┌────────────────┐┌─┐ ┌─┐
q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├──■───────■──┤M├
└───┘└────────────────┘└╥┘┌─┴─┐┌─┐┌─┴─┐└╥┘
q_1: ────────────────────────╫─┤ X ├┤M├┤ X ├─╫─
║ └───┘└╥┘└───┘ ║
c: 2/════════════════════════╩═══════╩═══════╩═
0 1 0
(output)
┌───┐ ┌────────────────┐┌─┐ ┌─────────────────┐ ┌─┐»
q_0: ───────┤ X ├───────┤ Delay(112[dt]) ├┤M├──■──┤ Delay(1600[dt]) ├──■──┤M├»
┌──────┴───┴──────┐└────────────────┘└╥┘┌─┴─┐└───────┬─┬───────┘┌─┴─┐└╥┘»
q_1: ┤ Delay(1872[dt]) ├───────────────────╫─┤ X ├────────┤M├────────┤ X ├─╫─»
└─────────────────┘ ║ └───┘ └╥┘ └───┘ ║ »
c: 2/══════════════════════════════════════╩═══════════════╩═══════════════╩═»
0 1 0 »
«
«q_0: ───────────────────
« ┌─────────────────┐
«q_1: ┤ Delay(1600[dt]) ├
« └─────────────────┘
«c: 2/═══════════════════
«
Delay for the other channel paired by multi-qubit instruction is also scheduled.
Delay (1872dt) = X (160dt) + Delay (100dt + extra 12dt) + Measure (1600dt).
"""
circuit = QuantumCircuit(2, 2)
circuit.x(0)
circuit.delay(100, 0, unit="dt")
circuit.measure(0, 0)
circuit.cx(0, 1)
circuit.measure(1, 1)
circuit.cx(0, 1)
circuit.measure(0, 0)
timed_circuit = self.time_conversion_pass(circuit)
scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"})
aligned_circuit = self.align_measure_pass(
scheduled_circuit, property_set={"time_unit": "dt"}
)
ref_circuit = QuantumCircuit(2, 2)
ref_circuit.x(0)
ref_circuit.delay(112, 0, unit="dt")
ref_circuit.measure(0, 0)
ref_circuit.delay(160 + 112 + 1600, 1, unit="dt")
ref_circuit.cx(0, 1)
ref_circuit.delay(1600, 0, unit="dt")
ref_circuit.measure(1, 1)
ref_circuit.cx(0, 1)
ref_circuit.delay(1600, 1, unit="dt")
ref_circuit.measure(0, 0)
self.assertEqual(aligned_circuit, ref_circuit)
def test_alignment_is_not_processed(self):
"""Test avoid pass processing if delay is aligned."""
circuit = QuantumCircuit(2, 2)
circuit.x(0)
circuit.delay(160, 0, unit="dt")
circuit.measure(0, 0)
circuit.cx(0, 1)
circuit.measure(1, 1)
circuit.cx(0, 1)
circuit.measure(0, 0)
# pre scheduling is not necessary because alignment is skipped
# this is to minimize breaking changes to existing code.
transpiled = self.align_measure_pass(circuit, property_set={"time_unit": "dt"})
self.assertEqual(transpiled, circuit)
def test_circuit_using_clbit(self):
"""Test a circuit with instructions using a common clbit.
(input)
┌───┐┌────────────────┐┌─┐
q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├──────────────
└───┘└────────────────┘└╥┘ ┌───┐
q_1: ────────────────────────╫────┤ X ├──────
║ └─╥─┘ ┌─┐
q_2: ────────────────────────╫──────╫─────┤M├
║ ┌────╨────┐└╥┘
c: 1/════════════════════════╩═╡ c_0 = T ╞═╩═
0 └─────────┘ 0
(aligned)
┌───┐ ┌────────────────┐┌─┐┌────────────────┐
q_0: ───────┤ X ├───────┤ Delay(112[dt]) ├┤M├┤ Delay(160[dt]) ├───
┌──────┴───┴──────┐└────────────────┘└╥┘└─────┬───┬──────┘
q_1: ┤ Delay(1872[dt]) ├───────────────────╫───────┤ X ├──────────
└┬────────────────┤ ║ └─╥─┘ ┌─┐
q_2: ─┤ Delay(432[dt]) ├───────────────────╫─────────╫─────────┤M├
└────────────────┘ ║ ┌────╨────┐ └╥┘
c: 1/══════════════════════════════════════╩════╡ c_0 = T ╞═════╩═
0 └─────────┘ 0
Looking at the q_0, the total schedule length T becomes
160 (x) + 112 (aligned delay) + 1600 (measure) + 160 (delay) = 2032.
The last delay comes from ALAP scheduling called before the AlignMeasure pass,
which aligns stop times as late as possible, so the start time of x(1).c_if(0)
and the stop time of measure(0, 0) become T - 160.
"""
circuit = QuantumCircuit(3, 1)
circuit.x(0)
circuit.delay(100, 0, unit="dt")
circuit.measure(0, 0)
circuit.x(1).c_if(0, 1)
circuit.measure(2, 0)
timed_circuit = self.time_conversion_pass(circuit)
scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"})
aligned_circuit = self.align_measure_pass(
scheduled_circuit, property_set={"time_unit": "dt"}
)
self.assertEqual(aligned_circuit.duration, 2032)
ref_circuit = QuantumCircuit(3, 1)
ref_circuit.x(0)
ref_circuit.delay(112, 0, unit="dt")
ref_circuit.delay(1872, 1, unit="dt") # 2032 - 160
ref_circuit.delay(432, 2, unit="dt") # 2032 - 1600
ref_circuit.measure(0, 0)
ref_circuit.x(1).c_if(0, 1)
ref_circuit.delay(160, 0, unit="dt")
ref_circuit.measure(2, 0)
self.assertEqual(aligned_circuit, ref_circuit)
class TestPulseGateValidation(QiskitTestCase):
"""A test for pulse gate validation pass."""
def setUp(self):
super().setUp()
self.pulse_gate_validation_pass = ValidatePulseGates(granularity=16, min_length=64)
def test_invalid_pulse_duration(self):
"""Kill pass manager if invalid pulse gate is found."""
# this is invalid duration pulse
# this will cause backend error since this doesn't fit with waveform memory chunk.
custom_gate = pulse.Schedule(name="custom_x_gate")
custom_gate.insert(
0, pulse.Play(pulse.Constant(100, 0.1), pulse.DriveChannel(0)), inplace=True
)
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.add_calibration("x", qubits=(0,), schedule=custom_gate)
with self.assertRaises(TranspilerError):
self.pulse_gate_validation_pass(circuit)
def test_short_pulse_duration(self):
"""Kill pass manager if invalid pulse gate is found."""
# this is invalid duration pulse
# this will cause backend error since this doesn't fit with waveform memory chunk.
custom_gate = pulse.Schedule(name="custom_x_gate")
custom_gate.insert(
0, pulse.Play(pulse.Constant(32, 0.1), pulse.DriveChannel(0)), inplace=True
)
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.add_calibration("x", qubits=(0,), schedule=custom_gate)
with self.assertRaises(TranspilerError):
self.pulse_gate_validation_pass(circuit)
def test_short_pulse_duration_multiple_pulse(self):
"""Kill pass manager if invalid pulse gate is found."""
# this is invalid duration pulse
# however total gate schedule length is 64, which accidentally satisfies the constraints
# this should fail in the validation
custom_gate = pulse.Schedule(name="custom_x_gate")
custom_gate.insert(
0, pulse.Play(pulse.Constant(32, 0.1), pulse.DriveChannel(0)), inplace=True
)
custom_gate.insert(
32, pulse.Play(pulse.Constant(32, 0.1), pulse.DriveChannel(0)), inplace=True
)
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.add_calibration("x", qubits=(0,), schedule=custom_gate)
with self.assertRaises(TranspilerError):
self.pulse_gate_validation_pass(circuit)
def test_valid_pulse_duration(self):
"""No error raises if valid calibration is provided."""
# this is valid duration pulse
custom_gate = pulse.Schedule(name="custom_x_gate")
custom_gate.insert(
0, pulse.Play(pulse.Constant(160, 0.1), pulse.DriveChannel(0)), inplace=True
)
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.add_calibration("x", qubits=(0,), schedule=custom_gate)
# just not raise an error
self.pulse_gate_validation_pass(circuit)
def test_no_calibration(self):
"""No error raises if no calibration is addedd."""
circuit = QuantumCircuit(1)
circuit.x(0)
# just not raise an error
self.pulse_gate_validation_pass(circuit)
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the QAOA algorithm with opflow."""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from functools import partial
import numpy as np
from scipy.optimize import minimize as scipy_minimize
from ddt import ddt, idata, unpack
import rustworkx as rx
from qiskit import QuantumCircuit
from qiskit_algorithms.minimum_eigensolvers import QAOA
from qiskit_algorithms.optimizers import COBYLA, NELDER_MEAD
from qiskit.circuit import Parameter
from qiskit.opflow import PauliSumOp
from qiskit.quantum_info import Pauli
from qiskit.result import QuasiDistribution
from qiskit.primitives import Sampler
from qiskit.utils import algorithm_globals
I = PauliSumOp.from_list([("I", 1)])
X = PauliSumOp.from_list([("X", 1)])
W1 = np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]])
P1 = 1
M1 = (I ^ I ^ I ^ X) + (I ^ I ^ X ^ I) + (I ^ X ^ I ^ I) + (X ^ I ^ I ^ I)
S1 = {"0101", "1010"}
W2 = np.array(
[
[0.0, 8.0, -9.0, 0.0],
[8.0, 0.0, 7.0, 9.0],
[-9.0, 7.0, 0.0, -8.0],
[0.0, 9.0, -8.0, 0.0],
]
)
P2 = 1
M2 = None
S2 = {"1011", "0100"}
CUSTOM_SUPERPOSITION = [1 / np.sqrt(15)] * 15 + [0]
@ddt
class TestQAOA(QiskitAlgorithmsTestCase):
"""Test QAOA with MaxCut."""
def setUp(self):
super().setUp()
self.seed = 10598
algorithm_globals.random_seed = self.seed
self.sampler = Sampler()
@idata(
[
[W1, P1, M1, S1],
[W2, P2, M2, S2],
]
)
@unpack
def test_qaoa(self, w, reps, mixer, solutions):
"""QAOA test"""
self.log.debug("Testing %s-step QAOA with MaxCut on graph\n%s", reps, w)
qubit_op, _ = self._get_operator(w)
qaoa = QAOA(self.sampler, COBYLA(), reps=reps, mixer=mixer)
with self.assertWarns(DeprecationWarning):
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
self.assertIn(graph_solution, solutions)
@idata(
[
[W1, P1, S1],
[W2, P2, S2],
]
)
@unpack
def test_qaoa_qc_mixer(self, w, prob, solutions):
"""QAOA test with a mixer as a parameterized circuit"""
self.log.debug(
"Testing %s-step QAOA with MaxCut on graph with a mixer as a parameterized circuit\n%s",
prob,
w,
)
optimizer = COBYLA()
qubit_op, _ = self._get_operator(w)
num_qubits = qubit_op.num_qubits
mixer = QuantumCircuit(num_qubits)
theta = Parameter("θ")
mixer.rx(theta, range(num_qubits))
qaoa = QAOA(self.sampler, optimizer, reps=prob, mixer=mixer)
with self.assertWarns(DeprecationWarning):
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
self.assertIn(graph_solution, solutions)
def test_qaoa_qc_mixer_many_parameters(self):
"""QAOA test with a mixer as a parameterized circuit with the num of parameters > 1."""
optimizer = COBYLA()
qubit_op, _ = self._get_operator(W1)
num_qubits = qubit_op.num_qubits
mixer = QuantumCircuit(num_qubits)
for i in range(num_qubits):
theta = Parameter("θ" + str(i))
mixer.rx(theta, range(num_qubits))
qaoa = QAOA(self.sampler, optimizer, reps=2, mixer=mixer)
with self.assertWarns(DeprecationWarning):
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
self.log.debug(x)
graph_solution = self._get_graph_solution(x)
self.assertIn(graph_solution, S1)
def test_qaoa_qc_mixer_no_parameters(self):
"""QAOA test with a mixer as a parameterized circuit with zero parameters."""
qubit_op, _ = self._get_operator(W1)
num_qubits = qubit_op.num_qubits
mixer = QuantumCircuit(num_qubits)
# just arbitrary circuit
mixer.rx(np.pi / 2, range(num_qubits))
qaoa = QAOA(self.sampler, COBYLA(), reps=1, mixer=mixer)
with self.assertWarns(DeprecationWarning):
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
# we just assert that we get a result, it is not meaningful.
self.assertIsNotNone(result.eigenstate)
def test_change_operator_size(self):
"""QAOA change operator size test"""
qubit_op, _ = self._get_operator(
np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]])
)
qaoa = QAOA(self.sampler, COBYLA(), reps=1)
with self.assertWarns(DeprecationWarning):
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
with self.subTest(msg="QAOA 4x4"):
self.assertIn(graph_solution, {"0101", "1010"})
qubit_op, _ = self._get_operator(
np.array(
[
[0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0],
]
)
)
with self.assertWarns(DeprecationWarning):
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
with self.subTest(msg="QAOA 6x6"):
self.assertIn(graph_solution, {"010101", "101010"})
@idata([[W2, S2, None], [W2, S2, [0.0, 0.0]], [W2, S2, [1.0, 0.8]]])
@unpack
def test_qaoa_initial_point(self, w, solutions, init_pt):
"""Check first parameter value used is initial point as expected"""
qubit_op, _ = self._get_operator(w)
first_pt = []
def cb_callback(eval_count, parameters, mean, metadata):
nonlocal first_pt
if eval_count == 1:
first_pt = list(parameters)
qaoa = QAOA(
self.sampler,
COBYLA(),
initial_point=init_pt,
callback=cb_callback,
)
with self.assertWarns(DeprecationWarning):
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
with self.subTest("Initial Point"):
# If None the preferred random initial point of QAOA variational form
if init_pt is None:
self.assertLess(result.eigenvalue, -0.97)
else:
self.assertListEqual(init_pt, first_pt)
with self.subTest("Solution"):
self.assertIn(graph_solution, solutions)
def test_qaoa_random_initial_point(self):
"""QAOA random initial point"""
w = rx.adjacency_matrix(
rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed)
)
qubit_op, _ = self._get_operator(w)
qaoa = QAOA(self.sampler, NELDER_MEAD(disp=True), reps=2)
with self.assertWarns(DeprecationWarning):
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
self.assertLess(result.eigenvalue, -0.97)
def test_optimizer_scipy_callable(self):
"""Test passing a SciPy optimizer directly as callable."""
w = rx.adjacency_matrix(
rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed)
)
qubit_op, _ = self._get_operator(w)
qaoa = QAOA(
self.sampler,
partial(scipy_minimize, method="Nelder-Mead", options={"maxiter": 2}),
)
with self.assertWarns(DeprecationWarning):
result = qaoa.compute_minimum_eigenvalue(qubit_op)
self.assertEqual(result.cost_function_evals, 5)
def _get_operator(self, weight_matrix):
"""Generate Hamiltonian for the max-cut problem of a graph.
Args:
weight_matrix (numpy.ndarray) : adjacency matrix.
Returns:
PauliSumOp: operator for the Hamiltonian
float: a constant shift for the obj function.
"""
num_nodes = weight_matrix.shape[0]
pauli_list = []
shift = 0
for i in range(num_nodes):
for j in range(i):
if weight_matrix[i, j] != 0:
x_p = np.zeros(num_nodes, dtype=bool)
z_p = np.zeros(num_nodes, dtype=bool)
z_p[i] = True
z_p[j] = True
pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))])
shift -= 0.5 * weight_matrix[i, j]
opflow_list = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list]
with self.assertWarns(DeprecationWarning):
return PauliSumOp.from_list(opflow_list), shift
def _get_graph_solution(self, x: np.ndarray) -> str:
"""Get graph solution from binary string.
Args:
x : binary string as numpy array.
Returns:
a graph solution as string.
"""
return "".join([str(int(i)) for i in 1 - x])
def _sample_most_likely(self, state_vector: QuasiDistribution) -> np.ndarray:
"""Compute the most likely binary string from state vector.
Args:
state_vector: Quasi-distribution.
Returns:
Binary string as numpy.ndarray of ints.
"""
values = list(state_vector.values())
n = int(np.log2(len(values)))
k = np.argmax(np.abs(values))
x = np.zeros(n)
for i in range(n):
x[i] = k % 2
k >>= 1
return x
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import logging
import time
from qiskit import __version__ as terra_version
from qiskit.assembler.run_config import RunConfig
from qiskit.transpiler import Layout
from .utils import (run_qobjs, compile_circuits, CircuitCache,
get_measured_qubits_from_qobj,
build_measurement_error_mitigation_fitter,
mitigate_measurement_error)
from .utils.backend_utils import (is_aer_provider,
is_ibmq_provider,
is_statevector_backend,
is_simulator_backend,
is_local_backend)
logger = logging.getLogger(__name__)
class QuantumInstance:
"""Quantum Backend including execution setting."""
BACKEND_CONFIG = ['basis_gates', 'coupling_map']
COMPILE_CONFIG = ['pass_manager', 'initial_layout', 'seed_transpiler']
RUN_CONFIG = ['shots', 'max_credits', 'memory', 'seed']
QJOB_CONFIG = ['timeout', 'wait']
NOISE_CONFIG = ['noise_model']
# https://github.com/Qiskit/qiskit-aer/blob/master/qiskit/providers/aer/backends/qasm_simulator.py
BACKEND_OPTIONS_QASM_ONLY = ["statevector_sample_measure_opt", "max_parallel_shots"]
BACKEND_OPTIONS = ["initial_statevector", "chop_threshold", "max_parallel_threads",
"max_parallel_experiments", "statevector_parallel_threshold",
"statevector_hpc_gate_opt"] + BACKEND_OPTIONS_QASM_ONLY
def __init__(self, backend, shots=1024, seed=None, max_credits=10,
basis_gates=None, coupling_map=None,
initial_layout=None, pass_manager=None, seed_transpiler=None,
backend_options=None, noise_model=None, timeout=None, wait=5,
circuit_caching=True, cache_file=None, skip_qobj_deepcopy=True,
skip_qobj_validation=True, measurement_error_mitigation_cls=None,
cals_matrix_refresh_period=30):
"""Constructor.
Args:
backend (BaseBackend): instance of selected backend
shots (int, optional): number of repetitions of each circuit, for sampling
seed (int, optional): random seed for simulators
max_credits (int, optional): maximum credits to use
basis_gates (list[str], optional): list of basis gate names supported by the
target. Default: ['u1','u2','u3','cx','id']
coupling_map (list[list]): coupling map (perhaps custom) to target in mapping
initial_layout (dict, optional): initial layout of qubits in mapping
pass_manager (PassManager, optional): pass manager to handle how to compile the circuits
seed_transpiler (int, optional): the random seed for circuit mapper
backend_options (dict, optional): all running options for backend, please refer to the provider.
noise_model (qiskit.provider.aer.noise.noise_model.NoiseModel, optional): noise model for simulator
timeout (float, optional): seconds to wait for job. If None, wait indefinitely.
wait (float, optional): seconds between queries to result
circuit_caching (bool, optional): USe CircuitCache when calling compile_and_run_circuits
cache_file(str, optional): filename into which to store the cache as a pickle file
skip_qobj_deepcopy (bool, optional): Reuses the same qobj object over and over to avoid deepcopying
skip_qobj_validation (bool, optional): Bypass Qobj validation to decrease submission time
measurement_error_mitigation_cls (callable, optional): the approach to mitigate measurement error,
CompleteMeasFitter or TensoredMeasFitter
cals_matrix_refresh_period (int): how long to refresh the calibration matrix in measurement mitigation,
unit in minutes
"""
self._backend = backend
# setup run config
run_config = RunConfig(shots=shots, max_credits=max_credits)
if seed:
run_config.seed = seed
if getattr(run_config, 'shots', None) is not None:
if self.is_statevector and run_config.shots != 1:
logger.info("statevector backend only works with shot=1, change "
"shots from {} to 1.".format(run_config.shots))
run_config.shots = 1
self._run_config = run_config
# setup backend config
basis_gates = basis_gates or backend.configuration().basis_gates
coupling_map = coupling_map or getattr(backend.configuration(),
'coupling_map', None)
self._backend_config = {
'basis_gates': basis_gates,
'coupling_map': coupling_map
}
# setup noise config
noise_config = None
if noise_model is not None:
if is_aer_provider(self._backend):
if not self.is_statevector:
noise_config = noise_model
else:
logger.info("The noise model can be only used with Aer qasm simulator. "
"Change it to None.")
else:
logger.info("The noise model can be only used with Qiskit Aer. "
"Please install it.")
self._noise_config = {} if noise_config is None else {'noise_model': noise_config}
# setup compile config
if initial_layout is not None and not isinstance(initial_layout, Layout):
initial_layout = Layout(initial_layout)
self._compile_config = {
'pass_manager': pass_manager,
'initial_layout': initial_layout,
'seed_transpiler': seed_transpiler
}
# setup job config
self._qjob_config = {'timeout': timeout} if self.is_local \
else {'timeout': timeout, 'wait': wait}
# setup backend options for run
self._backend_options = {}
if is_ibmq_provider(self._backend):
logger.info("backend_options can not used with the backends in IBMQ provider.")
else:
self._backend_options = {} if backend_options is None \
else {'backend_options': backend_options}
self._shared_circuits = False
self._circuit_summary = False
self._circuit_cache = CircuitCache(skip_qobj_deepcopy=skip_qobj_deepcopy,
cache_file=cache_file) if circuit_caching else None
self._skip_qobj_validation = skip_qobj_validation
self._measurement_error_mitigation_cls = None
if self.is_statevector:
if measurement_error_mitigation_cls is not None:
logger.info("Measurement error mitigation does not work with statevector simulation, disable it.")
else:
self._measurement_error_mitigation_cls = measurement_error_mitigation_cls
self._measurement_error_mitigation_fitter = None
self._measurement_error_mitigation_method = 'least_squares'
self._cals_matrix_refresh_period = cals_matrix_refresh_period
self._prev_timestamp = 0
if self._measurement_error_mitigation_cls is not None:
logger.info("The measurement error mitigation is enable. "
"It will automatically submit an additional job to help calibrate the result of other jobs. "
"The current approach will submit a job with 2^N circuits to build the calibration matrix, "
"where N is the number of measured qubits. "
"Furthermore, Aqua will re-use the calibration matrix for {} minutes "
"and re-build it after that.".format(self._cals_matrix_refresh_period))
logger.info(self)
def __str__(self):
"""Overload string.
Returns:
str: the info of the object.
"""
info = "\nQiskit Terra version: {}\n".format(terra_version)
info += "Backend: '{} ({})', with following setting:\n{}\n{}\n{}\n{}\n{}\n{}".format(
self.backend_name, self._backend.provider(), self._backend_config, self._compile_config,
self._run_config, self._qjob_config, self._backend_options, self._noise_config)
info += "\nMeasurement mitigation: {}".format(self._measurement_error_mitigation_cls)
return info
def execute(self, circuits, **kwargs):
"""
A wrapper to interface with quantum backend.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute
Returns:
Result: Result object
"""
qobjs = compile_circuits(circuits, self._backend, self._backend_config, self._compile_config, self._run_config,
show_circuit_summary=self._circuit_summary, circuit_cache=self._circuit_cache,
**kwargs)
if self._measurement_error_mitigation_cls is not None:
if self.maybe_refresh_cals_matrix():
logger.info("Building calibration matrix for measurement error mitigation.")
qubit_list = get_measured_qubits_from_qobj(qobjs)
self._measurement_error_mitigation_fitter = build_measurement_error_mitigation_fitter(qubit_list,
self._measurement_error_mitigation_cls,
self._backend,
self._backend_config,
self._compile_config,
self._run_config,
self._qjob_config,
self._backend_options,
self._noise_config)
result = run_qobjs(qobjs, self._backend, self._qjob_config, self._backend_options, self._noise_config,
self._skip_qobj_validation)
if self._measurement_error_mitigation_fitter is not None:
result = mitigate_measurement_error(result, self._measurement_error_mitigation_fitter,
self._measurement_error_mitigation_method)
if self._circuit_summary:
self._circuit_summary = False
return result
def set_config(self, **kwargs):
"""Set configurations for the quantum instance."""
for k, v in kwargs.items():
if k in QuantumInstance.RUN_CONFIG:
setattr(self._run_config, k, v)
elif k in QuantumInstance.QJOB_CONFIG:
self._qjob_config[k] = v
elif k in QuantumInstance.COMPILE_CONFIG:
self._compile_config[k] = v
elif k in QuantumInstance.BACKEND_CONFIG:
self._backend_config[k] = v
elif k in QuantumInstance.BACKEND_OPTIONS:
if is_ibmq_provider(self._backend):
logger.info("backend_options can not used with the backends in IBMQ provider.")
else:
if k in QuantumInstance.BACKEND_OPTIONS_QASM_ONLY and self.is_statevector:
logger.info("'{}' is only applicable for qasm simulator but "
"statevector simulator is used. Skip the setting.")
else:
if 'backend_options' not in self._backend_options:
self._backend_options['backend_options'] = {}
self._backend_options['backend_options'][k] = v
elif k in QuantumInstance.NOISE_CONFIG:
self._noise_config[k] = v
else:
raise ValueError("unknown setting for the key ({}).".format(k))
@property
def qjob_config(self):
"""Getter of qjob_config."""
return self._qjob_config
@property
def backend_config(self):
"""Getter of backend_config."""
return self._backend_config
@property
def compile_config(self):
"""Getter of compile_config."""
return self._compile_config
@property
def run_config(self):
"""Getter of run_config."""
return self._run_config
@property
def noise_config(self):
"""Getter of noise_config."""
return self._noise_config
@property
def backend_options(self):
"""Getter of backend_options."""
return self._backend_options
@property
def shared_circuits(self):
"""Getter of shared_circuits."""
return self._shared_circuits
@shared_circuits.setter
def shared_circuits(self, new_value):
self._shared_circuits = new_value
@property
def circuit_summary(self):
"""Getter of circuit summary."""
return self._circuit_summary
@circuit_summary.setter
def circuit_summary(self, new_value):
self._circuit_summary = new_value
@property
def backend(self):
"""Return BaseBackend backend object."""
return self._backend
@property
def backend_name(self):
"""Return backend name."""
return self._backend.name()
@property
def is_statevector(self):
"""Return True if backend is a statevector-type simulator."""
return is_statevector_backend(self._backend)
@property
def is_simulator(self):
"""Return True if backend is a simulator."""
return is_simulator_backend(self._backend)
@property
def is_local(self):
"""Return True if backend is a local backend."""
return is_local_backend(self._backend)
@property
def circuit_cache(self):
return self._circuit_cache
@property
def has_circuit_caching(self):
return self._circuit_cache is not None
@property
def skip_qobj_validation(self):
return self._skip_qobj_validation
@skip_qobj_validation.setter
def skip_qobj_validation(self, new_value):
self._skip_qobj_validation = new_value
def maybe_refresh_cals_matrix(self):
"""
Calculate the time difference from the query of last time.
Returns:
bool: whether or not refresh the cals_matrix
"""
ret = False
curr_timestamp = time.time()
difference = int(curr_timestamp - self._prev_timestamp) / 60.0
if difference > self._cals_matrix_refresh_period:
self._prev_timestamp = curr_timestamp
ret = True
return ret
@property
def cals_matrix(self):
cals_matrix = None
if self._measurement_error_mitigation_fitter is not None:
cals_matrix = self._measurement_error_mitigation_fitter.cal_matrix
return cals_matrix
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeAuckland
backend = FakeAuckland()
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
ghz.draw(output='mpl')
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019, 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 Skip Qobj Validation"""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer
from qiskit.utils import QuantumInstance
from qiskit.exceptions import QiskitError
def _compare_dict(dict1, dict2):
equal = True
for key1, value1 in dict1.items():
if key1 not in dict2:
equal = False
break
if value1 != dict2[key1]:
equal = False
break
return equal
class TestSkipQobjValidation(QiskitAlgorithmsTestCase):
"""Test Skip Qobj Validation"""
def setUp(self):
super().setUp()
self.random_seed = 10598
# ┌───┐ ░ ┌─┐ ░
# q0_0: ┤ H ├──■───░─┤M├─░────
# └───┘┌─┴─┐ ░ └╥┘ ░ ┌─┐
# q0_1: ─────┤ X ├─░──╫──░─┤M├
# └───┘ ░ ║ ░ └╥┘
# c0: 2/══════════════╩═════╩═
# 0 1
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
qc.cx(qr[0], qr[1])
# Ensure qubit 0 is measured before qubit 1
qc.barrier(qr)
qc.measure(qr[0], cr[0])
qc.barrier(qr)
qc.measure(qr[1], cr[1])
self.qc = qc
self.backend = BasicAer.get_backend("qasm_simulator")
def test_wo_backend_options(self):
"""without backend options test"""
with self.assertWarns(DeprecationWarning):
quantum_instance = QuantumInstance(
self.backend,
seed_transpiler=self.random_seed,
seed_simulator=self.random_seed,
shots=1024,
)
# run without backend_options and without noise
res_wo_bo = quantum_instance.execute(self.qc).get_counts(self.qc)
self.assertGreaterEqual(quantum_instance.time_taken, 0.0)
quantum_instance.reset_execution_results()
quantum_instance.skip_qobj_validation = True
res_wo_bo_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc)
self.assertGreaterEqual(quantum_instance.time_taken, 0.0)
quantum_instance.reset_execution_results()
self.assertTrue(_compare_dict(res_wo_bo, res_wo_bo_skip_validation))
def test_w_backend_options(self):
"""with backend options test"""
# run with backend_options
with self.assertWarns(DeprecationWarning):
quantum_instance = QuantumInstance(
self.backend,
seed_transpiler=self.random_seed,
seed_simulator=self.random_seed,
shots=1024,
backend_options={"initial_statevector": [0.5, 0.5, 0.5, 0.5]},
)
res_w_bo = quantum_instance.execute(self.qc).get_counts(self.qc)
self.assertGreaterEqual(quantum_instance.time_taken, 0.0)
quantum_instance.reset_execution_results()
quantum_instance.skip_qobj_validation = True
res_w_bo_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc)
self.assertGreaterEqual(quantum_instance.time_taken, 0.0)
quantum_instance.reset_execution_results()
self.assertTrue(_compare_dict(res_w_bo, res_w_bo_skip_validation))
def test_w_noise(self):
"""with noise test"""
# build noise model
# Asymmetric readout error on qubit-0 only
try:
from qiskit.providers.aer.noise import NoiseModel
from qiskit import Aer
self.backend = Aer.get_backend("qasm_simulator")
except ImportError as ex:
self.skipTest(f"Aer doesn't appear to be installed. Error: '{str(ex)}'")
return
probs_given0 = [0.9, 0.1]
probs_given1 = [0.3, 0.7]
noise_model = NoiseModel()
noise_model.add_readout_error([probs_given0, probs_given1], [0])
with self.assertWarns(DeprecationWarning):
quantum_instance = QuantumInstance(
self.backend,
seed_transpiler=self.random_seed,
seed_simulator=self.random_seed,
shots=1024,
noise_model=noise_model,
)
res_w_noise = quantum_instance.execute(self.qc).get_counts(self.qc)
quantum_instance.skip_qobj_validation = True
res_w_noise_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc)
self.assertTrue(_compare_dict(res_w_noise, res_w_noise_skip_validation))
with self.assertWarns(DeprecationWarning):
# BasicAer should fail:
with self.assertRaises(QiskitError):
_ = QuantumInstance(BasicAer.get_backend("qasm_simulator"), noise_model=noise_model)
with self.assertRaises(QiskitError):
quantum_instance = QuantumInstance(BasicAer.get_backend("qasm_simulator"))
quantum_instance.set_config(noise_model=noise_model)
if __name__ == "__main__":
unittest.main()
|
https://github.com/suvoooo/Qubits-Qiskit
|
suvoooo
|
# !pip install qiskit
import math
import matplotlib.pyplot as plt
import numpy as np
import qiskit as q
from qiskit.visualization import plot_bloch_vector, plot_state_city
from google.colab import drive
drive.mount('/content/drive')
path = '/content/drive/My Drive/Colab Notebooks/Quantum_Compute/'
coords = [1, math.pi/2, math.pi]
plot_bloch_vector(coords, coord_type='spherical', figsize=(6, 6), )
## check density matrix from state vector
initial_state1 = [0.j + 1./np.sqrt(2), 0, 0, 1/np.sqrt(2) + 0.j]
initial_state2 = [0.j + 1./2., 0, 0, 0.j + np.sqrt(3)/2.]
m1 = q.quantum_info.Statevector(initial_state1)
print ('check the first statevector: ', m1)
m2 = q.quantum_info.Statevector(initial_state2)
print ('check the first statevector: ', m2)
rho_1 = q.quantum_info.DensityMatrix(m1, dims=4)
print ('check the density matrix corresponding to 1st statevector: ', '\n', rho_1)
rho_2 = q.quantum_info.DensityMatrix(m2, dims=4)
print ('check the density matrix corresponding to 2nd statevector: ', '\n', rho_2)
rho_1.draw('latex', prefix='\\rho_{1} = ')
plot_state_city(rho_1.data, title=r'Density Matrix for StateVector: $\frac{1}{\sqrt{2}}\left(|0\rangle + |1\rangle\right)$',
color=['magenta', 'purple'], alpha=0.7, figsize=(11, 7), )
rho_2.draw('latex', prefix='\\rho_{2} = ')
plot_state_city(rho_2.data, title=r'Density Matrix for StateVector: $\left(\frac{1}{2}|0\rangle + \frac{\sqrt{3}}{2}|1\rangle\right)$',
color=['magenta', 'purple'], alpha=0.7, figsize=(11, 7), )
rho_H_matrix = np.array([[9/20, 0, 0, np.sqrt(3)/20 + 8/20], [0, 0, 0, 0], [0, 0, 0, 0], [np.sqrt(3)/20 + 8/20, 0, 0, 11/20]])
rho_H = q.quantum_info.DensityMatrix(rho_H_matrix)
rho_H.draw('latex', prefix='\\rho_{mix} = ')
final_density_matrix = 0.8*rho_1 + 0.2*rho_2
check_rho_H = q.quantum_info.DensityMatrix(final_density_matrix)
check_rho_H.draw('latex', prefix='\\rho_{mix} = ')
### check the first property
rho_H_matrix_square = np.matmul(rho_H_matrix, rho_H_matrix)
rho_H_square = q.quantum_info.DensityMatrix(rho_H_matrix_square)
rho_H_matrix_square_Trace = np.trace(rho_H_matrix_square)
print ('Trace of the square of the density matrix: ', rho_H_matrix_square_Trace)
rho_H_square.draw('latex', prefix='\\rho_{mix}^2 = ')
### check the second property
rho_H_matrix_eigenvals = np.linalg.eigvals(rho_H_matrix)
print ('check the eigenvalues of the density matrix', rho_H_matrix_eigenvals[0], rho_H_matrix_eigenvals[1])
print ('check sum of the eigenvalues of the density matrix: ', np.sum(rho_H_matrix_eigenvals))
plot_state_city(check_rho_H.data,
title=r'Density Matrix for Mixed State: $0.8\times\frac{1}{\sqrt{2}}\left(|0\rangle + |1\rangle\right) + 0.2\times \left(\frac{1}{2}|0\rangle + \frac{\sqrt{3}}{2}|1\rangle\right)$',
color=['crimson', 'purple'], alpha=0.4, figsize=(11, 7), )
reduced_density_matrix = np.array([[9/20, np.sqrt(3)/20 + 8/20], [np.sqrt(3)/20 + 8/20, 11/20]])
red_rho_H = q.quantum_info.DensityMatrix(reduced_density_matrix)
red_rho_H.draw('latex', prefix='\\rho_{mix} = ')
from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(state=red_rho_H.data, figsize=(6, 6), )
|
https://github.com/thyung/qiskit_factorization
|
thyung
|
N = 37 * 31
a = 29
print(N)
import math
math.gcd(a, N)
import matplotlib.pyplot as plt
z = range(N)
y = [a**z0 % N for z0 in z]
plt.plot(z, y)
plt.xlabel('z')
plt.ylabel('{}^z mod {}'.format(a, N))
plt.show()
r = y[1:].index(1)+1
print(r)
if r%2 == 0:
x = (a**(r//2)) % N
print('x = {}'.format(x))
if ((x+1)%N) != 0:
print(math.gcd(int(x)+1, N), math.gcd(int(x)-1, N))
else:
print('x+1 % N = 0')
else:
print('r = {} is odd'.format(r))
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
from hide_toggle import hide_toggle
#usage:
#1 create a cell with: hide_toggle(for_next=True)
#2 put the commented solution in the next cell
import qiskit as qk
import numpy as np
from scipy.linalg import expm
import matplotlib.pyplot as plt
import math
# definition of single qubit operators
sx = np.array([[0.0, 1.0],[1.0, 0.0]])
sy = np.array([[0.0, -1.0*1j],[1.0*1j, 0.0]])
sz = np.array([[1.0, 0.0],[0.0, -1.0]])
idt = np.array([[1.0, 0.0],[0.0, 1.0]])
psi0 = np.array([1.0, 0.0])
thetas = np.linspace(0,4*math.pi,200)
avg_sx_tot = np.zeros(len(thetas))
for i in range(len(thetas)):
psi_theta = expm(-1j*0.5*thetas[i]*(sx+sz)/math.sqrt(2)).dot(psi0)
avg_sx_tot[i] = np.real(psi_theta.conjugate().transpose().dot(sx.dot(psi_theta)))
plt.plot(thetas,avg_sx_tot)
plt.xlabel(r'$\theta$')
plt.ylabel(r'$\langle\sigma_x\rangle_\theta$')
plt.show()
#solution
hide_toggle(for_next=True)
#avg_sx_zx = np.zeros(len(thetas))
#avg_sx_xz = np.zeros(len(thetas))
#for i in range(len(thetas)):
# psi_theta_zx = expm(-1j*0.5*thetas[i]*(sz)/math.sqrt(2)).dot(expm(-1j*0.5*thetas[i]*(sx)/math.sqrt(2)).dot(psi0))
# psi_theta_xz = expm(-1j*0.5*thetas[i]*(sx)/math.sqrt(2)).dot(expm(-1j*0.5*thetas[i]*(sz)/math.sqrt(2)).dot(psi0))
# avg_sx_zx[i] = np.real(psi_theta_zx.conjugate().transpose().dot(sx.dot(psi_theta_zx)))
#avg_sx_xz[i] = np.real(psi_theta_xz.conjugate().transpose().dot(sx.dot(psi_theta_xz)))
#plt.plot(thetas,avg_sx_tot)
#plt.plot(thetas,avg_sx_zx)
#plt.plot(thetas,avg_sx_xz)
#plt.xlabel(r'$\theta$')
#plt.ylabel(r'$\langle\sigma_x\rangle_\theta$')
#plt.legend(['Around x = z', 'x first', 'z first'],loc=1)
#plt.show()
# Try this with e.g. ntrot = 1, 5, 10, 50.
# You can also try to do sx and sz slices in the reverse order: both choices will become good approximations for large n
ntrot = 10
avg_sx_n = np.zeros(len(thetas))
for i in range(len(thetas)):
rot = expm(-1j*0.5*thetas[i]*(sx)/(ntrot*math.sqrt(2))).dot(expm(-1j*0.5*thetas[i]*(sz)/(ntrot*math.sqrt(2))))
for j in range(ntrot-1):
rot = expm(-1j*0.5*thetas[i]*(sx)/(ntrot*math.sqrt(2))).dot(expm(-1j*0.5*thetas[i]*(sz)/(ntrot*math.sqrt(2)))).dot(rot)
psi_theta_n = rot.dot(psi0)
avg_sx_n[i] = np.real(psi_theta_n.conjugate().transpose().dot(sx.dot(psi_theta_n)))
plt.plot(thetas,avg_sx_tot)
plt.plot(thetas,avg_sx_n,'--')
plt.xlabel(r'$\theta$')
plt.ylabel(r'$\langle\sigma_x\rangle_\theta$')
plt.legend(['Exact', 'ntrot = ' + str(ntrot)],loc=1)
plt.show()
#solution
hide_toggle(for_next=True)
# commutation function
#def comm_check(a,b):
# aa = np.dot(a,a)
# bb = np.dot(b,b)
# return (np.dot(aa,bb) - np.dot(bb,aa))
#comm_check(sx,sy)
delta = 0.1
qr = qk.QuantumRegister(2,name='qr')
zz_example = qk.QuantumCircuit(qr)
zz_example.cx(qr[0],qr[1])
zz_example.u1(2*delta,qr[1])
zz_example.cx(qr[0],qr[1])
zz_example.draw(output='mpl')
#solution
J = 1
c_times = np.linspace(0,0.5*math.pi/abs(J),1000)
q_times = np.linspace(0,0.5*math.pi/abs(J),10)
### Classical simulation of the Heisenberg dimer model
psi0 = np.kron( np.array([0,1]), np.array([1,0]) )
H = J * ( np.kron(sx,sx) + np.kron(sy,sy) + np.kron(sz,sz) )
sz1_t = np.zeros(len(c_times))
sz2_t = np.zeros(len(c_times))
sz1 = np.kron(sz,idt)
sz2 = np.kron(idt,sz)
for i in range(len(c_times)):
t = c_times[i]
psi_t = expm(-1j*H*t).dot(psi0)
sz1_t[i] = np.real(psi_t.conjugate().transpose().dot(sz1.dot(psi_t)))
sz2_t[i] = np.real(psi_t.conjugate().transpose().dot(sz2.dot(psi_t)))
### Digital quantum simulation of the Heisenberg dimer model using qiskit
nshots = 1024
sz1q_t = np.zeros(len(q_times))
sz2q_t = np.zeros(len(q_times))
#Solution: try to write the circuit and the quantum evolution,
#hints: start with:
#for k in range(len(q_times)):
#delta =
#define QuantumRegister, ClassicalRegister and QuantumCircuit (Heis2)
#define initial state
#define each part of the circuit: ZZ, YY, XX
#measurement
# Post processing of outcomes to get sz expectation values
#sz1q = 0
#sz2q = 0
#for key,value in counts.items():
#if key == '00':
#sz1q += value
#sz2q += value
#elif key == '01':
#sz1q -= value
#sz2q += value
#elif key == '10':
#sz1q += value
#sz2q -= value
#elif key == '11':
#sz1q -= value
#sz2q -= value
#sz1q_t[k] = sz1q/nshots
#sz2q_t[k] = sz2q/nshots
# Run the quantum algorithm and colect the result, counts
hide_toggle(for_next=True)
#for k in range(len(q_times)):
#delta = J*q_times[k]
#qr = qk.QuantumRegister(2,name='qr')
#cr = qk.ClassicalRegister(2,name='cr')
#Heis2 = qk.QuantumCircuit(qr,cr)
# Initial state preparation
#Heis2.x(qr[0])
# ZZ
#Heis2.cx(qr[0],qr[1])
#Heis2.u1(-2*delta,qr[1])
#Heis2.cx(qr[0],qr[1])
# YY
#Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[0])
#Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
#Heis2.cx(qr[0],qr[1])
#Heis2.u1(-2*delta,qr[1])
#Heis2.cx(qr[0],qr[1])
#Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[0])
#Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
# XX
#Heis2.u3(-math.pi/2, 0.0, 0.0, qr[0])
#Heis2.u3(-math.pi/2, 0.0, 0.0, qr[1])
#Heis2.cx(qr[0],qr[1])
#Heis2.u1(-2*delta,qr[1])
#Heis2.cx(qr[0],qr[1])
#Heis2.u3(math.pi/2, 0.0, 0.0, qr[0])
#Heis2.u3(math.pi/2, 0.0, 0.0, qr[1])
# measure
#Heis2.measure(qr,cr)
# Post processing of outcomes to get sz expectation values
#sz1q = 0
#sz2q = 0
#for key,value in counts.items():
#if key == '00':
#sz1q += value
#sz2q += value
#elif key == '01':
#sz1q -= value
#sz2q += value
#elif key == '10':
#sz1q += value
#sz2q -= value
#elif key == '11':
#sz1q -= value
#sz2q -= value
#sz1q_t[k] = sz1q/nshots
#sz2q_t[k] = sz2q/nshots
# Run the quantum algorithm
#backend = qk.BasicAer.get_backend('qasm_simulator')
#job = qk.execute(Heis2, backend, shots=nshots)
#result = job.result()
#counts = result.get_counts()
plt.plot(abs(J)*c_times,0.5*sz1_t,'b--')
plt.plot(abs(J)*c_times,0.5*sz2_t,'c')
plt.plot(abs(J)*q_times,0.5*sz1q_t,'rd')
plt.plot(abs(J)*q_times,0.5*sz2q_t,'ko')
plt.legend(['sz1','sz2','sz1q','sz2q'])
plt.xlabel(r'$\delta = |J|t$')
plt.show()
# WARNING: all these cells can take a few minutes to run!
ntrotter = 5
J12 = 1
J23 = 1
c_times = np.linspace(0,math.pi/abs(J12),1000)
q_times = np.linspace(0,math.pi/abs(J12),20)
### Classical simulation of the Heisenberg trimer model
psi0 = np.kron( np.kron( np.array([0,1]), np.array([1,0]) ) , np.array([1,0]) )
# SOLUTION:
#sxsx12 = np.kron(sx, np.kron(sx,idt))
#sysy12 =
#szsz12 =
#sxsx23 =
#sysy23 =
#szsz23 =
#H12 = J12 * ( sxsx12 + sysy12 + szsz12 )
#H23 =
#H = H12 + H23
hide_toggle(for_next=True)
#sxsx12 = np.kron(sx, np.kron(sx,idt))
#sysy12 = np.kron(sy, np.kron(sy,idt))
#szsz12 = np.kron(sz, np.kron(sz,idt))
#sxsx23 = np.kron(idt, np.kron(sx,sx))
#sysy23 = np.kron(idt, np.kron(sy,sy))
#szsz23 = np.kron(idt, np.kron(sz,sz))
#H12 = J12 * ( sxsx12 + sysy12 + szsz12 )
#H23 = J23 * ( sxsx23 + sysy23 + szsz23 )
#H = H12 + H23
sz1_t = np.zeros(len(c_times))
sz2_t = np.zeros(len(c_times))
sz3_t = np.zeros(len(c_times))
sz1 = np.kron(sz, np.kron(idt,idt))
sz2 = np.kron(idt, np.kron(sz,idt))
sz3 = np.kron(idt, np.kron(idt,sz))
#SOLUTION:
#for i in range(len(c_times)):
#t = c_times[i]
#psi_t =
#sz1_t[i] =
#sz2_t[i] =
#sz3_t[i] =
hide_toggle(for_next=True)
#for i in range(len(c_times)):
#t = c_times[i]
#psi_t = expm(-1j*H*t).dot(psi0)
#sz1_t[i] = np.real(psi_t.conjugate().transpose().dot(sz1.dot(psi_t)))
#sz2_t[i] = np.real(psi_t.conjugate().transpose().dot(sz2.dot(psi_t)))
#sz3_t[i] = np.real(psi_t.conjugate().transpose().dot(sz3.dot(psi_t)))
### Classical simulation of the Heisenberg trimer model WITH SUZUKI TROTTER DIGITALIZATION
sz1st_t = np.zeros(len(c_times))
sz2st_t = np.zeros(len(c_times))
sz3st_t = np.zeros(len(c_times))
for i in range(len(c_times)):
t = c_times[i]
Ust = expm(-1j*H23*t/ntrotter).dot(expm(-1j*H12*t/ntrotter))
for j in range(ntrotter-1):
Ust = expm(-1j*H23*t/ntrotter).dot(expm(-1j*H12*t/ntrotter)).dot(Ust)
psi_t = Ust.dot(psi0)
sz1st_t[i] = np.real(psi_t.conjugate().transpose().dot(sz1.dot(psi_t)))
sz2st_t[i] = np.real(psi_t.conjugate().transpose().dot(sz2.dot(psi_t)))
sz3st_t[i] = np.real(psi_t.conjugate().transpose().dot(sz3.dot(psi_t)))
### Digital quantum simulation of the Heisenberg model using qiskit
hide_toggle(for_next=True)
### Digital quantum simulation of the Heisenberg model using qiskit
nshots = 1024
sz1q_t = np.zeros(len(q_times))
sz2q_t = np.zeros(len(q_times))
sz3q_t = np.zeros(len(q_times))
for k in range(len(q_times)):
delta12n = J12*q_times[k]/ntrotter
delta23n = J23*q_times[k]/ntrotter
qr = qk.QuantumRegister(3,name='qr')
cr = qk.ClassicalRegister(3,name='cr')
Heis3 = qk.QuantumCircuit(qr,cr)
# Initial state preparation
Heis3.x(qr[0])
for n in range(ntrotter):
# 1-2 bond mapped on qubits 0 and 1 in the quantum register
# ZZ
Heis3.cx(qr[0],qr[1])
Heis3.u1(-2*delta12n,qr[1])
Heis3.cx(qr[0],qr[1])
# YY
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u1(-2*delta12n,qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
# XX
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[0])
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u1(-2*delta12n,qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[0])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[1])
# 2-3 bond mapped on qubits 1 and 2 in the quantum register
# ZZ
Heis3.cx(qr[1],qr[2])
Heis3.u1(-2*delta12n,qr[2])
Heis3.cx(qr[1],qr[2])
# YY
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u1(-2*delta12n,qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[2])
# XX
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u1(-2*delta12n,qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[1])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[2])
# measure
Heis3.measure(qr,cr)
# Run the quantum algorithm
backend = qk.BasicAer.get_backend('qasm_simulator')
job = qk.execute(Heis3, backend, shots=nshots)
result = job.result()
counts = result.get_counts()
# Post processing of outcomes to get sz expectation values
sz1q = 0
sz2q = 0
sz3q = 0
for key,value in counts.items():
if key == '000':
sz1q += value
sz2q += value
sz3q += value
elif key == '001':
sz1q -= value
sz2q += value
sz3q += value
elif key == '010':
sz1q += value
sz2q -= value
sz3q += value
elif key == '011':
sz1q -= value
sz2q -= value
sz3q += value
elif key == '100':
sz1q += value
sz2q += value
sz3q -= value
elif key == '101':
sz1q -= value
sz2q += value
sz3q -= value
elif key == '110':
sz1q += value
sz2q -= value
sz3q -= value
elif key == '111':
sz1q -= value
sz2q -= value
sz3q -= value
sz1q_t[k] = sz1q/nshots
sz2q_t[k] = sz2q/nshots
sz3q_t[k] = sz3q/nshots
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(abs(J12)*c_times,0.5*sz1_t,'b', label='sz1 full')
ax.plot(abs(J12)*c_times,0.5*sz2_t,'r', label='sz2 full')
ax.plot(abs(J12)*c_times,0.5*sz3_t,'g', label='sz3 full')
ax.plot(abs(J12)*c_times,0.5*sz1st_t,'b--',label='sz1 n = ' + str(ntrotter) + ' (classical)')
ax.plot(abs(J12)*c_times,0.5*sz2st_t,'r--', label='sz2 n = ' + str(ntrotter) + ' (classical)')
ax.plot(abs(J12)*c_times,0.5*sz3st_t,'g--', label='sz3 n = ' + str(ntrotter) + ' (classical)')
ax.plot(abs(J12)*q_times,0.5*sz1q_t,'b*',label='sz1 n = ' + str(ntrotter) + ' (quantum)')
ax.plot(abs(J12)*q_times,0.5*sz2q_t,'ro', label='sz2 n = ' + str(ntrotter) + ' (quantum)')
ax.plot(abs(J12)*q_times,0.5*sz3q_t,'gd', label='sz3 n = ' + str(ntrotter) + ' (quantum)')
chartBox = ax.get_position()
ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*1, chartBox.height])
ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.8), shadow=True, ncol=1)
plt.xlabel(r'$\delta_{12} = |J_{12}|t$')
plt.show()
import Qconfig
from qiskit.tools.monitor import job_monitor
qk.IBMQ.enable_account(Qconfig.APItoken, **Qconfig.config)
delta = 0.5*math.pi
qr = qk.QuantumRegister(2,name='qr')
cr = qk.ClassicalRegister(2,name='cr')
Heis2 = qk.QuantumCircuit(qr,cr)
# Initial state preparation
Heis2.x(qr[0])
# ZZ
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
# YY
Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
# XX
Heis2.u3(-math.pi/2, 0.0, 0.0, qr[0])
Heis2.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u3(math.pi/2, 0.0, 0.0, qr[0])
Heis2.u3(math.pi/2, 0.0, 0.0, qr[1])
# measure
Heis2.measure(qr,cr)
my_backend = qk.IBMQ.get_backend('ibmqx4')
job = qk.execute(Heis2, backend=my_backend, shots=1024)
job_monitor(job, interval=5)
result = job.result()
counts = result.get_counts()
print(counts)
plot_histogram(counts)
my_backend.configuration().coupling_map # In the output, the first entry in a pair [a,b] is a control, second is the
# corresponding target for a CNOT
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# Imports
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from qiskit.quantum_info.analyzation.average import average_data
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
IBMQ.load_accounts()
# use simulator to learn more about entangled quantum states where possible
sim_backend = BasicAer.get_backend('qasm_simulator')
sim_shots = 8192
# use device to test entanglement
device_shots = 1024
device_backend = least_busy(IBMQ.backends(operational=True, simulator=False))
print("the best backend is " + device_backend.name())
# Creating registers
q = QuantumRegister(2)
c = ClassicalRegister(2)
# quantum circuit to make an entangled bell state
bell = QuantumCircuit(q, c)
bell.h(q[0])
bell.cx(q[0], q[1])
# quantum circuit to measure q in the standard basis
measureZZ = QuantumCircuit(q, c)
measureZZ.measure(q[0], c[0])
measureZZ.measure(q[1], c[1])
bellZZ = bell+measureZZ
# quantum circuit to measure q in the superposition basis
measureXX = QuantumCircuit(q, c)
measureXX.h(q[0])
measureXX.h(q[1])
measureXX.measure(q[0], c[0])
measureXX.measure(q[1], c[1])
bellXX = bell+measureXX
# quantum circuit to measure ZX
measureZX = QuantumCircuit(q, c)
measureZX.h(q[0])
measureZX.measure(q[0], c[0])
measureZX.measure(q[1], c[1])
bellZX = bell+measureZX
# quantum circuit to measure XZ
measureXZ = QuantumCircuit(q, c)
measureXZ.h(q[1])
measureXZ.measure(q[0], c[0])
measureXZ.measure(q[1], c[1])
bellXZ = bell+measureXZ
circuits = [bellZZ,bellXX,bellZX,bellXZ]
bellZZ.draw(output='mpl')
bellXX.draw(output='mpl')
bellZX.draw(output='mpl')
bellXZ.draw(output='mpl')
job = execute(circuits, backend=device_backend, shots=device_shots)
job_monitor(job)
result = job.result()
observable_first ={'00': 1, '01': -1, '10': 1, '11': -1}
observable_second ={'00': 1, '01': 1, '10': -1, '11': -1}
observable_correlated ={'00': 1, '01': -1, '10': -1, '11': 1}
print('IZ = ' + str(average_data(result.get_counts(bellZZ),observable_first)))
print('ZI = ' + str(average_data(result.get_counts(bellZZ),observable_second)))
print('ZZ = ' + str(average_data(result.get_counts(bellZZ),observable_correlated)))
print('IX = ' + str(average_data(result.get_counts(bellXX),observable_first)))
print('XI = ' + str(average_data(result.get_counts(bellXX),observable_second)))
print('XX = ' + str(average_data(result.get_counts(bellXX),observable_correlated)))
print('ZX = ' + str(average_data(result.get_counts(bellZX),observable_correlated)))
print('XZ = ' + str(average_data(result.get_counts(bellXZ),observable_correlated)))
CHSH = lambda x : x[0]+x[1]+x[2]-x[3]
measure = [measureZZ, measureZX, measureXX, measureXZ]
# Theory
sim_chsh_circuits = []
sim_x = []
sim_steps = 30
for step in range(sim_steps):
theta = 2.0*np.pi*step/30
bell_middle = QuantumCircuit(q,c)
bell_middle.ry(theta,q[0])
for m in measure:
sim_chsh_circuits.append(bell+bell_middle+m)
sim_x.append(theta)
job = execute(sim_chsh_circuits, backend=sim_backend, shots=sim_shots)
result = job.result()
sim_chsh = []
circ = 0
for x in range(len(sim_x)):
temp_chsh = []
for m in range(len(measure)):
temp_chsh.append(average_data(result.get_counts(sim_chsh_circuits[circ].name),observable_correlated))
circ += 1
sim_chsh.append(CHSH(temp_chsh))
# Experiment
real_chsh_circuits = []
real_x = []
real_steps = 10
for step in range(real_steps):
theta = 2.0*np.pi*step/10
bell_middle = QuantumCircuit(q,c)
bell_middle.ry(theta,q[0])
for m in measure:
real_chsh_circuits.append(bell+bell_middle+m)
real_x.append(theta)
job = execute(real_chsh_circuits, backend=device_backend, shots=device_shots)
job_monitor(job)
result = job.result()
real_chsh = []
circ = 0
for x in range(len(real_x)):
temp_chsh = []
for m in range(len(measure)):
temp_chsh.append(average_data(result.get_counts(real_chsh_circuits[circ].name),observable_correlated))
circ += 1
real_chsh.append(CHSH(temp_chsh))
plt.plot(sim_x, sim_chsh, 'r-', real_x, real_chsh, 'bo')
plt.plot([0, 2*np.pi], [2, 2], 'b-')
plt.plot([0, 2*np.pi], [-2, -2], 'b-')
plt.grid()
plt.ylabel('CHSH', fontsize=20)
plt.xlabel(r'$Y(\theta)$', fontsize=20)
plt.show()
print(real_chsh)
# 2 - qubits
# quantum circuit to make GHZ state
q2 = QuantumRegister(2)
c2 = ClassicalRegister(2)
ghz = QuantumCircuit(q2, c2)
ghz.h(q2[0])
ghz.cx(q2[0],q2[1])
# quantum circuit to measure q in standard basis
measureZZ = QuantumCircuit(q2, c2)
measureZZ.measure(q2[0], c2[0])
measureZZ.measure(q2[1], c2[1])
ghzZZ = ghz+measureZZ
measureXX = QuantumCircuit(q2, c2)
measureXX.h(q2[0])
measureXX.h(q2[1])
measureXX.measure(q2[0], c2[0])
measureXX.measure(q2[1], c2[1])
ghzXX = ghz+measureXX
circuits2 = [ghzZZ, ghzXX]
ghzZZ.draw(output='mpl')
ghzXX.draw(output='mpl')
job2 = execute(circuits2, backend=sim_backend, shots=sim_shots)
result2 = job2.result()
plot_histogram(result2.get_counts(ghzZZ))
plot_histogram(result2.get_counts(ghzXX))
# 3 - qubits
# quantum circuit to make GHZ state
q3 = QuantumRegister(3)
c3 = ClassicalRegister(3)
ghz3 = QuantumCircuit(q3, c3)
ghz3.h(q3[0])
ghz3.cx(q3[0],q3[1])
ghz3.cx(q3[1],q3[2])
# quantum circuit to measure q in standard basis
measureZZZ = QuantumCircuit(q3, c3)
measureZZZ.measure(q3[0], c3[0])
measureZZZ.measure(q3[1], c3[1])
measureZZZ.measure(q3[2], c3[2])
ghzZZZ = ghz3+measureZZZ
measureXXX = QuantumCircuit(q3, c3)
measureXXX.h(q3[0])
measureXXX.h(q3[1])
measureXXX.h(q3[2])
measureXXX.measure(q3[0], c3[0])
measureXXX.measure(q3[1], c3[1])
measureXXX.measure(q3[2], c3[2])
ghzXXX = ghz3+measureXXX
circuits3 = [ghzZZZ, ghzXXX]
ghzZZZ.draw(output='mpl')
ghzXXX.draw(output='mpl')
job3 = execute(circuits3, backend=sim_backend, shots=sim_shots)
result3 = job3.result()
plot_histogram(result3.get_counts(ghzZZZ))
plot_histogram(result3.get_counts(ghzXXX))
# 4 - qubits
# quantum circuit to make GHZ state
q4 = QuantumRegister(4)
c4 = ClassicalRegister(4)
ghz4 = QuantumCircuit(q4, c4)
ghz4.h(q4[0])
ghz4.cx(q4[0],q4[1])
ghz4.cx(q4[1],q4[2])
ghz4.h(q4[3])
ghz4.h(q4[2])
ghz4.cx(q4[3],q4[2])
ghz4.h(q4[3])
ghz4.h(q4[2])
# quantum circuit to measure q in standard basis
measureZZZZ = QuantumCircuit(q4, c4)
measureZZZZ.measure(q4[0], c4[0])
measureZZZZ.measure(q4[1], c4[1])
measureZZZZ.measure(q4[2], c4[2])
measureZZZZ.measure(q4[3], c4[3])
ghzZZZZ = ghz4+measureZZZZ
measureXXXX = QuantumCircuit(q4, c4)
measureXXXX.h(q4[0])
measureXXXX.h(q4[1])
measureXXXX.h(q4[2])
measureXXXX.h(q4[3])
measureXXXX.measure(q4[0], c4[0])
measureXXXX.measure(q4[1], c4[1])
measureXXXX.measure(q4[2], c4[2])
measureXXXX.measure(q4[3], c4[3])
ghzXXXX = ghz4+measureXXXX
circuits4 = [ghzZZZZ, ghzXXXX]
ghzZZZZ.draw(output='mpl')
ghzXXXX.draw(output='mpl')
job4 = execute(circuits4, backend=sim_backend, shots=sim_shots)
result4 = job4.result()
plot_histogram(result4.get_counts(ghzZZZZ))
plot_histogram(result4.get_counts(ghzXXXX))
# quantum circuit to make GHZ state
q3 = QuantumRegister(3)
c3 = ClassicalRegister(3)
ghz3 = QuantumCircuit(q3, c3)
ghz3.h(q3[0])
ghz3.cx(q3[0],q3[1])
ghz3.cx(q3[0],q3[2])
# quantum circuit to measure q in standard basis
measureZZZ = QuantumCircuit(q3, c3)
measureZZZ.measure(q3[0], c3[0])
measureZZZ.measure(q3[1], c3[1])
measureZZZ.measure(q3[2], c3[2])
ghzZZZ = ghz3+measureZZZ
circuits5 = [ghzZZZ]
ghzZZZ.draw(output='mpl')
job5 = execute(circuits5, backend=sim_backend, shots=sim_shots)
result5 = job5.result()
plot_histogram(result5.get_counts(ghzZZZ))
MerminM = lambda x : x[0]*x[1]*x[2]*x[3]
observable ={'000': 1, '001': -1, '010': -1, '011': 1, '100': -1, '101': 1, '110': 1, '111': -1}
# quantum circuit to measure q XXX
measureXXX = QuantumCircuit(q3, c3)
measureXXX.h(q3[0])
measureXXX.h(q3[1])
measureXXX.h(q3[2])
measureXXX.measure(q3[0], c3[0])
measureXXX.measure(q3[1], c3[1])
measureXXX.measure(q3[2], c3[2])
ghzXXX = ghz3+measureXXX
# quantum circuit to measure q XYY
measureXYY = QuantumCircuit(q3, c3)
measureXYY.s(q3[1]).inverse()
measureXYY.s(q3[2]).inverse()
measureXYY.h(q3[0])
measureXYY.h(q3[1])
measureXYY.h(q3[2])
measureXYY.measure(q3[0], c3[0])
measureXYY.measure(q3[1], c3[1])
measureXYY.measure(q3[2], c3[2])
ghzXYY = ghz3+measureXYY
# quantum circuit to measure q YXY
measureYXY = QuantumCircuit(q3, c3)
measureYXY.s(q3[0]).inverse()
measureYXY.s(q3[2]).inverse()
measureYXY.h(q3[0])
measureYXY.h(q3[1])
measureYXY.h(q3[2])
measureYXY.measure(q3[0], c3[0])
measureYXY.measure(q3[1], c3[1])
measureYXY.measure(q3[2], c3[2])
ghzYXY = ghz3+measureYXY
# quantum circuit to measure q YYX
measureYYX = QuantumCircuit(q3, c3)
measureYYX.s(q3[0]).inverse()
measureYYX.s(q3[1]).inverse()
measureYYX.h(q3[0])
measureYYX.h(q3[1])
measureYYX.h(q3[2])
measureYYX.measure(q3[0], c3[0])
measureYYX.measure(q3[1], c3[1])
measureYYX.measure(q3[2], c3[2])
ghzYYX = ghz3+measureYYX
circuits6 = [ghzXXX, ghzYYX, ghzYXY, ghzXYY]
ghzXXX.draw(output='mpl')
ghzYYX.draw(output='mpl')
ghzYXY.draw(output='mpl')
ghzXYY.draw(output='mpl')
job6 = execute(circuits6, backend=device_backend, shots=device_shots)
job_monitor(job6)
result6 = job6.result()
temp=[]
temp.append(average_data(result6.get_counts(ghzXXX),observable))
temp.append(average_data(result6.get_counts(ghzYYX),observable))
temp.append(average_data(result6.get_counts(ghzYXY),observable))
temp.append(average_data(result6.get_counts(ghzXYY),observable))
print(MerminM(temp))
|
https://github.com/CynthiaRios/quantum_orchestra
|
CynthiaRios
|

## General Imports
from qiskit import QuantumCircuit, execute
from qiskit import Aer
from shutil import copyfile
from qiskit.visualization import plot_histogram
from qiskit import IBMQ
import qiskit.tools.jupyter
import os
%qiskit_job_watcher
from IPython.display import Audio
import wave
import numpy as np
## Button Display Imports (Needs installations mentioned above)
from IPython.display import display, Markdown, clear_output
# widget packages
import ipywidgets as widgets
from pydub import AudioSegment
 #Will redo on quentin's computer tomorrow (today)
piano_input = [None] * 5
piano = widgets.Dropdown(
options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'],
value='No Gate',
description='Insert a :')
piano2 = widgets.Dropdown(
options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'],
value='No Gate',
description='Insert a :')
piano3 = widgets.Dropdown(
options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'],
value='No Gate',
description='Insert a :')
piano4 = widgets.Dropdown(
options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'],
value='No Gate',
description='Insert a :')
piano5 = widgets.Dropdown(
options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'],
value='No Gate',
description='Insert a :')
box = widgets.VBox([piano, piano2, piano3, piano4, piano5])
box
guitar_input = [None] * 5
guitar = widgets.Dropdown(
options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'],
value='No Gate',
description='Insert a :')
guitar2 = widgets.Dropdown(
options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'],
value='No Gate',
description='Insert a :')
guitar3 = widgets.Dropdown(
options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'],
value='No Gate',
description='Insert a :')
guitar4 = widgets.Dropdown(
options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'],
value='No Gate',
description='Insert a :')
guitar5 = widgets.Dropdown(
options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'],
value='No Gate',
description='Insert a :')
box = widgets.VBox([guitar, guitar2, guitar3, guitar4, guitar5])
box
bass_input = [None] * 5
bass = widgets.Dropdown(
options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'],
value='No Gate',
description='Insert a :')
bass2 = widgets.Dropdown(
options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'],
value='No Gate',
description='Insert a :')
bass3 = widgets.Dropdown(
options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'],
value='No Gate',
description='Insert a :')
bass4 = widgets.Dropdown(
options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'],
value='No Gate',
description='Insert a :')
bass5 = widgets.Dropdown(
options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'],
value='No Gate',
description='Insert a :')
box = widgets.VBox([bass, bass2, bass3, bass4, bass5])
box
trumpet_input = [None] * 5
trumpet = widgets.Dropdown(
options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'],
value='No Gate',
description='Insert a :')
trumpet2 = widgets.Dropdown(
options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'],
value='No Gate',
description='Insert a :')
trumpet3 = widgets.Dropdown(
options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'],
value='No Gate',
description='Insert a :')
trumpet4 = widgets.Dropdown(
options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'],
value='No Gate',
description='Insert a :')
trumpet5 = widgets.Dropdown(
options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'],
value='No Gate',
description='Insert a :')
box = widgets.VBox([trumpet, trumpet2, trumpet3, trumpet4, trumpet5])
box
def GetGates(piano_input, guitar_input, bass_input, trumpet_input):
if (piano.value == 'No Gate'):
piano_input[0] = 'n'
if (piano.value == 'X-Gate'):
piano_input[0] = 'x'
if (piano.value == 'Y-Gate'):
piano_input[0] = 'y'
if (piano.value == 'Z-Gate'):
piano_input[0] = 'z'
if (piano2.value == 'No Gate'):
piano_input[1] = 'n'
if (piano2.value == 'X-Gate'):
piano_input[1] = 'x'
if (piano2.value == 'Y-Gate'):
piano_input[1] = 'y'
if (piano2.value == 'Z-Gate'):
piano_input[1] = 'z'
if (piano3.value == 'No Gate'):
piano_input[2] = 'n'
if (piano3.value == 'X-Gate'):
piano_input[2] = 'x'
if (piano3.value == 'Y-Gate'):
piano_input[2] = 'y'
if (piano3.value == 'Z-Gate'):
piano_input[2] = 'z'
if (piano4.value == 'No Gate'):
piano_input[3] = 'n'
if (piano4.value == 'X-Gate'):
piano_input[3] = 'x'
if (piano4.value == 'Y-Gate'):
piano_input[3] = 'y'
if (piano4.value == 'Z-Gate'):
piano_input[3] = 'z'
if (piano5.value == 'No Gate'):
piano_input[4] = 'n'
if (piano5.value == 'X-Gate'):
piano_input[4] = 'x'
if (piano5.value == 'Y-Gate'):
piano_input[4] = 'y'
if (piano5.value == 'Z-Gate'):
piano_input[4] = 'z'
if (guitar.value == 'No Gate'):
guitar_input[0] = 'n'
if (guitar.value == 'X-Gate'):
guitar_input[0] = 'x'
if (guitar.value == 'Y-Gate'):
guitar_input[0] = 'y'
if (guitar.value == 'Z-Gate'):
guitar_input[0] = 'z'
if (guitar2.value == 'No Gate'):
guitar_input[1] = 'n'
if (guitar2.value == 'X-Gate'):
guitar_input[1] = 'x'
if (guitar2.value == 'Y-Gate'):
guitar_input[1] = 'y'
if (guitar2.value == 'Z-Gate'):
guitar_input[1] = 'z'
if (guitar3.value == 'No Gate'):
guitar_input[2] = 'n'
if (guitar3.value == 'X-Gate'):
guitar_input[2] = 'x'
if (guitar3.value == 'Y-Gate'):
guitar_input[2] = 'y'
if (guitar3.value == 'Z-Gate'):
guitar_input[2] = 'z'
if (guitar4.value == 'No Gate'):
guitar_input[3] = 'n'
if (guitar4.value == 'X-Gate'):
guitar_input[3] = 'x'
if (guitar4.value == 'Y-Gate'):
guitar_input[3] = 'y'
if (guitar4.value == 'Z-Gate'):
guitar_input[3] = 'z'
if (guitar5.value == 'No Gate'):
guitar_input[4] = 'n'
if (guitar5.value == 'X-Gate'):
guitar_input[4] = 'x'
if (guitar5.value == 'Y-Gate'):
guitar_input[4] = 'y'
if (guitar5.value == 'Z-Gate'):
guitar_input[4] = 'z'
if (bass.value == 'No Gate'):
bass_input[0] = 'n'
if (bass.value == 'X-Gate'):
bass_input[0] = 'x'
if (bass.value == 'Y-Gate'):
bass_input[0] = 'y'
if (bass.value == 'Z-Gate'):
bass_input[0] = 'z'
if (bass2.value == 'No Gate'):
bass_input[1] = 'n'
if (bass2.value == 'X-Gate'):
bass_input[1] = 'x'
if (bass2.value == 'Y-Gate'):
bass_input[1] = 'y'
if (bass2.value == 'Z-Gate'):
bass_input[1] = 'z'
if (bass3.value == 'No Gate'):
bass_input[2] = 'n'
if (bass3.value == 'X-Gate'):
bass_input[2] = 'x'
if (bass3.value == 'Y-Gate'):
bass_input[2] = 'y'
if (bass3.value == 'Z-Gate'):
bass_input[2] = 'z'
if (bass4.value == 'No Gate'):
bass_input[3] = 'n'
if (bass4.value == 'X-Gate'):
bass_input[3] = 'x'
if (bass4.value == 'Y-Gate'):
bass_input[3] = 'y'
if (bass4.value == 'Z-Gate'):
bass_input[3] = 'z'
if (bass5.value == 'No Gate'):
bass_input[4] = 'n'
if (bass5.value == 'X-Gate'):
bass_input[4] = 'x'
if (bass5.value == 'Y-Gate'):
bass_input[4] = 'y'
if (bass5.value == 'Z-Gate'):
bass_input[4] = 'z'
if (trumpet.value == 'No Gate'):
trumpet_input[0] = 'n'
if (trumpet.value == 'X-Gate'):
trumpet_input[0] = 'x'
if (trumpet.value == 'Y-Gate'):
trumpet_input[0] = 'y'
if (trumpet.value == 'Z-Gate'):
trumpet_input[0] = 'z'
if (trumpet2.value == 'No Gate'):
trumpet_input[1] = 'n'
if (trumpet2.value == 'X-Gate'):
trumpet_input[1] = 'x'
if (trumpet2.value == 'Y-Gate'):
trumpet_input[1] = 'y'
if (trumpet2.value == 'Z-Gate'):
trumpet_input[1] = 'z'
if (trumpet3.value == 'No Gate'):
trumpet_input[2] = 'n'
if (trumpet3.value == 'X-Gate'):
trumpet_input[2] = 'x'
if (trumpet3.value == 'Y-Gate'):
trumpet_input[2] = 'y'
if (trumpet3.value == 'Z-Gate'):
trumpet_input[2] = 'z'
if (trumpet4.value == 'No Gate'):
trumpet_input[3] = 'n'
if (trumpet4.value == 'X-Gate'):
trumpet_input[3] = 'x'
if (trumpet4.value == 'Y-Gate'):
trumpet_input[3] = 'y'
if (trumpet4.value == 'Z-Gate'):
trumpet_input[3] = 'z'
if (trumpet5.value == 'No Gate'):
trumpet_input[4] = 'n'
if (trumpet5.value == 'X-Gate'):
trumpet_input[4] = 'x'
if (trumpet5.value == 'Y-Gate'):
trumpet_input[4] = 'y'
if (trumpet5.value == 'Z-Gate'):
trumpet_input[4] = 'z'
return (piano_input, guitar_input, bass_input, trumpet_input)
piano_input, guitar_input, bass_input, trumpet_input = GetGates(piano_input, guitar_input, bass_input, trumpet_input)
#minimum user input will just be for them to fill out the create quantum circuit function inthe backend
n = 5 #number of gates
backend = Aer.get_backend('statevector_simulator')
piano_states = []
guitar_states = []
bass_states = []
trumpet_states = []
def CreateQuantumCircuit(piano_input, guitar_input, bass_input, trumpet_input):
cct = QuantumCircuit(4,1)
piano_states = []
guitar_states = []
bass_states = []
trumpet_states = []
for i in range(n-1):
cct.h(i-1)
cct.barrier()
for i in range(n):
if piano_input[i-1] == 'x':
cct.x(0)
if piano_input[i-1] == 'y':
cct.y(0)
if piano_input[i-1] == 'z':
cct.z(0)
piano_states.append(execute(cct, backend).result().get_statevector())
if guitar_input[i-1] == 'x':
cct.x(1)
if guitar_input[i-1] == 'y':
cct.y(1)
if guitar_input[i-1] == 'z':
cct.z(1)
guitar_states.append(execute(cct, backend).result().get_statevector())
if bass_input[i-1] == 'x':
cct.x(2)
if bass_input[i-1] == 'y':
cct.y(2)
if bass_input[i-1] == 'z':
cct.z(2)
bass_states.append(execute(cct, backend).result().get_statevector())
if trumpet_input[i-1] == 'x':
cct.x(3)
if trumpet_input[i-1] == 'y':
cct.y(3)
if trumpet_input[i-1] == 'z':
cct.z(3)
trumpet_states.append(execute(cct, backend).result().get_statevector())
cct.barrier()
cct.draw('mpl')
return piano_states, guitar_states, bass_states, trumpet_states, cct
piano_states, guitar_states, bass_states, trumpet_states, cct = CreateQuantumCircuit(piano_input, guitar_input, bass_input, trumpet_input)
cct.draw(output="mpl")
def SeperateArrays(states, vals_real, vals_imaginary):
vals = []
for i in range(n+1):
vals.append(states[i-1][0])
for i in range(n+1):
vals_real.append((states[i-1][0].real))
vals_imaginary.append((states[i-1][0]).imag)
return vals_real, vals_imaginary
piano_real = []
piano_imaginary = []
piano_vals = []
guitar_real = []
guitar_imaginary = []
guitar_vals = []
bass_real = []
bass_imaginary = []
bass_vals = []
trumpet_real = []
trumpet_imaginary = []
trumpet_vals = []
piano_real, piano_imaginary = SeperateArrays(piano_states, piano_real, piano_imaginary)
guitar_real, guitar_imaginary = SeperateArrays(guitar_states, guitar_real, guitar_imaginary)
bass_real, bass_imaginary = SeperateArrays(bass_states, bass_real, bass_imaginary)
trumpet_real, trumpet_imaginary = SeperateArrays(trumpet_states, trumpet_real, trumpet_imaginary)
def MusicalTransformation(real, imaginary):
tune_array=[]
for i in range(n+1):
if(real[i-1] < 0 and imaginary[i-1] > 0):
tune_array.append('c')
tune_array.append('g')
tune_array.append('e')
if(real[i-1] < 0 and imaginary[i-1] <= 0):
tune_array.append('c')
tune_array.append('f')
tune_array.append('g')
if(real[i-1] < 0 and imaginary[i-1] > 0):
tune_array.append('d')
tune_array.append('f')
tune_array.append('a')
if(real[i-1] < 0 and imaginary[i-1] <= 0):
tune_array.append('f')
tune_array.append('a')
tune_array.append('c')
if(real[i-1] > 0 and imaginary[i-1] > 0):
tune_array.append('g')
tune_array.append('b')
tune_array.append('d')
if(real[i-1] > 0 and imaginary[i-1] < 0):
tune_array.append('d')
tune_array.append('f')
tune_array.append('a')
if(real[i-1] > 0 and imaginary[i-1] >= 0):
tune_array.append('e')
tune_array.append('g')
tune_array.append('b')
if(real[i-1] > 0 and imaginary[i-1] < 0):
tune_array.append('a')
tune_array.append('c')
tune_array.append('b')
if(real[i-1] == 0 and imaginary[i-1] == 0):
tune_array.append('n')
tune_array.append('n')
tune_array.append('n')
return tune_array
tune_array_piano = MusicalTransformation(piano_real, piano_imaginary)
tune_array_guitar = MusicalTransformation(guitar_real, guitar_imaginary)
tune_array_bass = MusicalTransformation(bass_real, bass_imaginary)
tune_array_trumpet = MusicalTransformation(trumpet_real, trumpet_imaginary)
def PlayPianoTune(character, songs):
if character == 'a':
sound_file = "./Audio/Piano/1.wav"
songs.append(sound_file)
if character == 'b':
sound_file = "./Audio/Piano/2.wav"
songs.append(sound_file)
if character == 'c':
sound_file = "./Audio/Piano/3.wav"
songs.append(sound_file)
if character == 'd':
sound_file = "./Audio/Piano/4.wav"
songs.append(sound_file)
if character == 'e':
sound_file = "./Audio/Piano/5.wav"
songs.append(sound_file)
if character == 'f':
sound_file = "./Audio/Piano/6.wav"
songs.append(sound_file)
if character == 'g':
sound_file = "./Audio/Piano/7.wav"
songs.append(sound_file)
if character == 'n':
sound_file = "./Audio/blank.wav"
songs.append(sound_file)
return songs
def PlayGuitarTune(character, songs):
if character == 'a':
sound_file = "./Audio/Guitar/1.wav"
songs.append(sound_file)
if character == 'b':
sound_file = "./Audio/Guitar/2.wav"
songs.append(sound_file)
if character == 'c':
sound_file = "./Audio/Guitar/3.wav"
songs.append(sound_file)
if character == 'd':
sound_file = "./Audio/Guitar/4.wav"
songs.append(sound_file)
if character == 'e':
sound_file = "./Audio/Guitar/5.wav"
songs.append(sound_file)
if character == 'f':
sound_file = "./Audio/Guitar/6.wav"
songs.append(sound_file)
if character == 'g':
sound_file = "./Audio/Guitar/7.wav"
songs.append(sound_file)
if character == 'n':
sound_file = "./Audio/blank.wav"
songs.append(sound_file)
return songs
def PlayBassTune(character, songs):
if character == 'a':
sound_file = "./Audio/Bass/1.wav"
songs.append(sound_file)
if character == 'b':
sound_file = "./Audio/Bass/2.wav"
songs.append(sound_file)
if character == 'c':
sound_file = "./Audio/Bass/3.wav"
songs.append(sound_file)
if character == 'd':
sound_file = "./Audio/Bass/4.wav"
songs.append(sound_file)
if character == 'e':
sound_file = "./Audio/Bass/5.wav"
songs.append(sound_file)
if character == 'f':
sound_file = "./Audio/Bass/6.wav"
songs.append(sound_file)
if character == 'g':
sound_file = "./Audio/Bass/7.wav"
songs.append(sound_file)
if character == 'n':
sound_file = "./Audio/blank.wav"
songs.append(sound_file)
return songs
def PlayTrumpetTune(character, songs):
if character == 'a':
sound_file = "./Audio/Trumpet/1.wav"
songs.append(sound_file)
if character == 'b':
sound_file = "./Audio/Trumpet/2.wav"
songs.append(sound_file)
if character == 'c':
sound_file = "./Audio/Trumpet/3.wav"
songs.append(sound_file)
if character == 'd':
sound_file = "./Audio/Trumpet/4.wav"
songs.append(sound_file)
if character == 'e':
sound_file = "./Audio/Trumpet/5.wav"
songs.append(sound_file)
if character == 'f':
sound_file = "./Audio/Trumpet/6.wav"
songs.append(sound_file)
if character == 'g':
sound_file = "./Audio/Trumpet/7.wav"
songs.append(sound_file)
if character == 'n':
sound_file = "./Audio/blank.wav"
songs.append(sound_file)
return songs
piano_song = []
for i in range(len(tune_array_piano)):
character = tune_array_piano[i-1]
piano_song = PlayPianoTune(character, piano_song)
os.remove("./pianosounds.wav")
copyfile('./Audio/blank.wav','./pianosounds.wav')
for i in range(len(tune_array_piano)):
infiles = [piano_song[i-1], "pianosounds.wav"]
outfile = "pianosounds.wav"
data= []
for infile in infiles:
w = wave.open(infile, 'rb')
data.append( [w.getparams(), w.readframes(w.getnframes())] )
w.close()
output = wave.open(outfile, 'wb')
output.setparams(data[0][0])
for i in range(len(data)):
output.writeframes(data[i][1])
output.close()
guitar_song = []
for i in range(len(tune_array_guitar)):
character = tune_array_piano[i-1]
guitar_song = PlayGuitarTune(character, guitar_song)
os.remove("./guitarsounds.wav")
copyfile('./Audio/blank.wav','./guitarsounds.wav')
for i in range(len(tune_array_guitar)):
infiles = [guitar_song[i-1], "guitarsounds.wav"]
outfile = "guitarsounds.wav"
data= []
for infile in infiles:
w = wave.open(infile, 'rb')
data.append( [w.getparams(), w.readframes(w.getnframes())] )
w.close()
output = wave.open(outfile, 'wb')
output.setparams(data[0][0])
for i in range(len(data)):
output.writeframes(data[i][1])
output.close()
bass_song = []
for i in range(len(tune_array_bass)):
character = tune_array_bass[i-1]
bass_song = PlayBassTune(character, bass_song)
os.remove("./basssounds.wav")
copyfile('./Audio/blank.wav','./basssounds.wav')
for i in range(len(tune_array_bass)):
infiles = [bass_song[i-1], "basssounds.wav"]
outfile = "basssounds.wav"
data= []
for infile in infiles:
w = wave.open(infile, 'rb')
data.append( [w.getparams(), w.readframes(w.getnframes())] )
w.close()
output = wave.open(outfile, 'wb')
output.setparams(data[0][0])
for i in range(len(data)):
output.writeframes(data[i][1])
output.close()
trumpet_song = []
for i in range(len(tune_array_trumpet)):
character = tune_array_trumpet[i-1]
trumpet_song = PlayTrumpetTune(character, trumpet_song)
os.remove("./trumpetsounds.wav")
copyfile('./Audio/blank.wav','./trumpetsounds.wav')
for i in range(len(tune_array_trumpet)):
infiles = [trumpet_song[i-1], "trumpetsounds.wav"]
outfile = "trumpetsounds.wav"
data= []
for infile in infiles:
w = wave.open(infile, 'rb')
data.append( [w.getparams(), w.readframes(w.getnframes())] )
w.close()
output = wave.open(outfile, 'wb')
output.setparams(data[0][0])
for i in range(len(data)):
output.writeframes(data[i][1])
output.close()
os.remove("./combined.wav")
copyfile('./Audio/blank.wav','./combined.wav')
os.remove("./combined2.wav")
copyfile('./Audio/blank.wav','./combined2.wav')
copyfile('./Audio/blank.wav','./output_song.wav')
sound1 = AudioSegment.from_file("./trumpetsounds.wav")
sound2 = AudioSegment.from_file("./basssounds.wav")
combined = sound1.overlay(sound2)
combined.export("./combined.wav", format='wav')
sound3 = AudioSegment.from_file("./guitarsounds.wav")
sound4 = AudioSegment.from_file("./pianosounds.wav")
combined2 = sound3.overlay(sound4)
combined2.export("./combined2.wav", format='wav')
sound5 = AudioSegment.from_file("./combined.wav")
sound6 = AudioSegment.from_file("./combined2.wav")
output_song = sound5.overlay(sound6)
output_song.export("./outputsong.wav", format='wav')
sound_file = "./outputsong.wav"
Audio(sound_file, autoplay=True)
#https://musescore.org/en/download/musescore.msi
!pip install music21
!pip install RISE
from music21 import *
#for Windows OS error
#us = environment.UserSettings()
#C:\Program Files\MuseScore 3\bin\MuseScore3.exe
#us['musicxmlPath'] = "C:\\Program Files\\MuseScore 3\\bin\\MuseScore3.exe"
#us['musescoreDirectPNGPath'] = "C:\\Program Files\\MuseScore 3\\bin\\MuseScore3.exe"
piano_stream = stream.Stream()
guitar_stream = stream.Stream()
bass_stream = stream.Stream()
trumpet_stream = stream.Stream()
note1 = note.Note("A")
note2 = note.Note("B")
note3 = note.Note("C")
note4 = note.Note("D")
note5 = note.Note("E")
note6 = note.Note("F")
note7 = note.Note("G")
note8 = note.Rest()
def append_stream(array, stream):
for i in range(n+1):
if array[i-1] == 'a':
stream.append(note1)
if array[i-1] == 'b':
stream.append(note2)
if array[i-1] == 'c':
stream.append(note3)
if array[i-1] == 'd':
stream.append(note4)
if array[i-1] == 'e':
stream.append(note5)
if array[i-1] == 'f':
stream.append(note6)
if array[i-1] == 'g':
stream.append(note7)
if array[i-1] == 'n':
stream.append(note8)
return stream
piano_stream=append_stream(tune_array_piano, piano_stream)
guitar_stream=append_stream(tune_array_guitar, guitar_stream)
bass_stream=append_stream(tune_array_bass, bass_stream)
trumpet_stream=append_stream(tune_array_trumpet, trumpet_stream)
print("Piano")
piano_stream.show()
print("Guitar")
guitar_stream.show()
print("Bass")
bass_stream.show()
print("Trumpet")
trumpet_stream.show()
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
from math import sqrt
# Create a quantum circuit with a single qubit
# The default initial state of qubit will be |0> or [1,0]
qc = QuantumCircuit(1)
# declare the intial sate as [0,1] or |1>
initial_state = [1/sqrt(2),1j/sqrt(2)]
qc.initialize(initial_state,0)
qc.x(0)
qc.measure_all()
#Draw the circuit
# qc.draw()
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
out = execute(qc,backend).result().get_statevector()
print(out)
plot_bloch_multivector(out)
# visualize the output as an animation
# visualize_transition(qc)
#execute the circuit and get the plain result
out = execute(qc,backend).result()
counts = out.get_counts()
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from sklearn.datasets import make_blobs
# example dataset
features, labels = make_blobs(n_samples=20, n_features=2, centers=2, random_state=3, shuffle=True)
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
features = MinMaxScaler(feature_range=(0, np.pi)).fit_transform(features)
train_features, test_features, train_labels, test_labels = train_test_split(
features, labels, train_size=15, shuffle=False
)
# number of qubits is equal to the number of features
num_qubits = 2
# number of steps performed during the training procedure
tau = 100
# regularization parameter
C = 1000
from qiskit import BasicAer
from qiskit.circuit.library import ZFeatureMap
from qiskit.utils import algorithm_globals
from qiskit_machine_learning.kernels import FidelityQuantumKernel
algorithm_globals.random_seed = 12345
feature_map = ZFeatureMap(feature_dimension=num_qubits, reps=1)
qkernel = FidelityQuantumKernel(feature_map=feature_map)
from qiskit_machine_learning.algorithms import PegasosQSVC
pegasos_qsvc = PegasosQSVC(quantum_kernel=qkernel, C=C, num_steps=tau)
# training
pegasos_qsvc.fit(train_features, train_labels)
# testing
pegasos_score = pegasos_qsvc.score(test_features, test_labels)
print(f"PegasosQSVC classification test score: {pegasos_score}")
grid_step = 0.2
margin = 0.2
grid_x, grid_y = np.meshgrid(
np.arange(-margin, np.pi + margin, grid_step), np.arange(-margin, np.pi + margin, grid_step)
)
meshgrid_features = np.column_stack((grid_x.ravel(), grid_y.ravel()))
meshgrid_colors = pegasos_qsvc.predict(meshgrid_features)
import matplotlib.pyplot as plt
plt.figure(figsize=(5, 5))
meshgrid_colors = meshgrid_colors.reshape(grid_x.shape)
plt.pcolormesh(grid_x, grid_y, meshgrid_colors, cmap="RdBu", shading="auto")
plt.scatter(
train_features[:, 0][train_labels == 0],
train_features[:, 1][train_labels == 0],
marker="s",
facecolors="w",
edgecolors="r",
label="A train",
)
plt.scatter(
train_features[:, 0][train_labels == 1],
train_features[:, 1][train_labels == 1],
marker="o",
facecolors="w",
edgecolors="b",
label="B train",
)
plt.scatter(
test_features[:, 0][test_labels == 0],
test_features[:, 1][test_labels == 0],
marker="s",
facecolors="r",
edgecolors="r",
label="A test",
)
plt.scatter(
test_features[:, 0][test_labels == 1],
test_features[:, 1][test_labels == 1],
marker="o",
facecolors="b",
edgecolors="b",
label="B test",
)
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Pegasos Classification")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.72" # Two Hydrogen atoms, 0.72 Angstrom apart
)
molecule = driver.run()
from qiskit_nature.second_q.mappers import QubitConverter, ParityMapper
qubit_converter = QubitConverter(ParityMapper())
hamiltonian = qubit_converter.convert(molecule.second_q_ops()[0])
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
sol = NumPyMinimumEigensolver().compute_minimum_eigenvalue(hamiltonian)
real_solution = molecule.interpret(sol)
real_solution.groundenergy
from qiskit_ibm_runtime import QiskitRuntimeService, Estimator, Session, Options
service = QiskitRuntimeService()
backend = "ibmq_qasm_simulator"
from qiskit.algorithms.minimum_eigensolvers import VQE
# Use RealAmplitudes circuit to create trial states
from qiskit.circuit.library import RealAmplitudes
ansatz = RealAmplitudes(num_qubits=2, reps=2)
# Search for better states using SPSA algorithm
from qiskit.algorithms.optimizers import SPSA
optimizer = SPSA(150)
# Set a starting point for reproduceability
import numpy as np
np.random.seed(6)
initial_point = np.random.uniform(-np.pi, np.pi, 12)
# Create an object to store intermediate results
from dataclasses import dataclass
@dataclass
class VQELog:
values: list
parameters: list
def update(self, count, parameters, mean, _metadata):
self.values.append(mean)
self.parameters.append(parameters)
print(f"Running circuit {count} of ~350", end="\r", flush=True)
log = VQELog([],[])
# Main calculation
with Session(service=service, backend=backend) as session:
options = Options()
options.optimization_level = 3
vqe = VQE(Estimator(session=session, options=options),
ansatz, optimizer, callback=log.update, initial_point=initial_point)
result = vqe.compute_minimum_eigenvalue(hamiltonian)
print("Experiment complete.".ljust(30))
print(f"Raw result: {result.optimal_value}")
if 'simulator' not in backend:
# Run once with ZNE error mitigation
options.resilience_level = 2
vqe = VQE(Estimator(session=session, options=options),
ansatz, SPSA(1), initial_point=result.optimal_point)
result = vqe.compute_minimum_eigenvalue(hamiltonian)
print(f"Mitigated result: {result.optimal_value}")
import matplotlib.pyplot as plt
plt.rcParams["font.size"] = 14
# Plot energy and reference value
plt.figure(figsize=(12, 6))
plt.plot(log.values, label="Estimator VQE")
plt.axhline(y=real_solution.groundenergy, color="tab:red", ls="--", label="Target")
plt.legend(loc="best")
plt.xlabel("Iteration")
plt.ylabel("Energy [H]")
plt.title("VQE energy")
plt.show()
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
from qiskit import QuantumCircuit, IBMQ, Aer
def qc_ezz(t):
qc = QuantumCircuit(2, name = 'e^(-itZZ)')
qc.cx(0, 1); qc.rz(2*t, 1); qc.cx(0, 1)
return qc
def qc_exx(t):
qc = QuantumCircuit(2, name = 'e^(-itXX)')
qc.h([0,1]); qc.cx(0, 1); qc.rz(2*t, 1); qc.cx(0, 1); qc.h([0,1])
return qc
def qc_eyy(t):
qc = QuantumCircuit(2, name = 'e^(-itYY)')
qc.sdg([0,1]); qc.h([0,1]); qc.cx(0, 1); qc.rz(2*t, 1); qc.cx(0, 1); qc.h([0,1]); qc.s([0,1])
return qc
def qc_Bj(t):
qc = QuantumCircuit(3, name = 'B_j')
qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t)
qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2])
qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1])
return qc
import math
qc_Bj_ = qc_Bj(math.pi)
qc_Bj_.draw(output = 'mpl')
qc_Bj_.decompose().draw(output = 'mpl')
nshots = 8192
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
#provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
device = provider.get_backend('ibmq_jakarta')
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.tools.monitor import backend_overview, backend_monitor
def qc_psi0():
qc = QuantumCircuit(3, name = 'psi0')
qc.x([0,1])
return qc
import numpy as np
ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1
psi0_ = np.kron(ket1, np.kron(ket1, ket0));
psi0__ = np.kron(ket0, np.kron(ket1, ket1)) # para calcular a fidelidade com o estado da tomografia
psi0_.T, psi0__.T
import scipy
I = np.array([[1,0],[0,1]]); X = np.array([[0,1],[1,0]]); Y = np.array([[0,-1j],[1j,0]]); Z = np.array([[1,0],[0,-1]])
H2 = np.kron(X, X) + np.kron(Y, Y) + np.kron(Z, Z)
def UHxxx12_num(t):
H = np.kron(H2, I)
return scipy.linalg.expm(-1j*t*H)
def UHxxx23_num(t):
H = np.kron(I, H2)
return scipy.linalg.expm(-1j*t*H)
#U = UHxxx23_num(math.pi); print(U.shape[0])
from qiskit import quantum_info, execute
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
t = math.pi
for j in range(0, 8): # muda o No. de passos de Trotter
# teórico
U12 = UHxxx12_num(t/(j+1)); U23 = UHxxx23_num(t/(j+1))
B = np.dot(U12, U23); U = np.linalg.matrix_power(B, j+1); psit = np.dot(U, psi0_)
F_teo = quantum_info.state_fidelity(psi0_, psit)
# circuit q
qc = QuantumCircuit(7)
qc.x([5, 3]) # initial state
qc_Bj_ = qc_Bj(t/(j+1))
for k in range(0, j+1):
qc.append(qc_Bj_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulação
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim = quantum_info.state_fidelity(psi0__, rho_sim)
# experimento
job_exp = execute(qstc, backend = device, shots = nshots)
job_monitor(job_exp)
qstf_exp = StateTomographyFitter(job_exp.result(), qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp = quantum_info.state_fidelity(psi0__, rho_exp)
print('No. passos=', j+1, ',F_teo=', F_teo, ',F_sim=', F_sim, ',F_exp=', F_exp)
qc.draw(output = 'mpl')
npt = 7
dt = math.pi/16; t = np.arange(0, math.pi+dt, dt); d = len(t)
F_teo = np.zeros(d); F_sim = np.zeros(d); F_exp = np.zeros(d)
for j in range(0, d):
# teórico
U12 = UHxxx12_num(t[j]/npt); U23 = UHxxx23_num(t[j]/npt)
B = np.dot(U12, U23); U = np.linalg.matrix_power(B, npt); psit = np.dot(U, psi0_)
F_teo[j] = qiskit.quantum_info.state_fidelity(psi0_, psit)
# circuito quântico
qc = QuantumCircuit(7); qc.x([5, 3]) # initial state
qc_Bj_ = qc_Bj(t[j]/npt)
for k in range(0, npt):
qc.append(qc_Bj_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulação
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim[j] = quantum_info.state_fidelity(psi0__, rho_sim)
# experimento
job_exp = execute(qstc, backend = device, shots = nshots)
job_monitor(job_exp)
qstf_exp = StateTomographyFitter(job_exp.result(), qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp[j] = quantum_info.state_fidelity(psi0__, rho_exp)
qc.draw(output = 'mpl')
print('t = ', t[j], 'F_exp = ', F_exp[j])
%run init.ipynb
plt.figure(figsize = (8,5), dpi = 100)
plt.plot(t, F_teo, '-.', label = r'$F_{teo}$'); plt.plot(t, F_sim, '-.', label = r'$F_{sim}$')
plt.plot(t, F_exp, '-.', label = r'$F_{exp}$')
plt.xlabel(r'$t$'); plt.legend(bbox_to_anchor=(1.05, 1.0), loc='upper left')
plt.grid(); plt.show()
|
https://github.com/rohitgit1/Quantum-Computing-Summer-School
|
rohitgit1
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/QuSTaR/kaleidoscope
|
QuSTaR
|
# -*- coding: utf-8 -*-
# This code is part of Kaleidoscope.
#
# (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 Bloch routines"""
import pytest
from qiskit import QuantumCircuit
from qiskit. quantum_info import DensityMatrix, partial_trace
from kaleidoscope import qsphere
from kaleidoscope.errors import KaleidoscopeError
def test_qsphere_bad_dm_input():
"""Tests the qsphere raises when passed impure dm"""
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0, 1)
qc.cx(1, 2)
dm = DensityMatrix.from_instruction(qc)
pdm = partial_trace(dm, [0, 1])
with pytest.raises(KaleidoscopeError):
assert qsphere(pdm)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.