repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
---|---|---|
https://github.com/Interlin-q/diskit
|
Interlin-q
|
import numpy as np
from numpy import pi
# importing Qiskit
from qiskit import QuantumCircuit, transpile, assemble, Aer
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qc = QuantumCircuit(3)
qc.h(2)
qc.cp(pi/2, 1, 2)
qc.cp(pi/4, 0, 2)
qc.h(1)
qc.cp(pi/2, 0, 1)
qc.h(0)
qc.swap(0, 2)
qc.draw()
def qft_rotations(circuit, n):
if n == 0:
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cp(pi/2**(n-qubit), qubit, n)
qft_rotations(circuit, n)
def swap_registers(circuit, n):
for qubit in range(n//2):
circuit.swap(qubit, n-qubit-1)
return circuit
def qft(circuit, n):
qft_rotations(circuit, n)
swap_registers(circuit, n)
return circuit
qc = QuantumCircuit(4)
qft(qc,4)
qc.draw()
# Create the circuit
qc = QuantumCircuit(3)
# Encode the state 5 (101 in binary)
qc.x(0)
qc.x(2)
qc.draw()
sim = Aer.get_backend("aer_simulator")
qc_init = qc.copy()
qc_init.save_statevector()
statevector = sim.run(qc_init).result().get_statevector()
plot_bloch_multivector(statevector)
qft(qc, 3)
qc.draw()
qc.save_statevector()
statevector = sim.run(qc).result().get_statevector()
plot_bloch_multivector(statevector)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Tests for the topdown.py module.
"""
from unittest import TestCase
import numpy as np
from qiskit import ClassicalRegister, transpile
from qiskit_aer import AerSimulator
from qclib.state_preparation import TopDownInitialize
from qclib.util import get_state, measurement
# pylint: disable=missing-function-docstring
# pylint: disable=missing-class-docstring
backend = AerSimulator()
SHOTS = 8192
class TestTopDown(TestCase):
@staticmethod
def measurement(circuit, n_qubits, classical_reg):
circuit.measure(list(range(n_qubits)), classical_reg)
job = backend.run(
transpile(circuit, backend),
shots=SHOTS,
optimization_level=3
)
counts = job.result().get_counts(circuit)
sum_values = sum(counts.values())
counts2 = {}
for i in range(2**n_qubits):
pattern = f'{i:0{n_qubits}b}'
if pattern in counts:
counts2[pattern] = counts[pattern]
else:
counts2[pattern] = 0.0
return [ value/sum_values for (key, value) in counts2.items() ]
@staticmethod
def topdown_experiment(state):
circuit = TopDownInitialize(state).definition
n_qubits = int(np.log2(len(state)))
classical_reg = ClassicalRegister(n_qubits)
circuit.add_register(classical_reg)
return measurement(circuit, n_qubits, classical_reg, backend, SHOTS)
def test_topdown_state_real(self):
state_vector = np.random.rand(32)
state_vector = state_vector / np.linalg.norm(state_vector)
circuit = TopDownInitialize(state_vector).definition
state = get_state(circuit)
self.assertTrue(np.allclose(state_vector, state))
def test_topdown_state_complex(self):
state_vector = np.random.rand(32) + np.random.rand(32) * 1j
state_vector = state_vector / np.linalg.norm(state_vector)
circuit = TopDownInitialize(state_vector).definition
state = get_state(circuit)
self.assertTrue(np.allclose(state_vector, state))
def test_topdown_measure(self):
state_vector = np.random.rand(32) + np.random.rand(32) * 1j
state_vector = state_vector / np.linalg.norm(state_vector)
state = TestTopDown.topdown_experiment(state_vector)
self.assertTrue(np.allclose(np.power(np.abs(state_vector), 2), state,
rtol=1e-01, atol=0.005))
def test_topdown_fixed_state(self):
state_vector = [
0, np.sqrt(2 / 8) * np.exp(-1.0j * np.pi / 7),
np.sqrt(3 / 8) * np.exp(-1.0j * np.pi / 3), 0,
0, 0, np.sqrt(3 / 8), 0
]
circuit = TopDownInitialize(state_vector).definition
state = get_state(circuit)
self.assertTrue(np.allclose(state_vector, state))
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# %%writefile FILENAME.py
# your function is here
from math import cos, sin, pi
from random import randrange
def random_quantum_state2():
#
# your codes are here
#
# randomly create quantum states
angle_random = randrange(361)
# get the angles cos, sin
angle_random_radian = (2 * pi * angle_random)/(360)
return [cos(angle_random_radian), sin(angle_random_radian)]
# visually test your function
%run qlatvia.py
draw_qubit()
#
# your solution is here
#
for i in range(100):
[x, y] = random_quantum_state2()
draw_quantum_state(x,y,"")
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
%run init.ipynb
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
input_3sat_instance = '''
c example DIMACS-CNF 3-SAT
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
'''
import os
import tempfile
from qiskit.exceptions import MissingOptionalLibraryError
from qiskit.circuit.library.phase_oracle import PhaseOracle
fp = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
fp.write(input_3sat_instance)
file_name = fp.name
fp.close()
oracle = None
try:
oracle = PhaseOracle.from_dimacs_file(file_name)
except MissingOptionalLibraryError as ex:
print(ex)
finally:
os.remove(file_name)
from qiskit.algorithms import AmplificationProblem
problem = None
if oracle is not None:
problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring)
from qiskit.algorithms import Grover
from qiskit.primitives import Sampler
grover = Grover(sampler=Sampler())
result = None
if problem is not None:
result = grover.amplify(problem)
print(result.assignment)
from qiskit.tools.visualization import plot_histogram
if result is not None:
display(plot_histogram(result.circuit_results[0]))
expression = '(w ^ x) & ~(y ^ z) & (x & y & z)'
try:
oracle = PhaseOracle(expression)
problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring)
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
display(plot_histogram(result.circuit_results[0]))
except MissingOptionalLibraryError as ex:
print(ex)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/microsoft/qiskit-qir
|
microsoft
|
##
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
##
from typing import List, Optional, Union
from pyqir import Module, Context
from qiskit import ClassicalRegister, QuantumRegister
from qiskit.circuit.bit import Bit
from qiskit.circuit.quantumcircuit import QuantumCircuit, Instruction
from abc import ABCMeta, abstractmethod
class _QuantumCircuitElement(metaclass=ABCMeta):
@classmethod
def from_element_list(cls, elements):
return [cls(elem) for elem in elements]
@abstractmethod
def accept(self, visitor):
pass
class _Register(_QuantumCircuitElement):
def __init__(self, register: Union[QuantumRegister, ClassicalRegister]):
self._register: Union[QuantumRegister, ClassicalRegister] = register
def accept(self, visitor):
visitor.visit_register(self._register)
class _Instruction(_QuantumCircuitElement):
def __init__(self, instruction: Instruction, qargs: List[Bit], cargs: List[Bit]):
self._instruction: Instruction = instruction
self._qargs = qargs
self._cargs = cargs
def accept(self, visitor):
visitor.visit_instruction(self._instruction, self._qargs, self._cargs)
class QiskitModule:
def __init__(
self,
circuit: QuantumCircuit,
name: str,
module: Module,
num_qubits: int,
num_clbits: int,
reg_sizes: List[int],
elements: List[_QuantumCircuitElement],
):
self._circuit = circuit
self._name = name
self._module = module
self._elements = elements
self._num_qubits = num_qubits
self._num_clbits = num_clbits
self.reg_sizes = reg_sizes
@property
def circuit(self) -> QuantumCircuit:
return self._circuit
@property
def name(self) -> str:
return self._name
@property
def module(self) -> Module:
return self._module
@property
def num_qubits(self) -> int:
return self._num_qubits
@property
def num_clbits(self) -> int:
return self._num_clbits
@classmethod
def from_quantum_circuit(
cls, circuit: QuantumCircuit, module: Optional[Module] = None
) -> "QiskitModule":
"""Create a new QiskitModule from a qiskit.QuantumCircuit object."""
elements: List[_QuantumCircuitElement] = []
reg_sizes = [len(creg) for creg in circuit.cregs]
# Registers
elements.extend(_Register.from_element_list(circuit.qregs))
elements.extend(_Register.from_element_list(circuit.cregs))
# Instructions
for instruction, qargs, cargs in circuit._data:
elements.append(_Instruction(instruction, qargs, cargs))
if module is None:
module = Module(Context(), circuit.name)
return cls(
circuit=circuit,
name=circuit.name,
module=module,
num_qubits=circuit.num_qubits,
num_clbits=circuit.num_clbits,
reg_sizes=reg_sizes,
elements=elements,
)
def accept(self, visitor):
visitor.visit_qiskit_module(self)
for element in self._elements:
element.accept(visitor)
visitor.record_output(self)
visitor.finalize()
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
from qiskit import QuantumRegister
from qiskit.circuit import QuantumCircuit, Parameter
from qiskit_cold_atom.spins.spins_gate_library import RydbergFull
from qiskit_cold_atom.spins import SpinSimulator
import numpy as np
import matplotlib.pyplot as plt
Nwires = 2
backend = SpinSimulator()
qc_rabi = QuantumCircuit(QuantumRegister(Nwires, "spin"))
all_modes=range(Nwires)
omega_t = Parameter("ω")
qc_rabi.rlx(omega_t, [0, 1])
qc_rabi.measure_all()
qc_rabi.draw(output='mpl', style='clifford')
phases = np.linspace(0, 2*np.pi, 15)
rabi_list = [
qc_rabi.assign_parameters(
{omega_t: phase},
inplace=False,
)
for phase in phases
]
n_shots = 500
job_rabi = backend.run(rabi_list, shots=n_shots)
result_rabi = job_rabi.result()
counts_rabi = result_rabi.get_counts()
sum_rabi = []
for i, _ in enumerate(phases):
counts_up = 0
for outcome, count in counts_rabi[i].items():
if outcome[0] == "1":
counts_up += count
if outcome[-1] == "1":
counts_up += count
sum_rabi.append(counts_up/n_shots)
f, ax = plt.subplots()
ax.plot(phases, sum_rabi, 'o')
ax.set_xlabel('phase')
ax.set_ylabel('sum of spins up')
Nwires = 2
backend = SpinSimulator()
qc_block = QuantumCircuit(QuantumRegister(Nwires, "spin"))
all_modes=range(Nwires)
omega_t = Parameter("ω")
phi_t = Parameter("φ")
qc_block.rydberg_full(omega=omega_t, delta=0, phi=phi_t, modes=all_modes)
qc_block.measure_all()
qc_block.draw(output='mpl', style='clifford')
phases = np.linspace(0., 2*np.pi, 15)
block_list = [
qc_block.assign_parameters(
{omega_t: phase, phi_t: phase*10},
inplace=False,
)
for phase in phases
]
job_block = backend.run(block_list, shots=n_shots)
result_block = job_block.result()
counts_block = job_block.result().get_counts()
sum_block = []
for i, _ in enumerate(phases):
counts_up = 0
for outcome, count in counts_block[i].items():
if outcome[0] == "1":
counts_up += count
if outcome[-1] == "1":
counts_up += count
sum_block.append(counts_up/n_shots)
f, ax = plt.subplots()
ax.plot(phases, sum_rabi, 'o', label= 'Rabi')
ax.plot(phases, sum_block, 'o', label= 'Blockade')
ax.plot(phases, (1-np.cos(np.sqrt(2)*phases))/2, '-', color = "C1", alpha = 0.5, linewidth = 3, label= 'blocked theory')
ax.legend()
ax.set_xlabel('phase')
ax.set_ylabel('sum of spins up')
Nwires = 2
backend = SpinSimulator()
qc_entangle = QuantumCircuit(QuantumRegister(Nwires, "spin"))
all_modes=range(Nwires)
qc_entangle.rlx(np.pi/2, all_modes)
qc_entangle.rydberg_block(np.pi, modes=all_modes)
qc_entangle.rly(np.pi/2, 0)
qc_entangle.rly(np.pi/2, 1)
qc_entangle.measure_all()
qc_entangle.draw(output='mpl', style='clifford')
job_entangle = backend.run(qc_entangle, shots=500)
result_entangle = job_entangle.result()
print(result_entangle.get_counts())
Nwires = 5
backend = SpinSimulator()
qc_rabi = QuantumCircuit(QuantumRegister(Nwires, "spin"))
all_modes=range(Nwires)
omega_t = Parameter("ω")
qc_rabi.rlx(omega_t, all_modes)
qc_rabi.measure_all()
qc_rabi.draw(output='mpl', style='clifford')
phases = np.linspace(0, 2*np.pi, 15)
rabi_list = [
qc_rabi.assign_parameters(
{omega_t: phase},
inplace=False,
)
for phase in phases
]
job_rabi = backend.run(rabi_list, shots=500)
result_rabi = job_rabi.result()
outcomes_rabi = [result_rabi.get_memory(i) for i in range(len(rabi_list))]
for i, outcome in enumerate(outcomes_rabi):
for j, run in enumerate(outcome):
outcomes_rabi[i][j] = np.array(run.split(' '), dtype = int)
outcomes_rabi = np.array(outcomes_rabi)
means_rabi = outcomes_rabi.mean(axis=1)
f, ax = plt.subplots()
im = ax.pcolormesh(phases, np.arange(Nwires), means_rabi.T)
f.colorbar(im, ax=ax)
ax.set_ylabel('site')
ax.set_xlabel('time')
Nwires = 7
backend = SpinSimulator()
qc_block = QuantumCircuit(QuantumRegister(Nwires, "spin"))
all_modes=range(Nwires)
omega_t = Parameter("ω")
phi_t = Parameter("φ")
qc_block.rydberg_full(omega=omega_t, delta=0, phi=phi_t, modes=all_modes)
qc_block.measure_all()
qc_block.draw(output='mpl', style='clifford')
phases = np.linspace(0, 2*np.pi, 15)
block_list = [
qc_block.assign_parameters(
{omega_t: phase, phi_t: phase*5},
inplace=False,
)
for phase in phases
]
job_block = backend.run(block_list, shots=500)
result_block = job_block.result()
outcomes = [result_block.get_memory(i) for i in range(len(block_list))]
for i, outcome in enumerate(outcomes):
for j, run in enumerate(outcome):
outcomes[i][j] = np.array(run.split(' '), dtype = int)
outcomes = np.array(outcomes)
means_block = outcomes.mean(axis=1)
f, ax = plt.subplots()
im = ax.pcolormesh(phases, np.arange(Nwires), means_block.T)
f.colorbar(im, ax=ax)
ax.set_ylabel('site')
ax.set_xlabel('time')
from qiskit_cold_atom.providers import ColdAtomProvider
from pprint import pprint
#provider = ColdAtomProvider.save_account(
# url=[
# "https://qlued.alqor.io/api/v2/singlequdit",
# "https://qlued.alqor.io/api/v2/multiqudit",
# "https://qlued.alqor.io/api/v2/fermions",
# "https://qlued.alqor.io/api/v2/rydberg",
# ],
# username="name",
# token="token",
# overwrite=True
#)
provider = ColdAtomProvider.load_account()
spin_device_backend = provider.get_backend("alqor_rydberg_simulator")
pprint(spin_device_backend.configuration().supported_instructions)
Nwires = 5
qc_rabi = QuantumCircuit(5)
all_modes=range(Nwires)
omega_t = Parameter("ω")
qc_rabi.rlx( omega_t, all_modes)
qc_rabi.measure_all()
qc_rabi.draw(output='mpl')
phases = np.linspace(0, 2*np.pi,15)
remote_rabi_list = [
qc_rabi.assign_parameters(
{omega_t: phase},
inplace=False,
)
for phase in phases
]
job_remote_rabi = spin_device_backend.run(remote_rabi_list, shots=500)
job_remote_rabi.job_id()
job_rabi_retrieved = spin_device_backend.retrieve_job(job_id=job_remote_rabi.job_id())
print("job status: ", job_rabi_retrieved.status())
result_remote_rabi = job_rabi_retrieved.result()
outcomes = [result_remote_rabi.get_memory(i) for i in range(len(remote_rabi_list))]
for i, outcome in enumerate(outcomes):
for j, run in enumerate(outcome):
outcomes[i][j] = np.array(run.split(' '), dtype = int)
outcomes = np.array(outcomes)
means_remote_rabi = outcomes.mean(axis=1)
f, ax = plt.subplots()
im = ax.pcolormesh(phases,np.arange(5), means_remote_rabi.T)
f.colorbar(im, ax=ax)
ax.set_ylabel('site')
ax.set_xlabel('time')
Nwires = 5
qc2 = QuantumCircuit(5)
all_modes=range(Nwires)
alpha = Parameter("α")
beta = Parameter("β")
qc2.rydberg_full(omega = alpha, delta =0, phi = beta, modes=all_modes)
qc2.measure_all()
qc2.draw(output='mpl')
phases = np.linspace(0, 2*np.pi,15)
circuit2_list = [
qc2.assign_parameters(
{alpha: phase, beta: phase*2},
inplace=False,
)
for phase in phases
]
job2 = spin_device_backend.run(circuit2_list, shots=500)
job2.job_id()
job_retrieved2 = spin_device_backend.retrieve_job(job_id=job2.job_id())
print("job status: ", job_retrieved2.status())
result2 = job_retrieved2.result()
outcomes = [result2.get_memory(i) for i in range(len(circuit2_list))]
for i, outcome in enumerate(outcomes):
for j, run in enumerate(outcome):
outcomes[i][j] = np.array(run.split(' '), dtype = int)
outcomes = np.array(outcomes)
means_1 = outcomes.mean(axis=1)
means_1.shape
f, ax = plt.subplots()
im = ax.pcolormesh(phases,np.arange(5), means_1.T)
f.colorbar(im, ax=ax)
ax.set_ylabel('site')
ax.set_xlabel('time')
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
""" This file allows to test the various QFT implemented. The user must specify:
1) The number of qubits it wants the QFT to be implemented on
2) The kind of QFT want to implement, among the options:
-> Normal QFT with SWAP gates at the end
-> Normal QFT without SWAP gates at the end
-> Inverse QFT with SWAP gates at the end
-> Inverse QFT without SWAP gates at the end
The user must can also specify, in the main function, the input quantum state. By default is a maximal superposition state
This file uses as simulator the local simulator 'statevector_simulator' because this simulator saves
the quantum state at the end of the circuit, which is exactly the goal of the test file. This simulator supports sufficient
qubits to the size of the QFTs that are going to be used in Shor's Algorithm because the IBM simulator only supports up to 32 qubits
"""
""" Imports from qiskit"""
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, IBMQ, BasicAer
""" Imports to Python functions """
import time
""" Local Imports """
from qfunctions import create_QFT, create_inverse_QFT
""" Function to properly print the final state of the simulation """
""" This is only possible in this way because the program uses the statevector_simulator """
def show_good_coef(results, n):
i=0
max = pow(2,n)
if max > 100: max = 100
""" Iterate to all possible states """
while i<max:
binary = bin(i)[2:].zfill(n)
number = results.item(i)
number = round(number.real, 3) + round(number.imag, 3) * 1j
""" Print the respective component of the state if it has a non-zero coefficient """
if number!=0:
print('|{}>'.format(binary),number)
i=i+1
""" Main program """
if __name__ == '__main__':
""" Select how many qubits want to apply the QFT on """
n = int(input('\nPlease select how many qubits want to apply the QFT on: '))
""" Select the kind of QFT to apply using the variable what_to_test:
what_to_test = 0: Apply normal QFT with the SWAP gates at the end
what_to_test = 1: Apply normal QFT without the SWAP gates at the end
what_to_test = 2: Apply inverse QFT with the SWAP gates at the end
what_to_test = 3: Apply inverse QFT without the SWAP gates at the end
"""
print('\nSelect the kind of QFT to apply:')
print('Select 0 to apply normal QFT with the SWAP gates at the end')
print('Select 1 to apply normal QFT without the SWAP gates at the end')
print('Select 2 to apply inverse QFT with the SWAP gates at the end')
print('Select 3 to apply inverse QFT without the SWAP gates at the end\n')
what_to_test = int(input('Select your option: '))
if what_to_test<0 or what_to_test>3:
print('Please select one of the options')
exit()
print('\nTotal number of qubits used: {0}\n'.format(n))
print('Please check source file to change input quantum state. By default is a maximal superposition state with |+> in every qubit.\n')
ts = time.time()
""" Create quantum and classical registers """
quantum_reg = QuantumRegister(n)
classic_reg = ClassicalRegister(n)
""" Create Quantum Circuit """
circuit = QuantumCircuit(quantum_reg, classic_reg)
""" Create the input state desired
Please change this as you like, by default we put H gates in every qubit,
initializing with a maximimal superposition state
"""
#circuit.h(quantum_reg)
""" Test the right QFT according to the variable specified before"""
if what_to_test == 0:
create_QFT(circuit,quantum_reg,n,1)
elif what_to_test == 1:
create_QFT(circuit,quantum_reg,n,0)
elif what_to_test == 2:
create_inverse_QFT(circuit,quantum_reg,n,1)
elif what_to_test == 3:
create_inverse_QFT(circuit,quantum_reg,n,0)
else:
print('Noting to implement, exiting program')
exit()
""" show results of circuit creation """
create_time = round(time.time()-ts, 3)
if n < 8: print(circuit)
print(f"... circuit creation time = {create_time}")
ts = time.time()
""" Simulate the created Quantum Circuit """
simulation = execute(circuit, backend=BasicAer.get_backend('statevector_simulator'),shots=1)
""" Get the results of the simulation in proper structure """
sim_result=simulation.result()
""" Get the statevector of the final quantum state """
outputstate = sim_result.get_statevector(circuit, decimals=3)
""" show execution time """
exec_time = round(time.time()-ts, 3)
print(f"... circuit execute time = {exec_time}")
""" Print final quantum state to user """
print('The final state after applying the QFT is:\n')
show_good_coef(outputstate,n)
|
https://github.com/weiT1993/qiskit_helper_functions
|
weiT1993
|
import random, pickle, os, copy, random, qiskit_aer, psutil
from qiskit import QuantumCircuit
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.dagcircuit.dagcircuit import DAGCircuit
from qiskit.quantum_info import Statevector
import numpy as np
from qiskit_helper_functions.conversions import dict_to_array
def scrambled(orig):
dest = orig[:]
random.shuffle(dest)
return dest
def read_dict(filename):
if os.path.isfile(filename):
f = open(filename, "rb")
file_content = {}
while 1:
try:
file_content.update(pickle.load(f))
except EOFError:
break
f.close()
else:
file_content = {}
return file_content
def apply_measurement(circuit, qubits):
measured_circuit = QuantumCircuit(circuit.num_qubits, len(qubits))
for circuit_inst, circuit_qubits, circuit_clbits in circuit.data:
measured_circuit.append(circuit_inst, circuit_qubits, circuit_clbits)
measured_circuit.barrier(qubits)
measured_circuit.measure(qubits, measured_circuit.clbits)
return measured_circuit
def evaluate_circ(circuit, backend, options=None):
circuit = copy.deepcopy(circuit)
max_memory_mb = psutil.virtual_memory().total >> 20
max_memory_mb = int(max_memory_mb / 4 * 3)
if backend == "statevector_simulator":
simulator = qiskit_aer.StatevectorSimulator()
result = simulator.run(circuits=[circuit]).result()
statevector = result.get_statevector(circuit)
prob_vector = Statevector(statevector).probabilities()
return prob_vector
elif backend == "noiseless_qasm_simulator":
simulator = qiskit_aer.AerSimulator(max_memory_mb=max_memory_mb)
if isinstance(options, dict) and "num_shots" in options:
num_shots = options["num_shots"]
else:
num_shots = max(1024, 2**circuit.num_qubits)
if isinstance(options, dict) and "memory" in options:
memory = options["memory"]
else:
memory = False
if circuit.num_clbits == 0:
circuit.measure_all()
result = simulator.run(circuit, shots=num_shots, memory=memory).result()
if memory:
qasm_memory = np.array(result.get_memory(circuit))
assert len(qasm_memory) == num_shots
return qasm_memory
else:
noiseless_counts = result.get_counts(circuit)
assert sum(noiseless_counts.values()) == num_shots
noiseless_counts = dict_to_array(
distribution_dict=noiseless_counts, force_prob=True
)
return noiseless_counts
else:
raise NotImplementedError
def circuit_stripping(circuit):
# Remove all single qubit gates and barriers in the circuit
dag = circuit_to_dag(circuit)
stripped_dag = DAGCircuit()
[stripped_dag.add_qreg(x) for x in circuit.qregs]
for vertex in dag.topological_op_nodes():
if len(vertex.qargs) == 2 and vertex.op.name != "barrier":
stripped_dag.apply_operation_back(op=vertex.op, qargs=vertex.qargs)
return dag_to_circuit(stripped_dag)
def dag_stripping(dag, max_gates):
"""
Remove all single qubit gates and barriers in the DAG
Only leaves the first max_gates gates
If max_gates is None, do all gates
"""
stripped_dag = DAGCircuit()
[stripped_dag.add_qreg(dag.qregs[qreg_name]) for qreg_name in dag.qregs]
vertex_added = 0
for vertex in dag.topological_op_nodes():
within_gate_count = max_gates is None or vertex_added < max_gates
if vertex.op.name != "barrier" and len(vertex.qargs) == 2 and within_gate_count:
stripped_dag.apply_operation_back(op=vertex.op, qargs=vertex.qargs)
vertex_added += 1
return stripped_dag
def _calc_exp_val(num_qubits: int, observable: str, state: int, prob: float) -> float:
"""Calculate the weighted eigen value of a state and its given prob
Z|0> = |0>
Z|1> = -|1>
I|0> = |0>
I|1> = |1>
Args:
num_qubits (int): _description_
observable (str): _description_
state_prob (Tuple[int, float]): _description_
Returns:
float: _description_
"""
eigenvals = {"Z": {"0": 1, "1": -1}, "I": {"0": 1, "1": 1}}
bin_state = bin(state)[2:].zfill(num_qubits)
eigenval = 1
for bit, base in zip(bin_state, observable):
eigenval *= eigenvals[base][bit]
return prob * eigenval
def expectation_val(prob_vector: np.ndarray, observable: str) -> float:
"""Calculate the expectation value of a given probability vector
Args:
prob_vector (np.ndarray): input probability vector
observable (str): Z or I observables
Returns:
float: expectation value
"""
num_qubits = len(observable)
exp_val = 0
for state, prob in enumerate(prob_vector):
exp_val += _calc_exp_val(num_qubits, observable, state, prob)
return exp_val
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw, IQXDebugging
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, style=IQXDebugging(), backend=FakeBoeblingen())
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the RemoveBarriers pass"""
import unittest
from qiskit.transpiler.passes import RemoveBarriers
from qiskit.converters import circuit_to_dag
from qiskit import QuantumCircuit
from qiskit.test import QiskitTestCase
class TestMergeAdjacentBarriers(QiskitTestCase):
"""Test the MergeAdjacentBarriers pass"""
def test_remove_barriers(self):
"""Remove all barriers"""
circuit = QuantumCircuit(2)
circuit.barrier()
circuit.barrier()
pass_ = RemoveBarriers()
result_dag = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result_dag.size(), 0)
def test_remove_barriers_other_gates(self):
"""Remove all barriers, leave other gates intact"""
circuit = QuantumCircuit(1)
circuit.barrier()
circuit.x(0)
circuit.barrier()
circuit.h(0)
pass_ = RemoveBarriers()
result_dag = pass_.run(circuit_to_dag(circuit))
op_nodes = result_dag.op_nodes()
self.assertEqual(result_dag.size(), 2)
for ii, name in enumerate(["x", "h"]):
self.assertEqual(op_nodes[ii].name, name)
def test_simple_if_else(self):
"""Test that the pass recurses into an if-else."""
pass_ = RemoveBarriers()
base_test = QuantumCircuit(1, 1)
base_test.barrier()
base_test.measure(0, 0)
base_expected = QuantumCircuit(1, 1)
base_expected.measure(0, 0)
test = QuantumCircuit(1, 1)
test.if_else(
(test.clbits[0], True), base_test.copy(), base_test.copy(), test.qubits, test.clbits
)
expected = QuantumCircuit(1, 1)
expected.if_else(
(expected.clbits[0], True),
base_expected.copy(),
base_expected.copy(),
expected.qubits,
expected.clbits,
)
self.assertEqual(pass_(test), expected)
def test_nested_control_flow(self):
"""Test that the pass recurses into nested control flow."""
pass_ = RemoveBarriers()
base_test = QuantumCircuit(1, 1)
base_test.barrier()
base_test.measure(0, 0)
base_expected = QuantumCircuit(1, 1)
base_expected.measure(0, 0)
body_test = QuantumCircuit(1, 1)
body_test.for_loop((0,), None, base_expected.copy(), body_test.qubits, body_test.clbits)
body_expected = QuantumCircuit(1, 1)
body_expected.for_loop(
(0,), None, base_expected.copy(), body_expected.qubits, body_expected.clbits
)
test = QuantumCircuit(1, 1)
test.while_loop((test.clbits[0], True), body_test, test.qubits, test.clbits)
expected = QuantumCircuit(1, 1)
expected.while_loop(
(expected.clbits[0], True), body_expected, expected.qubits, expected.clbits
)
self.assertEqual(pass_(test), expected)
if __name__ == "__main__":
unittest.main()
|
https://github.com/alvinli04/Quantum-Steganography
|
alvinli04
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, AncillaRegister
from qiskit import execute
from qiskit import Aer
from qiskit import IBMQ
from qiskit.compiler import transpile
import neqr
import random
import steganography
def arraynxn(n):
return [[random.randint(0,255) for i in range(n)] for j in range(n)]
'''
NEQR Unit Tests
'''
def convert_to_bits_test():
array2x2 = [[random.randint(0, 255), random.randint(0, 255)], [random.randint(0, 255), random.randint(0, 255)]]
print(array2x2)
bits_arr = neqr.convert_to_bits(array2x2)
print(bits_arr)
def neqr_test():
testarr = arraynxn(4)
print('test array:')
print(testarr)
flattened_array = neqr.convert_to_bits(testarr)
print([''.join([str(b) for i,b in enumerate(a)]) for a in flattened_array])
idx = QuantumRegister(4)
intensity = QuantumRegister(8)
result_circuit = QuantumCircuit(intensity, idx)
neqr.neqr(flattened_array, result_circuit, idx, intensity)
backend = Aer.get_backend('statevector_simulator')
job = execute(result_circuit, backend=backend, shots=1, memory=True)
job_result = job.result()
statevec = job_result.get_statevector(result_circuit)
for i in range(len(statevec)):
if statevec[i] != 0:
print(f"{format(i, '012b')}: {statevec[i].real}")
print(result_circuit)
############################################################################################################################
'''
Steganography Unit Tests
'''
def comparator_test():
#creating registers and adding them to circuit
regX = QuantumRegister(4)
regY = QuantumRegister(4)
circuit = QuantumCircuit(regX, regY)
cr = ClassicalRegister(2)
#changing registers to make them different
circuit.x(regX[0])
circuit.x(regX[2])
circuit.x(regY[1])
circuit.x(regY[3])
result = QuantumRegister(2)
circuit.add_register(result)
circuit.add_register(cr)
#comparator returns the circuit
steganography.comparator(regY, regX, circuit, result)
#result --> ancillas from function
circuit.measure(result, cr)
#measuring
simulator = Aer.get_backend('aer_simulator')
simulation = execute(circuit, simulator, shots=1, memory=True)
simResult = simulation.result()
counts = simResult.get_counts(circuit)
for(state, count) in counts.items():
big_endian_state = state[::-1]
print(big_endian_state)
def coordinate_comparator_test():
regXY = QuantumRegister(2)
regAB = QuantumRegister(2)
result = QuantumRegister(1)
circuit = QuantumCircuit(regXY, regAB, result)
#uncomment this to make the registers different
#regXY is in |00> and regAB in |01>
#circuit.x(regAB[1])
#circuit.x(regXY[1])
steganography.coordinate_comparator(circuit, result, regXY, regAB)
print(circuit)
backend = Aer.get_backend('statevector_simulator')
simulation = execute(circuit, backend=backend, shots=1, memory=True)
simResult = simulation.result()
statevec = simResult.get_statevector(circuit)
for state in range(len(statevec)):
if statevec[state] != 0:
#note: output is in little endian
print(f"{format(state, '05b')}: {statevec[state].real}")
def difference_test():
regY = QuantumRegister(4, "regY")
regX = QuantumRegister(4, "regX")
difference = QuantumRegister(4, 'difference')
cr = ClassicalRegister(4, 'measurement')
circuit = QuantumCircuit(regY, regX, difference, cr)
circuit.barrier()
steganography.difference(circuit, regY, regX, difference)
#print(circuit.draw())
circuit.measure(difference, cr)
simulator = Aer.get_backend('aer_simulator')
simulation = execute(circuit, simulator, shots=1)
result = simulation.result()
counts = result.get_counts(circuit)
for(state, count) in counts.items():
big_endian_state = state[::-1]
print(big_endian_state)
def get_secret_image_test():
test_arr = [[[random.randint(0,1) for i in range(4)] for j in range(4)] for k in range(5)]
test_result = steganography.get_secret_image(5, test_arr)
for a in test_arr:
print(a)
print(f'result:\n {test_result}')
def invert_test():
test_arr = arraynxn(4)
print(neqr.convert_to_bits(test_arr))
idx = QuantumRegister(4)
intensity = QuantumRegister(8)
inverse = QuantumRegister(8)
circuit = QuantumCircuit(inverse, intensity, idx)
neqr.neqr(neqr.convert_to_bits(test_arr), circuit, idx, intensity)
steganography.invert(circuit, intensity, inverse)
backend = Aer.get_backend('statevector_simulator')
simulation = execute(circuit, backend=backend, shots=1, memory=True)
simResult = simulation.result()
statevec = simResult.get_statevector(circuit)
for state in range(len(statevec)):
if statevec[state] != 0:
#note: output is in little endian
#only have to look at first bit
print(f"{format(state, '012b')}: {statevec[state].real}")
def get_key_test():
test_cover = arraynxn(2)
test_secret = arraynxn(2)
print(f'cover:\n {test_cover} \nsecret:\n{test_secret}')
sz = 4
cover_idx, cover_intensity = QuantumRegister(2), QuantumRegister(8)
cover = QuantumCircuit(cover_intensity, cover_idx)
secret_idx, secret_intensity = QuantumRegister(2), QuantumRegister(8)
secret = QuantumCircuit(secret_intensity, secret_idx)
neqr.neqr(neqr.convert_to_bits(test_cover), cover, cover_idx, cover_intensity)
neqr.neqr(neqr.convert_to_bits(test_secret), secret, secret_idx, secret_intensity)
key_idx, key_result = QuantumRegister(2), QuantumRegister(1)
inv = QuantumRegister(8)
diff1 = QuantumRegister(8)
diff2 = QuantumRegister(8)
comp_res = QuantumRegister(2)
key_mes = ClassicalRegister(3)
circuit = QuantumCircuit(cover_intensity, cover_idx, secret_intensity, secret_idx, key_idx, key_result, inv, diff1, diff2, comp_res, key_mes)
steganography.invert(circuit, secret_intensity, inv)
steganography.get_key(circuit, key_idx, key_result, cover_intensity, secret_intensity, inv, diff1, diff2, comp_res, sz)
circuit.measure(key_result[:] + key_idx[:], key_mes)
provider = IBMQ.load_account()
simulator = provider.get_backend('simulator_mps')
simulation = execute(circuit, simulator, shots=1024)
result = simulation.result()
counts = result.get_counts(circuit)
for(state, count) in counts.items():
big_endian_state = state[::-1]
print(f"Measured {big_endian_state} {count} times.")
def load_test():
idx = QuantumRegister(2)
odx = QuantumRegister(1)
cr = ClassicalRegister(3)
qc = QuantumCircuit(idx, odx, cr)
qc.h(idx)
qc.measure(idx[:] + odx[:], cr)
simulator = Aer.get_backend("aer_simulator")
simulation = execute(qc, simulator, shots=1024)
result = simulation.result()
counts = result.get_counts(qc)
for(state, count) in counts.items():
big_endian_state = state[::-1]
print(f"Measured {big_endian_state} {count} times.")
def main():
get_key_test()
if __name__ == '__main__':
main()
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram
from qiskit.providers.aer import noise
from qiskit.compiler import transpile
import numpy as np
coupling_map = [[1, 0], [2, 0], [2, 1], [3, 2], [3, 4], [4, 2]]
noise_dict = {'errors': [{'type': 'qerror', 'operations': ['u2'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0004721766167523067, 0.0004721766167523067, 0.0004721766167523067, 0.9985834701497431], 'gate_qubits': [[0]]}, {'type': 'qerror', 'operations': ['u2'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0005151090708174488, 0.0005151090708174488, 0.0005151090708174488, 0.9984546727875476], 'gate_qubits': [[1]]}, {'type': 'qerror', 'operations': ['u2'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0005151090708174488, 0.0005151090708174488, 0.0005151090708174488, 0.9984546727875476], 'gate_qubits': [[2]]}, {'type': 'qerror', 'operations': ['u2'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.000901556048412383, 0.000901556048412383, 0.000901556048412383, 0.9972953318547628], 'gate_qubits': [[3]]}, {'type': 'qerror', 'operations': ['u2'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0011592423249461303, 0.0011592423249461303, 0.0011592423249461303, 0.9965222730251616], 'gate_qubits': [[4]]}, {'type': 'qerror', 'operations': ['u3'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0009443532335046134, 0.0009443532335046134, 0.0009443532335046134, 0.9971669402994862], 'gate_qubits': [[0]]}, {'type': 'qerror', 'operations': ['u3'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0010302181416348977, 0.0010302181416348977, 0.0010302181416348977, 0.9969093455750953], 'gate_qubits': [[1]]}, {'type': 'qerror', 'operations': ['u3'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0010302181416348977, 0.0010302181416348977, 0.0010302181416348977, 0.9969093455750953], 'gate_qubits': [[2]]}, {'type': 'qerror', 'operations': ['u3'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.001803112096824766, 0.001803112096824766, 0.001803112096824766, 0.9945906637095256], 'gate_qubits': [[3]]}, {'type': 'qerror', 'operations': ['u3'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0023184846498922607, 0.0023184846498922607, 0.0023184846498922607, 0.9930445460503232], 'gate_qubits': [[4]]}, {'type': 'qerror', 'operations': ['cx'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'x', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.9672573379090872], 'gate_qubits': [[1, 0]]}, {'type': 'qerror', 'operations': ['cx'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'x', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.9699888805021712], 'gate_qubits': [[2, 0]]}, {'type': 'qerror', 'operations': ['cx'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'x', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.9627184072576159], 'gate_qubits': [[2, 1]]}, {'type': 'qerror', 'operations': ['cx'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'x', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.9437457618579164], 'gate_qubits': [[3, 2]]}, {'type': 'qerror', 'operations': ['cx'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'x', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.9339816349935997], 'gate_qubits': [[3, 4]]}, {'type': 'qerror', 'operations': ['cx'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'x', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.9307167621063416], 'gate_qubits': [[4, 2]]}, {'type': 'roerror', 'operations': ['measure'], 'probabilities': [[0.9372499999999999, 0.06275000000000008], [0.06275000000000008, 0.9372499999999999]], 'gate_qubits': [[0]]}, {'type': 'roerror', 'operations': ['measure'], 'probabilities': [[0.9345, 0.0655], [0.0655, 0.9345]], 'gate_qubits': [[1]]}, {'type': 'roerror', 'operations': ['measure'], 'probabilities': [[0.97075, 0.029249999999999998], [0.029249999999999998, 0.97075]], 'gate_qubits': [[2]]}, {'type': 'roerror', 'operations': ['measure'], 'probabilities': [[0.9742500000000001, 0.02574999999999994], [0.02574999999999994, 0.9742500000000001]], 'gate_qubits': [[3]]}, {'type': 'roerror', 'operations': ['measure'], 'probabilities': [[0.8747499999999999, 0.12525000000000008], [0.12525000000000008, 0.8747499999999999]], 'gate_qubits': [[4]]}], 'x90_gates': []}
noise_model = noise.noise_model.NoiseModel.from_dict( noise_dict )
qr = QuantumRegister(5, 'qr')
cr = ClassicalRegister(1, 'cr')
backend = Aer.get_backend('qasm_simulator')
def AND (input1,input2, q_1=0,q_2=1,q_out=2):
# The keyword q_1 specifies the qubit used to encode input1
# The keyword q_2 specifies qubit used to encode input2
# The keyword q_out specifies qubit to be as output
qc = QuantumCircuit(qr, cr)
# prepare input on qubits q1 and q2
if input1=='1':
qc.x( qr[ q_1 ] )
if input2=='1':
qc.x( qr[ q_2 ] )
qc.ccx(qr[ q_1 ],qr[ q_2 ],qr[ q_out ]) # the AND just needs a c
qc.measure(qr[ q_out ],cr[0]) # output from qubit 1 is measured
# the circuit is run on a simulator, but we do it so that the noise and connectivity of Tenerife are also reproduced
job = execute(qc, backend, shots=10000, noise_model=noise_model,
coupling_map=coupling_map,
basis_gates=noise_model.basis_gates)
output = job.result().get_counts()
return output
result = AND('0','0')
print( result )
plot_histogram( result )
worst = 1
for input1 in ['0','1']:
for input2 in ['0','1']:
print('\nProbability of correct answer for inputs',input1,input2)
prob = AND(input1,input2, q_1=0,q_2=1,q_out=2)[str(int( input1=='1' and input2=='1' ))]/10000
print( prob )
worst = min(worst,prob)
print('\nThe lowest of these probabilities was',worst)
for j in range(5):
qc = QuantumCircuit(qr, cr)
qc.measure(qr[j],cr[0])
job = execute(qc, backend, shots=10000, noise_model=noise_model, coupling_map=coupling_map, basis_gates=noise_model.basis_gates)
output = job.result().get_counts()
print('Probability of incorrect output for qubit',j,'is',output['1']/10000)
worst = 1
for input1 in ['0','1']:
for input2 in ['0','1']:
print('\nProbability of correct answer for inputs',input1,input2)
prob = AND(input1,input2, q_1=3,q_2=4,q_out=2)[str(int( input1=='1' and input2=='1' ))]/10000
print( prob )
worst = min(worst,prob)
print('\nThe lowest of these probabilities was',worst)
def AND (input1,input2, q_1=0,q_2=1,q_out=2):
# The keyword q_1 specifies the qubit used to encode input1
# The keyword q_2 specifies qubit used to encode input2
# The keyword q_out specifies qubit to be as output
qc = QuantumCircuit(qr, cr)
# prepare input on qubits q1 and q2
if input1=='1':
qc.x( qr[ q_1 ] )
if input2=='1':
qc.x( qr[ q_2 ] )
qc.ch(qr[q_1],qr[q_out])
qc.cz(qr[q_2],qr[q_out])
qc.ch(qr[q_1],qr[q_out])
qc.measure(qr[ q_out ],cr[0]) # output from qubit 1 is measured
# the circuit is run on a simulator, but we do it so that the noise and connectivity of Tenerife are also reproduced
job = execute(qc, backend, shots=10000, noise_model=noise_model,
coupling_map=coupling_map,
basis_gates=noise_model.basis_gates)
output = job.result().get_counts()
return output
worst = 1
for input1 in ['0','1']:
for input2 in ['0','1']:
print('\nProbability of correct answer for inputs',input1,input2)
prob = AND(input1,input2, q_1=0,q_2=1,q_out=2)[str(int( input1=='1' and input2=='1' ))]/10000
print( prob )
worst = min(worst,prob)
print('\nThe lowest of these probabilities was',worst)
qc = QuantumCircuit(qr, cr)
qc.ch(qr[1],qr[0])
print('Original circuit')
print(qc)
print('Compiled circuit')
qc_compiled = transpile(qc,backend=backend)
print(qc_compiled)
def AND (input1,input2, q_1=0,q_2=1,q_out=2):
# The keyword q_1 specifies the qubit used to encode input1
# The keyword q_2 specifies qubit used to encode input2
# The keyword q_out specifies qubit to be as output
qc = QuantumCircuit(qr, cr)
# prepare input on qubits q1 and q2
if input1=='1':
qc.x( qr[ q_1 ] )
if input2=='1':
qc.x( qr[ q_2 ] )
qc.ry(-np.pi/4,qr[q_out])
qc.cx(qr[q_1],qr[q_out])
qc.ry(np.pi/4,qr[q_out])
qc.cz(qr[q_2],qr[q_out])
qc.ry(-np.pi/4,qr[q_out])
qc.cx(qr[q_1],qr[q_out])
qc.ry(np.pi/4,qr[q_out])
qc.measure(qr[ q_out ],cr[0]) # output from qubit 1 is measured
# the circuit is run on a simulator, but we do it so that the noise and connectivity of Tenerife are also reproduced
job = execute(qc, backend, shots=10000, noise_model=noise_model,
coupling_map=coupling_map,
basis_gates=noise_model.basis_gates)
output = job.result().get_counts()
return output
worst = 1
for input1 in ['0','1']:
for input2 in ['0','1']:
print('\nProbability of correct answer for inputs',input1,input2)
prob = AND(input1,input2, q_1=0,q_2=1,q_out=2)[str(int( input1=='1' and input2=='1' ))]/10000
print( prob )
worst = min(worst,prob)
print('\nThe lowest of these probabilities was',worst)
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import pandas as pd
import itertools
import cma
import os
import sys
import argparse
import pickle
import random
import re
from pprint import pprint
import qiskit
from qiskit import *
from qiskit import Aer
from qiskit import IBMQ
from qiskit.providers.aer.noise.noise_model import NoiseModel
from qiskit.test.mock import *
from qiskit.providers.aer import AerSimulator, QasmSimulator
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
import mitiq
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
provider = IBMQ.get_provider(hub='', group='internal', project='hirashi-jst')
print("provider:", provider)
L = 3
p = 2
dt = 1.0
tf = 20
shots = 8192
def TwirlCircuit(circ: str) -> QuantumCircuit:
"""
そのまま使う: 修正は後回し
"""
#! qasm ベタ書き
def apply_pauli(num: int, qb: int) -> str:
if (num == 0):
return f'id q[{qb}];\n'
elif (num == 1):
return f'x q[{qb}];\n'
elif (num == 2):
return f'y q[{qb}];\n'
else:
return f'z q[{qb}];\n'
paulis = [(i,j) for i in range(0,4) for j in range(0,4)]
paulis.remove((0,0))
paulis_map = [(0, 1), (3, 2), (3, 3), (1, 1), (1, 0), (2, 3), (2, 2), (2, 1), (2, 0), (1, 3), (1, 2), (3, 0), (3, 1), (0, 2), (0, 3)]
new_circ = ''
ops = circ.qasm().splitlines(True) #! 生のqasmコードを持ってきてる: オペレータに分解
for op in ops:
if (op[:2] == 'cx'): # can add for cz, etc.
num = random.randrange(len(paulis)) #! permute paulis
qbs = re.findall('q\[(.)\]', op)
new_circ += apply_pauli(paulis[num][0], qbs[0])
new_circ += apply_pauli(paulis[num][1], qbs[1])
new_circ += op
new_circ += apply_pauli(paulis_map[num][0], qbs[0])
new_circ += apply_pauli(paulis_map[num][1], qbs[1])
else:
new_circ += op
return qiskit.circuit.QuantumCircuit.from_qasm_str(new_circ)
# とりあえずOK
def evolve(alpha: float, q0: Union[int, QuantumRegister], q1: Union[int, QuantumRegister]) -> QuantumCircuit:
"""
The implementation of Fig. 4 in https://arxiv.org/abs/2112.12654
"""
qc = QuantumCircuit(2)
qc.rz(-np.pi / 2, q1)
qc.cnot(q1, q0)
qc.rz(alpha - np.pi / 2, q0)
qc.ry(np.pi / 2 - alpha, q1)
qc.cnot(q0, q1)
qc.ry(alpha - np.pi / 2, q1)
qc.cnot(q1, q0)
qc.rz(np.pi / 2, q0)
return qc
# とりあえずOK
def make_ansatz_circuit(num_qubits: int, ansatz_depth: int, parameters: np.array) -> QuantumCircuit:
"""
Prepare ansatz circuit
code reference: https://gitlab.com/QANED/heis_dynamics
method reference: https://arxiv.org/abs/1906.06343
== AnsatzCircuit(param, p) -> QuantumCircuit
Args:
parameters: 1d array (for 2d parameters on circuit)
"""
qc = QuantumCircuit(num_qubits)
for l in range(ansatz_depth):
if num_qubits & 1:
for i in range(0, num_qubits, 2): # linear condition
qc.compose(evolve(parameters[l * ansatz_depth + i] / 4), [i, i + 1], inplace = True) #! we do not have to divide the angle by 4
for i in range(1, num_qubits - 1, 2): # linear condition
# ! we do not have to divide the angle by 4
qc.compose(evolve(parameters[l * ansatz_depth + i] / 4), [i, i + 1], inplace=True)
else:
for i in range(0, num_qubits - 1, 2): # linear condition
# ! we do not have to divide the angle by 4
qc.compose(evolve(parameters[l * ansatz_depth + i]), [i, i + 1], inplace=True)
for i in range(1, num_qubits - 1, 2): # linear condition
# ! we do not have to divide the angle by 4
qc.compose(evolve(parameters[l * ansatz_depth + i]), [i, i + 1], inplace=True)
return qc
# とりあえずOK
def make_trotter_circuit(num_qubits: int, time_interval: float) -> QuantumCircuit:
"""
Prepare Trotter circuit
code reference: https://gitlab.com/QANED/heis_dynamics
method reference: https://arxiv.org/abs/1906.06343
== TrotterEvolveCircuit(dt, nt, init) -> QuantumCircuit
"""
qc = QuantumCircuit(num_qubits)
for n in range(trotter_steps): #! time_interval の符号に注意
if num_qubits & 1:
for i in range(0, num_qubits, 2): # linear condition
qc.compose(evolve(time_interval / 4), [i, i + 1], inplace = True) #! we do not have to divide the angle by 4
for i in range(1, num_qubits - 1, 2): # linear condition
qc.compose(evolve(time_interval / 4), [i, i + 1], inplace = True) # ! we do not have to divide the angle by 4
else:
for i in range(0, num_qubits - 1, 2): # linear condition
qc.compose(evolve(time_interval / 4), [i, i + 1], inplace = True) #! we do not have to divide the angle by 4
for i in range(1, num_qubits - 1, 2): # linear condition
qc.compose(evolve(time_interval / 4), [i, i + 1], inplace = True) # ! we do not have to divide the angle by 4
return qc
#TODO VTCとは別実装?→ no, 同じ実装に。
def SimulateAndReorder(circ):
"""
#! execution wrapper
Executes a circuit using the statevector simulator and reorders basis to match with standard
"""
backend = Aer.get_backend('statevector_simulator')
return execute(circ.reverse_bits(), backend).result().get_statevector()
def Simulate(circ):
"""
#! execution wrapper
Executes a circuit using the statevector simulator. Doesn't reorder -- which is needed for intermediate steps in the VTC
"""
backend = Aer.get_backend('statevector_simulator')
return execute(circ, backend).result().get_statevector()
#TODO
def LoschmidtEchoExecutor(circuits, backend, shots, filter):
"""
#! 回路を実行
Returns the expectation value to be mitigated.
:param circuit: Circuit to run. #! ここでのcircuitsは
:param backend: backend to run the circuit on
:param shots: Number of times to execute the circuit to compute the expectation value.
:param fitter: measurement error mitigator
"""
# circuits = [TwirlCircuit(circ) for circ in circuits]
scale_factors = [1.0, 2.0, 3.0] #! ZNEのノイズスケーリングパラメタ
folded_circuits = [] #! ZNE用の回路
for circuit in circuits:
folded_circuits.append([mitiq.zne.scaling.fold_gates_at_random(circuit, scale) for scale in scale_factors]) #! ここでmitiqを使用
folded_circuits = list(itertools.chain(*folded_circuits)) #! folded_circuitsを平坦化
folded_circuits = [TwirlCircuit(circ) for circ in folded_circuits] #! 後からPauli Twirlingを施す!
print("length of circuit in job", len(folded_circuits))
#! jobを投げる
job = qiskit.execute(
experiments=folded_circuits,
backend=backend,
optimization_level=0,
shots=shots
)
print("casted job")
#! fidelity測定用(VTCをしないなら、ここはtomographyで良い)
c = ['1','1','0'] #! これをpermutationする
# c = [str((1 + (-1)**(i+1)) // 2) for i in range(L)]
c = ''.join(c)[::-1] #! endianを反転 (big endianへ)
res = job.result()
if (filter is not None): #! QREM
res = filter.apply(res)
print("retrieved job")
all_counts = [job.result().get_counts(i) for i in range(len(folded_circuits))]
expectation_values = []
for counts in all_counts:
total_allowed_shots = [counts.get(''.join(p)) for p in set(itertools.permutations(c))] #! ここでcをpermutationしている
total_allowed_shots = sum([0 if x is None else x for x in total_allowed_shots])
if counts.get(c) is None:
expectation_values.append(0)
else:
expectation_values.append(counts.get(c)/total_allowed_shots)
# expectation_values = [counts.get(c) / shots for counts in all_counts]
zero_noise_values = []
if isinstance(backend, qiskit.providers.aer.backends.qasm_simulator.QasmSimulator): # exact_sim
for i in range(len(circuits)):
zero_noise_values.append(np.mean(expectation_values[i*len(scale_factors):(i+1)*len(scale_factors)]))
else: #device_sim, real_device
fac = mitiq.zne.inference.LinearFactory(scale_factors)
for i in range(len(circuits)):
zero_noise_values.append(fac.extrapolate(scale_factors,
expectation_values[i*len(scale_factors):(i+1)*len(scale_factors)]))
print("zero_noise_values")
pprint(zero_noise_values)
print()
return zero_noise_values
#TODO
def LoschmidtEchoCircuit(params, U_v, U_trot, init, p):
"""
#! 回路を作成
Cost function using the Loschmidt Echo. Just using statevectors currently -- can rewrite using shots
:param params: parameters new variational circuit that represents U_trot U_v | init >. Need dagger for cost function
:param U_v: variational circuit that stores the state before the trotter step
:param U_trot: trotter step
:param init: initial state
:param p: number of ansatz steps
"""
U_v_prime = AnsatzCircuit(params, p)
circ = init + U_v + U_trot + U_v_prime.inverse()
circ.measure_all()
return circ
def LoschmidtEcho(params, U_v, U_trot, init, p, backend, shots, filter):
"""
#! 実行パート
"""
circs = []
for param in params:
circs.append(LoschmidtEchoCircuit(param, U_v, U_trot, init, p)) #! 回路を作成
print("length of circuits without zne:", len(circs))
res = LoschmidtEchoExecutor(circs, backend, shots, filter) #! 回路を実行
return abs(1 - np.array(res))
def LoschmidtEchoExact(params, U_v, U_trot, init, p):
"""
#! unused function
"""
U_v_prime = AnsatzCircuit(params, p)
circ = init + U_v + U_trot + U_v_prime.inverse()
circ_vec = Simulate(circ)
init_vec = Simulate(init)
return 1 - abs(np.conj(circ_vec) @ init_vec)**2
def CMAES(U_v, U_trot, init, p, backend, shots, filter):
"""
#! 実行 + 最適化パート
"""
init_params = np.random.uniform(0, 2*np.pi, (L-1)*p)
es = cma.CMAEvolutionStrategy(init_params, np.pi/2)
es.opts.set({'ftarget':5e-3, 'maxiter':1000})
# es = pickle.load(open(f'./results_{L}/optimizer_dump', 'rb'))
while not es.stop(): #! 最適化パート
# solutions = es.ask(25) # ! 25 = number of returned solutions
solutions = es.ask(10)
print("solutions")
pprint(solutions)
es.tell(solutions, LoschmidtEcho(solutions, U_v, U_trot, init, p, backend, shots, filter)) #! 実行パート
# es.tell(solutions, LoschmidtEchoExact(solutions, U_v, U_trot, init, p)) #! 実行パート
es.disp()
open(f'./results_{L}/optimizer_dump', 'wb').write(es.pickle_dumps())
return es.result_pretty()
def VTC(tf, dt, p, init, backend, shots, filter):
"""
#! tf: 総経過時間
#! dt: trotter step size: 時間間隔
#! p: ansatzのステップ数
"""
VTCParamList = [np.zeros((L-1)*p)] #! デフォルトのパラメタ(初期値)
VTCStepList = [SimulateAndReorder(init.copy())] #! type: List[Statevector]
# TrotterFixStepList = [init]
TimeStep = [0]
if (os.path.exists(f'./results_{L}/VTD_params_{tf}_{L}_{p}_{dt}_{shots}.csv')): #! 2巡目からこっち
VTCParamList = pd.read_csv(f'./results_{L}/VTD_params_{tf}_{L}_{p}_{dt}_{shots}.csv', index_col=0)
VTCStepList = pd.read_csv(f'./results_{L}/VTD_results_{tf}_{L}_{p}_{dt}_{shots}.csv', index_col=0)
temp = VTCParamList.iloc[-1]
print(temp, "th time interval")
U_v = AnsatzCircuit(temp, p)
else: #! 最初はこっちに入る
VTCParamList = pd.DataFrame(np.array(VTCParamList), index=np.array(TimeStep))
VTCStepList = pd.DataFrame(np.array(VTCStepList), index=np.array(TimeStep))
print("0 th time interval")
print()
U_v = QuantumCircuit(L)
ts = VTCParamList.index
#! 時間間隔
U_trot = TrotterEvolveCircuit(dt, p, QuantumCircuit(L)) #! Trotter分解のunitaryを作る
print()
print("start CMAES")
print()
res = CMAES(U_v, U_trot, init, p, backend, shots, filter) #! ここでプロセスを実行!!!!
print()
print("res")
pprint(res)
#! 新しいループ結果を追加し、tsを更新
res = res.xbest # ! best solution evaluated
print("res.xbest")
pprint(res)
VTCParamList.loc[ts[-1]+(dt*p)] = np.array(res)
VTCStepList.loc[ts[-1]+(dt*p)] = np.array(SimulateAndReorder(init + AnsatzCircuit(res, p)))
ts = VTCParamList.index
# VTCParamList = pd.DataFrame(np.array(VTCParamList), index=np.array(TimeStep))
# VTCStepList = pd.DataFrame(np.array(VTCStepList), index=np.array(TimeStep))
#! csvファイルを更新
VTCParamList.to_csv(f'./results_{L}/VTD_params_{tf}_{L}_{p}_{dt}_{shots}.csv')
VTCStepList.to_csv(f'./results_{L}/VTD_results_{tf}_{L}_{p}_{dt}_{shots}.csv')
if (ts[-1] >= tf):
return
else:
print("next step")
VTC(tf, dt, p, init, backend, shots, filter)
#! ここからQREM回路
qr = QuantumRegister(L)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# device_backend = FakeJakarta()
# device_sim = AerSimulator.from_backend(device_backend)
real_device = provider.get_backend('ibmq_jakarta')
noise_model = NoiseModel.from_backend(real_device)
device_sim = QasmSimulator(method='statevector', noise_model=noise_model)
exact_sim = Aer.get_backend('qasm_simulator') # QasmSimulator(method='statevector')
t_qc = transpile(meas_calibs)
qobj = assemble(t_qc, shots=8192)
# cal_results = real_device.run(qobj, shots=8192).result()
cal_results = device_sim.run(qobj, shots=8192).result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
print("qrem done")
# np.around(meas_fitter.cal_matrix, decimals=2)
init = QuantumCircuit(L)
# c = [str((1 + (-1)**(i+1)) // 2) for i in range(L)]
c = ['1','1','0'] #! なぜinitial stateが110なの??????? もしかしてopen science prizeを意識???
#! けどループでこのプログラムが実行されるたびにここが|110>だとおかしくないか?
for q in range(len(c)):
if (c[q] == '1'):
init.x(q)
#! ここまでQREM回路
nt = int(np.ceil(tf / (dt * p)))
# f = open(f'./results_{L}/logging.txt', 'a')
# sys.stdout = f
#! tf: シミュレーションの(経過)時間
#! dt: trotter分解のステップ数
#! p: ansatzのステップ数 (論文中のL)
# VTC(tf, dt, p, init, real_device, shots, meas_fitter.filter) #! mainの処理
print("vtc start!!!! \n\n\n")
VTC(tf, dt, p, init, device_sim, shots, meas_fitter.filter) #! mainの処理
# f.close()
|
https://github.com/pedroripper/qiskit_tutoriais
|
pedroripper
|
from qiskit import *
# Para representar o qubit em uma esfera de bloch devemos pensar nele na seguinte forma:
# Depois de encontrar o theta, phi que desejamos, vamos ter os valores necessários para plotar nossa
# esfera de bloch
# Para plotar precisamos chamar a função plot_bloch_vector_spherical() que leva como parâmetro
# o vetor de bloch
# para encontrar o vetor de bloch seguimos a fórmula
# Para o exemplo vamos usar o qubit no estado |+> que fica da seguinte forma:
# Para conseguir representar esse estado no formato dado anteriormente vamos precisar
# de um theta valendo pi/2 e de um phi valendo 0
# portanto vamos ter o vetor de bloch como (1,0,0)
# Finalmente podemos exibir a esfera de bloch
from qiskit.visualization import plot_bloch_vector
%matplotlib inline
plot_bloch_vector([1,0,0], title="Minha Primeira Esfera de Bloch")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_optimization import QuadraticProgram
problem = QuadraticProgram("sample")
problem.binary_var("x")
problem.binary_var("y")
problem.maximize(linear={"x": 1, "y": -2})
print(problem.prettyprint())
from qiskit.algorithms import NumPyMinimumEigensolver
from qiskit_optimization.algorithms import MinimumEigenOptimizer
mes = NumPyMinimumEigensolver()
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_optimization.algorithms import MinimumEigenOptimizer
mes = NumPyMinimumEigensolver()
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit import BasicAer
from qiskit.algorithms import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit_optimization.algorithms import MinimumEigenOptimizer
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
qins = QuantumInstance(backend=backend, shots=shots)
mes = QAOA(optimizer=COBYLA(), quantum_instance=qins)
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit.algorithms.minimum_eigensolvers import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
shots = 1000
mes = QAOA(sampler=Sampler(), optimizer=COBYLA())
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit import BasicAer
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.utils import QuantumInstance
from qiskit_optimization.algorithms import MinimumEigenOptimizer
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
qins = QuantumInstance(backend=backend, shots=shots)
mes = VQE(ansatz=RealAmplitudes(), optimizer=COBYLA(), quantum_instance=qins)
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit.algorithms.minimum_eigensolvers import SamplingVQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
mes = SamplingVQE(sampler=Sampler(), ansatz=RealAmplitudes(), optimizer=COBYLA())
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.primitives import Estimator
from qiskit_optimization.algorithms import MinimumEigenOptimizer
mes = VQE(estimator=Estimator(), ansatz=RealAmplitudes(), optimizer=COBYLA())
try:
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
except TypeError as ex:
print(ex)
from qiskit import BasicAer
from qiskit.algorithms import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit_optimization.algorithms import WarmStartQAOAOptimizer, SlsqpOptimizer
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
qins = QuantumInstance(backend=backend, shots=shots)
qaoa = QAOA(optimizer=COBYLA(), quantum_instance=qins)
optimizer = WarmStartQAOAOptimizer(
pre_solver=SlsqpOptimizer(), relax_for_pre_solver=True, qaoa=qaoa, epsilon=0.25
)
result = optimizer.solve(problem)
print(result)
from qiskit.algorithms.minimum_eigensolvers import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import WarmStartQAOAOptimizer, SlsqpOptimizer
qaoa = QAOA(sampler=Sampler(), optimizer=COBYLA())
optimizer = WarmStartQAOAOptimizer(
pre_solver=SlsqpOptimizer(), relax_for_pre_solver=True, qaoa=qaoa, epsilon=0.25
)
result = optimizer.solve(problem)
print(result)
from qiskit import BasicAer
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit_optimization.algorithms import GroverOptimizer
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
qins = QuantumInstance(backend=backend, shots=shots)
optimizer = GroverOptimizer(num_value_qubits=3, num_iterations=3, quantum_instance=qins)
result = optimizer.solve(problem)
print(result)
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import GroverOptimizer
optimizer = GroverOptimizer(num_value_qubits=3, num_iterations=3, sampler=Sampler())
result = optimizer.solve(problem)
print(result)
from qiskit import BasicAer
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import GroverOptimizer
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
qins = QuantumInstance(backend=backend, shots=shots)
try:
optimizer = GroverOptimizer(
num_value_qubits=3, num_iterations=3, quantum_instance=qins, sampler=Sampler()
)
# raises an error because both quantum_instance and sampler are set.
except ValueError as ex:
print(ex)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/WhenTheyCry96/qiskitHackathon2022
|
WhenTheyCry96
|
%load_ext autoreload
%autoreload 2
import os
import warnings
import numpy as np
import pandas as pd
import qiskit_metal as metal
from numpy import pi
from scipy.constants import c, h, pi, hbar, e
from qiskit_metal import designs, draw, MetalGUI, Dict, Headings
from qiskit_metal.qlibrary.qubits.transmon_pocket_6 import TransmonPocket6
from qiskit_metal.qlibrary.qubits.transmon_pocket_cl import TransmonPocketCL
from qiskit_metal.qlibrary.tlines.meandered import RouteMeander
from qiskit_metal.qlibrary.terminations.open_to_ground import OpenToGround
from qiskit_metal.qlibrary.lumped.cap_3_interdigital import Cap3Interdigital
from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled
from qiskit_metal.analyses.em.cpw_calculations import guided_wavelength
from qiskit_metal.analyses.quantization import LOManalysis, EPRanalysis
from qiskit_metal.analyses.quantization.lumped_capacitive import load_q3d_capacitance_matrix
from qiskit_metal.analyses.quantization.lom_core_analysis import CompositeSystem, Cell, Subsystem, QuantumSystemRegistry
ws_path = os.getcwd()
warnings.filterwarnings("ignore")
design = designs.DesignPlanar()
design.overwrite_enabled = True
#constants:
phi0 = h/(2*e)
varphi0 = phi0/(2*pi)
# project target parameters
f_qList = np.around(np.linspace(5.25, 5.75, 4),2) # GHz
f_rList = f_qList + 1.8 # GHz
L_JJList = np.around(varphi0**2/((f_qList*1e9+300e6)**2/(8*300e6))/h*1e9, 2) # nH
# initial CPW readout lengths
def find_resonator_length(frequency, line_width, line_gap, N):
#frequency in GHz
#line_width/line_gap in um
#N -> 2 for lambda/2, 4 for lambda/4
[lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6,
line_gap*10**-6, 750*10**-6, 200*10**-9)
return str(lambdaG/N*10**3)+" mm"
find_resonator_length(f_rList, 10, 6, 2)
find_resonator_length(np.around(np.linspace(8, 9, 4),2), 10, 6, 2)
chipX = 9
chipY = 9
design.chips.main.size_x = str(chipX)+"mm"
design.chips.main.size_y = str(chipY)+"mm"
gui = MetalGUI(design)
design.delete_all_components()
# basic parameters for inital cut
C_JJ = 2
pad_g = 30
pad_w = 450
pad_h = 150
readout_g = 30
buslineL_g = 30
buslineH_g = 30
C_JJU = str(C_JJ)+"fF"
pad_g = str(pad_g)+"um"
pad_w = str(pad_w)+"um"
pad_h = str(pad_h)+"um"
readout_g = str(readout_g)+"um"
buslineL_g = str(buslineL_g)+"um"
buslineH_g = str(buslineH_g)+"um"
connector1_pads_options = dict(
cR = dict(loc_W=0, loc_H=1, pad_width='80 um', pad_gap=readout_g, pad_height='30 um'), # readout resonator
cL = dict(loc_W=1, loc_H=-1, pad_width='80 um', pad_gap=buslineL_g, pad_height='30 um'), # bus line for lower frequency
cH = dict(loc_W=-1, loc_H=-1, pad_width='80 um', pad_gap=buslineH_g, pad_height='30 um') # bus line for higher frequency
)
connector2_pads_options = dict(
cR = dict(loc_W=0, loc_H=1, pad_width='80 um', pad_gap=readout_g, pad_height='30 um'), # readout resonator
cL = dict(loc_W=1, loc_H=-1, pad_width='80 um', pad_gap=buslineL_g, pad_height='30 um'), # bus line for lower frequency
cH = dict(loc_W=-1, loc_H=-1, pad_width='80 um', pad_gap=buslineH_g, pad_height='30 um') # bus line for higher frequency
)
connector3_pads_options = dict(
cR = dict(loc_W=0, loc_H=1, pad_width='80 um', pad_gap=readout_g, pad_height='30 um'), # readout resonator
cL = dict(loc_W=1, loc_H=-1, pad_width='80 um', pad_gap=buslineL_g, pad_height='30 um'), # bus line for lower frequency
cH = dict(loc_W=-1, loc_H=-1, pad_width='80 um', pad_gap=buslineH_g, pad_height='30 um') # bus line for higher frequency
)
connector4_pads_options = dict(
cR = dict(loc_W=0, loc_H=1, pad_width='80 um', pad_gap=readout_g, pad_height='30 um'), # readout resonator
cL = dict(loc_W=1, loc_H=-1, pad_width='80 um', pad_gap=buslineL_g, pad_height='30 um'), # bus line for lower frequency
cH = dict(loc_W=-1, loc_H=-1, pad_width='80 um', pad_gap=buslineH_g, pad_height='30 um') # bus line for higher frequency
)
# target f: 5.25
connection1_pads_options = dict(
B1 = dict(loc_W=1, loc_H=-1),
R= dict(loc_W=1, loc_H=1),
B2 = dict(loc_W=-1, loc_H=-1)
)
Q1 = TransmonPocketCL(design, 'Q1',
options=dict(pos_x=f'0mm',
pos_y=f'0mm',
pad_gap = pad_g,
pad_width = pad_w,
pad_height = pad_h,
orientation=0,
connection_pads=dict(**connection1_pads_options)))
gui.rebuild()
gui.autoscale()
from qiskit_metal.analyses.quantization import EPRanalysis
eig_qres = EPRanalysis(design, "hfss")
hfss = eig_qres.sim.renderer
hfss.start()
hfss.activate_ansys_design("Q1Readout", 'eigenmode')
hfss.render_design(['Q1'], [])
# Analysis properties
setup = hfss.pinfo.setup
setup.n_modes = 1
setup.passes = 10
setup.box_plus_buffer =True
print(f"""
Number of eigenmodes to find = {setup.n_modes}
Number of simulation passes = {setup.passes}
Convergence freq max delta percent diff = {setup.delta_f}
""")
pinfo = hfss.pinfo
pinfo.design.set_variable('Lj', str(L_JJList[0])+'nH')
pinfo.design.set_variable('Cj', C_JJU)
setup.analyze()
eig_qres.sim.convergence_t, eig_qres.sim.convergence_f, _ = hfss.get_convergences()
eig_qres.sim.plot_convergences()
import pyEPR as epr
pinfo = hfss.pinfo
pinfo.junctions['jj'] = {'Lj_variable': 'Lj', 'rect': 'JJ_rect_Lj_Q1_rect_jj',
'line': 'JJ_Lj_Q1_rect_jj_', 'Cj_variable': 'Cj'}
pinfo.validate_junction_info() # Check that valid names of variables and objects have been supplied
pinfo.dissipative['dielectrics_bulk'] = ['main'] # Dissipative elements: specify
eprd = epr.DistributedAnalysis(pinfo)
print(eprd)
ℰ_elec = eprd.calc_energy_electric()
ℰ_elec_substrate = eprd.calc_energy_electric(None, 'main')
ℰ_mag = eprd.calc_energy_magnetic()
print(f"""
ℰ_elec_all = {ℰ_elec}
ℰ_elec_substrate = {ℰ_elec_substrate}
EPR of substrate = {ℰ_elec_substrate / ℰ_elec * 100 :.1f}%
ℰ_mag_all = {ℰ_mag}
ℰ_mag % of ℰ_elec_all = {ℰ_mag / ℰ_elec * 100 :.1f}%
""")
eprd.do_EPR_analysis()
# 4a. Perform Hamiltonian spectrum post-analysis, building on mw solutions using EPR
epra = epr.QuantumAnalysis(eprd.data_filename)
epra.analyze_all_variations(cos_trunc = 8, fock_trunc = 7)
hfss.modeler._modeler.ShowWindow()
hfss.plot_fields('main')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
problem = driver.run()
print(problem)
hamiltonian = problem.hamiltonian
coefficients = hamiltonian.electronic_integrals
print(coefficients.alpha)
second_q_op = hamiltonian.second_q_op()
print(second_q_op)
hamiltonian.nuclear_repulsion_energy # NOT included in the second_q_op above
problem.molecule
problem.reference_energy
problem.num_particles
problem.num_spatial_orbitals
problem.basis
problem.properties
problem.properties.particle_number
problem.properties.angular_momentum
problem.properties.magnetization
problem.properties.electronic_dipole_moment
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import JordanWignerMapper
solver = GroundStateEigensolver(
JordanWignerMapper(),
NumPyMinimumEigensolver(),
)
result = solver.solve(problem)
print(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
%matplotlib inline
from qiskit import *
from qiskit.visualization import *
from qiskit.tools.monitor import *
import random, time
# We will create a random qubit by directly assigning random amplitudes
a1 = random.random()*2 -1 #Uniform number in [-1,1]
a2 = random.random()*2 -1
b1 = random.random()*2 -1
b2 = random.random()*2 -1
# We need to normalize
norm = (a1**2 + a2**2 + b1**2 + b2**2)**0.5
c1 = complex(a1/norm,a2/norm) #Amplitude for |0>
c2 = complex(b1/norm,b2/norm) #Amplitude for |1>
psi = QuantumRegister(1, name = 'psi') # The qubit to teleport
bell = QuantumRegister(2, name = 'bell') # The shared entangled pair
c = ClassicalRegister(2, name = 'c') # Two classical bits for the measures
teleport = QuantumCircuit(psi,bell,c) # We create the circuit with the two quantum registers and the classical bits
teleport.initialize([c1,c2],psi) # We set the amplitudes for Alice's quibt
teleport.barrier()
print("Alice's qubit is:")
print(c1,"|0> + ",
c2,"|1>")
# Now we create the Bell pair
teleport.h(bell[0])
teleport.cx(bell[0],bell[1])
teleport.barrier()
# We apply CNOT to |psi> and Alice's part of the entangled pair
# We also apply the H gate
# Then, Alice measure her qubits and send the results to Bob
teleport.cx(psi,bell[0])
teleport.h(psi)
teleport.measure([psi[0],bell[0]],c)
teleport.barrier()
# Bob applies his gates depending on the values received from Alice
teleport.cx(bell[0],bell[1])
teleport.cz(psi,bell[1])
teleport.draw(output='mpl')
# We run the circuit and access the amplitudes to check that Bob got the qubit
backend = Aer.get_backend('statevector_simulator')
job = execute(teleport, backend)
outputstate = job.result().get_statevector()
print(outputstate)
# We start by creating the Bell pair that Alice and Bob share
bell = QuantumRegister(2, name = 'bell') # We need two qubits
c = ClassicalRegister(2) # And two bits for the measurements
dense = QuantumCircuit(bell,c)
dense.h(bell[0])
dense.cx(bell[0],bell[1])
dense.barrier()
# We randomly choose which bits to send
b1 = random.randint(0,1)
b2 = random.randint(0,1)
print("Alice wants to send ",b1,b2)
# And we apply the gates accordingly
if(b2==1):
dense.x(bell[0])
if(b1==1):
dense.z(bell[0])
dense.barrier()
dense.draw(output='mpl')
# Alice sends her qubit to Bob, who applies his gates and measures
dense.cx(bell[0],bell[1])
dense.h(bell[0])
dense.barrier()
dense.measure(bell,c)
dense.draw(output='mpl')
# Let us run the circuit
backend = Aer.get_backend('qasm_simulator')
job = execute(dense, backend, shots = 1, memory = True)
result = job.result().get_memory()
print("Bob has received ",int(result[0][1]),int(result[0][0]))
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
| |
https://github.com/Alfaxad/IBM_QC_Africa_2021
|
Alfaxad
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, execute
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.providers.aer import QasmSimulator
backend = Aer.get_backend('statevector_simulator')
qc1 = QuantumCircuit(4)
# perform gate operations on individual qubits
qc1.x(0)
qc1.y(1)
qc1.z(2)
qc1.s(3)
# Draw circuit
qc1.draw()
# Plot blochshere
out1 = execute(qc1,backend).result().get_statevector()
plot_bloch_multivector(out1)
qc2 = QuantumCircuit(4)
# initialize qubits
qc2.x(range(4))
# perform gate operations on individual qubits
qc2.x(0)
qc2.y(1)
qc2.z(2)
qc2.s(3)
# Draw circuit
qc2.draw()
# Plot blochshere
out2 = execute(qc2,backend).result().get_statevector()
plot_bloch_multivector(out2)
qc3 = QuantumCircuit(4)
# initialize qubits
qc3.h(range(4))
# perform gate operations on individual qubits
qc3.x(0)
qc3.y(1)
qc3.z(2)
qc3.s(3)
# Draw circuit
qc3.draw()
# Plot blochshere
out3 = execute(qc3,backend).result().get_statevector()
plot_bloch_multivector(out3)
qc4 = QuantumCircuit(4)
# initialize qubits
qc4.x(range(4))
qc4.h(range(4))
# perform gate operations on individual qubits
qc4.x(0)
qc4.y(1)
qc4.z(2)
qc4.s(3)
# Draw circuit
qc4.draw()
# Plot blochshere
out4 = execute(qc4,backend).result().get_statevector()
plot_bloch_multivector(out4)
qc5 = QuantumCircuit(4)
# initialize qubits
qc5.h(range(4))
qc5.s(range(4))
# perform gate operations on individual qubits
qc5.x(0)
qc5.y(1)
qc5.z(2)
qc5.s(3)
# Draw circuit
qc5.draw()
# Plot blochshere
out5 = execute(qc5,backend).result().get_statevector()
plot_bloch_multivector(out5)
qc6 = QuantumCircuit(4)
# initialize qubits
qc6.x(range(4))
qc6.h(range(4))
qc6.s(range(4))
# perform gate operations on individual qubits
qc6.x(0)
qc6.y(1)
qc6.z(2)
qc6.s(3)
# Draw circuit
qc6.draw()
# Plot blochshere
out6 = execute(qc6,backend).result().get_statevector()
plot_bloch_multivector(out6)
import qiskit
qiskit.__qiskit_version__
|
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/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
import numpy as np
import qiskit
from qiskit import QuantumCircuit
sys.path.append("..")
from external.NuOp.parallel_two_qubit_gate_decomposition import *
from external.NuOp.gates_numpy import (
cnot_gate,
fsim_gate,
cphase_gate,
xy_gate,
get_gate_unitary_qiskit,
iswap,
fsim,
)
from itertools import product
from qiskit.transpiler import PassManager
import sys
from clonk.utils.riswap_gates.riswap import RiSwapGate
import h5py
from tqdm import tqdm
# test
qc = QuantumCircuit(2)
from qiskit.quantum_info import random_unitary
qc.append(random_unitary(dims=(2, 2)), [0, 1])
# qc.draw(output='mpl')
from qiskit.converters import circuit_to_dag, dag_to_circuit
dag = circuit_to_dag(qc)
base_fidelity = 1 - 5e-3
alpha_range = [2, 3, 5, 7]
gate_range = range(2, 9)
qc = QuantumCircuit(2)
from qiskit.circuit.library.standard_gates import SwapGate
qc.append(SwapGate(), [0, 1])
dag = circuit_to_dag(qc)
# alpha_range = [2,3,4,5,6,7]
# # alpha_range = [5]
# gate_range = range(2,11)#9
# don't change, would break previous data collection
# XXX
alpha_range = [2, 3, 4, 5, 6, 7]
# # alpha_range = [5]
# gate_range = range(2,11)#9
# alpha_range = [1,2,3,4,5,6]
gate_range = range(2, 9) # 11
from qiskit.quantum_info import random_unitary
def collect_random2q_data(base_fidelity, N=15, mode="swap"):
# alpha_range = [2,3,4,5,6,7]
# # alpha_range = [5]
# gate_range = range(2,9)#11
base_fidelity = base_fidelity
empty_flag = 0
filename = f"data-archive2/data1_{mode}.h5" # f'data-archive2/data1_{mode}.h5' #f'data-archive/data1_{mode}.h5', #archive2 uses 2-7, archive3 uses 1-6
# filename = f'src/clonk/benchmark_suite/data/data5_{mode}.h5'
# load in previous data
try:
with h5py.File(filename, "r") as h5f:
# gate_error = h5f['random2q_gate_error'][:]
decomp_error = h5f["decomp_error"][:]
# fidelity_error = h5f['random2q_fidelity_error'][:]
# backfill data
gate_error = np.zeros(
shape=(len(decomp_error), len(alpha_range), len(gate_range))
)
fidelity_error = np.zeros(
shape=(len(decomp_error), len(alpha_range), len(gate_range))
)
for i in range(len(decomp_error)):
for alpha_index, alpha in enumerate(alpha_range):
alpha = 1 / alpha
for gate_index, gate_count in enumerate(gate_range):
gate_error[i][alpha_index][gate_index] = (
1 - (alpha * (1 - base_fidelity))
) ** gate_count
fidelity_error[i][alpha_index][gate_index] = (
decomp_error[i][alpha_index][gate_index]
) * gate_error[i][alpha_index][gate_index]
except Exception:
# case where data doesn't already exist
empty_flag = 1
decomp_error = []
for n in tqdm(range(N - len(decomp_error))):
# if not empty_flag and len(gate_error) >= N:
# break
qc = QuantumCircuit(2)
if mode == "random":
qc.append(random_unitary(dims=(2, 2)), [0, 1])
else:
qc.append(SwapGate(), [0, 1])
dag = circuit_to_dag(qc)
# new data for this iteration
temp_gate_error = np.zeros(shape=(1, len(alpha_range), len(gate_range)))
temp_decomp_error = np.zeros(shape=(1, len(alpha_range), len(gate_range)))
temp_fidelity_error = np.zeros(shape=(1, len(alpha_range), len(gate_range)))
for alpha_index, alpha in enumerate(alpha_range):
alpha = 1 / alpha
for gate_index, gate_count in enumerate(gate_range):
params = [[alpha]]
gate_labels = [f"$iSwap^{alpha}$"]
gate_defs = [RiSwapGate]
temp_gate_error[0][alpha_index][gate_index] = (
1 - (alpha * (1 - base_fidelity))
) ** gate_count
# run perfect if it doesn't already exist
fid_2q = {(0, 1): [1]}
pgrp = ParallelGateReplacementPass(
gate_defs,
params,
fid_2q,
fidelity_list_1q_gate=[1 for _ in range(54)],
tol=1e-10,
force_gate_count=gate_count,
)
approx = pgrp.run(dag)
temp_decomp_error[0][alpha_index][gate_index] = pgrp.property_set[
"best_fid"
]
temp_fidelity_error[0][alpha_index][gate_index] = (
temp_gate_error[0][alpha_index][gate_index]
) * temp_decomp_error[0][alpha_index][gate_index]
# run noisy
# fid_2q = {(0,1):[1-alpha*(1-base_fidelity)]}
# pgrp = ParallelGateReplacementPass(gate_defs, params ,fid_2q, fidelity_list_1q_gate=[1 for _ in range(54)], tol=1e-10, force_gate_count=gate_count)
# approx = pgrp.run(dag)
# temp_fidelity_error[0][alpha_index][gate_index] = (pgrp.property_set["best_fid"])
# these are equivalent - save some time and just calculate it using the previous values
# print(f"{gate_error[-1]}, {decomp_error[-1]}, {fidelity_error[-1]}")
# update data
if empty_flag:
gate_error = temp_gate_error
decomp_error = temp_decomp_error
fidelity_error = temp_fidelity_error
empty_flag = 0
else:
gate_error = np.append(gate_error, temp_gate_error, axis=0)
decomp_error = np.append(decomp_error, temp_decomp_error, axis=0)
fidelity_error = np.append(fidelity_error, temp_fidelity_error, axis=0)
# write back data after each iteration in case we end early
with h5py.File(filename, "a") as h5f:
print(f"saving iter {n}")
# delete old, differently sized dataset
try:
del h5f["gate_error"]
del h5f["decomp_error"]
del h5f["fidelity_error"]
except Exception:
# don't need to delete if they don't exist
pass
h5f.create_dataset("gate_error", data=gate_error)
h5f.create_dataset("decomp_error", data=decomp_error)
h5f.create_dataset("fidelity_error", data=fidelity_error)
return gate_error, decomp_error, fidelity_error
# #don't change, would break previous data collection
# from qiskit.quantum_info import random_unitary
# def fooo(base_fidelity, N=15, mode="swap"):
# #XXX
# alpha_range = [1]
# # alpha_range = [5]
# gate_range = range(2,4)#9
# base_fidelity = base_fidelity
# empty_flag = 0
# filename = f'data-archive2/data_fooo{mode}.h5' #f'data-archive/data1_{mode}.h5'
# # filename = f'data/data5_{mode}.h5'
# #load in previous data
# try:
# with h5py.File(filename, 'r') as h5f:
# #gate_error = h5f['random2q_gate_error'][:]
# decomp_error = h5f['decomp_error'][:]
# #fidelity_error = h5f['random2q_fidelity_error'][:]
# #backfill data
# gate_error = np.zeros(shape=(len(decomp_error), len(alpha_range), len(gate_range)))
# fidelity_error = np.zeros(shape=(len(decomp_error), len(alpha_range), len(gate_range)))
# for i in range(len(decomp_error)):
# for alpha_index, alpha in enumerate(alpha_range):
# alpha = 1/alpha
# for gate_index, gate_count in enumerate(gate_range):
# gate_error[i][alpha_index][gate_index] = ((1-(alpha*(1-base_fidelity)))**gate_count)
# fidelity_error[i][alpha_index][gate_index] = (decomp_error[i][alpha_index][gate_index])*gate_error[i][alpha_index][gate_index]
# except Exception:
# #case where data doesn't already exist
# empty_flag = 1
# decomp_error = []
# for n in range(N-len(decomp_error)):
# # if not empty_flag and len(gate_error) >= N:
# # break
# qc = QuantumCircuit(2)
# if mode == "random":
# qc.append(random_unitary(dims=(2,2)),[0,1])
# else:
# qc.append(SwapGate(), [0,1])
# dag = circuit_to_dag(qc)
# #new data for this iteration
# temp_gate_error = np.zeros(shape=(1, len(alpha_range), len(gate_range)))
# temp_decomp_error = np.zeros(shape=(1, len(alpha_range), len(gate_range)))
# temp_fidelity_error = np.zeros(shape=(1, len(alpha_range), len(gate_range)))
# for alpha_index, alpha in enumerate(alpha_range):
# alpha = 1/alpha
# for gate_index, gate_count in enumerate(gate_range):
# params = [[alpha]]
# gate_labels = [f'$iSwap^{alpha}$']
# gate_defs = [RiSwapGate]
# temp_gate_error[0][alpha_index][gate_index] = ((1-(alpha*(1-base_fidelity)))**gate_count)
# #run perfect if it doesn't already exist
# fid_2q = {(0,1):[1]}
# pgrp = ParallelGateReplacementPass(gate_defs, params ,fid_2q, fidelity_list_1q_gate=[1 for _ in range(54)], tol=1e-10, force_gate_count=gate_count)
# approx = pgrp.run(dag)
# temp_decomp_error[0][alpha_index][gate_index] = (pgrp.property_set["best_fid"])
# temp_fidelity_error[0][alpha_index][gate_index] = (temp_gate_error[0][alpha_index][gate_index])*temp_decomp_error[0][alpha_index][gate_index]
# #run noisy
# # fid_2q = {(0,1):[1-alpha*(1-base_fidelity)]}
# # pgrp = ParallelGateReplacementPass(gate_defs, params ,fid_2q, fidelity_list_1q_gate=[1 for _ in range(54)], tol=1e-10, force_gate_count=gate_count)
# # approx = pgrp.run(dag)
# # temp_fidelity_error[0][alpha_index][gate_index] = (pgrp.property_set["best_fid"])
# #these are equivalent - save some time and just calculate it using the previous values
# # print(f"{gate_error[-1]}, {decomp_error[-1]}, {fidelity_error[-1]}")
# #update data
# if empty_flag:
# gate_error = temp_gate_error
# decomp_error = temp_decomp_error
# fidelity_error = temp_fidelity_error
# empty_flag = 0
# else:
# gate_error = np.append(gate_error, temp_gate_error, axis=0)
# decomp_error = np.append(decomp_error, temp_decomp_error, axis=0)
# fidelity_error = np.append(fidelity_error, temp_fidelity_error, axis=0)
# #write back data after each iteration in case we end early
# with h5py.File(filename, 'a') as h5f:
# print(f"saving iter {n}")
# # delete old, differently sized dataset
# try:
# del h5f['gate_error']
# del h5f['decomp_error']
# del h5f['fidelity_error']
# except Exception:
# #don't need to delete if they don't exist
# pass
# h5f.create_dataset('gate_error', data=gate_error)
# h5f.create_dataset('decomp_error', data=decomp_error)
# h5f.create_dataset('fidelity_error', data=fidelity_error)
# return gate_error, decomp_error, fidelity_error
# collect_random2q_data(.99, N=15, mode="random")
# qc = QuantumCircuit(2)
# from qiskit.quantum_info import random_unitary
# qc.append(random_unitary(dims=(2,2)),[0,1])
# dag = circuit_to_dag(qc)
# qc.decompose().draw(output='mpl')
# alpha = 1/2
# gate_count = 3
# params = [[alpha]]
# gate_labels = [f'$iSwap^{alpha}$']
# gate_defs = [RiSwapGate]
# #temp_gate_error[0][alpha_index][gate_index] = ((1-(alpha*(1-base_fidelity)))**gate_count)
# #run perfect if it doesn't already exist
# fid_2q = {(0,1):[1]}
# pgrp = ParallelGateReplacementPass(gate_defs, params ,fid_2q, fidelity_list_1q_gate=[1 for _ in range(54)], tol=1e-10, force_gate_count=gate_count)
# approx = pgrp.run(dag)
# from qiskit.converters import dag_to_circuit
# print(pgrp.property_set["best_fid"])
# dag_to_circuit(approx).draw(output='mpl')
# alpha = 1/2
# gate_count = 3
# params = [[alpha]]
# gate_labels = [f'$iSwap^{alpha}$']
# gate_defs = [RiSwapGate]
# #temp_gate_error[0][alpha_index][gate_index] = ((1-(alpha*(1-base_fidelity)))**gate_count)
# #run perfect if it doesn't already exist
# fid_2q = {(0,1):[1]}
# pgrp = ParallelGateReplacementPass(gate_defs, params ,fid_2q, fidelity_list_1q_gate=[1 for _ in range(54)], tol=1e-10, force_gate_count=gate_count)
# approx = pgrp.run(dag)
# from qiskit.converters import dag_to_circuit
# print(pgrp.property_set["best_fid"])
# dag_to_circuit(approx).draw(output='mpl')
from scipy.stats import sem
# import h5py
# with h5py.File('data.h5', 'r') as h5f:
# gate_error = h5f['random2q_gate_error'][:]
# decomp_error = h5f['random2q_decomp_error'][:]
# fidelity_error = h5f['random2q_fidelity_error'][:]
import matplotlib.pyplot as plt
plt.style.use(["science", "no-latex"])
def create_plot(gate_error, decomp_error, fidelity_error):
fig, axs = plt.subplots(
1, len(gate_error[0]), sharey=True, sharex=True, figsize=(12, 4)
)
for alpha_index in range(len(gate_error[0])):
alpha = 1 / alpha_range[alpha_index]
gate_unit_time = [el * alpha for el in gate_range]
axs[alpha_index].plot(
gate_unit_time,
np.average(gate_error, axis=0)[alpha_index],
label="Gate Error",
linestyle="--",
marker="o",
)
axs[alpha_index].errorbar(
gate_unit_time,
np.average(decomp_error, axis=0)[alpha_index],
yerr=sem(decomp_error, axis=0)[alpha_index],
label="Decomp Error",
linestyle="--",
marker="s",
)
axs[alpha_index].errorbar(
gate_unit_time,
np.average(fidelity_error, axis=0)[alpha_index],
yerr=sem(fidelity_error, axis=0)[alpha_index],
label="Total Fidelity",
marker="^",
)
axs[alpha_index].set_xlabel("Gate Unit Time")
axs[alpha_index].set_title(f"iSwap^(1/{1/alpha})")
# for i, key in enumerate(np.max(np.average(fidelity_error, axis=0),axis=1)):
# axs[i].annotate(key, (i, frequency_list[key]))
# if i >= 3:
# break
axs[-1].legend()
axs[0].set_ylabel("Avg Fidelity")
axs[0].set_yscale("logit")
fig.tight_layout()
fig.show()
filename = "nuop_experiment"
fig.savefig("{}.pdf".format(filename), format="pdf", facecolor="white")
# gate_error, decomp_error, fidelity_error = collect_random2q_data(1-5e-2, N=25, mode="random")
# create_plot(gate_error, decomp_error, fidelity_error)
from scipy.stats import sem
def get_max(fidelity_error):
max_list = []
sem_list = []
for alpha_index in range(len(fidelity_error[0])):
best_over_templatelength = 0
sem_temp = []
for template_length_index in range(len(fidelity_error[0][0])):
best_temp_average = []
for n_repetition in range(len(fidelity_error)):
best_temp_average.append(
fidelity_error[n_repetition][alpha_index][template_length_index]
)
val = np.sum(best_temp_average) / len(fidelity_error)
if val > best_over_templatelength:
best_over_templatelength = val
sem_temp = sem(best_temp_average)
# print(best_over_templatelength)
sem_list.append(sem_temp)
max_list.append(best_over_templatelength)
return max_list, sem_list
gate_error, decomp_error, fidelity_error = collect_random2q_data(
0.90, N=20, mode="random"
)
get_max(fidelity_error)
b = get_max(fidelity_error)
print((1 - b[0][1]) / (1 - b[0][1])) # 1/2
print((1 - b[0][1]) / (1 - b[0][2])) # 1/3
print((1 - b[0][1]) / (1 - b[0][3])) # 1/4
print((1 - b[0][1]) / (1 - b[0][4])) # 1/5
# gate_error, decomp_error, fidelity_error = fooo(.99, mode="random")
# # get_max(fidelity_error)
# get_max(fidelity_error)
# (1-.9874641583423502)/(1-0.9886633054798327)
N = 20
import itertools
marker = itertools.cycle(("o", "^", "s", "d", "v", "*"))
color = itertools.cycle(
(
"tab:blue",
"tab:olive",
"tab:purple",
"tab:red",
"tab:green",
"tab:pink",
"tab:orange",
"tab:cyan",
)
)
# color = itertools.cycle(("tab:green", "tab:pink", "tab:orange", "tab:cyan"))
base_fidelity_list = [0.97, 0.98, 1 - 10e-3, 1 - 5e-3, 1 - 10e-4, 1]
gate_error, decomp_error, fidelity_error = collect_random2q_data(
1 - 10e-3, N=N, mode="random"
)
from scipy.stats import sem
def create_plot2(gate_error, decomp_error, fidelity_error, plot_bool):
plt.style.use(["science"]) # , 'ieee'])
SMALL_SIZE = 4
MEDIUM_SIZE = 6
BIGGER_SIZE = 12
plt.rc("font", size=MEDIUM_SIZE + 2) # controls default text sizes
plt.rc("axes", titlesize=MEDIUM_SIZE + 2) # fontsize of the axes title
plt.rc("axes", labelsize=MEDIUM_SIZE + 1) # fontsize of the x and y labels
plt.rc("xtick", labelsize=SMALL_SIZE + 2) # fontsize of the tick labels
plt.rc("ytick", labelsize=SMALL_SIZE + 2) # fontsize of the tick labels
plt.rc("legend", fontsize=MEDIUM_SIZE) # legend fontsize
plt.rc("figure", titlesize=MEDIUM_SIZE + 2) # fontsize of the figure title
plt.rc("lines", markersize=1.2, linewidth=0.65)
# fig = plt.figure()
# gs = fig.add_gridspec(2,2)
# ax1 = fig.add_subplot(gs[0, 0])
# ax2 = fig.add_subplot(gs[0, 1])
# ax3 = fig.add_subplot(gs[1, :])
# axs = [ax1,ax2,ax3]
if plot_bool:
fig, axs = plt.subplots(
1, 2, figsize=(2, 1.25), sharey=True, gridspec_kw={"width_ratios": [1, 2]}
)
for alpha_index in range(len(gate_error[0])):
alpha = 1 / alpha_range[alpha_index]
set_color = next(color)
set_marker = next(marker)
#
gate_unit_time = gate_range
c = len([el for el in gate_unit_time if el <= 8])
axs[0].errorbar(
gate_unit_time[:c],
[1 - el for el in np.average(decomp_error, axis=0)[alpha_index][:c]],
yerr=sem(decomp_error, axis=0)[alpha_index][:c],
capsize=1.5,
elinewidth=0.5,
ecolor=set_color,
label=r"$\sqrt[" + str(int(1 / alpha)) + r"]{iSwap}$",
marker=set_marker,
color=set_color,
)
#
gate_unit_time = [el * alpha for el in gate_range]
# gate_unit_time = gate_range
# axs[1].plot(gate_unit_time, np.average(gate_error, axis=0)[alpha_index], label=f"Gate Error {alpha}", linestyle='--', marker='o')
# cutting off values past 2 to make pulse duration plot look nicer
c = len([el for el in gate_unit_time if el <= 2])
c_bottom = len(gate_unit_time) - len(
[el for el in gate_unit_time if el >= 0]
)
# c = len(gate_unit_time)
axs[1].errorbar(
gate_unit_time[c_bottom:c],
[
1 - el
for el in np.average(decomp_error, axis=0)[alpha_index][c_bottom:c]
],
yerr=sem(decomp_error, axis=0)[alpha_index][c_bottom:c],
capsize=1.5,
elinewidth=0.5,
ecolor=set_color,
label=r"$\sqrt[" + str(int(1 / alpha)) + r"]{iSwap}$",
marker=set_marker,
color=set_color,
)
# axs.errorbar(gate_unit_time, np.average(fidelity_error, axis=0)[alpha_index], yerr=sem(fidelity_error, axis=0)[alpha_index], label=f"Total Fidelity{alpha}", marker='^')
# axs[alpha_index].set_xlabel("Gate Unit Time")
# axs[alpha_index].set_title(f"iSwap^(1/{1/alpha})")
# for i, key in enumerate(np.max(np.average(fidelity_error, axis=0),axis=1)):
# axs[i].annotate(key, (i, frequency_list[key]))
# if i >= 3:
# break
axs[0].set_yscale("log")
# axs[1].set_xscale('log')
axs[0].set_xlabel(r"Gate Count ($k$)")
axs[1].set_xlabel(r"Pulse Duration ($k/n$)")
fig.suptitle(r"$\sqrt[n]{iSwap}$ Expected Decomp Fidelity")
# axs[0].legend(bbox_to_anchor=(2,-.2), ncol=2)
handles, labels = axs[0].get_legend_handles_labels()
# fig.legend(handles,labels,bbox_to_anchor=(.95,-.08),ncol=3)
# axs[0].legend(bbox_to_anchor=(1.0,-.2), ncol=2)
# axs[0].yaxis.set_major_locator(plt.LogitLocator(3))
# axs[0].ticklabel_format(axis="y", style="sci", scilimits=(0, 0))
# axs[-1].legend()
axs[0].set_ylabel(r"Avg Infidelity ($1-F_d$)")
axs[0].set_xticks(range(2, 9))
axs[0].minorticks_on()
axs[0].xaxis.set_tick_params(which="minor", bottom=False, top=False)
else: # if plot_bool:
fig, axs = plt.subplots(1, 1, figsize=(2, 1.15), sharey=True)
ydata = []
ysem = []
base_fidelity_list = np.arange(0.9, 1, 0.01)
for bf in base_fidelity_list:
gate_error, decomp_error, fidelity_error = collect_random2q_data(
bf, N=N, mode="random"
)
ydata.append(get_max(fidelity_error)[0])
ysem.append(get_max(fidelity_error)[1])
# axs.errorbar([bf]*len(alpha_range), get_max(fidelity_error)[0], yerr=get_max(fidelity_error)[1], capsize=1.5, elinewidth=.5, ecolor='black', linestyle="-", marker=next(marker), label=bf,color=next(color))
for i, n in enumerate(range(len(gate_error[0]))):
alpha = 1 / alpha_range[i]
set_color = next(color)
axs.errorbar(
base_fidelity_list,
[el[i] for el in ydata],
yerr=[el[i] for el in ysem],
capsize=1,
elinewidth=0.5,
ecolor=set_color,
linestyle="-",
marker=next(marker),
label=r"$\sqrt[" + str(int(1 / alpha)) + r"]{iSwap}$",
color=set_color,
)
# axs.set_xlabel(r"$\sqrt[x]{iSwap}$")
axs.set_xlabel(r"$F_b(\texttt{iSwap})$")
axs.invert_xaxis()
axs.set_yscale("linear")
axs.minorticks_on()
axs.xaxis.set_tick_params(which="minor", bottom=False, top=False)
# # axs[1].set_ylabel("Avg fidelity")
# # legend = axs[1].legend(title="iSwap Fidelity", bbox_to_anchor=(1.25,-.22), ncol=2)
axs.legend(bbox_to_anchor=(1.0, -0.22), ncol=3)
# # legend._legend_box.align = "bottoms"
# axs.yaxis.set_major_locator(plt.MaxNLocator(4))
axs.set_xticks(np.linspace(0.9, 1, 5))
# #axs[0].xaxis.set_major_locator(plt.MaxNLocator(integer=True))
# axs[1].ticklabel_format(axis="y", style="sci", scilimits=(0, 0))
# # axs[1].set_title(f"Random 2Q Fidelity vs nth root iswap")
# axs.set_yscale('log')
axs.set_ylabel(r"Avg Total Fidelity $F_t$")
# axs.set_ylabel("Average Fidelity")
axs.set_title(r"$\sqrt[n]{iSwap}$ Expected Total Fidelity")
# axs.minorticks_off()
# axs.set_ylabel("Average Infidelity")
# axs.set_xticks = [2,3,4,5,6,7,8]
# axs.minorticks_off()
# fig.suptitle(f"Random 2Q Fidelity (N={N})")
# plt.axes().xaxis.set_major_locator(plt.MaxNLocator(integer=True))
# fig.tight_layout()
fig.show()
filename = "nuop_experiment"
fig.savefig("{}.svg".format(filename), format="svg", facecolor=None)
create_plot2(gate_error, decomp_error, fidelity_error, plot_bool=0);
%matplotlib widget
print(np.array(fidelity_error).shape)
# base_fidelity_list = [1-10e-3,1-5e-3, 1-10e-4]
# fig, axs = plt.subplots(1, 1, sharey=True))
# for bf in base_fidelity_list:
# gate_error, decomp_error, fidelity_error = collect_random2q_data(bf, N=25, mode="random")
# axs.plot(alpha_range, np.max(np.average(fidelity_error, axis=0),axis=1), '-o', label=bf)
# axs.set_xlabel("nth root iswap")
# axs.set_ylabel("Avg fidelity")
# axs.set_title(f"Random 2Q Fidelity vs nth root iswap")
# axs.set_yscale('logit')
# fig.legend(loc='upper center', bbox_to_anchor=(0.5,0), ncol=3)
# fig.tight_layout()
# gate_error, decomp_error, fidelity_error = collect_random2q_data(1-5e-2, N=5, mode="swap")
# create_plot(gate_error, decomp_error, fidelity_error)
# base_fidelity_list = [1-10e-3,1-5e-3, 1-10e-4]
# fig, axs = plt.subplots(1, 1, sharey=True, figsize=(4, 4))
# for bf in base_fidelity_list:
# gate_error, decomp_error, fidelity_error = collect_random2q_data(bf, N=5, mode="swap")
# axs.plot(alpha_range, np.max(np.average(fidelity_error, axis=0),axis=1), '-o', label=bf)
# axs.set_xlabel("nth root iswap")
# axs.set_ylabel("max average fidelity")
# axs.set_title(f"Max fidelity vs nth root iswap")
# axs.set_yscale('logit')
# fig.legend()
# fig.tight_layout()
# #modify nuop so works with trotterization constraint - such that there is only U1 and U2 1Q gate solutions that are interleaved
# #eliminate gate_range parameter, beacuse now we must force the number of template reptetitions to be exactly n for nriswap
# #XXX
# from qiskit.converters import dag_to_circuit
# alpha_range = range(2,11)
# # alpha_range = [5]
# from qiskit.quantum_info import random_unitary
# def collect_trotterization_data(base_fidelity, N=15, mode="swap"):
# base_fidelity = base_fidelity
# empty_flag = 0
# filename = f'data/trotter_{mode}.h5'
# # filename = f'data/data5_{mode}.h5'
# #load in previous data
# try:
# with h5py.File(filename, 'r') as h5f:
# #gate_error = h5f['random2q_gate_error'][:]
# decomp_error = h5f['decomp_error'][:]
# #fidelity_error = h5f['random2q_fidelity_error'][:]
# #backfill data
# gate_error = np.zeros(shape=(len(decomp_error), len(alpha_range)))
# fidelity_error = np.zeros(shape=(len(decomp_error), len(alpha_range)))
# for i in range(len(decomp_error)):
# for alpha_index, alpha in enumerate(alpha_range):
# gate_count = alpha #constraint enforced by trotterization
# alpha = 1/alpha
# gate_error[i][alpha_index] = ((1-(alpha*(1-base_fidelity)))**gate_count)
# fidelity_error[i][alpha_index] = (decomp_error[i][alpha_index])*gate_error[i][alpha_index]
# except Exception:
# #case where data doesn't already exist
# empty_flag = 1
# decomp_error = []
# for n in range(N-len(decomp_error)):
# # if not empty_flag and len(gate_error) >= N:
# # break
# qc = QuantumCircuit(2)
# if mode == "random":
# qc.append(random_unitary(dims=(2,2)),[0,1])
# else:
# qc.append(SwapGate(), [0,1])
# dag = circuit_to_dag(qc)
# #new data for this iteration
# temp_gate_error = np.zeros(shape=(1, len(alpha_range)))
# temp_decomp_error = np.zeros(shape=(1, len(alpha_range)))
# temp_fidelity_error = np.zeros(shape=(1, len(alpha_range)))
# for alpha_index, alpha in enumerate(alpha_range):
# gate_count = alpha #constraint enforced by trotterization
# alpha = 1/alpha
# params = [[alpha]]
# gate_labels = [f'$iSwap^{alpha}$']
# gate_defs = [RiSwapGate]
# temp_gate_error[0][alpha_index] = ((1-(alpha*(1-base_fidelity)))**gate_count)
# #run perfect if it doesn't already exist
# fid_2q = {(0,1):[1]}
# pgrp = ParallelGateReplacementPass(gate_defs, params ,fid_2q, fidelity_list_1q_gate=[1 for _ in range(54)], tol=1e-10, force_gate_count=gate_count,trotterization=True)
# approx = pgrp.run(dag)
# #print(dag_to_circuit(approx).draw(fold=-1))
# print(f"Completed iter{n}, gate {alpha}...")
# temp_decomp_error[0][alpha_index] = (pgrp.property_set["best_fid"])
# temp_fidelity_error[0][alpha_index] = (temp_gate_error[0][alpha_index])*temp_decomp_error[0][alpha_index]
# #run noisy
# # fid_2q = {(0,1):[1-alpha*(1-base_fidelity)]}
# # pgrp = ParallelGateReplacementPass(gate_defs, params ,fid_2q, fidelity_list_1q_gate=[1 for _ in range(54)], tol=1e-10, force_gate_count=gate_count)
# # approx = pgrp.run(dag)
# # temp_fidelity_error[0][alpha_index][gate_index] = (pgrp.property_set["best_fid"])
# #these are equivalent - save some time and just calculate it using the previous values
# # print(f"{gate_error[-1]}, {decomp_error[-1]}, {fidelity_error[-1]}")
# #update data
# if empty_flag:
# gate_error = temp_gate_error
# decomp_error = temp_decomp_error
# fidelity_error = temp_fidelity_error
# empty_flag = 0
# else:
# gate_error = np.append(gate_error, temp_gate_error, axis=0)
# decomp_error = np.append(decomp_error, temp_decomp_error, axis=0)
# fidelity_error = np.append(fidelity_error, temp_fidelity_error, axis=0)
# #write back data after each iteration in case we end early
# with h5py.File(filename, 'a') as h5f:
# print(f"saving iter {n}")
# # delete old, differently sized dataset
# try:
# del h5f['gate_error']
# del h5f['decomp_error']
# del h5f['fidelity_error']
# except Exception:
# #don't need to delete if they don't exist
# pass
# h5f.create_dataset('gate_error', data=gate_error)
# h5f.create_dataset('decomp_error', data=decomp_error)
# h5f.create_dataset('fidelity_error', data=fidelity_error)
# return gate_error, decomp_error, fidelity_error
# gate_error, decomp_error, fidelity_error = collect_trotterization_data(base_fidelity, N=1, mode="swap")
# gate_error.shape
# decomp_error
# gate_count = 3 #constraint enforced by trotterization
# alpha = 1/gate_count
# from qiskit.circuit.library.standard_gates import *
# qc = QuantumCircuit(2)
# mode = "swap"
# if mode == "random":
# qc.append(random_unitary(dims=(2,2)),[0,1])
# else:
# #qc.append(SwapGate(), [0,1])
# qc.append(CXGate(), [0,1])
# dag = circuit_to_dag(qc)
# params = [[alpha]]
# gate_labels = [r"$\sqrt[" + str(int(1/alpha))+ r"]{iSwap}$"]
# gate_defs = [RiSwapGate]
# fid_2q = {(0,1):[1]}
# pgrp = ParallelGateReplacementPass(gate_defs, params ,fid_2q, fidelity_list_1q_gate=[1 for _ in range(54)], tol=1e-10, force_gate_count=gate_count)
# approx = pgrp.run(dag)
# print(f"Completed iter, gate {alpha}...")
# t = (pgrp.property_set["best_fid"])
# print(t)
# print(dag_to_circuit(approx).draw(output='mpl'))
# gate = Operator(dag_to_circuit(approx)).data
# gate = Operator(CXGate()).data
# import weylchamber
# c1, c2, c3 = weylchamber.c1c2c3(gate)
# print(c1,c2,c3)
# import itertools
# marker = itertools.cycle(('o', '^', 's', 'd'))
# color = itertools.cycle(("tab:blue", "tab:olive", "tab:purple", "tab:red", "tab:green", "tab:pink", "tab:orange", "tab:cyan"))
# #color = itertools.cycle(("tab:green", "tab:pink", "tab:orange", "tab:cyan"))
# base_fidelity_list = [1-10e-3,1-5e-3, 1-10e-4, 1]
# gate_error, decomp_error, fidelity_error = collect_trotterization_data(base_fidelity, N=1, mode="swap")
# from scipy.stats import sem
# def create_plot3(gate_error, decomp_error, fidelity_error):
# plt.style.use(['science', 'ieee'])
# SMALL_SIZE = 4
# MEDIUM_SIZE = 6
# BIGGER_SIZE = 12
# plt.rc("font", size=MEDIUM_SIZE+2) # controls default text sizes
# plt.rc("axes", titlesize=MEDIUM_SIZE+2) # fontsize of the axes title
# plt.rc("axes", labelsize=MEDIUM_SIZE + 1) # fontsize of the x and y labels
# plt.rc("xtick", labelsize=SMALL_SIZE + 2) # fontsize of the tick labels
# plt.rc("ytick", labelsize=SMALL_SIZE + 2) # fontsize of the tick labels
# plt.rc("legend", fontsize=MEDIUM_SIZE + 2) # legend fontsize
# plt.rc("figure", titlesize=MEDIUM_SIZE + 4) # fontsize of the figure title
# plt.rc("lines", markersize=2, linewidth=.75)
# fig, axs = plt.subplots(1,1, figsize=(2,1.75))
# if True:
# for alpha_index in range(len(gate_error[0])):
# alpha = 1/alpha_range[alpha_index]
# gate_unit_time = [el*alpha for el in gate_range]
# gate_unit_time = gate_range
# #axs[1].plot(gate_unit_time, np.average(gate_error, axis=0)[alpha_index], label=f"Gate Error {alpha}", linestyle='--', marker='o')
# axs.errorbar(gate_unit_time, [1-el for el in np.average(decomp_error, axis=0)[alpha_index]], yerr=sem(decomp_error, axis=0)[alpha_index], capsize=1.5, elinewidth=.5, ecolor='black', label=r"$\sqrt[" + str(int(1/alpha))+ r"]{iSwap}$", marker=next(marker), color=next(color))
# #axs.errorbar(gate_unit_time, np.average(fidelity_error, axis=0)[alpha_index], yerr=sem(fidelity_error, axis=0)[alpha_index], label=f"Total Fidelity{alpha}", marker='^')
# # axs[alpha_index].set_xlabel("Gate Unit Time")
# #axs[alpha_index].set_title(f"iSwap^(1/{1/alpha})")
# # for i, key in enumerate(np.max(np.average(fidelity_error, axis=0),axis=1)):
# # axs[i].annotate(key, (i, frequency_list[key]))
# # if i >= 3:
# # break
# axs.set_yscale('log')
# axs.set_xlabel("2Q Gate Count")
# axs.set_title("Decomp Infidelity")
# axs.legend(bbox_to_anchor=(1.2,-.2), ncol=2)
# axs.legend(bbox_to_anchor=(1.0,-.2), ncol=2)
# # axs[0].yaxis.set_major_locator(plt.LogitLocator(3))
# # axs[0].ticklabel_format(axis="y", style="sci", scilimits=(0, 0))
# # axs[-1].legend()
# axs.set_ylabel("Avg Fidelity")
# else:
# for bf in base_fidelity_list:
# gate_error, decomp_error, fidelity_error = collect_random2q_data(bf, N=N, mode="random")
# x_axis = alpha_range
# axs.errorbar(x_axis, get_max(fidelity_error)[0], yerr=get_max(fidelity_error)[1], capsize=1.5, elinewidth=.5, ecolor='black', linestyle="-", marker=next(marker), label=bf,color=next(color))
# axs.set_xlabel(r"$\sqrt[x]{iSwap}$")
# # # axs[1].set_ylabel("Avg fidelity")
# # # legend = axs[1].legend(title="iSwap Fidelity", bbox_to_anchor=(1.25,-.22), ncol=2)
# axs.legend(bbox_to_anchor=(1.25,-.22), ncol=2)
# # # legend._legend_box.align = "bottoms"
# # axs.yaxis.set_major_locator(plt.MaxNLocator(4))
# axs.xaxis.set_major_locator(plt.MaxNLocator(integer=True))
# # #axs[0].xaxis.set_major_locator(plt.MaxNLocator(integer=True))
# # axs[1].ticklabel_format(axis="y", style="sci", scilimits=(0, 0))
# # # axs[1].set_title(f"Random 2Q Fidelity vs nth root iswap")
# #axs.set_yscale('log')
# axs.set_ylabel("Avg Infidelity")
# #axs.set_ylabel("Average Fidelity")
# axs.set_title("Best Total Fidelity")
# #axs.minorticks_off()
# #axs.set_ylabel("Average Infidelity")
# #axs.set_xticks = [2,3,4,5,6,7,8]
# #axs.minorticks_off()
# #fig.suptitle(f"Random 2Q Fidelity (N={N})")
# #plt.axes().xaxis.set_major_locator(plt.MaxNLocator(integer=True))
# #fig.tight_layout()
# fig.show()
# filename = "nuop_experiment"
# fig.savefig('{}.pdf'.format(filename), format="pdf", facecolor='white')
# create_plot2(gate_error, decomp_error, fidelity_error)
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
# The snipplet above ==== is buggy version; the code below ==== is fixed version.
from math import pi,pow
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, BasicAer, execute
def IQFT(circuit, qin, n):
for i in range (int(n/2)):
circuit.swap(qin[i], qin[n -1 -i])
for i in range (n):
circuit.h(qin[i])
for j in range (i +1, n, 1):
circuit.cu1(-pi/ pow(2, j-i), qin[j], qin[i])
n = 3
qin = QuantumRegister(n)
cr = ClassicalRegister(n)
circuit = QuantumCircuit(qin, cr, name="Inverse_Quantum_Fourier_Transform")
circuit.h(qin)
circuit.z(qin[2])
circuit.s(qin[1])
circuit.z(qin[0])
circuit.t(qin[0])
IQFT(circuit, qin, n)
circuit.measure (qin, cr)
backend = BasicAer.get_backend("qasm_simulator")
result = execute(circuit, backend, shots = 500).result()
counts = result.get_counts(circuit)
print(counts)
#============
from math import pi,pow
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, BasicAer, execute
def QFT(n, inverse=False):
"""This function returns a circuit implementing the (inverse) QFT."""
circuit = QuantumCircuit(n, name='IQFT' if inverse else 'QFT')
# here's your old code, building the inverse QFT
for i in range(int(n/2)):
# note that I removed the qin register, since registers are not
# really needed and you can just use the qubit indices
circuit.swap(i, n - 1 - i)
for i in range(n):
circuit.h(i)
for j in range(i + 1, n, 1):
circuit.cu1(-pi / pow(2, j - i), j, i)
# now we invert it to get the regular QFT
if inverse:
circuit = circuit.inverse()
return circuit
n = 3
qin = QuantumRegister(n)
cr = ClassicalRegister(n)
circuit = QuantumCircuit(qin, cr)
circuit.h(qin)
circuit.z(qin[2])
circuit.s(qin[1])
circuit.z(qin[0])
circuit.t(qin[0])
# get the IQFT and add it to your circuit with ``compose``
# if you want the regular QFT, just set inverse=False
iqft = QFT(n, inverse=True)
circuit.compose(iqft, inplace=True)
circuit.measure (qin, cr)
backend = BasicAer.get_backend("qasm_simulator")
result = execute(circuit, backend, shots = 500).result()
counts = result.get_counts(circuit)
print(counts)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Helper function for converting a circuit to a dag"""
import copy
from qiskit.dagcircuit.dagcircuit import DAGCircuit
def circuit_to_dag(circuit, copy_operations=True, *, qubit_order=None, clbit_order=None):
"""Build a ``DAGCircuit`` object from a ``QuantumCircuit``.
Args:
circuit (QuantumCircuit): the input circuit.
copy_operations (bool): Deep copy the operation objects
in the :class:`~.QuantumCircuit` for the output :class:`~.DAGCircuit`.
This should only be set to ``False`` if the input :class:`~.QuantumCircuit`
will not be used anymore as the operations in the output
:class:`~.DAGCircuit` will be shared instances and modifications to
operations in the :class:`~.DAGCircuit` will be reflected in the
:class:`~.QuantumCircuit` (and vice versa).
qubit_order (Iterable[Qubit] or None): the order that the qubits should be indexed in the
output DAG. Defaults to the same order as in the circuit.
clbit_order (Iterable[Clbit] or None): the order that the clbits should be indexed in the
output DAG. Defaults to the same order as in the circuit.
Return:
DAGCircuit: the DAG representing the input circuit.
Raises:
ValueError: if the ``qubit_order`` or ``clbit_order`` parameters do not match the bits in
the circuit.
Example:
.. code-block::
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
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)
"""
dagcircuit = DAGCircuit()
dagcircuit.name = circuit.name
dagcircuit.global_phase = circuit.global_phase
dagcircuit.calibrations = circuit.calibrations
dagcircuit.metadata = circuit.metadata
if qubit_order is None:
qubits = circuit.qubits
elif len(qubit_order) != circuit.num_qubits or set(qubit_order) != set(circuit.qubits):
raise ValueError("'qubit_order' does not contain exactly the same qubits as the circuit")
else:
qubits = qubit_order
if clbit_order is None:
clbits = circuit.clbits
elif len(clbit_order) != circuit.num_clbits or set(clbit_order) != set(circuit.clbits):
raise ValueError("'clbit_order' does not contain exactly the same clbits as the circuit")
else:
clbits = clbit_order
dagcircuit.add_qubits(qubits)
dagcircuit.add_clbits(clbits)
for register in circuit.qregs:
dagcircuit.add_qreg(register)
for register in circuit.cregs:
dagcircuit.add_creg(register)
for instruction in circuit.data:
op = instruction.operation
if copy_operations:
op = copy.deepcopy(op)
dagcircuit.apply_operation_back(op, instruction.qubits, instruction.clbits)
dagcircuit.duration = circuit.duration
dagcircuit.unit = circuit.unit
return dagcircuit
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test boolean expression."""
import unittest
from os import path
from ddt import ddt, unpack, data
from qiskit.test.base import QiskitTestCase
from qiskit import execute, BasicAer
from qiskit.utils.optionals import HAS_TWEEDLEDUM
if HAS_TWEEDLEDUM:
from qiskit.circuit.classicalfunction.boolean_expression import BooleanExpression
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
@ddt
class TestBooleanExpression(QiskitTestCase):
"""Test boolean expression."""
@data(
("x | x", "1", True),
("x & x", "0", False),
("(x0 & x1 | ~x2) ^ x4", "0110", False),
("xx & xxx | ( ~z ^ zz)", "0111", True),
)
@unpack
def test_evaluate(self, expression, input_bitstring, expected):
"""Test simulate"""
expression = BooleanExpression(expression)
result = expression.simulate(input_bitstring)
self.assertEqual(result, expected)
@data(
("x", False),
("not x", True),
("(x0 & x1 | ~x2) ^ x4", True),
("xx & xxx | ( ~z ^ zz)", True),
)
@unpack
def test_synth(self, expression, expected):
"""Test synth"""
expression = BooleanExpression(expression)
expr_circ = expression.synth()
new_creg = expr_circ._create_creg(1, "c")
expr_circ.add_register(new_creg)
expr_circ.measure(expression.num_qubits - 1, new_creg)
[result] = (
execute(
expr_circ,
backend=BasicAer.get_backend("qasm_simulator"),
shots=1,
seed_simulator=14,
)
.result()
.get_counts()
.keys()
)
self.assertEqual(bool(int(result)), expected)
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
class TestBooleanExpressionDIMACS(QiskitTestCase):
"""Loading from a cnf file"""
def normalize_filenames(self, filename):
"""Given a filename, returns the directory in terms of __file__."""
dirname = path.dirname(__file__)
return path.join(dirname, filename)
def test_simple(self):
"""Loads simple_v3_c2.cnf and simulate"""
filename = self.normalize_filenames("dimacs/simple_v3_c2.cnf")
simple = BooleanExpression.from_dimacs_file(filename)
self.assertEqual(simple.name, "simple_v3_c2.cnf")
self.assertEqual(simple.num_qubits, 4)
self.assertTrue(simple.simulate("101"))
def test_quinn(self):
"""Loads quinn.cnf and simulate"""
filename = self.normalize_filenames("dimacs/quinn.cnf")
simple = BooleanExpression.from_dimacs_file(filename)
self.assertEqual(simple.name, "quinn.cnf")
self.assertEqual(simple.num_qubits, 16)
self.assertFalse(simple.simulate("1010101010101010"))
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# 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.
"""
Utility functions for debugging and testing.
"""
from typing import Tuple
import numpy as np
from scipy.stats import unitary_group
import qiskit.transpiler.synthesis.aqc.fast_gradient.fast_grad_utils as fgu
def relative_error(a_mat: np.ndarray, b_mat: np.ndarray) -> float:
"""
Computes relative residual between two matrices in Frobenius norm.
"""
return float(np.linalg.norm(a_mat - b_mat, "fro")) / float(np.linalg.norm(b_mat, "fro"))
def make_unit_vector(pos: int, nbits: int) -> np.ndarray:
"""
Makes a unit vector ``e = (0 ... 0 1 0 ... 0)`` of size ``2^n`` with
unit at the position ``num``. **Note**: result depends on bit ordering.
Args:
pos: position of unit in vector.
nbits: number of meaningful bit in the number "pos".
Returns:
unit vector of size ``2^n``.
"""
vec = np.zeros((2**nbits,), dtype=np.int64)
vec[fgu.reverse_bits(pos, nbits, enable=True)] = 1
return vec
def eye_int(n: int) -> np.ndarray:
"""
Creates an identity matrix with integer entries.
Args:
n: number of bits.
Returns:
unit matrix of size ``2^n`` with integer entries.
"""
return np.eye(2**n, dtype=np.int64)
def kron3(a_mat: np.ndarray, b_mat: np.ndarray, c_mat: np.ndarray) -> np.ndarray:
"""
Computes Kronecker product of 3 matrices.
"""
return np.kron(a_mat, np.kron(b_mat, c_mat))
def kron5(
a_mat: np.ndarray, b_mat: np.ndarray, c_mat: np.ndarray, d_mat: np.ndarray, e_mat: np.ndarray
) -> np.ndarray:
"""
Computes Kronecker product of 5 matrices.
"""
return np.kron(np.kron(np.kron(np.kron(a_mat, b_mat), c_mat), d_mat), e_mat)
def rand_matrix(dim: int, kind: str = "complex") -> np.ndarray:
"""
Generates a random complex or integer value matrix.
Args:
dim: matrix size dim-x-dim.
kind: "complex" or "randint".
Returns:
a random matrix.
"""
if kind == "complex":
return (
np.random.rand(dim, dim).astype(np.cfloat)
+ np.random.rand(dim, dim).astype(np.cfloat) * 1j
)
else:
return np.random.randint(low=1, high=100, size=(dim, dim), dtype=np.int64)
def make_test_matrices2x2(n: int, k: int, kind: str = "complex") -> Tuple[np.ndarray, np.ndarray]:
"""
Creates a ``2^n x 2^n`` random matrix made as a Kronecker product of identity
ones and a single 1-qubit gate. This models a layer in quantum circuit with
an arbitrary 1-qubit gate somewhere in the middle.
Args:
n: number of qubits.
k: index of qubit a 1-qubit gate is acting on.
kind: entries of the output matrix are defined as:
"complex", "primes" or "randint".
Returns:
A tuple of (1) ``2^n x 2^n`` random matrix; (2) ``2 x 2`` matrix of 1-qubit
gate used for matrix construction.
"""
if kind == "primes":
a_mat = np.asarray([[2, 3], [5, 7]], dtype=np.int64)
else:
a_mat = rand_matrix(dim=2, kind=kind)
m_mat = kron3(eye_int(k), a_mat, eye_int(n - k - 1))
return m_mat, a_mat
def make_test_matrices4x4(
n: int, j: int, k: int, kind: str = "complex"
) -> Tuple[np.ndarray, np.ndarray]:
"""
Creates a ``2^n x 2^n`` random matrix made as a Kronecker product of identity
ones and a single 2-qubit gate. This models a layer in quantum circuit with
an arbitrary 2-qubit gate somewhere in the middle.
Args:
n: number of qubits.
j: index of the first qubit the 2-qubit gate acting on.
k: index of the second qubit the 2-qubit gate acting on.
kind: entries of the output matrix are defined as:
"complex", "primes" or "randint".
Returns:
A tuple of (1) ``2^n x 2^n`` random matrix; (2) ``4 x 4`` matrix of
2-qubit gate used for matrix construction.
"""
if kind == "primes":
a_mat = np.asarray([[2, 3], [5, 7]], dtype=np.int64)
b_mat = np.asarray([[11, 13], [17, 19]], dtype=np.int64)
c_mat = np.asarray([[47, 53], [41, 43]], dtype=np.int64)
d_mat = np.asarray([[31, 37], [23, 29]], dtype=np.int64)
else:
a_mat, b_mat = rand_matrix(dim=2, kind=kind), rand_matrix(dim=2, kind=kind)
c_mat, d_mat = rand_matrix(dim=2, kind=kind), rand_matrix(dim=2, kind=kind)
if j < k:
m_mat = kron5(eye_int(j), a_mat, eye_int(k - j - 1), b_mat, eye_int(n - k - 1)) + kron5(
eye_int(j), c_mat, eye_int(k - j - 1), d_mat, eye_int(n - k - 1)
)
else:
m_mat = kron5(eye_int(k), b_mat, eye_int(j - k - 1), a_mat, eye_int(n - j - 1)) + kron5(
eye_int(k), d_mat, eye_int(j - k - 1), c_mat, eye_int(n - j - 1)
)
g_mat = np.kron(a_mat, b_mat) + np.kron(c_mat, d_mat)
return m_mat, g_mat
def rand_circuit(num_qubits: int, depth: int) -> np.ndarray:
"""
Generates a random circuit of unit blocks for debugging and testing.
"""
blocks = np.tile(np.arange(num_qubits).reshape(num_qubits, 1), depth)
for i in range(depth):
np.random.shuffle(blocks[:, i])
return blocks[0:2, :].copy()
def rand_su_mat(dim: int) -> np.ndarray:
"""
Generates a random SU matrix.
Args:
dim: matrix size ``dim-x-dim``.
Returns:
random SU matrix.
"""
u_mat = unitary_group.rvs(dim)
u_mat /= np.linalg.det(u_mat) ** (1.0 / float(dim))
return u_mat
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# the first and second elements are 1 and 1
F = [1,1]
for i in range(2,30):
F.append(F[i-1] + F[i-2])
# print the final list
print(F)
# define an empty list
N = []
for i in range(11):
N.append([ i , i*i , i*i*i , i*i + i*i*i ]) # a list having four elements is added to the list N
# Alternatively:
#N.append([i , i**2 , i**3 , i**2 + i**3]) # ** is the exponent operator
#N = N + [ [i , i*i , i*i*i , i*i + i*i*i] ] # Why using double brackets?
#N = N + [ [i , i**2 , i**3 , i**2 + i**3] ] # Why using double brackets?
# In the last two alternative solutions, you may try with a single bracket,
# and then see why double brackets are needed for the exact answer.
# print the final list
print(N)
# let's print the list N element by element
for i in range(len(N)):
print(N[i])
# let's print the list N element by element by using an alternative method
for el in N: # el will iteratively takes the values of elements in N
print(el)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
input_3sat_instance = '''
c example DIMACS-CNF 3-SAT
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
'''
import os
import tempfile
from qiskit.exceptions import MissingOptionalLibraryError
from qiskit.circuit.library.phase_oracle import PhaseOracle
fp = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
fp.write(input_3sat_instance)
file_name = fp.name
fp.close()
oracle = None
try:
oracle = PhaseOracle.from_dimacs_file(file_name)
except MissingOptionalLibraryError as ex:
print(ex)
finally:
os.remove(file_name)
from qiskit.algorithms import AmplificationProblem
problem = None
if oracle is not None:
problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring)
from qiskit.algorithms import Grover
from qiskit.primitives import Sampler
grover = Grover(sampler=Sampler())
result = None
if problem is not None:
result = grover.amplify(problem)
print(result.assignment)
from qiskit.tools.visualization import plot_histogram
if result is not None:
display(plot_histogram(result.circuit_results[0]))
expression = '(w ^ x) & ~(y ^ z) & (x & y & z)'
try:
oracle = PhaseOracle(expression)
problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring)
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
display(plot_histogram(result.circuit_results[0]))
except MissingOptionalLibraryError as ex:
print(ex)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.drivers import Molecule
from qiskit_nature.drivers.second_quantization import (
ElectronicStructureDriverType,
ElectronicStructureMoleculeDriver,
PySCFDriver,
)
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer
from qiskit_nature.settings import settings
settings.dict_aux_operators = True
molecule = Molecule(
geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]], charge=0, multiplicity=1
)
driver = ElectronicStructureMoleculeDriver(
molecule, basis="sto3g", driver_type=ElectronicStructureDriverType.PYSCF
)
# or equivalently:
driver = PySCFDriver.from_molecule(molecule, basis="sto3g")
transformer = FreezeCoreTransformer()
problem = ElectronicStructureProblem(driver, transformers=[transformer])
# Note: at this point, `driver.run()` has NOT been called yet. We can trigger this indirectly like so:
second_q_ops = problem.second_q_ops()
hamiltonian = second_q_ops["ElectronicEnergy"]
print(hamiltonian)
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo
from qiskit_nature.second_q.transformers import FreezeCoreTransformer
molecule = MoleculeInfo(["H", "H"], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.735)], charge=0, multiplicity=1)
driver = PySCFDriver.from_molecule(molecule, basis="sto3g")
# this is now done explicitly
problem = driver.run()
transformer = FreezeCoreTransformer()
# and you also apply transformers explicitly
problem = transformer.transform(problem)
hamiltonian = problem.hamiltonian.second_q_op()
print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."]))
from qiskit_nature.drivers import Molecule
from qiskit_nature.drivers.second_quantization import PySCFDriver
molecule = Molecule(
geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]], charge=0, multiplicity=1
)
driver = PySCFDriver.from_molecule(molecule)
result = driver.run()
print(type(result))
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo
molecule = MoleculeInfo(["H", "H"], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.735)], charge=0, multiplicity=1)
driver = PySCFDriver.from_molecule(molecule, basis="sto3g")
result = driver.run()
print(type(result))
from qiskit_nature.drivers.second_quantization import FCIDumpDriver
path_to_fcidump = "aux_files/h2.fcidump"
driver = FCIDumpDriver(path_to_fcidump)
result = driver.run()
print(type(result))
from qiskit_nature.second_q.formats.fcidump import FCIDump
path_to_fcidump = "aux_files/h2.fcidump"
fcidump = FCIDump.from_file(path_to_fcidump)
print(type(fcidump))
from qiskit_nature.second_q.formats.fcidump_translator import fcidump_to_problem
problem = fcidump_to_problem(fcidump)
print(type(problem))
from qiskit_nature.drivers.second_quantization import PySCFDriver
from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer
transformer = FreezeCoreTransformer()
driver = PySCFDriver()
transformed_result = transformer.transform(driver.run())
print(type(transformed_result))
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.transformers import FreezeCoreTransformer
transformer = FreezeCoreTransformer()
driver = PySCFDriver()
transformed_result = transformer.transform(driver.run())
print(type(transformed_result))
from qiskit_nature.drivers.second_quantization import PySCFDriver
from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer
driver = PySCFDriver()
transformer = FreezeCoreTransformer()
problem = ElectronicStructureProblem(driver, transformers=[transformer])
# we trigger driver.run() implicitly like so:
second_q_ops = problem.second_q_ops()
hamiltonian_op = second_q_ops.pop("ElectronicEnergy")
aux_ops = second_q_ops
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.transformers import FreezeCoreTransformer
driver = PySCFDriver()
problem = driver.run()
transformer = FreezeCoreTransformer()
problem = transformer.transform(problem)
hamiltonian_op, aux_ops = problem.second_q_ops()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
"""
Grover's Search Benchmark Program - QSim
"""
import sys
import time
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
sys.path[1:1] = ["_common", "_common/qsim"]
sys.path[1:1] = ["../../_common", "../../_common/qsim"]
import execute as ex
import metrics as metrics
from execute import BenchmarkResult
# Benchmark Name
benchmark_name = "Grover's Search"
np.random.seed(0)
verbose = False
# saved circuits for display
QC_ = None
grover_oracle = None
diffusion_operator = None
# for validating the implementation of an mcx shim
_use_mcx_shim = False
############### Circuit Definition
def GroversSearch(num_qubits, marked_item, n_iterations):
# allocate qubits
qr = QuantumRegister(num_qubits);
cr = ClassicalRegister(num_qubits);
qc = QuantumCircuit(qr, cr, name=f"grovers-{num_qubits}-{marked_item}")
# Start with Hadamard on all qubits
for i_qubit in range(num_qubits):
qc.h(qr[i_qubit])
# loop over the estimated number of iterations
for _ in range(n_iterations):
qc.barrier()
# add the grover oracle
qc.append(add_grover_oracle(num_qubits, marked_item).to_instruction(), qr)
# add the diffusion operator
qc.append(add_diffusion_operator(num_qubits).to_instruction(), qr)
qc.barrier()
# measure all qubits
qc.measure(qr, cr) # to get the partial_probability
# qc.measure(qr, cr, basis='Ensemble', add_param='Z') # to get the ensemble_probability
# save smaller circuit example for display
global QC_
if QC_ == None or num_qubits <= 5:
if num_qubits < 9: QC_ = qc
# return a handle on the circuit
return qc
############## Grover Oracle
def add_grover_oracle(num_qubits, marked_item):
global grover_oracle
marked_item_bits = format(marked_item, f"0{num_qubits}b")[::-1]
qr = QuantumRegister(num_qubits); qc = QuantumCircuit(qr, name="oracle")
for (q, bit) in enumerate(marked_item_bits):
if not int(bit):
qc.x(q)
qc.h(num_qubits - 1)
if _use_mcx_shim:
add_mcx(qc, [x for x in range(num_qubits - 1)], num_qubits - 1)
else:
qc.mcx([x for x in range(num_qubits - 1)], num_qubits - 1)
qc.h(num_qubits - 1)
qc.barrier()
for (q, bit) in enumerate(marked_item_bits):
if not int(bit):
qc.x(q)
if grover_oracle == None or num_qubits <= 5:
if num_qubits < 9: grover_oracle = qc
return qc
############## Grover Diffusion Operator
def add_diffusion_operator(num_qubits):
global diffusion_operator
qr = QuantumRegister(num_qubits); qc = QuantumCircuit(qr, name="diffuser")
for i_qubit in range(num_qubits):
qc.h(qr[i_qubit])
for i_qubit in range(num_qubits):
qc.x(qr[i_qubit])
qc.h(num_qubits - 1)
if _use_mcx_shim:
add_mcx(qc, [x for x in range(num_qubits - 1)], num_qubits - 1)
else:
qc.mcx([x for x in range(num_qubits - 1)], num_qubits - 1)
qc.h(num_qubits - 1)
qc.barrier()
for i_qubit in range(num_qubits):
qc.x(qr[i_qubit])
for i_qubit in range(num_qubits):
qc.h(qr[i_qubit])
if diffusion_operator == None or num_qubits <= 5:
if num_qubits < 9: diffusion_operator = qc
return qc
############### MCX shim
# single cx / cu1 unit for mcx implementation
def add_cx_unit(qc, cxcu1_unit, controls, target):
num_controls = len(controls)
i_qubit = cxcu1_unit[1]
j_qubit = cxcu1_unit[0]
theta = cxcu1_unit[2]
if j_qubit != None:
qc.cx(controls[j_qubit], controls[i_qubit])
qc.cu1(theta, controls[i_qubit], target)
i_qubit = i_qubit - 1
if j_qubit == None:
j_qubit = i_qubit + 1
else:
j_qubit = j_qubit - 1
if theta < 0:
theta = -theta
new_units = []
if i_qubit >= 0:
new_units += [ [ j_qubit, i_qubit, -theta ] ]
new_units += [ [ num_controls - 1, i_qubit, theta ] ]
return new_units
# mcx recursion loop
def add_cxcu1_units(qc, cxcu1_units, controls, target):
new_units = []
for cxcu1_unit in cxcu1_units:
new_units += add_cx_unit(qc, cxcu1_unit, controls, target)
cxcu1_units.clear()
return new_units
# mcx gate implementation: brute force and inefficent
# start with a single CU1 on last control and target
# and recursively expand for each additional control
def add_mcx(qc, controls, target):
num_controls = len(controls)
theta = np.pi / 2**num_controls
qc.h(target)
cxcu1_units = [ [ None, num_controls - 1, theta] ]
while len(cxcu1_units) > 0:
cxcu1_units += add_cxcu1_units(qc, cxcu1_units, controls, target)
qc.h(target)
################ Analysis
# Analyze and print measured results
# Expected result is always the secret_int, so fidelity calc is simple
def analyze_and_print_result(qc, result, num_qubits, marked_item, num_shots):
if result.backend_name == 'dm_simulator':
benchmark_result = BenchmarkResult(result, num_shots)
probs = benchmark_result.get_probs(num_shots) # get results as measured probability
else:
probs = result.get_counts(qc) # get results as measured counts
# # setting the threhold value to avoid getting exponential values which leads to nan values
# threshold = 3e-3
# probs = {key: value if value > threshold else 0.0 for key, value in probs.items()}
if verbose: print(f"For type {marked_item} measured: {probs}")
# we compare counts to analytical correct distribution
correct_dist = grovers_dist(num_qubits, marked_item)
if verbose: print(f"Marked item: {marked_item}, Correct dist: {correct_dist}")
# use our polarization fidelity rescaling
fidelity = metrics.polarization_fidelity(probs, correct_dist)
return probs, fidelity
def grovers_dist(num_qubits, marked_item):
n_iterations = int(np.pi * np.sqrt(2 ** num_qubits) / 4)
dist = {}
for i in range(2**num_qubits):
key = bin(i)[2:].zfill(num_qubits)[::-1]
theta = np.arcsin(1/np.sqrt(2 ** num_qubits))
if i == int(marked_item):
dist[key] = np.sin((2*n_iterations+1)*theta)**2
else:
dist[key] = (np.cos((2*n_iterations+1)*theta)/(np.sqrt(2 ** num_qubits - 1)))**2
return dist
################ Benchmark Loop
# Because this circuit size grows significantly with num_qubits (due to the mcx gate)
# limit the max_qubits here ...
MAX_QUBITS=8
# Execute program with default parameters
def run(min_qubits=2, max_qubits=6, skip_qubits=1, max_circuits=3, num_shots=100,
use_mcx_shim=False,
backend_id='dm_simulator', provider_backend=None,
# hub="ibm-q", group="open", project="main",
exec_options=None,
context=None):
print(f"{benchmark_name} Benchmark Program - QSim")
# Clamp the maximum number of qubits
if max_qubits > MAX_QUBITS:
print(f"INFO: {benchmark_name} benchmark is limited to a maximum of {MAX_QUBITS} qubits.")
max_qubits = MAX_QUBITS
# validate parameters (smallest circuit is 2 qubits)
max_qubits = max(2, max_qubits)
min_qubits = min(max(2, min_qubits), max_qubits)
skip_qubits = max(1, skip_qubits)
#print(f"min, max qubits = {min_qubits} {max_qubits}")
# create context identifier
if context is None: context = f"{benchmark_name} Benchmark"
# set the flag to use an mcx shim if given
global _use_mcx_shim
_use_mcx_shim = use_mcx_shim
if _use_mcx_shim:
print("... using MCX shim")
##########
# Initialize metrics module
metrics.init_metrics()
# Define custom result handler
def execution_handler(qc, result, num_qubits, s_int, num_shots):
# determine fidelity of result set
num_qubits = int(num_qubits)
probs, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots)
metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity)
# Initialize execution module using the execution result handler above and specified backend_id
ex.init_execution(execution_handler)
ex.set_execution_target(backend_id, provider_backend=provider_backend,
# hub=hub, group=group, project=project,
exec_options=exec_options,
context=context)
##########
# Execute Benchmark Program N times for multiple circuit sizes
# Accumulate metrics asynchronously as circuits complete
for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits):
# determine number of circuits to execute for this group
num_circuits = min(2 ** (num_qubits), max_circuits)
print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}")
# determine range of secret strings to loop over
if 2**(num_qubits) <= max_circuits:
s_range = list(range(num_circuits))
else:
s_range = np.random.choice(2**(num_qubits), num_circuits, False)
# loop over limited # of secret strings for this
for s_int in s_range:
# create the circuit for given qubit size and secret string, store time metric
ts = time.time()
n_iterations = int(np.pi * np.sqrt(2 ** num_qubits) / 4)
qc = GroversSearch(num_qubits, s_int, n_iterations)
metrics.store_metric(num_qubits, s_int, 'create_time', time.time() - ts)
# collapse the sub-circuits used in this benchmark (for qiskit)
qc2 = qc.decompose()
# submit circuit for execution on target (simulator, cloud simulator, or hardware)
ex.submit_circuit(qc2, num_qubits, s_int, num_shots)
# Wait for some active circuits to complete; report metrics when groups complete
ex.throttle_execution(metrics.finalize_group)
# Wait for all active circuits to complete; report metrics when groups complete
ex.finalize_execution(metrics.finalize_group)
##########
# print a sample circuit created (if not too large)
print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!")
print("\nOracle ="); print(grover_oracle if grover_oracle!= None else " ... too large!")
print("\nDiffuser ="); print(diffusion_operator )
# Plot metrics for all circuit sizes
metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim")
# if main, execute method
if __name__ == '__main__':
ex.local_args() # calling local_args() needed while taking noise parameters through command line arguments (for individual benchmarks)
run()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
# Import Qiskit
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
# Construct quantum circuit
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
circ.measure([0,1], [0,1])
# Select the AerSimulator from the Aer provider
simulator = AerSimulator(method='matrix_product_state')
# Run and get counts, using the matrix_product_state method
tcirc = transpile(circ, simulator)
result = simulator.run(tcirc).result()
counts = result.get_counts(0)
counts
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
# Define a snapshot that shows the current state vector
circ.save_statevector(label='my_sv')
circ.save_matrix_product_state(label='my_mps')
circ.measure([0,1], [0,1])
# Execute and get saved data
tcirc = transpile(circ, simulator)
result = simulator.run(tcirc).result()
data = result.data(0)
#print the result data
data
num_qubits = 50
circ = QuantumCircuit(num_qubits, num_qubits)
# Create EPR state
circ.h(0)
for i in range (0, num_qubits-1):
circ.cx(i, i+1)
# Measure
circ.measure(range(num_qubits), range(num_qubits))
tcirc = transpile(circ, simulator)
result = simulator.run(tcirc).result()
print("Time taken: {} sec".format(result.time_taken))
result.get_counts()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit.circuit import Parameter
from qiskit import pulse
from qiskit.test.mock.backends.almaden import *
phase = Parameter('phase')
with pulse.build(FakeAlmaden()) as phase_test_sched:
pulse.shift_phase(phase, pulse.drive_channel(0))
phase_test_sched.instructions # ()
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
import qiskit
qiskit.__qiskit_version__
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.compiler import transpile
from qiskit.tools.monitor import job_monitor
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
# Load our saved IBMQ accounts.
IBMQ.load_account()
nQubits = 14 # number of physical qubits
a = 101 # the hidden integer whose bitstring is 1100101
# make sure that a can be represented with nQubits
a = a % 2**(nQubits)
# Creating registers
# qubits for querying the oracle and finding the hidden integer
qr = QuantumRegister(nQubits)
# for recording the measurement on qr
cr = ClassicalRegister(nQubits)
circuitName = "BernsteinVazirani"
bvCircuit = QuantumCircuit(qr, cr)
# Apply Hadamard gates before querying the oracle
for i in range(nQubits):
bvCircuit.h(qr[i])
# Apply barrier so that it is not optimized by the compiler
bvCircuit.barrier()
# Apply the inner-product oracle
for i in range(nQubits):
if (a & (1 << i)):
bvCircuit.z(qr[i])
else:
bvCircuit.iden(qr[i])
# Apply barrier
bvCircuit.barrier()
#Apply Hadamard gates after querying the oracle
for i in range(nQubits):
bvCircuit.h(qr[i])
# Measurement
bvCircuit.barrier(qr)
bvCircuit.measure(qr, cr)
bvCircuit.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1000
results = execute(bvCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
backend = IBMQ.get_backend('ibmq_16_melbourne')
shots = 1000
bvCompiled = transpile(bvCircuit, backend=backend, optimization_level=1)
job_exp = execute(bvCircuit, backend=backend, shots=shots)
job_monitor(job_exp)
results = job_exp.result()
answer = results.get_counts(bvCircuit)
threshold = int(0.01 * shots) #the threshold of plotting significant measurements
filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} #filter the answer for better view of plots
removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) #number of counts removed
filteredAnswer['other_bitstrings'] = removedCounts #the removed counts is assigned to a new index
plot_histogram(filteredAnswer)
print(filteredAnswer)
|
https://github.com/oscarhiggott/pewpew-qube
|
oscarhiggott
|
%matplotlib notebook
# import pygame to run the PewPew emulator from a notebook
import pygame
# add the src directory to the search path to load modules
import sys
sys.path.insert(0, "../src/")
qiskit_images = (
(
(0, 3, 3, 3, 3, 3, 3, 0),
(3, 2, 0, 1, 1, 0, 0, 3),
(3, 0, 2, 0, 0, 1, 0, 3),
(3, 1, 0, 2, 0, 0, 1, 3),
(3, 3, 0, 0, 2, 0, 3, 3),
(3, 0, 3, 3, 3, 3, 0, 3),
(3, 0, 0, 0, 0, 0, 2, 3),
(0, 3, 3, 3, 3, 3, 3, 0)
),
(
(0, 3, 3, 3, 3, 3, 3, 0),
(3, 0, 0, 2, 1, 0, 0, 3),
(3, 0, 1, 2, 0, 1, 0, 3),
(3, 1, 0, 0, 2, 0, 1, 3),
(3, 3, 0, 0, 2, 0, 3, 3),
(3, 0, 3, 3, 3, 3, 0, 3),
(3, 0, 0, 0, 0, 2, 0, 3),
(0, 3, 3, 3, 3, 3, 3, 0)
),
(
(0, 3, 3, 3, 3, 3, 3, 0),
(3, 0, 0, 1, 2, 0, 0, 3),
(3, 0, 1, 0, 2, 1, 0, 3),
(3, 1, 0, 2, 0, 0, 1, 3),
(3, 3, 0, 2, 0, 0, 3, 3),
(3, 0, 3, 3, 3, 3, 0, 3),
(3, 0, 2, 0, 0, 0, 0, 3),
(0, 3, 3, 3, 3, 3, 3, 0)
),
(
(0, 3, 3, 3, 3, 3, 3, 0),
(3, 0, 0, 1, 1, 0, 2, 3),
(3, 0, 1, 0, 0, 2, 0, 3),
(3, 1, 0, 0, 2, 0, 1, 3),
(3, 3, 0, 2, 0, 0, 3, 3),
(3, 0, 3, 3, 3, 3, 0, 3),
(3, 2, 0, 0, 0, 0, 0, 3),
(0, 3, 3, 3, 3, 3, 3, 0)
)
)
import pew
i = 0 # frame counter
value = 0 # selected level
pew.init() # initialize the PewPew console
# main loop
while not value:
# check for pressed keys
keys = pew.keys()
if keys & pew.K_UP:
value = 1
elif keys & pew.K_RIGHT:
value = 2
elif keys & pew.K_DOWN:
value = 3
elif keys & pew.K_LEFT:
value = 4
# display the next frame
animation = (0,0,1,1,2,2,3,3,2,2,1,1)
i = (i + 1) % len(animation)
screen = qiskit_images[animation[i]]
pew.show(pew.Pix.from_iter(screen))
# wait 0.1 seconds
pew.tick(0.1)
# freeze the screen while a button is pressed
while pew.keys():
pew.tick(0.1)
# the following is just necessary in a jupyter notebook:
pygame.display.quit()
pygame.quit()
import random
import time
# initialize the random-number generator
random.seed(int(time.monotonic()*1000))
# unload unnecessary objects to save RAM
del qiskit_images
# load the new main loop
from loop import main_loop
# execute the new main loop passing to it the seleced level
if value == 1:
from rotations import instruction_set_XYZ
main_loop(instruction_set_XYZ())
else:
from instruction_sets import InstructionSet
from displays import IBMQ
main_loop(InstructionSet(level=value-2, goal=IBMQ))
# the following is just necessary in a jupyter notebook:
pygame.display.quit()
pygame.quit()
def main_loop(ins):
# initialize PewPew console
pew.init()
# Load start screens
for start_screen in start_screens:
pew.show(pew.Pix.from_iter(start_screen))
pew.tick(0.2)
pew.show(pew.Pix.from_iter(blank_screen))
pew.tick(0.5)
# display the first frame of the level
pew.show(ins.get_current_screen())
# flags used throughout the loop
bool_loop = True
old_keys = 0
# new main loop
while bool_loop:
keys = pew.keys()
if keys != 0 and keys != old_keys:
# old_keys is necessary to debounce the buttons
old_keys = keys
# dispatch the pushed buttons
if keys & pew.K_X:
value = pew.K_X
elif keys & pew.K_DOWN:
value = pew.K_DOWN
elif keys & pew.K_LEFT:
value = pew.K_LEFT
elif keys & pew.K_RIGHT:
value = pew.K_RIGHT
elif keys & pew.K_UP:
value = pew.K_UP
elif keys & pew.K_O:
# the key "O" ("Z" in the emulator) will terminate the game
value = pew.K_O
bool_loop = False
else:
value = 0
# send the pressed key to the instruction set
ins.key_pressed(value)
elif keys == 0:
# this is necessary to be able to push
# a button twice in a row
old_keys = keys
# update the screen and wait for 20ms
pew.show(ins.get_current_screen())
pew.tick(0.02)
# the program has been terminated.
# display the final sequence
for final_screen in final_screens:
pew.show(pew.Pix.from_iter(final_screen))
pew.tick(0.2)
pew.show(pew.Pix.from_iter(blank_screen))
pew.tick(0.2)
class instruction_set_XYZ:
def __init__(self):
# history of pushed keys
self.key_hist = []
# current state vector
self.state = random_state()
def key_pressed(self, key):
if key == pew.K_UP:
# forget all pushed buttons
self.key_hist = []
elif key == pew.K_LEFT or key == pew.K_DOWN or key == pew.K_RIGHT:
# append button to history
self.key_hist.append(key)
# if two buttons have been pressed, determine the corresponding transformation
if len(self.key_hist) == 2:
if self.key_hist[0] == pew.K_LEFT:
gate = 'x'
elif self.key_hist[0] == pew.K_DOWN:
gate = 'y'
else:
gate = 'z'
if self.key_hist[1] == pew.K_LEFT:
gate = gate + 'x'
elif self.key_hist[1] == pew.K_DOWN:
gate = gate + 'y'
else:
gate = gate + 'z'
# update the state vector
self.state = propagate_statevector(self.state, make_circuit(gate))
# clear the history of pushed buttons
self.key_hist = []
elif key == pew.K_X:
# restart the level
self.__init__()
def get_current_screen(self):
return make_image(self.state)
from aether import QuantumCircuit
pi4 = 0.785398
pi2 = 1.570796
def make_circuit(gate):
qc = QuantumCircuit(2)
if gate[0] == 'x':
qc.h(0)
elif gate[0] == 'y':
qc.rx(pi2,0)
if gate[1] == 'x':
qc.h(1)
elif gate[1] == 'y':
qc.rx(pi2,1)
qc.cx(0,1)
qc.h(1)
qc.rx(pi2,1)
qc.h(1)
qc.cx(0,1)
if gate[0] == 'x':
qc.h(0)
elif gate[0] == 'y':
qc.rx(-pi2,0)
if gate[1] == 'x':
qc.h(1)
elif gate[1] == 'y':
qc.rx(-pi2,1)
return qc
from aether import QuantumCircuit, simulate
def propagate_statevector(vec,qc):
qc_i = QuantumCircuit(2,0)
qc_i.initialize(vec)
return simulate(qc_i + qc, get='statevector')
def random_state():
state = [[1.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0]]
for i in range(5):
gate = ['xx','xy','xz','yx','yz','yy','zx','zy','zz'][randint(0,8)]
qc = make_circuit(gate)
state = propagate_statevector(state, qc)
return state
def make_image(state):
blocks = []
for num in state:
blocks.append(make_block(num))
image = pew.Pix()
for i in range(2):
for j in range(4):
tmp = blocks[2*i][j] + blocks[2*i+1][j]
for x in range(8):
image.pixel(x,4*i+j,tmp[x])
return image
def make_block(c_num):
amp = sqrt(c_num[0]*c_num[0] + c_num[1]*c_num[1])
phi = atan2(c_num[1], c_num[0])
if amp < 0.01:
phi = 0
scenario = 0
phases = [0.0, pi4, -pi4, 2.0*pi4, -2.0*pi4, 3.0*pi4, -3.0*pi4, 4.0*pi4, -4.0*pi4]
scenarios = [1, -1, -2, 4, 2, -4, -3, 3, 3 ]
for i in range(9):
if (phi - phases[i])*(phi - phases[i]) < 0.001:
scenario = scenarios[i]
continue
if amp < 0.25:
block = [[0,0,0,0],[0,2,2,0],[0,2,2,0],[0,0,0,0]]
elif amp < 0.6:
if scenario > 0:
block = [[0,0,2,0],[0,0,0,2],[0,0,0,2],[0,0,2,0]]
else:
block = [[0,0,0,0],[0,2,2,0],[0,0,2,0],[0,0,0,0]]
elif amp < 0.9:
if scenario > 0:
block = [[0,0,0,2],[0,0,2,0],[0,0,2,0],[0,0,0,2]]
else:
block = [[0,0,2,0],[0,0,2,2],[0,0,0,0],[0,0,0,0]]
else:
if scenario > 0:
block = [[0,0,0,2],[0,0,0,2],[0,0,0,2],[0,0,0,2]]
else:
block = [[0,0,2,2],[0,0,0,2],[0,0,0,0],[0,0,0,0]]
if scenario != 1 and scenario != -1:
for r in range(abs(scenario) - 1):
block = rot90(block)
return block
def rot90(block):
res = []
for i in range(len(block)):
transposed = []
for col in block:
transposed.append(col[i])
transposed.reverse()
res.append(transposed)
return res
|
https://github.com/Ilan-Bondarevsky/qiskit_algorithm
|
Ilan-Bondarevsky
|
from qiskit import QuantumCircuit, QuantumRegister, AncillaRegister, ClassicalRegister, Aer, execute
from bit_functions import full_bitfield, get_qubit_list
from Grover.grover_cirq import diffuser, calculate_iteration, prep_qubits_circuit, check_solution_grover, generate_grover_circuits_with_iterations, simulate_grover_qc_list
from circuits import cnz
from logic_gate_circuits import and_gate, or_gate, xor_gate, xnor_gate, nand_gate, nor_gate, mor_gate, mand_gate
from Grover.grover_cirq import diffuser
def check_same_num(num_qubit = None, max_num_value = None):
'''Returns a circuit that sets the last ancilla qubit (Answer) if the numbers are the same'''
if num_qubit is None and max_num_value is None:
return None
if num_qubit is not None:
pass
else:
num_qubit = max_num_value.bit_length()
num_a = QuantumRegister(num_qubit, 'A')
num_b = QuantumRegister(num_qubit, 'B')
xnor_qc = QuantumCircuit(num_a, num_b)
for i in range(num_qubit):
xnor_g = xnor_gate()
xnor_qc.add_register(AncillaRegister(1))
xnor_qc = xnor_qc.compose(xnor_g, [num_a[i], num_b[i], xnor_qc.ancillas[-1]])
qc = QuantumCircuit(xnor_qc.qubits)
qc = qc.compose(xnor_qc, xnor_qc.qubits)
if len(qc.ancillas) > 1:
qc.add_register(AncillaRegister(1))
qc.mcx(xnor_qc.ancillas, qc.ancillas[-1])
qc = qc.compose(xnor_qc.inverse(), xnor_qc.qubits)
qc.name = 'Check_Same_Num'
return qc
#def prep_cnz(nqubits, set_qubit_value = [] ,mode='noancilla'):
# '''Prepare cnz circuit with vgiven values of the qubits\n
# Returns the prepared circuit\n
# set_value_list contains a list of tuples that contains (qubit_index , 0 or 1)'''
#
# x_qubit = [value[0] for value in set_qubit_value if value[1] and value[0] < nqubits]
#
# cnz_qc = cnz(nqubits, mode)
#
# qc = QuantumCircuit(cnz_qc.qubits)
# qc.x(x_qubit) if len(x_qubit) else None
# qc.barrier(qc.qubits)
# qc = qc.compose(cnz_qc, qc.qubits)
# qc.barrier(qc.qubits)
# qc.x(x_qubit) if len(x_qubit) else None
#
# qc.name = f"cnz {nqubits}"
# return qc
def create_sudoko_iteration(max_value = 2):
max_cells = list(range(pow(max_value, 2)))
qubit_num = (max_value - 1).bit_length()
if not qubit_num:
return None
pairs = get_matrix_pairs(max_value)
qubit_list = QuantumRegister(len(max_cells) * qubit_num)
anc_list = AncillaRegister(qubit_num) if qubit_num > 1 else []
answer_anc_list = []
qc_pair = QuantumCircuit(qubit_list, anc_list)
for p in pairs:
check_equal_qc = check_same_num(qubit_num)
answer_anc_list.append(check_equal_qc.ancillas[-1])
qc_pair.add_register([answer_anc_list[-1]])
qubit_connection = list(qubit_list[p[0] * qubit_num : (p[0] + 1) * qubit_num]) + list(qubit_list[p[1] * qubit_num : (p[1] + 1) * qubit_num]) + list(anc_list) + [check_equal_qc.ancillas[-1]]
qc_pair = qc_pair.compose(check_equal_qc, qubit_connection)
qc_pair.barrier(qc_pair.qubits)
qc_z = cnz(len(answer_anc_list), [(i, 0) for i in range(len(answer_anc_list))])
diffuser_qc = diffuser(len(get_qubit_list(qc_pair)))
qc = QuantumCircuit(qc_pair.qubits)
qc = qc.compose(qc_pair, qc_pair.qubits)
qc.barrier(qc.qubits)
qc = qc.compose(qc_z, answer_anc_list)
qc.barrier(qc.qubits)
qc = qc.compose(qc_pair.inverse(), qc_pair.qubits)
qc.barrier(qc.qubits)
qc = qc.compose(diffuser_qc, get_qubit_list(qc))
return qc
def create_sudoko_circuits(max_value = 2, set_qubit_value = []):
qc_iter = create_sudoko_iteration(max_value)
return generate_grover_circuits_with_iterations(qc_iter, set_qubit_value)
def get_matrix_pairs(matrix_size = 4, start_cell = 0):
output = []
if start_cell >= pow(matrix_size, 2):
return output
cur_index = start_cell + 1
while cur_index % matrix_size:
pair = (start_cell, cur_index)
output.append(pair) if pair not in output else None
cur_index = cur_index + 1
cur_index = start_cell + matrix_size
while cur_index < pow(matrix_size, 2):
pair = (start_cell, cur_index)
output.append(pair) if pair not in output else None
cur_index = cur_index + matrix_size
output = output + [i for i in get_matrix_pairs(matrix_size=matrix_size, start_cell= start_cell + 1) if i not in output]
return output
def check_under_nine(nqubits):
'''Returns a circuit that calculates if the value of the qubits are under nine (0 - 8)\n
The answer will be on the final ancilla bit.\n
The ancillas, except the last one (Answer), can be reused'''
nine_bit_size = int(9).bit_length()
additional_qubits = nqubits - nine_bit_size
if additional_qubits < 0:
return None
nand_three = mand_gate(3, [1] * 3)
nand_three.x(nand_three.ancillas[-1])
nand_three.barrier(nand_three.qubits)
nand_fourth = nand_gate()
nine_qubit_qc = QuantumCircuit(nand_three.qubits, nand_fourth.qubits[1:])
nine_qubit_qc = nine_qubit_qc.compose(nand_three, nand_three.qubits)
nine_qubit_qc = nine_qubit_qc.compose(nand_fourth, [nand_three.ancillas[-1]] + list(nand_fourth.qubits[1:]))
if additional_qubits:
add_qubits = QuantumRegister(additional_qubits)
nine_qubit_qc.add_register(add_qubits)
nine_qubit_qc.x(add_qubits)
qc = QuantumCircuit(nine_qubit_qc.qubits, AncillaRegister(1))
qc = qc.compose(nine_qubit_qc, nine_qubit_qc.qubits)
qc.barrier(qc.qubits)
qc.mcx(list(add_qubits) + [nine_qubit_qc.ancillas[-1]], qc.ancillas[-1])
qc.barrier(qc.qubits)
qc = qc.compose(nine_qubit_qc.inverse(), nine_qubit_qc.qubits)
else:
qc = QuantumCircuit(nine_qubit_qc.qubits)
qc = qc.compose(nine_qubit_qc, nine_qubit_qc.qubits)
qc = qc.compose(nand_three.inverse(), nand_three.qubits)
qc.name = "Check_under_nine"
return qc
|
https://github.com/mrvee-qC-bee/UNHAN_Quantum_Workshop_2023
|
mrvee-qC-bee
|
#make sure your qiskit version is up to date
import qiskit.tools.jupyter
%qiskit_version_table
from qiskit import QuantumCircuit
# Create a Quantum Circuit acting on a quantum register of two qubits
circ = QuantumCircuit(2)
print(circ)
# 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)
circ.draw('mpl', style="iqp")
#One can also draw this as an ascii drawing
circ.draw()
from qiskit.primitives import Sampler
#Instantiate a new Sampler object
sampler = Sampler()
#We'll also need to add measurement
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
# Insert measurements on all qubits
circ.measure_all()
circ.draw('mpl', style='iqp')
# Now run the job and examine the results
sampler_job = sampler.run(circ)
result = sampler_job.result()
print(f"Job Result:\n>>> {result}")
print(f" > Quasi-probability distribution (integer): {result.quasi_dists[0]}")
print(f" > Quasi-probability distribution (bits): {result.quasi_dists[0].binary_probabilities(2)}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit.tools.visualization import plot_distribution
prob_distribution = sampler_job.result().quasi_dists[0].binary_probabilities()
plot_distribution(prob_distribution)
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session
#Initialize a QiskitRuntimeService object
service = QiskitRuntimeService()
#We will use the 127-qubit ibm_nazca or 133-qubit ibm_torino backend
backend = service.get_backend('ibm_cusco')
session = Session(service=service, backend=backend)
# sampler = Sampler(backend=backend)
sampler = Sampler(session=session)
job = sampler.run(circ)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Session ID: {job.session_id}")
print(f">>> Job Status: {job.status()}")
# Use a job id from a previous result
job = service.job("cnxwrpjmbjng0081zhc0")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f"Job Result:\n>>> {result}")
print(f" > Quasi-probability distribution (integer): {result.quasi_dists[0]}")
print(f" > Quasi-probability distribution (bits): {result.quasi_dists[0].binary_probabilities(2)}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit.visualization import plot_distribution
import matplotlib.pyplot as plt
plt.style.use('dark_background')
#plot_distribution(result.quasi_dists[0])
plot_distribution([result.quasi_dists[0].binary_probabilities(2),prob_distribution])
from qiskit import QuantumRegister, ClassicalRegister
#Create the circuit
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
# we can also write "qc = QuantumCircuit(2,2)"
#Add the hadamard and CNOT gates to the circuit
qc.h(0)
qc.cx(0, 1)
qc.draw('mpl', style="iqp")
# Import the SparesPauliOp class and create our observables variable
from qiskit.quantum_info import SparsePauliOp
observable = SparsePauliOp(["II", "XX", "YY", "ZZ"], coeffs=[1, 1, -1, 1])
# Import qiskit primitives
from qiskit.primitives import Estimator
estimator = Estimator()
job = estimator.run(qc, observable)
result_exact = job.result()
print(result_exact)
print(f"Expectation Value of <II+XX-YY+ZZ> = {result_exact.values[0]:.3f}")
from qiskit_ibm_runtime import Estimator, Session
#Initialize a QiskitRuntimeService object
service = QiskitRuntimeService()
#We will use the 127-qubit ibm_nazca backend
backend = service.get_backend('ibm_torino')
# create a Runtime session for efficient execution (optional)
session = Session(service=service, backend=backend)
# estimator = Estimator(backend=backend)
estimator = Estimator(session=session)
#Here we can get some status information about the backend
status = backend.status()
is_operational = status.operational
jobs_in_queue = status.pending_jobs
print('Operational?: {} \n Jobs in Queue: {}\n'.format(is_operational, jobs_in_queue))
# We can also obtain some configuration information
config = backend.configuration()
print(64*"#","\nConfiguration for: {}, version: {}".format(config.backend_name, config.backend_version))
print(" Number of Qubits: {}".format(config.n_qubits))
print(" Basis Gates: {}".format(config.basis_gates))
print(" OpenPulse Enabled: {}".format(config.open_pulse))
job = estimator.run(qc, observable)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Session ID: {job.session_id}")
print(f">>> Job Status: {job.status()}")
# Use a job id from a previous result
job = service.job("cnxwwhtmbjng0081zhxg")
print(f">>> Job Status: {job.status()}")
#Examine our results once the job has completed
result = job.result()
print(f">>> {result}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit.visualization import plot_histogram
import matplotlib.pyplot as plt
plt.style.use('dark_background')
data = {"Ideal": result_exact.values[0],"Result": result.values[0]}
plt.bar(range(len(data)), data.values(), align='center', color = "#7793f2")
plt.xticks(range(len(data)), list(data.keys()))
plt.show()
from qiskit_ibm_runtime import Options
# To set our resilience and optimization level we need to create this `Options` object
options = Options()
options.resilience_level = 2
options.optimization_level = 3
# We'll prepare the same example circuit as before
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
# we can also write "qc = QuantumCircuit(2,2)"
#Add the hadamard and CNOT gates to the circuit
qc.h(0)
qc.cx(0, 1)
# We'll also instantiate a new Runtime Estimator() object
# estimator = Estimator(options=options, backend=backend)
estimator = Estimator(options=options, session=session)
# and use the same observable as before
observable = SparsePauliOp(["II", "XX", "YY", "ZZ"], coeffs=[1, 1, -1, 1])
job = estimator.run(circuits=qc, observables=observable)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Session ID: {job.session_id}")
print(f">>> Job Status: {job.status()}")
# Use a job id from a previous result
job = service.job("cnxwx04ja3gg0085f6cg")
print(f">>> Job Status: {job.status()}")
#Examine our results once the job has completed
result_mitigated = job.result()
print(f">>> {result_mitigated}")
print(f" > Expectation value: {result_mitigated.values[0]}")
print(f" > Metadata: {result_mitigated.metadata[0]}")
from qiskit.visualization import plot_histogram
import matplotlib.pyplot as plt
plt.style.use('dark_background')
data = {"Ideal": result_exact.values[0],"Result": result.values[0],"Mitigated result": result_mitigated.values[0]}
plt.bar(range(len(data)), data.values(), align='center', color = "#7793f2")
plt.xticks(range(len(data)), list(data.keys()))
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(7)
qc.ccx(0, 1, 4)
qc.ccx(2, 3, 5)
qc.ccx(4, 5, 6)
qc.draw("mpl")
|
https://github.com/Chibikuri/qwopt
|
Chibikuri
|
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.3.1
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Optimization benchmarking
# Plotting benchmark result.
# +
import sys
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import copy
sys.path.append('../')
from qwopt.compiler import composer
from qwopt.benchmark import fidelity as fid
from numpy import pi
from qiskit import transpile
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit import Aer, execute
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import depolarizing_error
from tqdm import tqdm, trange
from mpl_toolkits.mplot3d import Axes3D
import warnings
warnings.simplefilter('ignore')
# -
# ## 1. Multi step of 4 node graph with one partition
# ## Target graph and probability transition matrix
# +
alpha = 0.85
target_graph = np.array([[0, 1, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 1],
[0, 0, 1, 0]])
E = np.array([[1/4, 1/2, 0, 1/2],
[1/4, 0, 1/2, 0],
[1/4, 1/2, 0, 1/2],
[1/4, 0, 1/2, 0]])
# use google matrix
prob_dist = alpha*E + ((1-alpha)/4)*np.ones((4, 4))
init_state = 1/2*np.array([np.sqrt(prob_dist[j][i]) for i in range(4) for j in range(4)])
# -
# ### Check points
# - How to decrease the fidelity over the number of steps
# - The number of operations
# ### Count operations
# #### Without any optimizations
# +
# Circuit
def four_node(opt, step):
rotation = np.radians(31.788)
cq = QuantumRegister(2, 'control')
tq = QuantumRegister(2, 'target')
c = ClassicalRegister(2, 'classical')
if opt:
anc = QuantumRegister(2, 'ancilla')
qc = QuantumCircuit(cq, tq, anc, c)
else:
qc = QuantumCircuit(cq, tq, c)
# initialize with probability distribution matrix
initial = 1/2*np.array([np.sqrt(prob_dist[j][i]) for i in range(4) for j in range(4)])
qc.initialize(initial, [*cq, *tq])
for t in range(step):
# Ti operation
qc.x(cq[1])
qc.ccx(cq[0], cq[1], tq[1])
qc.x(cq[1])
qc.barrier()
# Kdg operation
if opt:
qc.x(cq)
qc.rccx(cq[0], cq[1], anc[0])
qc.barrier()
qc.ch(anc[0], tq[0])
qc.ch(anc[0], tq[1])
qc.x(anc[0])
qc.cry(-rotation, anc[0], tq[1])
qc.ch(anc[0], tq[0])
qc.barrier()
else:
qc.x(cq)
qc.mcry(-pi/2, cq, tq[0], None)
qc.mcry(-pi/2, cq, tq[1], None)
qc.x(cq)
qc.barrier()
# qc.x(cq[1])
# qc.mcry(-pi/2, cq, tq[0], None)
# qc.mcry(-rotation, cq, tq[1], None)
# qc.x(cq[1])
# qc.barrier()
qc.x(cq[0])
qc.mcry(-pi/2, cq, tq[0], None)
qc.mcry(-rotation, cq, tq[1], None)
qc.x(cq[0])
qc.barrier()
qc.cry(-pi/2, cq[0], tq[0])
qc.cry(-rotation, cq[0], tq[1])
qc.barrier()
# qc.mcry(-pi/2, cq, tq[0], None)
# qc.mcry(-rotation, cq, tq[1], None)
# qc.barrier()
# D operation
qc.x(tq)
qc.cz(tq[0], tq[1])
qc.x(tq)
qc.barrier()
# K operation
if opt:
qc.ch(anc[0], tq[0])
qc.cry(rotation, anc[0], tq[1])
qc.x(anc[0])
qc.ch(anc[0], tq[1])
qc.ch(anc[0], tq[0])
qc.rccx(cq[0], cq[1], anc[0])
qc.x(cq)
qc.barrier()
else:
# previous, and naive imple
# qc.mcry(pi/2, cq, tq[0], None)
# qc.mcry(rotation, cq, tq[1], None)
# qc.barrier()
qc.cry(pi/2, cq[0], tq[0])
qc.cry(rotation, cq[0], tq[1])
qc.barrier()
qc.x(cq[0])
qc.mcry(pi/2, cq, tq[0], None)
qc.mcry(rotation, cq, tq[1], None)
qc.x(cq[0])
qc.barrier()
# qc.x(cq[1])
# qc.mcry(pi/2, cq, tq[0], None)
# qc.mcry(rotation, cq, tq[1], None)
# qc.x(cq[1])
# qc.barrier()
qc.x(cq)
qc.mcry(pi/2, cq, tq[0], None)
qc.mcry(pi/2, cq, tq[1], None)
qc.x(cq)
qc.barrier()
# Tidg operation
qc.x(cq[1])
qc.ccx(cq[0], cq[1], tq[1])
qc.x(cq[1])
qc.barrier()
# swap
qc.swap(tq[0], cq[0])
qc.swap(tq[1], cq[1])
qc.measure(tq, c)
return qc
# -
qc = four_node(True, 1)
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend=backend, shots=10000)
count = job.result().get_counts(qc)
print(count)
qc.draw(output='mpl')
# ### The number of operations in steps
# +
ex1_cx = []
ex1_u3 = []
ex2_cx = []
ex2_u3 = []
ex3_cx = []
ex3_u3 = []
ex4_cx = []
ex4_u3 = []
for step in trange(1, 11):
opt_qc = transpile(four_node(True, step), basis_gates=['cx', 'u3'], optimization_level=0)
ncx = opt_qc.count_ops().get('cx', 0)
nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0)
ex1_cx.append(ncx)
ex1_u3.append(nu3)
# ex2
opt_qc = transpile(four_node(True, step), basis_gates=['cx', 'u3'], optimization_level=3)
ncx = opt_qc.count_ops().get('cx', 0)
nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0)
ex2_cx.append(ncx)
ex2_u3.append(nu3)
# ex3
opt_qc = transpile(four_node(False, step), basis_gates=['cx', 'u3'], optimization_level=3)
ncx = opt_qc.count_ops().get('cx', 0)
nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0)
ex3_cx.append(ncx)
ex3_u3.append(nu3)
# ex4
nopt_qc = transpile(four_node(False, step), basis_gates=['cx', 'u3'], optimization_level=0)
ncx = nopt_qc.count_ops().get('cx', 0)
nu3 = nopt_qc.count_ops().get('u3', 0) + nopt_qc.count_ops().get('u2', 0) + nopt_qc.count_ops().get('u1', 0)
ex4_cx.append(ncx)
ex4_u3.append(nu3)
# -
cx = [ex1_cx, ex2_cx, ex3_cx, ex4_cx]
u3 = [ex1_u3, ex2_u3, ex3_u3, ex4_u3]
# color = ['#C23685', '#E38692', '#6BBED5', '#3EBA2B']
# labels = ['with my optimizations', 'with my and qiskit optimizations', 'with qiskit optimizations', 'without optimizations']
steps = range(1, 11)
fig = plt.figure(figsize=(20, 10))
ax = fig.add_subplot(111)
sns.set()
plt.xlabel('the number of steps', fontsize=30)
plt.xticks([i for i in range(11)])
plt.ylabel('the number of operations', fontsize=30)
plt.title('the nuber of operations over steps', fontsize=30)
plt.tick_params(labelsize=20)
plt.plot(steps, ex4_cx, color='#3EBA2B', label='# of CX without optimizations', linewidth=3)
plt.plot(steps, ex4_u3, color='#6BBED5', label='# of single qubit operations without optimizations', linewidth=3)
plt.legend(fontsize=25)
cx = [ex1_cx, ex2_cx, ex3_cx, ex4_cx]
u3 = [ex1_u3, ex2_u3, ex3_u3, ex4_u3]
color = ['#C23685', '#E38692', '#6BBED5', '#3EBA2B']
labels = ['with my optimizations', 'with my and qiskit optimizations', 'with qiskit optimizations', 'without optimizations']
steps = range(1, 11)
fig = plt.figure(figsize=(20, 10))
ax = fig.add_subplot(111)
sns.set()
plt.xlabel('the number of steps', fontsize=30)
plt.xticks([i for i in range(11)])
plt.ylabel('the number of cx', fontsize=30)
plt.title('the nuber of operations over steps', fontsize=30)
plt.tick_params(labelsize=20)
print(list(steps))
for cs, col, lab in zip(cx, color, labels):
plt.plot(steps, cs, color=col, label=lab, linewidth=3)
plt.legend(fontsize=25)
# ## Error rate transition
import warnings
warnings.simplefilter('ignore')
# +
qasm_sim = Aer.get_backend('qasm_simulator')
def KL_divergence(p, q, torelance=10e-9):
'''
p: np.array or list
q: np.array or list
'''
parray = np.array(p) + torelance
qarray = np.array(q) + torelance
divergence = np.sum(parray*np.log(parray/qarray))
return divergence
def get_error(qc, ideal, err_model, nq, type='KL', shots=10000):
bins = [format(i, '0%db'%nq) for i in range(2**nq)]
job = execute(qc, backend=qasm_sim, shots=shots, noise_model=err_model)
counts = job.result().get_counts(qc)
prob = np.array([counts.get(b, 0)/shots for b in bins])
id_prob = np.array(ideal)
# l2_error = np.sum([(i-j)**2 for i, j in zip(id_prob, prob)])
KL_error = KL_divergence(id_prob, prob)
return KL_error
def theoretical_prob(initial, step, ptran, nq):
Pi_op = Pi_operator(ptran)
swap = swap_operator(nq)
operator = (2*Pi_op) - np.identity(len(Pi_op))
Szegedy = np.dot(operator, swap)
Szegedy_n = copy.deepcopy(Szegedy)
if step == 0:
init_prob = np.array([abs(i)**2 for i in initial], dtype=np.float)
return init_prob
elif step == 1:
prob = np.array([abs(i)**2 for i in np.dot(Szegedy, initial)],
dtype=np.float)
return prob
else:
for n in range(step-1):
Szegedy_n = np.dot(Szegedy_n, Szegedy)
probs = np.array([abs(i)**2 for i in np.dot(Szegedy_n, initial)],
dtype=np.float)
return probs
def swap_operator(n_qubit):
q1 = QuantumRegister(n_qubit//2)
q2 = QuantumRegister(n_qubit//2)
qc = QuantumCircuit(q1, q2)
for c, t in zip(q1, q2):
qc.swap(c, t)
# FIXME
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend=backend)
swap = job.result().get_unitary(qc)
return swap
def Pi_operator(ptran):
'''
This is not a quantum operation,
just returning matrix
'''
lg = len(ptran)
psi_op = []
count = 0
for i in range(lg):
psi_vec = [0 for _ in range(lg**2)]
for j in range(lg):
psi_vec[count] = np.sqrt(ptran[j][i])
count += 1
psi_op.append(np.kron(np.array(psi_vec).T,
np.conjugate(psi_vec)).reshape((lg**2, lg**2)))
Pi = psi_op[0]
for i in psi_op[1:]:
Pi = np.add(Pi, i)
return Pi
# +
# circuit verifications
# for step in range(1, 11):
# opt_qc1 = transpile(four_node(True, step), basis_gates=['cx', 'u3'], optimization_level=0)
# opt_qc2 = transpile(four_node(True, step), basis_gates=['cx', 'u3'], optimization_level=3)
# opt_qc3 = transpile(four_node(False, step), basis_gates=['cx', 'u3'], optimization_level=3)
# nopt_qc = transpile(four_node(False, step), basis_gates=['cx', 'u3'], optimization_level=0)
# job1 = execute(opt_qc1, backend=qasm_sim, shots=10000)
# job2 = execute(opt_qc2, backend=qasm_sim, shots=10000)
# job3 = execute(opt_qc3, backend=qasm_sim, shots=10000)
# job4 = execute(nopt_qc, backend=qasm_sim, shots=10000)
# count1 = job1.result().get_counts()
# count2 = job2.result().get_counts()
# count3 = job3.result().get_counts()
# count4 = job4.result().get_counts()
# print(count1.get('00'), count2.get('00'), count3.get('00'), count4.get('00'))
# +
ex1_mean = []
ex1_std = []
ex2_mean = []
ex2_std = []
ex3_mean = []
ex3_std = []
ex4_mean = []
ex4_std = []
extime = 10
u3_error = depolarizing_error(0.001, 1)
qw_step = range(1, 11)
gate_error = np.arange(0, 0.03, 0.001)
# errors, steps= np.meshgrid(gate_error, qw_step)
bins = [format(i, '02b') for i in range(2**2)]
step = 5
opt_qc = four_node(True, step)
job = execute(opt_qc, backend=qasm_sim, shots=100000)
count = job.result().get_counts(opt_qc)
ideal_prob = [count.get(i, 0)/100000 for i in bins]
for cxerr in tqdm(gate_error):
# noise model
error_model = NoiseModel()
cx_error = depolarizing_error(cxerr, 2)
error_model.add_all_qubit_quantum_error(u3_error, ['u3', 'u2'])
error_model.add_all_qubit_quantum_error(cx_error, ['cx'])
# ex1
errors = []
for i in range(extime):
opt_qc = transpile(four_node(True, step), basis_gates=['cx', 'u3'], optimization_level=0)
error = get_error(opt_qc, ideal_prob, error_model, 2)
errors.append(error)
ex1_mean.append(np.mean(errors))
ex1_std.append(np.std(errors))
# ex2
errors = []
for i in range(extime):
opt_qc = transpile(four_node(True, step), basis_gates=['cx', 'u3'], optimization_level=3)
error = get_error(opt_qc, ideal_prob, error_model, 2)
errors.append(error)
ex2_mean.append(np.mean(errors))
ex2_std.append(np.std(errors))
# ex3
errors = []
for i in range(extime):
opt_qc = transpile(four_node(False, step), basis_gates=['cx', 'u3'], optimization_level=3)
error = get_error(opt_qc, ideal_prob, error_model, 2)
errors.append(error)
ex3_mean.append(np.mean(errors))
ex3_std.append(np.std(errors))
# ex4
errors=[]
for i in range(extime):
nopt_qc = transpile(four_node(False, step), basis_gates=['cx', 'u3'], optimization_level=0)
error = get_error(nopt_qc, ideal_prob, error_model, 2)
errors.append(error)
ex4_mean.append(np.mean(errors))
ex4_std.append(np.std(errors))
# +
fig = plt.figure(figsize=(20, 10))
# plt.errorbar(gate_error, ex1_mean, yerr=ex1_std, label='With my optimizations')
# # plt.errorbar(gate_error, ex2_mean, yerr=ex2_std, label='With my and qiskit optimizations')
# # plt.errorbar(gate_error, ex3_mean, yerr=ex3_std, label='With qiskit optimizations')
plt.errorbar(gate_error, ex4_mean, yerr=ex4_std, label='Without optimizations')
plt.title('error investigation of %dstep Quantum Walk'%step, fontsize=30)
plt.xlabel('cx error rate', fontsize=30)
plt.ylabel('KL divergence', fontsize=30)
plt.tick_params(labelsize=20)
plt.legend(fontsize=20)
plt.show()
# +
# ex1_mean = []
# ex1_std = []
# ex2_mean = []
# ex2_std = []
# ex3_mean = []
# ex3_std = []
# ex4_mean = []
# ex4_std = []
# extime = 10
# u3_error = depolarizing_error(0, 1)
# qw_step = range(1,6)
# gate_error = np.arange(0, 0.1, 0.01)
# errors, steps= np.meshgrid(gate_error, qw_step)
# bins = [format(i, '02b') for i in range(2**2)]
# for ce, st in tqdm(zip(errors, steps)):
# opt_qc = four_node(True, st[0])
# job = execute(opt_qc, backend=qasm_sim, shots=100000)
# count = job.result().get_counts(opt_qc)
# ideal_prob = [count.get(i, 0)/100000 for i in bins]
# for cxerr, step in zip(ce, st):
# # noise model
# error_model = NoiseModel()
# cx_error = depolarizing_error(cxerr, 2)
# error_model.add_all_qubit_quantum_error(u3_error, ['u3', 'u2'])
# error_model.add_all_qubit_quantum_error(cx_error, ['cx'])
# # ex1
# qcs1 = [four_node(True, step) for i in range(extime)]
# opt_qc1 = transpile(qcs1, basis_gates=['cx', 'u3'], optimization_level=0)
# errors = get_error(opt_qc1, ideal_prob, error_model, 2)
# ex1_mean.append(np.mean(errors))
# ex1_std.append(np.std(errors))
# # ex2
# qcs2 = [four_node(True, step) for i in range(extime)]
# opt_qc2 = transpile(qcs2, basis_gates=['cx', 'u3'], optimization_level=3)
# errors = get_error(opt_qc2, ideal_prob, error_model, 2)
# ex2_mean.append(np.mean(errors))
# ex2_std.append(np.std(errors))
# # ex3
# qcs3 = [four_node(False, step) for i in range(extime)]
# opt_qc3 = transpile(qcs3, basis_gates=['cx', 'u3'], optimization_level=3)
# errors = get_error(opt_qc, ideal_prob, error_model, 2)
# ex3_mean.append(np.mean(errors))
# ex3_std.append(np.std(errors))
# # ex4
# qcs4 = [four_node(False, step) for i in range(extime)]
# nopt_qc = transpile(qcs4, basis_gates=['cx', 'u3'], optimization_level=0)
# error = get_error(nopt_qc, ideal_prob, error_model, 2)
# ex4_mean.append(np.mean(errors))
# ex4_std.append(np.std(errors))
# -
# ### plot 3d
res1 = np.array(ex1_mean).reshape(10, 10)
res2 = np.array(ex2_mean).reshape(10, 10)
res3 = np.array(ex3_mean).reshape(10, 10)
res4 = np.array(ex4_mean).reshape(10, 10)
# +
# fig = plt.figure(figsize=(20, 10))
# ax = Axes3D(fig)
# ax.plot_wireframe(errors, steps, res1, color='#E6855E', linewidth=2, label='With my optimization')
# ax.plot_wireframe(errors, steps, res2, color='#F9DB57', linewidth=2, label='With my and qiskit optimizations')
# ax.plot_wireframe(errors, steps, res3, color='#3DB680', linewidth=2, label='With qiskit optimizations')
# ax.plot_wireframe(errors, steps, res4, color='#6A8CC7', linewidth=2, label='Without optimizations')
# ax.set_xlabel('Cx error rate', labelpad=30, fontsize=30)
# ax.set_ylabel('The number of steps', labelpad=30, fontsize=30)
# ax.set_zlabel('Error', labelpad=30, fontsize=30)
# plt.tick_params(labelsize=20)
# plt.legend(fontsize=20)
# plt.show()
# -
# ## 2. Multi step of 8 node graph with one partition
# ## Target graph and probability transition matrix
# +
# In this case, we're gonna investigate matrix that has just one partition
alpha = 0.85
target_graph = np.array([[0, 1, 0, 0, 0, 0, 0, 1],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 0, 0, 1, 0]])
E = np.array([[1/8, 1/2, 0, 0, 0, 0, 0, 1/2],
[1/8, 0, 1/2, 0, 0, 0, 0, 0],
[1/8, 1/2, 0, 1/2, 0, 0, 0, 0],
[1/8, 0, 1/2, 0, 1/2, 0, 0, 0],
[1/8, 0, 0, 1/2, 0, 1/2, 0, 0],
[1/8, 0, 0, 0, 1/2, 0, 1/2, 0],
[1/8, 0, 0, 0, 0, 1/2, 0, 1/2],
[1/8, 0, 0, 0, 0, 0, 1/2, 0]])
# use google matrix
lt = len(target_graph)
prob_dist = alpha*E + ((1-alpha)/lt)*np.ones((lt, lt))
init_state_eight = 1/np.sqrt(8)*np.array([np.sqrt(prob_dist[j][i]) for i in range(lt) for j in range(lt)])
# +
# Circuit
def eight_node(opt, step, initial, hardopt=False):
rotation1 = np.radians(31.788)
rotation2 = np.radians(90)
rotation3 = np.radians(23.232)
cq = QuantumRegister(3, 'control')
tq = QuantumRegister(3, 'target')
# ancilla for mct gates
anc = QuantumRegister(3, 'mct anc')
c = ClassicalRegister(3, 'classical')
if opt:
opt_anc = QuantumRegister(2, 'ancilla')
qc = QuantumCircuit(cq, tq, anc, opt_anc, c)
else:
qc = QuantumCircuit(cq, tq, anc, c)
# initialize with probability distribution matrix
if initial is not None:
qc.initialize(initial, [*cq, *tq])
for t in range(step):
# Ti operation
# T1
qc.x(cq[0])
qc.x(cq[2])
qc.mct(cq, tq[2], anc)
qc.x(cq[0])
qc.x(cq[2])
qc.barrier()
# T2
qc.x(cq[0])
qc.mct(cq, tq[1], anc)
qc.x(cq[0])
qc.barrier()
# T3
qc.x(cq[1:])
qc.mct(cq, tq[1], anc)
qc.mct(cq, tq[2], anc)
qc.x(cq[1:])
qc.barrier()
# T4
qc.x(cq[1])
qc.mct(cq, tq[0], anc)
qc.x(cq[1])
qc.barrier()
# T5
qc.x(cq[2])
qc.mct(cq, tq[0], anc)
qc.mct(cq, tq[2], anc)
qc.x(cq[2])
qc.barrier()
# T6
qc.x(tq[2])
qc.mct([*cq, *tq[1:]], tq[0], anc)
qc.x(tq[2])
qc.barrier()
# # Kdg operation
if opt:
qc.x(cq[:])
# qc.rcccx(cq[0], cq[1], cq[2], opt_anc[0])
qc.mct(cq, opt_anc[0], anc)
qc.x(cq[:])
for ryq in tq:
qc.cry(-pi/2, opt_anc[0], ryq)
if hardopt:
raise Exception('under_construction')
else:
qc.x(opt_anc[0])
qc.x(tq[0])
qc.mcry(-rotation3, [opt_anc[0], tq[0]], tq[2], anc)
qc.x(tq[0])
qc.mcry(3/2*pi, [opt_anc[0], tq[0]], tq[1], anc)
qc.mcry(3/2*pi, [opt_anc[0], tq[0]], tq[2], anc)
qc.x(tq[0])
qc.mcry(-rotation2, [opt_anc[0], tq[0]], tq[1], anc)
qc.x(tq[0])
qc.cry(-rotation1, opt_anc[0], tq[0])
qc.x(opt_anc[0])
else:
qc.x(cq[:])
for ryq in tq:
qc.mcry(-pi/2, cq, ryq, anc)
qc.barrier()
qc.x(cq[:])
for i in range(1, 8):
bins = list(format(i, '03b'))
for ib, b in enumerate(bins):
if b == '0':
qc.x(cq[ib])
qc.x(tq[0])
qc.mcry(-rotation3, [*cq, tq[0]], tq[2], anc)
qc.x(tq[0])
qc.mcry(3/2*pi, [*cq, tq[0]], tq[1], anc)
qc.mcry(3/2*pi, [*cq, tq[0]], tq[2], anc)
qc.x(tq[0])
qc.mcry(-rotation2, [*cq, tq[0]], tq[1], anc)
qc.x(tq[0])
qc.mcry(-rotation1, cq, tq[0], anc)
for ib, b in enumerate(bins):
if b == '0':
qc.x(cq[ib])
# D operation
qc.x(tq)
qc.h(tq[2])
qc.ccx(tq[0], tq[1], tq[2])
qc.h(tq[2])
qc.x(tq)
qc.barrier()
# # K operation
if opt:
if hardopt:
raise Exception('under...')
else:
qc.x(opt_anc[0])
qc.cry(rotation1, opt_anc[0], tq[0])
qc.x(tq[0])
qc.mcry(rotation2, [opt_anc[0], tq[0]], tq[1], anc)
qc.x(tq[0])
qc.mcry(3/2*pi, [opt_anc[0], tq[0]], tq[1], anc)
qc.mcry(3/2*pi, [opt_anc[0], tq[0]], tq[2], anc)
qc.x(tq[0])
qc.mcry(rotation3, [opt_anc[0], tq[0]], tq[2], anc)
qc.x(tq[0])
qc.x(opt_anc[0])
for anq in tq:
qc.cry(pi/2, opt_anc[0], anq)
qc.barrier()
qc.x(cq[:])
qc.mct(cq, opt_anc[0], anc)
qc.x(cq[:])
else:
for i in range(1, 8):
bins = list(format(i, '03b'))
for ib, b in enumerate(bins):
if b == '0':
qc.x(cq[ib])
qc.mcry(rotation1, cq, tq[0], anc)
qc.x(tq[0])
qc.mcry(rotation2, [*cq, tq[0]], tq[1], anc)
qc.x(tq[0])
qc.mcry(3/2*pi, [*cq, tq[0]], tq[2], anc)
qc.mcry(3/2*pi, [*cq, tq[0]], tq[1], anc)
qc.x(tq[0])
qc.mcry(rotation3, [*cq, tq[0]], tq[2], anc)
qc.x(tq[0])
for ib, b in enumerate(bins):
if b == '0':
qc.x(cq[ib])
qc.x(cq[:])
for anq in tq:
qc.mcry(pi/2, cq, anq, anc)
qc.x(cq[:])
# # Tidg operation
# T6
qc.x(tq[2])
qc.mct([*cq, *tq[1:]], tq[0], anc)
qc.x(tq[2])
qc.barrier()
# T5
qc.x(cq[2])
qc.mct(cq, tq[0], anc)
qc.mct(cq, tq[2], anc)
qc.x(cq[2])
qc.barrier()
# T4
qc.x(cq[1])
qc.mct(cq, tq[0], anc)
qc.x(cq[1])
qc.barrier()
# T3
qc.x(cq[1:])
qc.mct(cq, tq[1], anc)
qc.mct(cq, tq[2], anc)
qc.x(cq[1:])
qc.barrier()
# T2
qc.x(cq[0])
qc.mct(cq, tq[1], anc)
qc.x(cq[0])
qc.barrier()
# T1
qc.x(cq[0])
qc.x(cq[2])
qc.mct(cq, tq[2], anc)
qc.x(cq[0])
qc.x(cq[2])
qc.barrier()
# swap
for cont, targ in zip(cq, tq):
qc.swap(cont, targ)
qc.measure(cq, c)
return qc
# -
# circuit verifications
qasm_sim = Aer.get_backend("qasm_simulator")
for step in range(1, 11):
opt_qc1 = transpile(eight_node(True, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=0)
opt_qc2 = transpile(eight_node(True, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=3)
opt_qc3 = transpile(eight_node(False, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=3)
nopt_qc = transpile(eight_node(False, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=0)
job1 = execute(opt_qc1, backend=qasm_sim, shots=10000)
job2 = execute(opt_qc2, backend=qasm_sim, shots=10000)
job3 = execute(opt_qc3, backend=qasm_sim, shots=10000)
job4 = execute(nopt_qc, backend=qasm_sim, shots=10000)
count1 = job1.result().get_counts()
count2 = job2.result().get_counts()
count3 = job3.result().get_counts()
count4 = job4.result().get_counts()
print(count1.get('000'), count2.get('000'), count3.get('000'), count4.get('000'))
# +
ex1_cx = []
ex1_u3 = []
ex2_cx = []
ex2_u3 = []
ex3_cx = []
ex3_u3 = []
ex4_cx = []
ex4_u3 = []
for step in trange(1, 11):
opt_qc = transpile(eight_node(True, step, None), basis_gates=['cx', 'u3'], optimization_level=0)
ncx = opt_qc.count_ops().get('cx', 0)
nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0)
ex1_cx.append(ncx)
ex1_u3.append(nu3)
# ex2
opt_qc = transpile(eight_node(True, step, None), basis_gates=['cx', 'u3'], optimization_level=3)
ncx = opt_qc.count_ops().get('cx', 0)
nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0)
ex2_cx.append(ncx)
ex2_u3.append(nu3)
# ex3
opt_qc = transpile(eight_node(False, step, None), basis_gates=['cx', 'u3'], optimization_level=3)
ncx = opt_qc.count_ops().get('cx', 0)
nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0)
ex3_cx.append(ncx)
ex3_u3.append(nu3)
# ex4
nopt_qc = transpile(eight_node(False, step, None), basis_gates=['cx', 'u3'], optimization_level=0)
ncx = nopt_qc.count_ops().get('cx', 0)
nu3 = nopt_qc.count_ops().get('u3', 0) + nopt_qc.count_ops().get('u2', 0) + nopt_qc.count_ops().get('u1', 0)
ex4_cx.append(ncx)
ex4_u3.append(nu3)
# -
steps = range(1, 11)
fig = plt.figure(figsize=(20, 10))
ax = fig.add_subplot(111)
sns.set()
plt.xlabel('the number of steps', fontsize=30)
plt.ylabel('the number of cx', fontsize=30)
plt.title('the nuber of operations over steps', fontsize=30)
plt.tick_params(labelsize=20)
plt.xticks([i for i in range(11)])
# for cs, col, lab in zip(cx, color, labels):
plt.plot(steps, ex4_cx, color= '#3EBA2B', label= '# of CX without optimizations', linewidth=3)
plt.plot(steps, ex4_u3, color= '#6BBED5', label= '# of single qubit operations without optimizations', linewidth=3)
plt.legend(fontsize=25)
cx = [ex1_cx, ex2_cx, ex3_cx, ex4_cx]
u3 = [ex1_u3, ex2_u3, ex3_u3, ex4_u3]
color = ['#C23685', '#E38692', '#6BBED5', '#3EBA2B']
labels = ['with my optimizations', 'with my and qiskit optimizations', 'with qiskit optimizations', 'without optimizations']
steps = range(1, 11)
fig = plt.figure(figsize=(20, 10))
ax = fig.add_subplot(111)
sns.set()
plt.xlabel('the number of steps', fontsize=30)
plt.ylabel('the number of cx', fontsize=30)
plt.title('the nuber of operations over steps', fontsize=30)
plt.tick_params(labelsize=20)
for cs, col, lab in zip(cx, color, labels):
plt.plot(steps, cs, color=col, label=lab, linewidth=3)
plt.legend(fontsize=25)
# +
ex1_mean = []
ex1_std = []
ex2_mean = []
ex2_std = []
ex3_mean = []
ex3_std = []
ex4_mean = []
ex4_std = []
extime = 100
u3_error = depolarizing_error(0, 1)
qw_step = range(1, 11)
gate_error = np.arange(0, 0.03, 0.001)
# errors, steps= np.meshgrid(gate_error, qw_step)
bins = [format(i, '03b') for i in range(2**3)]
step = 3
opt_qc = eight_node(True, step, init_state_eight)
job = execute(opt_qc, backend=qasm_sim, shots=100000)
count = job.result().get_counts(opt_qc)
ideal_prob = [count.get(i, 0)/100000 for i in bins]
for cxerr in tqdm(gate_error, desc="error"):
# noise model
error_model = NoiseModel()
cx_error = depolarizing_error(cxerr, 2)
error_model.add_all_qubit_quantum_error(u3_error, ['u3', 'u2'])
error_model.add_all_qubit_quantum_error(cx_error, ['cx'])
# ex1
# opt_qc = [transpile(eight_node(True, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=0) for i in range(extime)]
# errors = []
# for eqc in opt_qc:
# errors.append(get_error(eqc, ideal_prob, error_model, 3))
# ex1_mean.append(np.mean(errors))
# ex1_std.append(np.std(errors))
# # ex2
# errors = []
# opt_qc = [transpile(eight_node(True, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=3) for i in range(extime)]
# for eqc in opt_qc:
# errors.append(get_error(eqc, ideal_prob, error_model, 3))
# ex2_mean.append(np.mean(errors))
# ex2_std.append(np.std(errors))
# # ex3
# errors = []
# opt_qc = [transpile(eight_node(False, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=3)for i in range(extime)]
# for eqc in opt_qc:
# errors.append(get_error(eqc, ideal_prob, error_model, 3))
# ex3_mean.append(np.mean(errors))
# ex3_std.append(np.std(errors))
# ex4
errors = []
nopt_qc = [transpile(eight_node(False, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=0) for i in range(extime)]
for eqc in nopt_qc:
errors.append(get_error(eqc, ideal_prob, error_model, 3))
ex4_mean.append(np.mean(errors))
ex4_std.append(np.std(errors))
# -
fig = plt.figure(figsize=(20, 10))
sns.set()
# plt.errorbar(gate_error, ex1_mean, yerr=ex1_std, label='With my optimizations')
# # plt.errorbar(gate_error, ex2_mean, yerr=ex2_std, label='With my and qiskit optimizations')
# # plt.errorbar(gate_error, ex3_mean, yerr=ex3_std, label='With qiskit optimizations')
plt.errorbar(gate_error, ex4_mean, yerr=ex4_std, label='Without optimizations')
plt.title('error investigation of %dstep Quantum Walk'%step, fontsize=30)
plt.xlabel('cx error rate', fontsize=30)
plt.ylabel('KL divergence', fontsize=30)
plt.tick_params(labelsize=20)
plt.legend(fontsize=20)
plt.show()
# +
# 1step
fig = plt.figure(figsize=(20, 10))
plt.plot(gate_error, ex1_mean, label='ex1')
plt.plot(gate_error, ex2_mean, label='ex2')
plt.plot(gate_error, ex3_mean, label='ex3')
plt.plot(gate_error, ex4_mean, label='ex4')
plt.tick_params(labelsize=20)
plt.legend(fontsize=20)
plt.show()
# +
# res1 = np.array(ex1_mean).reshape(10, 10)
# res2 = np.array(ex2_mean).reshape(10, 10)
# res3 = np.array(ex3_mean).reshape(10, 10)
# res4 = np.array(ex4_mean).reshape(10, 10)
# +
# fig = plt.figure(figsize=(20, 10))
# ax = Axes3D(fig)
# ax.plot_wireframe(errors, steps, res1, color='#E6855E', linewidth=2, label='With my optimization')
# ax.plot_wireframe(errors, steps, res2, color='#F9DB57', linewidth=2, label='With my and qiskit optimizations')
# ax.plot_wireframe(errors, steps, res3, color='#3DB680', linewidth=2, label='With qiskit optimizations')
# ax.plot_wireframe(errors, steps, res4, color='#6A8CC7', linewidth=2, label='Without optimizations')
# ax.set_xlabel('Cx error rate', labelpad=30, fontsize=30)
# ax.set_ylabel('The number of steps', labelpad=30, fontsize=30)
# ax.set_zlabel('Error', labelpad=30, fontsize=30)
# plt.tick_params(labelsize=20)
# plt.legend(fontsize=20)
# plt.show()
# -
# ## 3. Multi step of 8 node graph with multi partition
# + code_folding=[]
alpha = 0.85
target_graph = np.array([[0, 0, 0, 1, 1, 0, 0, 0],
[1, 0, 0, 0, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 0, 1, 1]])
E = np.array([[0, 0, 0, 1, 1/2, 0, 0, 0],
[1, 0, 0, 0, 1/2, 0, 0, 0],
[0, 1, 0, 0, 0, 1/2, 0, 0],
[0, 0, 1, 0, 0, 1/2, 0, 0],
[0, 0, 0, 0, 0, 0, 1/4, 1/4],
[0, 0, 0, 0, 0, 0, 1/4, 1/4],
[0, 0, 0, 0, 0, 0, 1/4, 1/4],
[0, 0, 0, 0, 0, 0, 1/4, 1/4]])
# use google matrix
prob_dist = alpha*E + ((1-alpha)/8)*np.ones((8, 8))
init_state_eight = 1/np.sqrt(8)*np.array([np.sqrt(prob_dist[j][i]) for i in range(8) for j in range(8)])
# -
def mch(qc, controls, target, anc, tganc):
# multi control hadamard gate
if len(controls) == 1:
qc.ch(*controls, target)
elif len(controls) == 2:
qc.ccx(controls[0], controls[1], tganc[0])
qc.ch(tganc[0], target)
qc.ccx(controls[0], controls[1], tganc[0])
elif len(controls) > 2:
qc.mct(controls, tganc[0], anc)
for tg in target:
qc.ch(tganc[0], tg)
qc.mct(controls, tganc[0], anc)
return qc
qasm_sim = Aer.get_backend("qasm_simulator")
q = QuantumRegister(6)
anc = QuantumRegister(3)
tganc = QuantumRegister(1)
c = ClassicalRegister(10)
qc = QuantumCircuit(q, anc, tganc, c)
mch(qc, [q[0], q[3]], [q[4], q[5]], anc, tganc)
qc.barrier()
qc.draw(output='mpl')
qc.measure(q, c[:6])
qc.measure(anc, c[6:9])
qc.measure(tganc, c[9])
job = execute(qc, backend=qasm_sim, shots=1024)
count = job.result().get_counts(qc)
print(count)
qc.draw(output='mpl')
# +
# Circuit
def eight_node_multi(opt, step, initial, hardopt=False):
rotation11 = np.radians(31.788)
rotation12 = np.radians(23.231)
rotation13 = np.radians(163.285)
rotation21 = np.radians(31.788)
rotation22 = np.radians(23.231)
rotation31 = np.radians(148.212)
# for multi qubit hadamrd gate
hs = QuantumCircuit.ch
cq = QuantumRegister(3, 'control')
tq = QuantumRegister(3, 'target')
# ancilla for mct gates
anc = QuantumRegister(3, 'mct anc')
tganc = QuantumRegister(1, 'tgancila')
c = ClassicalRegister(3, 'classical')
if opt:
opt_anc = QuantumRegister(2, 'ancilla')
qc = QuantumCircuit(cq, tq, anc, opt_anc, tganc, c)
else:
qc = QuantumCircuit(cq, tq, anc,tganc, c)
# initialize with probability distribution matrix
if initial is not None:
qc.initialize(initial, [*cq, *tq])
for t in range(step):
# Ti operation(opt)
# T11
qc.x(cq[1])
qc.ccx(cq[1], cq[2], tq[1])
qc.x(cq[1])
qc.barrier()
# T12
qc.x(cq[0])
qc.x(cq[2])
qc.mct(cq, tq[1], anc)
qc.x(cq[0])
qc.x(cq[2])
qc.barrier()
# T21
qc.x(cq[0])
qc.ccx(cq[0], cq[2], tq[2])
qc.x(cq[0])
qc.barrier()
# # Kdg operation
if opt:
if hardopt:
raise Exception('under const')
else:
# K1dg
qc.x(cq[0]) # s1
qc.x(tq[0]) # s2
mch(qc, [cq[0], tq[0], tq[1]], [tq[2]], anc, tganc)
qc.x(tq[1]) # s3
qc.mcry(-rotation13, [cq[0], tq[0], tq[1]], tq[2], anc)
qc.x(tq[1]) # e3
qc.x(tq[0]) # e2
mch(qc, [cq[0], tq[0]], [tq[1], tq[2]], anc, tganc)
qc.x(tq[0]) # s4
qc.mcry(-rotation12, [cq[0], tq[0]], tq[1], anc)
qc.x(tq[0]) # e4
qc.cry(-rotation11, cq[0], tq[0])
qc.x(cq[0]) # e1
qc.barrier
# K2dg
# map
qc.x(cq[1])
qc.ccx(cq[1], cq[0], opt_anc[0])
qc.x(cq[1])
# op
qc.ch(opt_anc[0], tq[2])
mch(qc, [opt_anc[0], tq[0]], tq[1], anc, tganc)
qc.x(tq[0])# s1
qc.mcry(-rotation22, [opt_anc[0], tq[0]], tq[1], anc)
qc.x(tq[0]) # e1
qc.cry(-rotation21, opt_anc[0], tq[0])
qc.barrier
# K3dg
#map
qc.ccx(cq[1], cq[0], opt_anc[1])
# op
qc.ch(opt_anc[1], tq[2])
qc.ch(opt_anc[1], tq[1])
qc.cry(-rotation31, opt_anc[1], tq[0])
qc.barrier
else:
# K1dg
qc.x(cq[0]) # s1
qc.x(tq[0]) # s2
mch(qc, [cq[0], tq[0], tq[1]], [tq[2]], anc, tganc)
qc.x(tq[1]) # s3
qc.mcry(-rotation13, [cq[0], tq[0], tq[1]], tq[2], anc) # rotation 3 dg
qc.x(tq[1]) # e3
qc.x(tq[0]) # e2
mch(qc, [cq[0], tq[0]], [tq[1], tq[2]], anc, tganc)
qc.x(tq[0]) # s4
qc.mcry(-rotation12, [cq[0], tq[0]], tq[1], anc)
qc.x(tq[0]) # e4
qc.cry(-rotation11, cq[0], tq[0])
qc.x(cq[0]) # e1
# K2dg
qc.x(cq[1]) # s1
qc.x(tq[0]) # s2
mch(qc, [cq[0], cq[1], tq[0]], [tq[2]], anc, tganc)
qc.x(tq[0]) # e2
mch(qc, [cq[0], cq[1], tq[0]], [tq[1], tq[2]], anc, tganc)
qc.x(tq[0]) # s3
qc.mcry(-rotation22, [cq[0], cq[1], tq[0]], tq[1], anc)
qc.x(tq[0]) # e3
qc.mcry(-rotation21, [cq[0], cq[1]], tq[0], anc)
qc.x(cq[1])
# K3dg
mch(qc, [cq[0], cq[1]], [tq[1], tq[2]], anc, tganc)
qc.mcry(-rotation31, [cq[0], cq[1]], tq[0], anc)
# D operation
qc.x(tq)
qc.h(tq[2])
qc.ccx(tq[0], tq[1], tq[2])
qc.h(tq[2])
qc.x(tq)
qc.barrier()
# # K operation
if opt:
if hardopt:
raise Exception('under')
else:
# K3
qc.cry(rotation31, opt_anc[1], tq[0])
qc.ch(opt_anc[1], tq[1])
qc.ch(opt_anc[1], tq[2])
#unmap
qc.ccx(cq[1], cq[0], opt_anc[1])
qc.barrier()
# K2
qc.cry(rotation21, opt_anc[0], tq[0])
qc.x(tq[0]) # s1
qc.mcry(rotation22, [opt_anc[0], tq[0]], tq[1], anc)
qc.x(tq[0])
mch(qc, [opt_anc[0], tq[0]], tq[1], anc, tganc)
qc.ch(opt_anc[0], tq[2])
# unmap
qc.x(cq[1])
qc.ccx(cq[1], cq[0], opt_anc[0])
qc.x(cq[1])
# op
qc.barrier
# K1
qc.x(cq[0]) # s1
qc.cry(rotation11, cq[0], tq[0])
qc.x(tq[0]) # s2
qc.mcry(rotation12, [cq[0], tq[0]], tq[1], anc)
qc.x(tq[0]) # e2
mch(qc, [cq[0], tq[0]], [tq[1], tq[2]], anc, tganc)
qc.x(tq[0]) #s3
qc.x(tq[1]) # s4
qc.mcry(rotation13, [cq[0], tq[0], tq[1]], tq[2], anc)
qc.x(tq[1]) # 4
mch(qc, [cq[0], tq[0], tq[1]], [tq[2]], anc, tganc)
qc.x(tq[0]) # e3
qc.x(cq[0]) # e1
qc.barrier
else:
# K3
qc.mcry(rotation31, [cq[0], cq[1]], tq[0], anc)
mch(qc, [cq[0], cq[1]], [tq[1], tq[2]], anc, tganc)
# K2
qc.x(cq[1])
qc.mcry(rotation21, [cq[0], cq[1]], tq[0], anc)
qc.x(tq[0]) # e3
qc.mcry(rotation22, [cq[0], cq[1], tq[0]], tq[1], anc)
qc.x(tq[0]) # s3
mch(qc, [cq[0], cq[1], tq[0]], [tq[1], tq[2]], anc, tganc)
qc.x(tq[0]) # e2
mch(qc, [cq[0], cq[1], tq[0]], [tq[2]], anc, tganc)
qc.x(tq[0]) # s2
qc.x(cq[0])
qc.x(cq[1]) # s1
# K1
qc.cry(rotation11, cq[0], tq[0])
qc.x(tq[0]) # e4
qc.mcry(rotation12, [cq[0], tq[0]], tq[1], anc)
qc.x(tq[0]) # s4
mch(qc, [cq[0], tq[0]], [tq[1], tq[2]], anc, tganc)
qc.x(tq[0]) # e2
qc.x(tq[1]) # e3
qc.mcry(rotation13, [cq[0], tq[0], tq[1]], tq[2], anc) # rotation 3 dg
qc.x(tq[1]) # s3
mch(qc, [cq[0], tq[0], tq[1]], [tq[2]], anc, tganc)
qc.x(tq[0]) # s2
qc.x(cq[0]) # s1
# T21 dg
qc.x(cq[0])
qc.ccx(cq[0], cq[2], tq[2])
qc.x(cq[0])
qc.barrier()
# T12dg
qc.x(cq[0])
qc.x(cq[2])
qc.mct(cq, tq[1], anc)
qc.x(cq[0])
qc.x(cq[2])
qc.barrier()
# T11 dg
qc.x(cq[1])
qc.ccx(cq[0], cq[1], tq[1])
qc.x(cq[1])
# swap
for cont, targ in zip(cq, tq):
qc.swap(cont, targ)
qc.measure(cq, c)
return qc
# -
qc = eight_node_multi(True, 1, None)
qc.draw(output='mpl')
# circuit verifications
qasm_sim = Aer.get_backend('qasm_simulator')
init_state = [np.sqrt(1/64) for i in range(64)]
for step in range(1, 11):
opt_qc1 = transpile(eight_node_multi(True, step, init_state), basis_gates=['cx', 'u3'], optimization_level=0)
opt_qc2 = transpile(eight_node_multi(True, step, init_state), basis_gates=['cx', 'u3'], optimization_level=3)
opt_qc3 = transpile(eight_node_multi(False, step, init_state), basis_gates=['cx', 'u3'], optimization_level=3)
nopt_qc = transpile(eight_node_multi(False, step, init_state), basis_gates=['cx', 'u3'], optimization_level=0)
job1 = execute(opt_qc1, backend=qasm_sim, shots=10000)
job2 = execute(opt_qc2, backend=qasm_sim, shots=10000)
job3 = execute(opt_qc3, backend=qasm_sim, shots=10000)
job4 = execute(nopt_qc, backend=qasm_sim, shots=10000)
count1 = job1.result().get_counts()
count2 = job2.result().get_counts()
count3 = job3.result().get_counts()
count4 = job4.result().get_counts()
print(count1.get('000'), count2.get('000'), count3.get('000'), count4.get('000'))
# +
ex1_cx = []
ex1_u3 = []
ex2_cx = []
ex2_u3 = []
ex3_cx = []
ex3_u3 = []
ex4_cx = []
ex4_u3 = []
for step in trange(1, 11):
opt_qc = transpile(eight_node_multi(True, step, None), basis_gates=['cx', 'u3'], optimization_level=0)
ncx = opt_qc.count_ops().get('cx', 0)
nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0)
ex1_cx.append(ncx)
ex1_u3.append(nu3)
# ex2
opt_qc = transpile(eight_node_multi(True, step, None), basis_gates=['cx', 'u3'], optimization_level=3)
ncx = opt_qc.count_ops().get('cx', 0)
nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0)
ex2_cx.append(ncx)
ex2_u3.append(nu3)
# ex3
opt_qc = transpile(eight_node_multi(False, step, None), basis_gates=['cx', 'u3'], optimization_level=3)
ncx = opt_qc.count_ops().get('cx', 0)
nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0)
ex3_cx.append(ncx)
ex3_u3.append(nu3)
# ex4
nopt_qc = transpile(eight_node_multi(False, step, None), basis_gates=['cx', 'u3'], optimization_level=0)
ncx = nopt_qc.count_ops().get('cx', 0)
nu3 = nopt_qc.count_ops().get('u3', 0) + nopt_qc.count_ops().get('u2', 0) + nopt_qc.count_ops().get('u1', 0)
ex4_cx.append(ncx)
ex4_u3.append(nu3)
# -
qc = eight_node_multi(False, 1, None)
print(qc.depth())
qc = eight_node_multi(False, 2, None)
print(qc.depth())
cx = [ex1_cx, ex4_cx]
u3 = [ex1_u3, ex4_u3]
color = ['#C23685', '#6BBED5', '#3EBA2B']
labels = ['with my optimizations', 'related works[6]']
steps = range(1, 11)
fig = plt.figure(figsize=(20, 10))
ax = fig.add_subplot(111)
sns.set()
plt.xlabel('the number of steps', fontsize=30)
plt.yticks(range(0, 9000, 500))
plt.xticks(range(0, 11, 1))
plt.ylabel('the number of cx', fontsize=30)
plt.title('the nuber of operations over steps', fontsize=30)
plt.tick_params(labelsize=20)
plt.plot(steps, ex4_cx, color= '#3EBA2B', label="# of CX paper circuit", linewidth=3)
plt.plot(steps, ex4_u3, color= '#6BBED5', label="# of single qubit gates of paper circuit", linewidth=3)
plt.legend(fontsize=25)
cx = [ex1_cx, ex4_cx]
u3 = [ex1_u3, ex4_u3]
color = ['#C23685', '#6BBED5', '#3EBA2B']
labels = ['with my optimizations', 'related works[6]']
steps = range(1, 11)
fig = plt.figure(figsize=(20, 10))
ax = fig.add_subplot(111)
sns.set()
plt.xlabel('the number of steps', fontsize=30)
plt.yticks(range(0, 4600, 200))
plt.xticks(range(0, 11, 1))
plt.ylabel('the number of cx', fontsize=30)
plt.title('the nuber of operations over steps', fontsize=30)
plt.tick_params(labelsize=20)
for cs, col, lab in zip(cx, color, labels):
plt.plot(steps, cs, color=col, label=lab, linewidth=3)
plt.legend(fontsize=25)
# +
ex1_mean = []
ex1_std = []
ex4_mean = []
ex4_std = []
extime = 10
u3_error = depolarizing_error(0, 1)
gate_error = np.arange(0, 0.03, 0.001)
# errors, steps= np.meshgrid(gate_error, qw_step)
bins = [format(i, '03b') for i in range(2**3)]
step = 5
opt_qc = eight_node_multi(False, step, init_state_eight)
job = execute(opt_qc, backend=qasm_sim, shots=100000)
count = job.result().get_counts(opt_qc)
ideal_prob = [count.get(i, 0)/100000 for i in bins]
for cxerr in tqdm(gate_error):
# noise model
error_model = NoiseModel()
cx_error = depolarizing_error(cxerr, 2)
error_model.add_all_qubit_quantum_error(u3_error, ['u3', 'u2'])
error_model.add_all_qubit_quantum_error(cx_error, ['cx'])
# ex1
opt_qc = transpile(eight_node_multi(True, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=0)
errors = []
for i in range(extime):
error = get_error(opt_qc, ideal_prob, error_model, 3)
errors.append(error)
ex1_mean.append(np.mean(errors))
ex1_std.append(np.std(errors))
# ex4
nopt_qc = transpile(eight_node_multi(False, step, init_state_eight), basis_gates=['cx', 'u3'], optimization_level=0)
for i in range(extime):
error = get_error(nopt_qc, ideal_prob, error_model, 3)
errors.append(error)
ex4_mean.append(np.mean(errors))
ex4_std.append(np.std(errors))
# -
fig = plt.figure(figsize=(20, 10))
sns.set()
# plt.errorbar(gate_error, ex1_mean, yerr=ex1_std, label='With my optimizations')
plt.errorbar(gate_error, ex4_mean, yerr=ex4_std, label='Without optimizations')
plt.title('error investigation of %dstep Quantum Walk'%step, fontsize=30)
plt.xlabel('cx error rate', fontsize=30)
plt.ylabel('KL divergence', fontsize=30)
plt.tick_params(labelsize=20)
plt.legend(fontsize=20)
plt.show()
# Play ground
q = QuantumRegister(1)
qc = QuantumCircuit(q)
rotation12 = np.radians(23.231)
qc.u3(pi/2+rotation12, 0, pi, q[0])
unit = Aer.get_backend('unitary_simulator')
job = execute(qc, backend=unit)
uni = job.result().get_unitary()
print(uni)
q = QuantumRegister(1)
qc = QuantumCircuit(q)
rotation12 = np.radians(23.231)
qc.u3(pi/2, 0, pi, q[0])
qc.ry(rotation12, q[0])
unit = Aer.get_backend('unitary_simulator')
job = execute(qc, backend=unit)
uni = job.result().get_unitary()
print(uni)
q = QuantumRegister(3,'qr')
anc = QuantumRegister(2, 'anc')
qc = QuantumCircuit(q, anc)
qc.mcmt([q[0], q[1]], anc, QuantumCircuit.ch, [q[2]])
qc.draw(output='mpl')
q = QuantumRegister(6)
qc = QuantumCircuit(q)
qc.initialize(init_state, q)
nqc = transpile(qc, basis_gates=['cx', 'h', 'x', 'u3'])
nqc.draw(output='mpl')
# ## 4. Multi step of 512 node graph with multi partition
|
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.
"""NumTensorFactors pass testing"""
import unittest
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.passes import NumTensorFactors
from qiskit.test import QiskitTestCase
class TestNumTensorsFactorPass(QiskitTestCase):
"""Tests for NumTensorFactors analysis methods."""
def test_empty_dag(self):
"""Empty DAG has 0 number of tensor factors."""
circuit = QuantumCircuit()
dag = circuit_to_dag(circuit)
pass_ = NumTensorFactors()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["num_tensor_factors"], 0)
def test_just_qubits(self):
"""A dag with 8 operations and 1 tensor factor."""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[1], qr[0])
dag = circuit_to_dag(circuit)
pass_ = NumTensorFactors()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["num_tensor_factors"], 1)
def test_depth_one(self):
"""A dag with operations in parallel (2 tensor factors)"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
dag = circuit_to_dag(circuit)
pass_ = NumTensorFactors()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["num_tensor_factors"], 2)
if __name__ == "__main__":
unittest.main()
|
https://github.com/VGGatGitHub/2020-QISKit-Summer-Jam
|
VGGatGitHub
|
import pandas as pd
data = pd.read_csv("data/breast-cancer.csv")
diagnosis = data["diagnosis"]
labels = diagnosis.map({"M": 1, "B": -1}).values
features = data.drop(["id", "diagnosis"], axis=1)
#VGG coomet next three lines to run with the originla data above
data = pd.read_csv("data/formatted_titanic.csv")
labels = data["survived"]+2*data["sex"]
features = data.drop(["survived","sex"], axis=1)
data.shape
# Data visualization
import matplotlib.pyplot as plt
import umap
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaled_features = scaler.fit_transform(features)
reducer = umap.UMAP(n_components=3)
embedding = reducer.fit_transform(scaled_features)
embedding.shape
plt.scatter(
embedding[:, 0],embedding[:, 1], c=labels)
plt.scatter(
embedding[:, 0],embedding[:, 2], c=labels)
plt.scatter(
embedding[:, 1],embedding[:, 2], c=labels)
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.scatter(embedding[:, 0],embedding[:, 1],embedding[:, 2], c=labels)
plt.show()
from sklearn.decomposition import PCA
pca = PCA(n_components=0.75)
features_pca = pca.fit_transform(features)
pca.n_components_
features_pca.shape
plt.scatter(features_pca[:, 0],features_pca[:, 1], c=labels)
plt.scatter(features_pca[:, 0],features_pca[:, 2], c=labels)
plt.scatter(features_pca[:, 1],features_pca[:, 2], c=labels)
fig3d = plt.figure()
ax3d = fig3d.add_subplot(projection='3d')
ax3d.scatter(features_pca[:, 0],features_pca[:, 1],features_pca[:, 2], c=labels)
plt.show()
from qcfl.preprocessing import scale_for_angle_encoding
features_scaled = scale_for_angle_encoding(features_pca)
from utils import split_data, write_shards
dataset = pd.DataFrame(data=features_scaled)
dataset['target'] = labels
dataset = dataset.sample(frac=1)
shards = split_data(dataset, [0.3, 0.1, 0.2, 0.2, 0.2])
write_shards(shards, 'cancer')
from pennylane import AdamOptimizer
from qcfl.penny.classifier import QuantumClassifier
from qcfl.penny.models import SimplQMLModel
from qcfl.penny.federated_qml import create_clients, FederatedServer, to_numpy_dataset
num_qubits = features_pca.shape[1]
num_layers = 3
batch_size = 5
clients = create_clients(shards[0:4], lambda: QuantumClassifier(num_qubits, num_layers, batch_size,
AdamOptimizer(),
SimplQMLModel(num_qubits)))
classifier = QuantumClassifier(num_qubits, num_layers, batch_size,
AdamOptimizer(),
SimplQMLModel(num_qubits))
server = FederatedServer(classifier, clients, client_epochs=10)
# Train
from pennylane import numpy as np
weights = 0.01 * np.random.randn(num_layers, num_qubits, 3, requires_grad=True)
bias = np.array(0.0, requires_grad=True)
trained_weights, trained_bias = server.train(weights, bias, iterations=15)
from sklearn.metrics import classification_report
test_features, test_labels = to_numpy_dataset(shards[-1])
test_predictions = [classifier.classify(trained_weights, trained_bias, f) for f in test_features]
target_names = ['Malignant', 'Benign']
target_names = [str(i) for i in set(labels.values).union()]#VGG comment this line for cancer
cr = classification_report(test_labels, test_predictions, target_names=target_names)
print(cr)
set(labels.values).union()
from typing import List, Tuple
from flwr.common import Metrics
def fit_round(server_round: int):
"""Send round number to client."""
return {"server_round": server_round}
def weighted_average(metrics: List[Tuple[int, Metrics]]) -> Metrics:
# Multiply accuracy of each client by number of examples used
accuracies = [num_examples * m["accuracy"] for num_examples, m in metrics]
examples = [num_examples for num_examples, _ in metrics]
# Aggregate and return custom metric (weighted average)
return {"accuracy": sum(accuracies) / sum(examples)}
def get_evaluate_fn(classifier, X_test, y_test):
"""Return an evaluation function for server-side evaluation."""
# The `evaluate` function will be called after every round
def evaluate(server_round, parameters: fl.common.NDArrays, config):
# Update model with the latest parameters
weights, bias = parameters[0], parameters[1]
classifier.set_parameters(weights, bias)
loss, accuracy = classifier.evaluate(server_round, X_test, y_test)
return loss, {"accuracy": accuracy}
return evaluate
from qcfl.flower.flower_qml_client import PennylaneClient
num_qubits = features_pca.shape[1]#VGG
NUM_CLIENTS = 4
client_resources = None
def client_fn(cid: str) -> PennylaneClient:
"""Create a Flower client representing a single organization."""
print(cid)
index = int(cid)+1
# Load a shard corresponding to this client
X_train, y_train = load_shard('cancer', index)
X_train = np.array(X_train, requires_grad=False)
y_train = np.array(y_train, requires_grad=False)
classifier = QuantumClassifier(num_qubits, 3, 5,
AdamOptimizer(),
SimplQMLModel(num_qubits))
# Define Flower client
return PennylaneClient(f'cancer{index}',
classifier,
X_train, y_train)
from utils import load_shard
# Load test data here to avoid the overhead of doing it in `evaluate` itself
X_test, y_test = load_shard('cancer', 5)
# Create a classifier to hold the final weights
classifier = QuantumClassifier(num_qubits, 3, 10,
AdamOptimizer(),
SimplQMLModel(num_qubits))
import flwr as fl
# Create FedAvg strategy
strategy = fl.server.strategy.FedAvg(
fraction_fit=1.0,
fraction_evaluate=0.5,
min_available_clients=NUM_CLIENTS,
on_fit_config_fn=fit_round,
evaluate_fn=get_evaluate_fn(classifier, X_test, y_test),
evaluate_metrics_aggregation_fn=weighted_average
)
# Run flower in simulation mode
fl.simulation.start_simulation(
client_fn=client_fn,
num_clients=NUM_CLIENTS,
config=fl.server.ServerConfig(num_rounds=15),
strategy=strategy,
client_resources=client_resources,
)
#TODO: Plot loss, accuracy
# Compute metrics on final model
test_features, test_labels = to_numpy_dataset(shards[-1])
test_predictions = [classifier.classify(trained_weights, trained_bias, f) for f in test_features]
target_names = ['Malignant', 'Benign']
cr = classification_report(test_labels, test_predictions, target_names=target_names)
print(cr)
|
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.
# pylint: disable=invalid-name
"""Test cases for the pulse schedule block."""
import re
import unittest
from typing import List, Any
from qiskit import pulse, circuit
from qiskit.pulse import transforms
from qiskit.pulse.exceptions import PulseError
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeOpenPulse2Q, FakeArmonk
from qiskit.utils import has_aer
class BaseTestBlock(QiskitTestCase):
"""ScheduleBlock tests."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.test_waveform0 = pulse.Constant(100, 0.1)
self.test_waveform1 = pulse.Constant(200, 0.1)
self.d0 = pulse.DriveChannel(0)
self.d1 = pulse.DriveChannel(1)
self.left_context = transforms.AlignLeft()
self.right_context = transforms.AlignRight()
self.sequential_context = transforms.AlignSequential()
self.equispaced_context = transforms.AlignEquispaced(duration=1000)
def _align_func(j):
return {1: 0.1, 2: 0.25, 3: 0.7, 4: 0.85}.get(j)
self.func_context = transforms.AlignFunc(duration=1000, func=_align_func)
def assertScheduleEqual(self, target, reference):
"""Check if two block are equal schedule representation."""
self.assertEqual(transforms.target_qobj_transform(target), reference)
class TestTransformation(BaseTestBlock):
"""Test conversion of ScheduleBlock to Schedule."""
def test_left_alignment(self):
"""Test left alignment context."""
block = pulse.ScheduleBlock(alignment_context=self.left_context)
block = block.append(pulse.Play(self.test_waveform0, self.d0))
block = block.append(pulse.Play(self.test_waveform1, self.d1))
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1))
self.assertScheduleEqual(block, ref_sched)
def test_right_alignment(self):
"""Test right alignment context."""
block = pulse.ScheduleBlock(alignment_context=self.right_context)
block = block.append(pulse.Play(self.test_waveform0, self.d0))
block = block.append(pulse.Play(self.test_waveform1, self.d1))
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1))
self.assertScheduleEqual(block, ref_sched)
def test_sequential_alignment(self):
"""Test sequential alignment context."""
block = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block = block.append(pulse.Play(self.test_waveform0, self.d0))
block = block.append(pulse.Play(self.test_waveform1, self.d1))
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform1, self.d1))
self.assertScheduleEqual(block, ref_sched)
def test_equispace_alignment(self):
"""Test equispace alignment context."""
block = pulse.ScheduleBlock(alignment_context=self.equispaced_context)
for _ in range(4):
block = block.append(pulse.Play(self.test_waveform0, self.d0))
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(300, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(600, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(900, pulse.Play(self.test_waveform0, self.d0))
self.assertScheduleEqual(block, ref_sched)
def test_func_alignment(self):
"""Test func alignment context."""
block = pulse.ScheduleBlock(alignment_context=self.func_context)
for _ in range(4):
block = block.append(pulse.Play(self.test_waveform0, self.d0))
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(50, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(200, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(650, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(800, pulse.Play(self.test_waveform0, self.d0))
self.assertScheduleEqual(block, ref_sched)
def test_nested_alignment(self):
"""Test nested block scheduling."""
block_sub = pulse.ScheduleBlock(alignment_context=self.right_context)
block_sub = block_sub.append(pulse.Play(self.test_waveform0, self.d0))
block_sub = block_sub.append(pulse.Play(self.test_waveform1, self.d1))
block_main = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block_main = block_main.append(block_sub)
block_main = block_main.append(pulse.Delay(10, self.d0))
block_main = block_main.append(block_sub)
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1))
ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(200, pulse.Delay(10, self.d0))
ref_sched = ref_sched.insert(210, pulse.Play(self.test_waveform1, self.d1))
ref_sched = ref_sched.insert(310, pulse.Play(self.test_waveform0, self.d0))
self.assertScheduleEqual(block_main, ref_sched)
class TestBlockOperation(BaseTestBlock):
"""Test fundamental operation on schedule block.
Because ScheduleBlock adapts to the lazy scheduling, no uniitest for
overlap constraints is necessary. Test scheme becomes simpler than the schedule.
Some tests have dependency on schedule conversion.
This operation should be tested in `test.python.pulse.test_block.TestTransformation`.
"""
def setUp(self):
super().setUp()
self.test_blocks = [
pulse.Play(self.test_waveform0, self.d0),
pulse.Play(self.test_waveform1, self.d1),
pulse.Delay(50, self.d0),
pulse.Play(self.test_waveform1, self.d0),
]
def test_append_an_instruction_to_empty_block(self):
"""Test append instructions to an empty block."""
block = pulse.ScheduleBlock()
block = block.append(pulse.Play(self.test_waveform0, self.d0))
self.assertEqual(block.blocks[0], pulse.Play(self.test_waveform0, self.d0))
def test_append_an_instruction_to_empty_block_sugar(self):
"""Test append instructions to an empty block with syntax sugar."""
block = pulse.ScheduleBlock()
block += pulse.Play(self.test_waveform0, self.d0)
self.assertEqual(block.blocks[0], pulse.Play(self.test_waveform0, self.d0))
def test_append_an_instruction_to_empty_block_inplace(self):
"""Test append instructions to an empty block with inplace."""
block = pulse.ScheduleBlock()
block.append(pulse.Play(self.test_waveform0, self.d0), inplace=True)
self.assertEqual(block.blocks[0], pulse.Play(self.test_waveform0, self.d0))
def test_append_a_block_to_empty_block(self):
"""Test append another ScheduleBlock to empty block."""
block = pulse.ScheduleBlock()
block.append(pulse.Play(self.test_waveform0, self.d0), inplace=True)
block_main = pulse.ScheduleBlock()
block_main = block_main.append(block)
self.assertEqual(block_main.blocks[0], block)
def test_append_an_instruction_to_block(self):
"""Test append instructions to a non-empty block."""
block = pulse.ScheduleBlock()
block = block.append(pulse.Delay(100, self.d0))
block = block.append(pulse.Delay(100, self.d0))
self.assertEqual(len(block.blocks), 2)
def test_append_an_instruction_to_block_inplace(self):
"""Test append instructions to a non-empty block with inplace."""
block = pulse.ScheduleBlock()
block = block.append(pulse.Delay(100, self.d0))
block.append(pulse.Delay(100, self.d0), inplace=True)
self.assertEqual(len(block.blocks), 2)
def test_duration(self):
"""Test if correct duration is returned with implicit scheduling."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
self.assertEqual(block.duration, 350)
def test_channels(self):
"""Test if all channels are returned."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
self.assertEqual(len(block.channels), 2)
def test_instructions(self):
"""Test if all instructions are returned."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
self.assertEqual(block.blocks, tuple(self.test_blocks))
def test_channel_duraction(self):
"""Test if correct durations is calculated for each channel."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
self.assertEqual(block.ch_duration(self.d0), 350)
self.assertEqual(block.ch_duration(self.d1), 200)
def test_cannot_append_schedule(self):
"""Test schedule cannot be appended. Schedule should be input as Call instruction."""
block = pulse.ScheduleBlock()
sched = pulse.Schedule()
sched += pulse.Delay(10, self.d0)
with self.assertRaises(PulseError):
block.append(sched)
def test_replace(self):
"""Test replacing specific instruction."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
replaced = pulse.Play(pulse.Constant(300, 0.1), self.d1)
target = pulse.Delay(50, self.d0)
block_replaced = block.replace(target, replaced, inplace=False)
# original schedule is not destroyed
self.assertListEqual(list(block.blocks), self.test_blocks)
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1))
ref_sched = ref_sched.insert(200, replaced)
ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform1, self.d0))
self.assertScheduleEqual(block_replaced, ref_sched)
def test_replace_inplace(self):
"""Test replacing specific instruction with inplace."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
replaced = pulse.Play(pulse.Constant(300, 0.1), self.d1)
target = pulse.Delay(50, self.d0)
block.replace(target, replaced, inplace=True)
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1))
ref_sched = ref_sched.insert(200, replaced)
ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform1, self.d0))
self.assertScheduleEqual(block, ref_sched)
def test_replace_block_by_instruction(self):
"""Test replacing block with instruction."""
sub_block1 = pulse.ScheduleBlock()
sub_block1 = sub_block1.append(pulse.Delay(50, self.d0))
sub_block1 = sub_block1.append(pulse.Play(self.test_waveform0, self.d0))
sub_block2 = pulse.ScheduleBlock()
sub_block2 = sub_block2.append(pulse.Delay(50, self.d0))
sub_block2 = sub_block2.append(pulse.Play(self.test_waveform1, self.d1))
main_block = pulse.ScheduleBlock()
main_block = main_block.append(pulse.Delay(50, self.d0))
main_block = main_block.append(pulse.Play(self.test_waveform0, self.d0))
main_block = main_block.append(sub_block1)
main_block = main_block.append(sub_block2)
main_block = main_block.append(pulse.Play(self.test_waveform0, self.d1))
replaced = main_block.replace(sub_block1, pulse.Delay(100, self.d0))
ref_blocks = [
pulse.Delay(50, self.d0),
pulse.Play(self.test_waveform0, self.d0),
pulse.Delay(100, self.d0),
sub_block2,
pulse.Play(self.test_waveform0, self.d1),
]
self.assertListEqual(list(replaced.blocks), ref_blocks)
def test_replace_instruction_by_block(self):
"""Test replacing instruction with block."""
sub_block1 = pulse.ScheduleBlock()
sub_block1 = sub_block1.append(pulse.Delay(50, self.d0))
sub_block1 = sub_block1.append(pulse.Play(self.test_waveform0, self.d0))
sub_block2 = pulse.ScheduleBlock()
sub_block2 = sub_block2.append(pulse.Delay(50, self.d0))
sub_block2 = sub_block2.append(pulse.Play(self.test_waveform1, self.d1))
main_block = pulse.ScheduleBlock()
main_block = main_block.append(pulse.Delay(50, self.d0))
main_block = main_block.append(pulse.Play(self.test_waveform0, self.d0))
main_block = main_block.append(pulse.Delay(100, self.d0))
main_block = main_block.append(sub_block2)
main_block = main_block.append(pulse.Play(self.test_waveform0, self.d1))
replaced = main_block.replace(pulse.Delay(100, self.d0), sub_block1)
ref_blocks = [
pulse.Delay(50, self.d0),
pulse.Play(self.test_waveform0, self.d0),
sub_block1,
sub_block2,
pulse.Play(self.test_waveform0, self.d1),
]
self.assertListEqual(list(replaced.blocks), ref_blocks)
def test_len(self):
"""Test __len__ method"""
block = pulse.ScheduleBlock()
self.assertEqual(len(block), 0)
for j in range(1, 10):
block = block.append(pulse.Delay(10, self.d0))
self.assertEqual(len(block), j)
def test_inherit_from(self):
"""Test creating schedule with another schedule."""
ref_metadata = {"test": "value"}
ref_name = "test"
base_sched = pulse.ScheduleBlock(name=ref_name, metadata=ref_metadata)
new_sched = pulse.ScheduleBlock.initialize_from(base_sched)
self.assertEqual(new_sched.name, ref_name)
self.assertDictEqual(new_sched.metadata, ref_metadata)
@unittest.skipUnless(has_aer(), "qiskit-aer doesn't appear to be installed.")
def test_execute_block(self):
"""Test executing a ScheduleBlock on a Pulse backend"""
with pulse.build(name="test_block") as sched_block:
pulse.play(pulse.Constant(160, 1.0), pulse.DriveChannel(0))
pulse.acquire(50, pulse.AcquireChannel(0), pulse.MemorySlot(0))
backend = FakeArmonk()
# TODO: Rewrite test to simulate with qiskit-dynamics
with self.assertWarns(DeprecationWarning):
test_result = backend.run(sched_block).result()
self.assertDictEqual(test_result.get_counts(), {"0": 1024})
class TestBlockEquality(BaseTestBlock):
"""Test equality of blocks.
Equality of instruction ordering is compared on DAG representation.
This should be tested for each transform.
"""
def test_different_channels(self):
"""Test equality is False if different channels."""
block1 = pulse.ScheduleBlock()
block1 += pulse.Delay(10, self.d0)
block2 = pulse.ScheduleBlock()
block2 += pulse.Delay(10, self.d1)
self.assertNotEqual(block1, block2)
def test_different_transform(self):
"""Test equality is False if different transforms."""
block1 = pulse.ScheduleBlock(alignment_context=self.left_context)
block1 += pulse.Delay(10, self.d0)
block2 = pulse.ScheduleBlock(alignment_context=self.right_context)
block2 += pulse.Delay(10, self.d0)
self.assertNotEqual(block1, block2)
def test_different_transform_opts(self):
"""Test equality is False if different transform options."""
context1 = transforms.AlignEquispaced(duration=100)
context2 = transforms.AlignEquispaced(duration=500)
block1 = pulse.ScheduleBlock(alignment_context=context1)
block1 += pulse.Delay(10, self.d0)
block2 = pulse.ScheduleBlock(alignment_context=context2)
block2 += pulse.Delay(10, self.d0)
self.assertNotEqual(block1, block2)
def test_instruction_out_of_order_left(self):
"""Test equality is True if two blocks have instructions in different order."""
block1 = pulse.ScheduleBlock(alignment_context=self.left_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.left_context)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertEqual(block1, block2)
def test_instruction_in_order_left(self):
"""Test equality is True if two blocks have instructions in same order."""
block1 = pulse.ScheduleBlock(alignment_context=self.left_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.left_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertEqual(block1, block2)
def test_instruction_out_of_order_right(self):
"""Test equality is True if two blocks have instructions in different order."""
block1 = pulse.ScheduleBlock(alignment_context=self.right_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.right_context)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertEqual(block1, block2)
def test_instruction_in_order_right(self):
"""Test equality is True if two blocks have instructions in same order."""
block1 = pulse.ScheduleBlock(alignment_context=self.right_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.right_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertEqual(block1, block2)
def test_instruction_out_of_order_sequential(self):
"""Test equality is False if two blocks have instructions in different order."""
block1 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertNotEqual(block1, block2)
def test_instruction_out_of_order_sequential_more(self):
"""Test equality is False if three blocks have instructions in different order.
This could detect a particular bug as discussed in this thread:
https://github.com/Qiskit/qiskit-terra/pull/8005#discussion_r966191018
"""
block1 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertNotEqual(block1, block2)
def test_instruction_in_order_sequential(self):
"""Test equality is True if two blocks have instructions in same order."""
block1 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertEqual(block1, block2)
def test_instruction_out_of_order_equispaced(self):
"""Test equality is False if two blocks have instructions in different order."""
block1 = pulse.ScheduleBlock(alignment_context=self.equispaced_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.equispaced_context)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertNotEqual(block1, block2)
def test_instruction_in_order_equispaced(self):
"""Test equality is True if two blocks have instructions in same order."""
block1 = pulse.ScheduleBlock(alignment_context=self.equispaced_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.equispaced_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertEqual(block1, block2)
def test_instruction_out_of_order_func(self):
"""Test equality is False if two blocks have instructions in different order."""
block1 = pulse.ScheduleBlock(alignment_context=self.func_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.func_context)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertNotEqual(block1, block2)
def test_instruction_in_order_func(self):
"""Test equality is True if two blocks have instructions in same order."""
block1 = pulse.ScheduleBlock(alignment_context=self.func_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.func_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertEqual(block1, block2)
def test_instrution_in_oder_but_different_node(self):
"""Test equality is False if two blocks have different instructions."""
block1 = pulse.ScheduleBlock(alignment_context=self.left_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform1, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.left_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertNotEqual(block1, block2)
def test_instruction_out_of_order_complex_equal(self):
"""Test complex schedule equality can be correctly evaluated."""
block1_a = pulse.ScheduleBlock(alignment_context=self.left_context)
block1_a += pulse.Delay(10, self.d0)
block1_a += pulse.Play(self.test_waveform1, self.d1)
block1_a += pulse.Play(self.test_waveform0, self.d0)
block1_b = pulse.ScheduleBlock(alignment_context=self.left_context)
block1_b += pulse.Play(self.test_waveform1, self.d1)
block1_b += pulse.Delay(10, self.d0)
block1_b += pulse.Play(self.test_waveform0, self.d0)
block2_a = pulse.ScheduleBlock(alignment_context=self.right_context)
block2_a += block1_a
block2_a += block1_b
block2_a += block1_a
block2_b = pulse.ScheduleBlock(alignment_context=self.right_context)
block2_b += block1_a
block2_b += block1_a
block2_b += block1_b
self.assertEqual(block2_a, block2_b)
def test_instruction_out_of_order_complex_not_equal(self):
"""Test complex schedule equality can be correctly evaluated."""
block1_a = pulse.ScheduleBlock(alignment_context=self.left_context)
block1_a += pulse.Play(self.test_waveform0, self.d0)
block1_a += pulse.Play(self.test_waveform1, self.d1)
block1_a += pulse.Delay(10, self.d0)
block1_b = pulse.ScheduleBlock(alignment_context=self.left_context)
block1_b += pulse.Play(self.test_waveform1, self.d1)
block1_b += pulse.Delay(10, self.d0)
block1_b += pulse.Play(self.test_waveform0, self.d0)
block2_a = pulse.ScheduleBlock(alignment_context=self.right_context)
block2_a += block1_a
block2_a += block1_b
block2_a += block1_a
block2_b = pulse.ScheduleBlock(alignment_context=self.right_context)
block2_b += block1_a
block2_b += block1_a
block2_b += block1_b
self.assertNotEqual(block2_a, block2_b)
class TestParametrizedBlockOperation(BaseTestBlock):
"""Test fundamental operation with parametrization."""
def setUp(self):
super().setUp()
self.amp0 = circuit.Parameter("amp0")
self.amp1 = circuit.Parameter("amp1")
self.dur0 = circuit.Parameter("dur0")
self.dur1 = circuit.Parameter("dur1")
self.test_par_waveform0 = pulse.Constant(self.dur0, self.amp0)
self.test_par_waveform1 = pulse.Constant(self.dur1, self.amp1)
def test_report_parameter_assignment(self):
"""Test duration assignment check."""
block = pulse.ScheduleBlock()
block += pulse.Play(self.test_par_waveform0, self.d0)
# check parameter evaluation mechanism
self.assertTrue(block.is_parameterized())
self.assertFalse(block.is_schedulable())
# assign duration
block = block.assign_parameters({self.dur0: 200})
self.assertTrue(block.is_parameterized())
self.assertTrue(block.is_schedulable())
def test_cannot_get_duration_if_not_assigned(self):
"""Test raise error when duration is not assigned."""
block = pulse.ScheduleBlock()
block += pulse.Play(self.test_par_waveform0, self.d0)
with self.assertRaises(PulseError):
# pylint: disable=pointless-statement
block.duration
def test_get_assigend_duration(self):
"""Test duration is correctly evaluated."""
block = pulse.ScheduleBlock()
block += pulse.Play(self.test_par_waveform0, self.d0)
block += pulse.Play(self.test_waveform0, self.d0)
block = block.assign_parameters({self.dur0: 300})
self.assertEqual(block.duration, 400)
def test_nested_parametrized_instructions(self):
"""Test parameters of nested schedule can be assigned."""
test_waveform = pulse.Constant(100, self.amp0)
param_sched = pulse.Schedule(pulse.Play(test_waveform, self.d0))
with self.assertWarns(DeprecationWarning):
call_inst = pulse.instructions.Call(param_sched)
sub_block = pulse.ScheduleBlock()
sub_block += call_inst
block = pulse.ScheduleBlock()
block += sub_block
self.assertTrue(block.is_parameterized())
# assign durations
block = block.assign_parameters({self.amp0: 0.1})
self.assertFalse(block.is_parameterized())
def test_equality_of_parametrized_channels(self):
"""Test check equality of blocks involving parametrized channels."""
par_ch = circuit.Parameter("ch")
block1 = pulse.ScheduleBlock(alignment_context=self.left_context)
block1 += pulse.Play(self.test_waveform0, pulse.DriveChannel(par_ch))
block1 += pulse.Play(self.test_par_waveform0, self.d0)
block2 = pulse.ScheduleBlock(alignment_context=self.left_context)
block2 += pulse.Play(self.test_par_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, pulse.DriveChannel(par_ch))
self.assertEqual(block1, block2)
block1_assigned = block1.assign_parameters({par_ch: 1})
block2_assigned = block2.assign_parameters({par_ch: 1})
self.assertEqual(block1_assigned, block2_assigned)
def test_replace_parametrized_instruction(self):
"""Test parametrized instruction can updated with parameter table."""
block = pulse.ScheduleBlock()
block += pulse.Play(self.test_par_waveform0, self.d0)
block += pulse.Delay(100, self.d0)
block += pulse.Play(self.test_waveform0, self.d0)
replaced = block.replace(
pulse.Play(self.test_par_waveform0, self.d0),
pulse.Play(self.test_par_waveform1, self.d0),
)
self.assertTrue(replaced.is_parameterized())
# check assign parameters
replaced_assigned = replaced.assign_parameters({self.dur1: 100, self.amp1: 0.1})
self.assertFalse(replaced_assigned.is_parameterized())
def test_parametrized_context(self):
"""Test parametrize context parameter."""
duration = circuit.Parameter("dur")
param_context = transforms.AlignEquispaced(duration=duration)
block = pulse.ScheduleBlock(alignment_context=param_context)
block += pulse.Delay(10, self.d0)
block += pulse.Delay(10, self.d0)
block += pulse.Delay(10, self.d0)
block += pulse.Delay(10, self.d0)
self.assertTrue(block.is_parameterized())
self.assertFalse(block.is_schedulable())
block.assign_parameters({duration: 100}, inplace=True)
self.assertFalse(block.is_parameterized())
self.assertTrue(block.is_schedulable())
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Delay(10, self.d0))
ref_sched = ref_sched.insert(30, pulse.Delay(10, self.d0))
ref_sched = ref_sched.insert(60, pulse.Delay(10, self.d0))
ref_sched = ref_sched.insert(90, pulse.Delay(10, self.d0))
self.assertScheduleEqual(block, ref_sched)
class TestBlockFilter(BaseTestBlock):
"""Test ScheduleBlock filtering methods."""
def test_filter_channels(self):
"""Test filtering over channels."""
with pulse.build() as blk:
pulse.play(self.test_waveform0, self.d0)
pulse.delay(10, self.d0)
pulse.play(self.test_waveform1, self.d1)
filtered_blk = self._filter_and_test_consistency(blk, channels=[self.d0])
self.assertEqual(len(filtered_blk.channels), 1)
self.assertTrue(self.d0 in filtered_blk.channels)
with pulse.build() as ref_blk:
pulse.play(self.test_waveform0, self.d0)
pulse.delay(10, self.d0)
self.assertEqual(filtered_blk, ref_blk)
filtered_blk = self._filter_and_test_consistency(blk, channels=[self.d1])
self.assertEqual(len(filtered_blk.channels), 1)
self.assertTrue(self.d1 in filtered_blk.channels)
with pulse.build() as ref_blk:
pulse.play(self.test_waveform1, self.d1)
self.assertEqual(filtered_blk, ref_blk)
filtered_blk = self._filter_and_test_consistency(blk, channels=[self.d0, self.d1])
self.assertEqual(len(filtered_blk.channels), 2)
for ch in [self.d0, self.d1]:
self.assertTrue(ch in filtered_blk.channels)
self.assertEqual(filtered_blk, blk)
def test_filter_channels_nested_block(self):
"""Test filtering over channels in a nested block."""
with pulse.build() as blk:
with pulse.align_sequential():
pulse.play(self.test_waveform0, self.d0)
pulse.delay(5, self.d0)
with pulse.build(self.backend) as cx_blk:
pulse.cx(0, 1)
pulse.call(cx_blk)
for ch in [self.d0, self.d1, pulse.ControlChannel(0)]:
filtered_blk = self._filter_and_test_consistency(blk, channels=[ch])
self.assertEqual(len(filtered_blk.channels), 1)
self.assertTrue(ch in filtered_blk.channels)
def test_filter_inst_types(self):
"""Test filtering on instruction types."""
with pulse.build() as blk:
pulse.acquire(5, pulse.AcquireChannel(0), pulse.MemorySlot(0))
with pulse.build() as blk_internal:
pulse.play(self.test_waveform1, self.d1)
pulse.call(blk_internal)
pulse.reference(name="dummy_reference")
pulse.delay(10, self.d0)
pulse.play(self.test_waveform0, self.d0)
pulse.barrier(self.d0, self.d1, pulse.AcquireChannel(0), pulse.MemorySlot(0))
pulse.set_frequency(10, self.d0)
pulse.shift_frequency(5, self.d1)
pulse.set_phase(3.14 / 4.0, self.d0)
pulse.shift_phase(-3.14 / 2.0, self.d1)
pulse.snapshot(label="dummy_snapshot")
# test filtering Acquire
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.Acquire])
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.Acquire)
self.assertEqual(len(filtered_blk.channels), 2)
# test filtering Reference
filtered_blk = self._filter_and_test_consistency(
blk, instruction_types=[pulse.instructions.Reference]
)
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.instructions.Reference)
# test filtering Delay
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.Delay])
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.Delay)
self.assertEqual(len(filtered_blk.channels), 1)
# test filtering Play
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.Play])
self.assertEqual(len(filtered_blk.blocks), 2)
self.assertIsInstance(filtered_blk.blocks[0].blocks[0], pulse.Play)
self.assertIsInstance(filtered_blk.blocks[1], pulse.Play)
self.assertEqual(len(filtered_blk.channels), 2)
# test filtering RelativeBarrier
filtered_blk = self._filter_and_test_consistency(
blk, instruction_types=[pulse.instructions.RelativeBarrier]
)
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.instructions.RelativeBarrier)
self.assertEqual(len(filtered_blk.channels), 4)
# test filtering SetFrequency
filtered_blk = self._filter_and_test_consistency(
blk, instruction_types=[pulse.SetFrequency]
)
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.SetFrequency)
self.assertEqual(len(filtered_blk.channels), 1)
# test filtering ShiftFrequency
filtered_blk = self._filter_and_test_consistency(
blk, instruction_types=[pulse.ShiftFrequency]
)
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.ShiftFrequency)
self.assertEqual(len(filtered_blk.channels), 1)
# test filtering SetPhase
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.SetPhase])
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.SetPhase)
self.assertEqual(len(filtered_blk.channels), 1)
# test filtering ShiftPhase
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.ShiftPhase])
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.ShiftPhase)
self.assertEqual(len(filtered_blk.channels), 1)
# test filtering SnapShot
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.Snapshot])
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.Snapshot)
self.assertEqual(len(filtered_blk.channels), 1)
def test_filter_functionals(self):
"""Test functional filtering."""
with pulse.build() as blk:
pulse.play(self.test_waveform0, self.d0, "play0")
pulse.delay(10, self.d0, "delay0")
with pulse.build() as blk_internal:
pulse.play(self.test_waveform1, self.d1, "play1")
pulse.call(blk_internal)
pulse.play(self.test_waveform1, self.d1)
def filter_with_inst_name(inst: pulse.Instruction) -> bool:
try:
if isinstance(inst.name, str):
match_obj = re.search(pattern="play", string=inst.name)
if match_obj is not None:
return True
except AttributeError:
pass
return False
filtered_blk = self._filter_and_test_consistency(blk, filter_with_inst_name)
self.assertEqual(len(filtered_blk.blocks), 2)
self.assertIsInstance(filtered_blk.blocks[0], pulse.Play)
self.assertIsInstance(filtered_blk.blocks[1].blocks[0], pulse.Play)
self.assertEqual(len(filtered_blk.channels), 2)
def test_filter_multiple(self):
"""Test filter composition."""
with pulse.build() as blk:
pulse.play(pulse.Constant(100, 0.1, name="play0"), self.d0)
pulse.delay(10, self.d0, "delay0")
with pulse.build(name="internal_blk") as blk_internal:
pulse.play(pulse.Constant(50, 0.1, name="play1"), self.d0)
pulse.call(blk_internal)
pulse.barrier(self.d0, self.d1)
pulse.play(pulse.Constant(100, 0.1, name="play2"), self.d1)
def filter_with_pulse_name(inst: pulse.Instruction) -> bool:
try:
if isinstance(inst.pulse.name, str):
match_obj = re.search(pattern="play", string=inst.pulse.name)
if match_obj is not None:
return True
except AttributeError:
pass
return False
filtered_blk = self._filter_and_test_consistency(
blk, filter_with_pulse_name, channels=[self.d1], instruction_types=[pulse.Play]
)
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.Play)
self.assertEqual(len(filtered_blk.channels), 1)
def _filter_and_test_consistency(
self, sched_blk: pulse.ScheduleBlock, *args: Any, **kwargs: Any
) -> pulse.ScheduleBlock:
"""
Returns sched_blk.filter(*args, **kwargs),
including a test that sched_blk.filter | sched_blk.exclude == sched_blk
in terms of instructions.
"""
filtered = sched_blk.filter(*args, **kwargs)
excluded = sched_blk.exclude(*args, **kwargs)
def list_instructions(blk: pulse.ScheduleBlock) -> List[pulse.Instruction]:
insts = []
for element in blk.blocks:
if isinstance(element, pulse.ScheduleBlock):
inner_insts = list_instructions(element)
if len(inner_insts) != 0:
insts.extend(inner_insts)
elif isinstance(element, pulse.Instruction):
insts.append(element)
return insts
sum_insts = list_instructions(filtered) + list_instructions(excluded)
ref_insts = list_instructions(sched_blk)
self.assertEqual(len(sum_insts), len(ref_insts))
self.assertTrue(all(inst in ref_insts for inst in sum_insts))
return filtered
|
https://github.com/ayushidubal/qram
|
ayushidubal
|
%matplotlib inline
from qiskit import QuantumCircuit, QuantumRegister, transpile, ClassicalRegister
from qiskit.quantum_info import Statevector
from qiskit.visualization import array_to_latex, plot_histogram, plot_bloch_multivector
from qiskit.circuit.library import CHGate
from qiskit_aer import AerSimulator
from functools import partial
import numpy as np
from utils import get_image_path
show_unitary = partial(array_to_latex, max_size=100000)
show_state = lambda qc: Statevector(qc).draw('latex')
def get_unitary(qc, sim=AerSimulator()):
qc_copy = qc.copy()
qc_copy.save_unitary()
unitary = sim.run(transpile(qc_copy, sim), shots=1000).result().get_unitary()
return unitary
def measure(qc, sim=AerSimulator(), qubits=None):
qc_copy = qc.copy()
if(not qubits):
qc_copy.measure_all()
else:
qc_copy.measure(qubits, list(range(len(qubits))))
result = sim.run(transpile(qc_copy, sim), shots=1000).result().get_counts()
return result
mem = QuantumCircuit(2, name="QROM")
mem.cz(0,1)
display(mem.draw('mpl'))
show_unitary(get_unitary(mem))
qc = QuantumCircuit(2)
qc.x(range(2))
qc.append(mem, [0,1])
qc.x(range(2))
display(qc.draw('mpl'))
display(show_unitary(get_unitary(qc)))
show_state(qc)
mem = QuantumCircuit(2, name="QROM")
mem.cp(np.pi/3,0,1)
display(mem.draw('mpl'))
show_unitary(get_unitary(mem))
qc = QuantumCircuit(2)
qc.x(range(2))
qc.append(mem, [0,1])
qc.x(range(2))
display(qc.draw('mpl'))
display(show_unitary(get_unitary(qc)))
show_state(qc)
plot_bloch_multivector(qc)
qc = QuantumCircuit(3)
qc.x(range(2))
qc.h(2)
qc.barrier()
qc.append(mem, [0,1])
qc.barrier()
qc.cx(2,1)
qc.x(range(2))
qc.h(2)
display(qc.draw('mpl'))
display(show_unitary(get_unitary(qc)))
display(show_state(qc))
display(plot_histogram(measure(qc)))
qc = QuantumCircuit(1)
#qc.h(0)
qc.p(np.pi/2, 0)
#qc.barrier()
#qc.cx(1,0)
qc.h(0)
display(qc.draw('mpl'))
display(show_unitary(get_unitary(qc)))
display(show_state(qc))
display(plot_histogram(measure(qc)))
mem = QuantumCircuit(2, name="QROM")
mem.cp(np.pi/3,0,1)
mem.x(range(2))
mem.cp(np.pi/7,0,1)
mem.x(range(2))
display(mem.draw('mpl'))
show_unitary(get_unitary(mem))
qc = QuantumCircuit(2)
#qc.x(range(2))
qc.append(mem, [0,1])
#qc.x(range(2))
display(qc.draw('mpl'))
display(show_unitary(get_unitary(qc)))
show_state(qc)
mem = QuantumCircuit(2, name="qrom")
mem.ch(0,1)
mem.x(0)
mem.cry(np.pi/3, 0, 1)
mem.x(0)
display(mem.draw('mpl', filename=get_image_path("qrom_1.png")))
display(show_unitary(get_unitary(mem)))
show_state(mem)
addr = QuantumRegister(1, name="addr")
out = QuantumRegister(1, name="out")
q = QuantumRegister(1,name="q")
result = ClassicalRegister(1, "m")
qc = QuantumCircuit(addr, out, q, result)
qc.x(addr)
qc.barrier(addr)
qc.append(mem, [addr, out])
qc.cx(out, q)
display(qc.draw('mpl'))
display(show_unitary(get_unitary(qc)))
display(show_state(qc))
display(plot_histogram(measure(qc, qubits=[2])))
addr = QuantumRegister(1, name="addr")
out = QuantumRegister(1, name="out")
q = QuantumRegister(1,name="q")
result = ClassicalRegister(1, "m")
qc = QuantumCircuit(addr, out, q)
qc.h(addr)
qc.barrier(addr)
qc.append(mem, [addr, out])
qc.cx(out, q)
display(qc.draw('mpl', filename=get_image_path("qrom_1_usage.png")))
display(show_unitary(get_unitary(qc)))
display(show_state(qc))
#display(plot_histogram(measure(qc, qubits=[2])))
CCH = CHGate().control(1)
addr = QuantumRegister(2, name="addr")
data = QuantumRegister(2, name="data")
mem = QuantumCircuit(addr, data, name="qrom")
mem.x(addr[0])
mem.ccx(addr[0], addr[1], data[0])
mem.x(addr[0])
mem.barrier()
mem.append(CCH, [addr[0], addr[1], data[0]])
mem.ccx(addr[0], addr[1], data[1])
display(mem.draw('mpl'))
display(show_unitary(get_unitary(mem)))
show_state(mem)
addr = QuantumRegister(2, name="addr")
data = QuantumRegister(2, name="data")
q = QuantumRegister(1, name="q")
out = ClassicalRegister(1, name="c")
qc = QuantumCircuit(addr, data, q, out)
qc.x(range(2))
qc.barrier(addr)
qc.append(mem, [*addr, *data])
qc.cx(data[1], q[0])
qc.cx(data[0], q[0])
qc.append(mem, [*addr, *data])
qc.barrier(addr)
qc.x(range(2))
display(qc.draw('mpl'))
#display(show_unitary(get_unitary(qc)))
display(show_state(qc))
display(plot_histogram(measure(qc, qubits=[4])))
#memory with teleportation
addr = QuantumRegister(1, name="addr")
data = QuantumRegister(1, name="data")
mem = QuantumCircuit(addr, data, name="qrom")
mem.cry(np.pi/5, 0, 1)
display(mem.draw('mpl'))
display(show_unitary(get_unitary(mem)))
show_state(mem)
addr = QuantumRegister(1, name="addr")
data = QuantumRegister(2, name="data")
q = QuantumRegister(1, name="q")
out = ClassicalRegister(1, name="c")
qc = QuantumCircuit(addr, data, q, out)
qc.x(addr)
qc.barrier(addr)
qc.append(mem, [addr, data[0]])
qc.cx(data[0], q)
qc.barrier(addr)
qc.append(mem, [addr, data[0]])
qc.x(addr)
display(qc.draw('mpl'))
#display(show_unitary(get_unitary(qc)))
display(show_state(qc))
display(plot_histogram(measure(qc, qubits=[3])))
addr = QuantumRegister(1, name="addr")
data = QuantumRegister(2, name="data")
q = QuantumRegister(1, name="q")
out = ClassicalRegister(1, name="c")
qc = QuantumCircuit(addr, data, q, out)
qc.x(addr)
qc.barrier(addr)
qc.append(mem, [addr, data[0]])
qc.h(data[1])
qc.cx(data[1], q)
qc.cx(data[0], data[1])
qc.h(data[0])
qc.cx(data[1], q)
qc.cz(data[0], q)
display(qc.draw('mpl'))
#display(show_unitary(get_unitary(qc)))
display(show_state(qc))
display(plot_histogram(measure(qc, qubits=[3])))
display(plot_histogram(measure(qc, qubits=[1])))
(np.cos(np.pi/5/2))**2, (np.sin(np.pi/5/2))**2
qc = QuantumCircuit(3,3)
qc.ry(np.pi/5, 0)
qc.barrier()
qc.h(1)
qc.cx(1,2)
qc.barrier()
qc.cx(0,1)
qc.h(0)
qc.cx(1,2)
qc.cz(0,2)
qc.draw('mpl')
display(qc.draw('mpl'))
#display(show_unitary(get_unitary(qc)))
display(show_state(qc))
display(plot_histogram(measure(qc, qubits=[2])))
data = QuantumRegister(1, name="data")
teleportation_provider = QuantumRegister(1, name="t")
q = QuantumRegister(1, name="q")
meas = ClassicalRegister(1, name="out")
qram = QuantumCircuit(data, teleportation_provider, q,meas)
qram.h(teleportation_provider)
qram.cx(teleportation_provider, data)
qram.barrier()
qram.ry(np.pi/7, q)
qram.barrier()
qram.cx(q, teleportation_provider)
qram.h(q)
qram.cx(teleportation_provider, data)
qram.cz(q, data)
display(qram.draw('mpl'))
#display(show_unitary(get_unitary(qram)))
display(show_state(qram))
display(plot_histogram(measure(qram, qubits=[0])))
display(plot_histogram(measure(qram, qubits=[2])))
np.cos(np.pi/7/2)**2, np.sin(np.pi/7/2)**2
data = QuantumRegister(2, name="data")
teleportation_provider = QuantumRegister(2, name="t")
q = QuantumRegister(2, name="q")
meas = ClassicalRegister(1, name="out")
qram = QuantumCircuit(data, teleportation_provider, q,meas)
qram.h(teleportation_provider)
qram.cx(teleportation_provider, data)
qram.barrier()
qram.ry(np.pi/3, q[0])
qram.ry(np.pi/7, q[1])
qram.barrier()
qram.cx(q, teleportation_provider)
qram.h(q)
qram.cx(teleportation_provider, data)
qram.cz(q, data)
display(qram.draw('mpl', filename=get_image_path('qram.png')))
#display(show_unitary(get_unitary(qram)))
display(show_state(qram))
display(plot_histogram(measure(qram, qubits=[0])))
display(plot_histogram(measure(qram, qubits=[4])))
display(plot_histogram(measure(qram, qubits=[1])))
display(plot_histogram(measure(qram, qubits=[5])))
np.cos(np.pi/3/2)**2, np.sin(np.pi/3/2)**2
data = QuantumRegister(2, name="data")
teleportation_provider = QuantumRegister(2, name="t")
q = QuantumRegister(2, name="q")
meas = ClassicalRegister(1, name="out")
qram = QuantumCircuit(data, teleportation_provider, q,meas)
qram.h(teleportation_provider)
qram.cx(teleportation_provider, data)
qram.barrier()
qram.h(q[0])
qram.h(q[1])
qram.barrier()
qram.cx(q, teleportation_provider)
qram.h(q)
qram.cx(teleportation_provider, data)
qram.cz(q, data)
qram.barrier(label='second')
qram.cz(q, data)
qram.cx(teleportation_provider, data)
qram.h(q)
qram.cx(q, teleportation_provider)
qram.barrier()
qram.h(q[0])
qram.barrier()
qram.cx(q, teleportation_provider)
qram.h(q)
qram.cx(teleportation_provider, data)
qram.cz(q, data)
display(qram.draw('mpl'))
#display(show_unitary(get_unitary(qram)))
display(show_state(qram))
display(plot_histogram(measure(qram, qubits=[0])))
display(plot_histogram(measure(qram, qubits=[4])))
display(plot_histogram(measure(qram, qubits=[1])))
display(plot_histogram(measure(qram, qubits=[5])))
data = QuantumRegister(2, name="data")
teleportation_provider = QuantumRegister(1, name="t")
q = QuantumRegister(2, name="q")
meas = ClassicalRegister(1, name="out")
qram = QuantumCircuit(data, teleportation_provider, q,meas)
qram.h(teleportation_provider)
qram.cx(teleportation_provider, data)
qram.barrier()
qram.ry(np.pi/3, q[0])
qram.ry(np.pi/7, q[1])
qram.barrier()
qram.cx(q, teleportation_provider)
qram.h(q)
qram.cx(teleportation_provider, data)
qram.cz(q, data)
display(qram.draw('mpl', filename=get_image_path('qram.png')))
#display(show_unitary(get_unitary(qram)))
display(show_state(qram))
display(plot_histogram(measure(qram, qubits=[0])))
display(plot_histogram(measure(qram, qubits=[4])))
display(plot_histogram(measure(qram, qubits=[1])))
display(plot_histogram(measure(qram, qubits=[5])))
|
https://github.com/SammithSB/virat-and-toss
|
SammithSB
|
# Do the necessary imports
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ
from qiskit.visualization import plot_histogram, plot_bloch_multivector
### Creating 3 qubit and 2 classical bits in each separate register
qr = QuantumRegister(3)
crz = ClassicalRegister(1)
crx = ClassicalRegister(1)
teleportation_circuit = QuantumCircuit(qr, crz, crx)
### A third party eve helps to create an entangled state
def create_bell_pair(qc, a, b):
qc.h(a)
qc.cx(a, b)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.draw()
def alice_gates(qc, a, b):
qc.cx(a, b)
qc.h(a)
teleportation_circuit.barrier()
alice_gates(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def measure_and_send(qc, a, b):
qc.barrier()
qc.measure(a,0)
qc.measure(b,1)
teleportation_circuit.barrier()
measure_and_send(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def bob_gates(qc, qubit, crz, crx):
qc.x(qubit).c_if(crx, 1)
qc.z(qubit).c_if(crz, 1)
teleportation_circuit.barrier()
bob_gates(teleportation_circuit, 2, crz, crx)
teleportation_circuit.draw()
from qiskit.extensions import Initialize
import math
qc = QuantumCircuit(1)
initial_state = [0,1]
init_gate = Initialize(initial_state)
# qc.append(initialize_qubit, [0])
qr = QuantumRegister(3) # Protocol uses 3 qubits
crz = ClassicalRegister(1) # and 2 classical registers
crx = ClassicalRegister(1)
qc = QuantumCircuit(qr, crz, crx)
# First, let's initialise Alice's q0
qc.append(init_gate, [0])
qc.barrier()
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
# Alice then sends her classical bits to Bob
measure_and_send(qc, 0, 1)
# Bob decodes qubits
bob_gates(qc, 2, crz, crx)
qc.draw()
backend = BasicAer.get_backend('statevector_simulator')
out_vector = execute(qc, backend).result().get_statevector()
plot_bloch_multivector(out_vector)
inverse_init_gate = init_gate.gates_to_uncompute()
qc.append(inverse_init_gate, [2])
qc.draw()
cr_result = ClassicalRegister(1)
qc.add_register(cr_result)
qc.measure(2,2)
qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(qc, backend, shots=1024).result().get_counts()
plot_histogram(counts)
def bob_gates(qc, a, b, c):
qc.cz(a, c)
qc.cx(b, c)
qc = QuantumCircuit(3,1)
# First, let's initialise Alice's q0
qc.append(init_gate, [0])
qc.barrier()
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
qc.barrier()
# Alice sends classical bits to Bob
bob_gates(qc, 0, 1, 2)
# We undo the initialisation process
qc.append(inverse_init_gate, [2])
# See the results, we only care about the state of qubit 2
qc.measure(2,0)
# View the results:
qc.draw()
from qiskit import IBMQ
IBMQ.save_account('### IMB TOKEN ')
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and
not b.configuration().simulator and b.status().operational==True))
job_exp = execute(qc, backend=backend, shots=8192)
exp_result = job_exp.result()
exp_measurement_result = exp_result.get_counts(qc)
print(exp_measurement_result)
plot_histogram(exp_measurement_result)
error_rate_percent = sum([exp_measurement_result[result] for result in exp_measurement_result.keys() if result[0]=='1']) \
* 100./ sum(list(exp_measurement_result.values()))
print("The experimental error rate : ", error_rate_percent, "%")
|
https://github.com/LSEG-API-Samples/Article.EikonAPI.Python.OptionPricingUsingQiskitAndEikonDataAPI
|
LSEG-API-Samples
|
# ! pip install qiskit qiskit-finance==0.2.1
import warnings
warnings.filterwarnings("ignore")
import qiskit.tools.jupyter
%qiskit_version_table
from qiskit import IBMQ
IBMQ.save_account('MY_API_TOKEN', overwrite=True)
# ! pip install eikon
import eikon as ek
print("Eikon version: ", ek.__version__)
eikon_key = open("eikon.txt","r")
ek.set_app_key(str(eikon_key.read()))
eikon_key.close()
import numpy as np
import pandas as pd
import datetime
import matplotlib.pyplot as plt
import seaborn as sns
import qiskit
from qiskit import Aer, QuantumCircuit
from qiskit_finance.data_providers._base_data_provider import BaseDataProvider
from qiskit.finance.applications.ising import portfolio
from qiskit.circuit.library import TwoLocal
from qiskit.aqua import QuantumInstance
from qiskit.optimization.applications.ising.common import sample_most_likely
from qiskit.aqua.algorithms import VQE, QAOA, NumPyMinimumEigensolver
from qiskit.aqua.components.optimizers import COBYLA
class EikonDataProvider(BaseDataProvider):
"""
The abstract base class for Eikon data_provider.
"""
def __init__(self, stocks_list, start_date, end_date):
'''
stocks -> List of interested assets
start -> start date to fetch historical data
end ->
'''
super().__init__()
self._stocks = stocks_list
self._start = start_date
self._end = end_date
self._data = []
self.stock_data = pd.DataFrame()
def run(self):
self._data = []
stocks_notfound = []
stock_data = ek.get_timeseries(self._stocks,
start_date=self._start,
end_date=self._end,
interval='daily',
corax='adjusted')
for ticker in self._stocks:
stock_value = stock_data['CLOSE']
self.stock_data[ticker] = stock_data['CLOSE']
if stock_value.dropna().empty:
stocks_notfound.append(ticker)
self._data.append(stock_value)
# List of stocks
stock_list = ['FB.O']
# Start Date
start_date = datetime.datetime(2020,12,1)
# End Date
end_date = datetime.datetime(2021,12,1)
# Set number of equities to the number of stocks
num_assets = len(stock_list)
# Set the risk factor
risk_factor = 0.7
# Set budget
budget = 2
# Scaling of budget penalty term will be dependant on the number of assets
penalty = num_assets
data = EikonDataProvider(stocks_list = stock_list, start_date=start_date, end_date=end_date)
data.run()
# Top 5 rows of data
df = data.stock_data
df.head()
df.describe()
# Closing Price History
fig, ax = plt.subplots(figsize=(15, 8))
ax.plot(df)
plt.title('Close Price History')
plt.xlabel('Date',fontsize =20)
plt.ylabel('Price in USD',fontsize = 20)
ax.legend(df.columns.values)
plt.show()
df.tail()
strike_price = 315 # agreed upon strike price
T = 40 / 253 # 40 days to maturity
S = 310.6 # initial spot price
# vol = 0.4 # volatility of 40%
vol = df['FB.O'].pct_change().std()
r = 0.05 # annual interest rate of 4%
# resulting parameters for log-normal distribution
mu = ((r - 0.5 * vol**2) * T + np.log(S))
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2/2)
variance = (np.exp(sigma**2) - 1) * np.exp(2*mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3*stddev)
high = mean + 3*stddev
low
high
import numpy as np
from qiskit.algorithms import AmplitudeEstimation
from qiskit_finance.circuit.library import EuropeanCallPricingObjective # F
from qiskit.circuit.library import LogNormalDistribution, NormalDistribution
from qiskit_finance.applications import EuropeanCallPricing
from qiskit_finance.applications.estimation import EuropeanCallDelta
from qiskit import Aer
from qiskit.algorithms import IterativeAmplitudeEstimation
sim = QuantumInstance(Aer.get_backend("aer_simulator"), shots=1000)
# number of qubits to represent the uncertainty
num_uncertainty_qubits = 5
distribution = LogNormalDistribution(num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high))
european_call_pricing = EuropeanCallPricing(num_state_qubits=num_uncertainty_qubits,
strike_price=strike_price,
rescaling_factor=0.25, # approximation constant for payoff function
bounds=(low, high),
uncertainty_model=distribution)
problem = european_call_pricing.to_estimation_problem()
problem.state_preparation.draw('mpl', style='iqx')
plt.show()
epsilon = 0.01 # determines final accuracy
alpha = 0.05 # determines how certain we are of the result
ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, quantum_instance=sim)
result = ae.estimate(problem)
conf_int_result = np.array(result.confidence_interval_processed)
print("Esimated value: \t%.4f" % european_call_pricing.interpret(result))
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int_result))
x = distribution.values
y = distribution.probabilities
plt.figure(figsize=(15,6))
plt.bar(x, y, width=0.3)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=10)
plt.grid()
plt.xlabel('Spot Price at Maturity $S_T$ (\$)', size=15)
plt.ylabel('Probability ($\%$)', size=15)
plt.show()
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = distribution.values
y = np.maximum(0, x - strike_price)
plt.figure(figsize=(15,6))
plt.plot(x, y, "ro-")
plt.grid()
plt.title("Payoff Function for Call Option", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value (normalized to the [0, 1] interval)
exact_value = np.dot(distribution.probabilities, y)
exact_delta = sum(distribution.probabilities[x >= strike_price])
print("exact expected value:\t%.4f" % exact_value)
print("exact delta value: \t%.4f" % exact_delta)
european_call_delta = EuropeanCallDelta(
num_state_qubits=num_uncertainty_qubits,
strike_price=strike_price,
bounds=(low, high),
uncertainty_model=distribution,
)
european_call_delta._objective.decompose().draw('mpl', style='iqx')
plt.show()
european_call_delta_circ = QuantumCircuit(european_call_delta._objective.num_qubits)
european_call_delta_circ.append(distribution, range(num_uncertainty_qubits))
european_call_delta_circ.append(
european_call_delta._objective, range(european_call_delta._objective.num_qubits)
)
european_call_delta_circ.draw('mpl', style='iqx')
plt.show()
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = european_call_delta.to_estimation_problem()
# construct amplitude estimation
ae_delta = IterativeAmplitudeEstimation(epsilon, alpha=alpha, quantum_instance=sim)
result_delta = ae_delta.estimate(problem)
conf_int = np.array(result_delta.confidence_interval_processed)
print("Exact delta: \t%.4f" % exact_delta)
print("Esimated value: \t%.4f" % european_call_delta.interpret(result_delta))
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
put_distribution = LogNormalDistribution(num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high))
put_european_call_pricing = EuropeanCallPricing(num_state_qubits=num_uncertainty_qubits,
strike_price=strike_price,
rescaling_factor=0.25, # approximation constant for payoff function
bounds=(low, high),
uncertainty_model=put_distribution)
put_problem = put_european_call_pricing.to_estimation_problem()
epsilon = 0.01 # determines final accuracy
alpha = 0.05 # determines how certain we are of the result
ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, quantum_instance=sim)
put_result = ae.estimate(put_problem)
put_conf_int_result = np.array(put_result.confidence_interval_processed)
print("Esimated value: \t%.4f" % european_call_pricing.interpret(put_result))
print("Confidence interval: \t[%.4f, %.4f]" % tuple(put_conf_int_result))
x = put_distribution.values
y = put_distribution.probabilities
plt.figure(figsize=(15,6))
plt.bar(x, y, width=0.3)
plt.xticks(x, size=12, rotation=90)
plt.yticks(size=12)
plt.xlabel('Spot Price at Maturity $S_T$ (\$)', size=15)
plt.ylabel('Probability ($\%$)', size=15)
plt.show()
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = distribution.values
y = np.maximum(0, strike_price-x)
plt.figure(figsize=(15,6))
plt.plot(x, y, "ro-")
plt.title("Payoff Function for Put Option", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=12, rotation=90)
plt.yticks(size=12)
plt.show()
# evaluate exact expected value (normalized to the [0, 1] interval)
put_exact_value = np.dot(put_distribution.probabilities, y)
conf_int = np.array(put_result.confidence_interval_processed)
print("Exact Expected Value:\t%.4f" % exact_value)
print("Esimated value: \t%.4f" % european_call_delta.interpret(put_result))
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
|
https://github.com/suvoooo/Qubits-Qiskit
|
suvoooo
|
!pip3 install qiskit
import qiskit as q
print ("check version: ", q.__qiskit_version__)
from qiskit import IBMQ
import matplotlib.pyplot as plt
IBMQ.save_account('find your own number')
IBMQ.load_account()
circuit = q.QuantumCircuit(2, 2) # creates a new circuit with 2 classical and 2 quantum bits
# apply a simple not gate
circuit.x(1) # as both the bits are at 0, 0 this will flip the second bit to 1. # the number generally always represents the index, i.e. 1-- second index
circuit.draw()
# after flipping the second bit to 1 now we apply the controlled not gate
circuit.cx(1, 0) # conrolled qubit is the 2nd one and the target qubit is the 1st one
# QuantumCircuit.cx(control_qubit, target_qubit, *, label=None, ctrl_state=None, ctl=None, tgt=None)
# here's the description [https://qiskit.org/documentation/stubs/qiskit.circuit.QuantumCircuit.cx.html].
# since the controlled bit is 1 so it will flip the target qubit which was initially sitting at 0, to 1.
# rather than values think of this 0, 1 inside circuit.cx() as indices of the qubits.
# so at this stage we will have 1, 1 as output.
circuit.draw()
circuit.measure([0, 1], [0, 1]) # measure: quantum bit into classical bit,
# again think of the 0, 1 as indices, first list is the quantum register consisting of 2 qubits
# second list is the classical register consisting of 2 classical bits.
# think of this as value for qubit 0 is what will be returned for classical bit 0 and so on.
circuit.draw(output='mpl')
# let's simulate this before sending it to a quantum computer
# idea is we simulate the quantum computer computation in local computer using Aer framework
simulator = q.Aer.get_backend('qasm_simulator') # qasm : quantum assembly lang.
results = q.execute(circuit, backend=simulator).result() # execute the circuit based on the simulator as backend
q.visualization.plot_histogram(results.get_counts(circuit))
# Now we will use IBM Quantum Computer to see the result
provider = IBMQ.get_provider('ibm-q')
qcomp = provider.get_backend('ibmq_burlington') # check which computer has 0 jobs on queue
job = q.execute(circuit, backend=qcomp)
q_result = job.result()
q.visualization.plot_histogram(q_result.get_counts(circuit))
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# all portions are stored in a list
all_portions = [7,5,4,2,6,1];
# let's calculate the total portion
total_portion = 0
for i in range(6):
total_portion = total_portion + all_portions[i]
print("total portion is",total_portion)
# find the weight of one portion
one_portion = 1/total_portion
print("the weight of one portion is",one_portion)
print() # print an empty line
# now we can calculate the probabilities of rolling 1,2,3,4,5, and 6
for i in range(6):
print("the probability of rolling",(i+1),"is",(one_portion*all_portions[i]))
# we will randomly create a probabilistic state
#
# we should be careful about two things:
# 1. a probability value must be between 0 and 1
# 2. the total probability must be 1
#
# let's use a list of size 4
# initial values are zeros
my_state = [0,0,0,0]
normalization_factor = 0 # this will be the summation of four values
# we pick for random values between 0 and 100
from random import randrange
while normalization_factor==0: # the normalization factor cannot be zero
for i in range(4):
my_state[i] = randrange(101) # pick a random value between 0 and (101-1)
normalization_factor += my_state[i]
print("the random values before the normalization",my_state)
# let's normalize each value
for i in range(4): my_state[i] = my_state[i]/normalization_factor
print("the random values after the normalization",my_state)
# let's find their summation
sum = 0
for i in range(4): sum += my_state[i]
print("the summation is",sum)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0, measure=True).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit.primitives import Sampler
sampler = Sampler()
job = sampler.run(circuit)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Quasi-distribution: {result.quasi_dists[0]}")
circuit = random_circuit(2, 2, seed=1, measure=True).decompose(reps=1)
job = sampler.run(circuit)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Quasi-distribution: {result.quasi_dists[0]}")
circuits = (
random_circuit(2, 2, seed=0, measure=True).decompose(reps=1),
random_circuit(2, 2, seed=1, measure=True).decompose(reps=1),
)
job = sampler.run(circuits)
result = job.result()
[display(cir.draw("mpl")) for cir in circuits]
print(f">>> Quasi-distribution: {result.quasi_dists}")
from qiskit.circuit.library import RealAmplitudes
circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1)
circuit.measure_all()
parameter_values = [0, 1, 2, 3, 4, 5]
job = sampler.run(circuit, parameter_values)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Parameter values: {parameter_values}")
print(f">>> Quasi-distribution: {result.quasi_dists[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.backend("ibmq_qasm_simulator")
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0, measure=True).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit_ibm_runtime import Sampler
sampler = Sampler(session=backend)
job = sampler.run(circuit)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Quasi-distribution: {result.quasi_dists[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
options = Options(optimization_level=3, environment={"log_level": "INFO"})
from qiskit_ibm_runtime import Options
options = Options()
options.resilience_level = 1
options.execution.shots = 2048
sampler = Sampler(session=backend, options=options)
result = sampler.run(circuit).result()
print(f">>> Metadata: {result.metadata[0]}")
sampler = Sampler(session=backend, options=options)
result = sampler.run(circuit, shots=1024).result()
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
# optimization_level=3 adds dynamical decoupling
# resilience_level=1 adds readout error mitigation
options = Options(optimization_level=3, resilience_level=1)
sampler = Sampler(session=backend, options=options)
result = sampler.run(circuit).result()
print(f">>> Quasi-distribution: {result.quasi_dists[0]}")
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Session, Estimator
with Session(backend=backend, max_time="1h"):
sampler = Sampler()
result = sampler.run(circuit).result()
print(f">>> Quasi-distribution from the first run: {result.quasi_dists[0]}")
result = sampler.run(circuit).result()
print(f">>> Quasi-distribution from the second run: {result.quasi_dists[0]}")
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info import SparsePauliOp
estimator_circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(estimator_circuit.draw("mpl"))
observable = SparsePauliOp("XZ")
print(f">>> Observable: {observable.paulis}")
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
result = sampler.run(circuit).result()
print(f">>> Quasi Distribution from the sampler job: {result.quasi_dists[0]}")
result = estimator.run(estimator_circuit, observable).result()
print(f">>> Expectation value from the estimator job: {result.values[0]}")
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
sampler_job = sampler.run(circuit)
estimator_job = estimator.run(estimator_circuit, observable)
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Estimator, Options
# 1. Initialize account
service = QiskitRuntimeService(channel="ibm_quantum")
# 2. Specify options, such as enabling error mitigation
options = Options(resilience_level=1)
# 3. Select a backend.
backend = service.backend("ibmq_qasm_simulator")
# 4. Create a session
with Session(backend=backend):
# 5. Create primitive instances
sampler = Sampler(options=options)
estimator = Estimator(options=options)
# 6. Submit jobs
sampler_job = sampler.run(circuit)
estimator_job = estimator.run(estimator_circuit, observable)
# 7. Get results
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
%qiskit_copyright
|
https://github.com/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 fake backend.
"""
import pytest
from qiskit import QuantumCircuit
from qiskit.providers import JobV1
from qiskit_aer.noise.noise_model import NoiseModel
from iqm.qiskit_iqm.fake_backends.iqm_fake_backend import IQMFakeBackend
@pytest.fixture
def backend(linear_architecture_3q, create_3q_error_profile):
return IQMFakeBackend(linear_architecture_3q, create_3q_error_profile())
def test_fake_backend_with_incomplete_t1s(linear_architecture_3q, create_3q_error_profile):
"""Test that IQMFakeBackend construction fails if T1 times are not provided for all qubits"""
with pytest.raises(ValueError, match="Length of t1s"):
error_profile = create_3q_error_profile(t1s={"QB1": 2000, "QB3": 2000})
IQMFakeBackend(linear_architecture_3q, error_profile)
def test_fake_backend_with_incomplete_t2s(linear_architecture_3q, create_3q_error_profile):
"""Test that IQMFakeBackend construction fails if T2 times are not provided for all qubits"""
with pytest.raises(ValueError, match="Length of t2s"):
error_profile = create_3q_error_profile(t2s={"QB1": 2000, "QB3": 2000})
IQMFakeBackend(linear_architecture_3q, error_profile)
def test_fake_backend_with_single_qubit_gate_depolarizing_errors_qubits_not_matching_quantum_architecture(
linear_architecture_3q,
create_3q_error_profile,
):
"""Test that IQMFakeBackend construction fails if depolarizing rates are not provided for all qubits"""
with pytest.raises(ValueError, match="The qubits specified for one-qubit gate"):
error_profile = create_3q_error_profile(
single_qubit_gate_depolarizing_error_parameters={"prx": {"QB1": 0.0001, "QB2": 0.0001}},
)
IQMFakeBackend(linear_architecture_3q, error_profile)
def test_fake_backend_with_single_qubit_gate_depolarizing_errors_more_qubits_than_in_quantum_architecture(
linear_architecture_3q,
create_3q_error_profile,
):
"""Test that IQMFakeBackend construction fails if depolarizing rates are provided for
other qubits than specified in the quantum architecture"""
with pytest.raises(ValueError, match="The qubits specified for one-qubit gate"):
error_profile = create_3q_error_profile(
single_qubit_gate_depolarizing_error_parameters={
"prx": {"QB1": 0.0001, "QB2": 0.0001, "QB3": 0.0001, "QB4": 0.0001}
},
)
IQMFakeBackend(linear_architecture_3q, error_profile)
def test_fake_backend_with_two_qubit_gate_depolarizing_errors_couplings_not_matching_quantum_architecture(
linear_architecture_3q,
create_3q_error_profile,
):
"""Test that IQMFakeBackend construction fails if depolarizing rates are
not provided for all couplings of the quantum architecture (QB1 -- QB2 -- QB3 here)"""
with pytest.raises(ValueError, match="The couplings specified for two-qubit gate"):
error_profile = create_3q_error_profile(
two_qubit_gate_depolarizing_error_parameters={"cz": {("QB1", "QB2"): 0.001}},
)
IQMFakeBackend(linear_architecture_3q, error_profile)
def test_fake_backend_with_two_qubit_gate_depolarizing_errors_more_couplings_than_in_quantum_architecture(
linear_architecture_3q,
create_3q_error_profile,
):
"""Test that IQMFakeBackend construction fails if depolarizing rates are provided for
other couplings than specified in the quantum architecture"""
with pytest.raises(ValueError, match="The couplings specified for two-qubit gate"):
error_profile = create_3q_error_profile(
two_qubit_gate_depolarizing_error_parameters={
"cz": {("QB1", "QB2"): 0.001, ("QB2", "QB3"): 0.001, ("QB1", "QB3"): 0.001}
},
)
IQMFakeBackend(linear_architecture_3q, error_profile)
@pytest.mark.parametrize(
"param_name,param_value",
[
(
"single_qubit_gate_depolarizing_error_parameters",
{"wrong": {"QB1": 0.0001, "QB2": 0.0001, "QB3": 0}},
),
(
"two_qubit_gate_depolarizing_error_parameters",
{"wrong": {("QB1", "QB2"): 0.001, ("QB2", "QB3"): 0.001}},
),
],
)
def test_fake_backend_not_matching_quantum_architecture(
linear_architecture_3q,
create_3q_error_profile,
param_name: str,
param_value: dict,
):
"""Test that IQMFakeBackend construction fails if one qubit depolarizing rates are
refering to a gate not available in quantum architecture"""
with pytest.raises(
ValueError,
match=f"Gate `wrong` in `{param_name}` is not supported",
):
error_profile = create_3q_error_profile(**{param_name: param_value})
IQMFakeBackend(linear_architecture_3q, error_profile)
def test_error_profile(linear_architecture_3q, create_3q_error_profile):
err_profile = create_3q_error_profile()
backend = IQMFakeBackend(linear_architecture_3q, err_profile)
assert backend.error_profile == err_profile
# Assert that error profile cannot be modified
backend.error_profile.t1s["QB1"] = backend.error_profile.t1s["QB1"] + 127
assert backend.error_profile == err_profile
def test_set_error_profile(backend, create_3q_error_profile):
with pytest.raises(NotImplementedError, match="Setting error profile of existing fake backend is not allowed."):
backend.error_profile = create_3q_error_profile()
def test_copy_with_error_profile(linear_architecture_3q, create_3q_error_profile):
err_profile = create_3q_error_profile()
backend = IQMFakeBackend(linear_architecture_3q, err_profile)
new_t1s = err_profile.t1s
new_t1s["QB1"] = new_t1s["QB1"] + 128
new_err_profile = create_3q_error_profile(t1s=new_t1s)
new_backend = backend.copy_with_error_profile(new_err_profile)
assert new_backend.error_profile == new_err_profile
def test_iqm_fake_backend_noise_model_instantiated(backend):
"""Test that creating a Fake Backend instantiates a Qiskit noise model"""
assert isinstance(backend.noise_model, NoiseModel)
def test_iqm_fake_backend_noise_model_basis_gates(backend):
"""Test that all operations named as part of the backend are utilizes in the noise_model"""
assert all(gates in backend.operation_names for gates in backend.noise_model.basis_gates)
def test_run_single_circuit(backend):
"""Test that the backend can be called with a circuit
or a list of circuits and returns a result."""
circuit = QuantumCircuit(1, 1)
circuit.measure(0, 0)
shots = 10
job = backend.run(circuit, qubit_mapping=None, shots=shots)
assert isinstance(job, JobV1)
assert job.result() is not None
# Should also work if the circuit is passed inside a list
job = backend.run([circuit], qubit_mapping=None, shots=shots)
assert isinstance(job, JobV1)
assert job.result() is not None
def test_error_on_empty_circuit_list(backend):
"""Test that calling run with an empty list of circuits raises a ValueError."""
with pytest.raises(ValueError, match="Empty list of circuits submitted for execution."):
backend.run([], qubit_mapping=None)
def test_noise_on_all_qubits(backend):
"""
Tests if noise is applied to all qubits of the device.
"""
noise_model = backend.noise_model
simulator_qubit_indices = list(range(backend.num_qubits))
noisy_qubits = noise_model.noise_qubits
assert simulator_qubit_indices == noisy_qubits
def test_noise_model_has_noise_terms(backend):
"""
Tests if the noise model has some noise terms, i.e., tests if the noise model
doesn't have no noise terms.
"""
noise_model = backend.noise_model
assert not noise_model.is_ideal()
def test_fake_backend_with_readout_errors_more_qubits_than_in_quantum_architecture(
linear_architecture_3q,
create_3q_error_profile,
):
"""Test that IQMFakeBackend construction fails if readout errors are provided for
other qubits than specified in the quantum architecture"""
with pytest.raises(ValueError, match="The qubits specified in readout errors"):
error_profile = create_3q_error_profile(
readout_errors={
"QB1": {"0": 0.02, "1": 0.03},
"QB2": {"0": 0.02, "1": 0.03},
"QB4": {"0": 0.02, "1": 0.03},
},
)
IQMFakeBackend(linear_architecture_3q, error_profile)
def test_noise_model_contains_all_errors(backend):
"""
Test that the noise model contains all necessary errors.
"""
assert set(backend.noise_model.noise_instructions) == {"r", "cz", "measure"}
# Assert that CZ gate error is applied independent of argument order in gate specification
assert set(backend.noise_model._local_quantum_errors["cz"].keys()) == set([(0, 1), (1, 0), (1, 2), (2, 1)])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev
f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2
pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits)
pw_approximation._build()
qc = QuantumCircuit(pw_approximation.num_qubits)
qc.h(list(range(num_state_qubits)))
qc.append(pw_approximation.to_instruction(), qc.qubits)
qc.draw(output='mpl')
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
| |
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Bounded Approximation version of Plesch's algorithm.
https://arxiv.org/abs/2111.03132
"""
from dataclasses import dataclass
from qiskit import QuantumCircuit
from qclib.gates.initialize import Initialize
from qclib.state_preparation.util.baa import adaptive_approximation
from .lowrank import LowRankInitialize
@dataclass
class _OptParams:
def __init__(self, opt_params):
if opt_params is None:
self.max_fidelity_loss = 0.0
self.isometry_scheme = "ccd"
self.unitary_scheme = "qsd"
self.strategy = "greedy"
self.max_combination_size = 0
self.use_low_rank = False
else:
self.max_fidelity_loss = 0.0 if opt_params.get("max_fidelity_loss") is None \
else opt_params.get("max_fidelity_loss")
self.isometry_scheme = "ccd" if opt_params.get("iso_scheme") is None else \
opt_params.get("iso_scheme")
self.unitary_scheme = "qsd" if opt_params.get("unitary_scheme") is None else \
opt_params.get("unitary_scheme")
self.strategy = "greedy" if opt_params.get("strategy") is None else \
opt_params.get("strategy")
self.max_combination_size = 0 if opt_params.get("max_combination_size") is None else \
opt_params.get("max_combination_size")
self.use_low_rank = False if opt_params.get("use_low_rank") is None else \
opt_params.get("use_low_rank")
if self.max_fidelity_loss < 0 or self.max_fidelity_loss > 1:
self.max_fidelity_loss = 0.0
class BaaLowRankInitialize(Initialize):
"""
State preparation using the bounded approximation algorithm via Schmidt
decomposition arXiv:1003.5760
https://arxiv.org/abs/2111.03132
This class implements a state preparation gate.
"""
def __init__(self, params, label=None, opt_params=None):
"""
Parameters
----------
params: list of complex
A unit vector representing a quantum state.
Values are amplitudes.
opt_params: Dictionary
max_fidelity_loss: float
``state`` allowed (fidelity) error for approximation
(0<=``max_fidelity_loss``<=1). If ``max_fidelity_loss`` is not in the valid
range, it will be ignored.
isometry_scheme: string
Scheme used to decompose isometries.
Possible values are ``'knill'`` and ``'ccd'`` (column-by-column decomposition).
Default is ``isometry_scheme='ccd'``.
unitary_scheme: string
Scheme used to decompose unitaries.
Possible values are ``'csd'`` (cosine-sine decomposition) and ``'qsd'`` (quantum
Shannon decomposition).
Default is ``unitary_scheme='qsd'``.
strategy: string
Method to search for the best approximation (``'brute_force'`` or ``'greedy'``).
For states larger than 2**8, the greedy strategy should preferably be used.
Default is ``strategy='greedy'``.
max_combination_size: int
Maximum size of the combination ``C(n_qubits, max_combination_size)``
between the qubits of an entangled subsystem of length ``n_qubits`` to
produce the possible bipartitions
(1 <= ``max_combination_size`` <= ``n_qubits``//2).
For example, if ``max_combination_size``==1, there will be ``n_qubits``
bipartitions between 1 and ``n_qubits``-1 qubits.
The default value is 0 (the size will be maximum for each level).
use_low_rank: bool
If set to True, ``rank``>1 approximations are also considered. This is fine
tuning for high-entanglement states and is slower.
The default value is False.
"""
self._name = "baa-lrsp"
self._get_num_qubits(params)
self.node = None
self.opt_params = _OptParams(opt_params)
if label is None:
self._label = "BAASP"
super().__init__(self._name, self.num_qubits, params, label=label)
def _define(self):
self.definition = self._define_initialize()
def _define_initialize(self):
self.node = adaptive_approximation(
self.params,
self.opt_params.max_fidelity_loss,
self.opt_params.strategy,
self.opt_params.max_combination_size,
self.opt_params.use_low_rank,
)
circuit = QuantumCircuit(self.num_qubits)
for vector, qubits, rank, partition in zip(
self.node.vectors, self.node.qubits, self.node.ranks, self.node.partitions
):
opt_params = {
"iso_scheme": self.opt_params.isometry_scheme,
"unitary_scheme": self.opt_params.unitary_scheme,
"partition": partition,
"lr": rank,
}
gate = LowRankInitialize(vector, opt_params=opt_params)
circuit.compose(gate, qubits[::-1], inplace=True) # qiskit little-endian.
return circuit.reverse_bits()
@staticmethod
def initialize(q_circuit, state, qubits=None, opt_params=None):
"""
Appends a BaaLowRankInitialize gate into the q_circuit
"""
if qubits is None:
q_circuit.append(
BaaLowRankInitialize(state, opt_params=opt_params), q_circuit.qubits
)
else:
q_circuit.append(BaaLowRankInitialize(state, opt_params=opt_params), qubits)
|
https://github.com/udayapeddirajub/Grovers-Algorithm-Implementation-on-3-qubit-database
|
udayapeddirajub
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
from qiskit.circuit.library.standard_gates import XGate, HGate
from operator import *
n = 3
N = 8 #2**n
index_colour_table = {}
colour_hash_map = {}
index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"}
colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'}
def database_oracle(index_colour_table, colour_hash_map):
circ_database = QuantumCircuit(n + n)
for i in range(N):
circ_data = QuantumCircuit(n)
idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
# qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0
# we therefore reverse the index string -> q0, ..., qn
data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour)
circ_database.append(data_gate, list(range(n+n)))
return circ_database
# drawing the database oracle circuit
print("Database Encoding")
database_oracle(index_colour_table, colour_hash_map).draw()
circ_data = QuantumCircuit(n)
m = 4
idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
print("Internal colour encoding for the colour green (as an example)");
circ_data.draw()
def oracle_grover(database, data_entry):
circ_grover = QuantumCircuit(n + n + 1)
circ_grover.append(database, list(range(n+n)))
target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target")
# control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()'
# The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class.
circ_grover.append(target_reflection_gate, list(range(n, n+n+1)))
circ_grover.append(database, list(range(n+n)))
return circ_grover
print("Grover Oracle (target example: orange)")
oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw()
def mcz_gate(num_qubits):
num_controls = num_qubits - 1
mcz_gate = QuantumCircuit(num_qubits)
target_mcz = QuantumCircuit(1)
target_mcz.z(0)
target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ")
mcz_gate.append(target_mcz, list(range(num_qubits)))
return mcz_gate.reverse_bits()
print("Multi-controlled Z (MCZ) Gate")
mcz_gate(n).decompose().draw()
def diffusion_operator(num_qubits):
circ_diffusion = QuantumCircuit(num_qubits)
qubits_list = list(range(num_qubits))
# Layer of H^n gates
circ_diffusion.h(qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of Multi-controlled Z (MCZ) Gate
circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of H^n gates
circ_diffusion.h(qubits_list)
return circ_diffusion
print("Diffusion Circuit")
diffusion_operator(n).draw()
# Putting it all together ... !!!
item = "green"
print("Searching for the index of the colour", item)
circuit = QuantumCircuit(n + n + 1, n)
circuit.x(n + n)
circuit.barrier()
circuit.h(list(range(n)))
circuit.h(n+n)
circuit.barrier()
unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator")
unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator")
M = countOf(index_colour_table.values(), item)
Q = int(np.pi * np.sqrt(N/M) / 4)
for i in range(Q):
circuit.append(unitary_oracle, list(range(n + n + 1)))
circuit.append(unitary_diffuser, list(range(n)))
circuit.barrier()
circuit.measure(list(range(n)), list(range(n)))
circuit.draw()
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(circuit)
if M==1:
print("Index of the colour", item, "is the index with most probable outcome")
else:
print("Indices of the colour", item, "are the indices the most probable outcomes")
from qiskit.visualization import plot_histogram
plot_histogram(counts)
|
https://github.com/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
# from cirq import cphase
import numpy as np
import qiskit.circuit.library.standard_gates as g
import qiskit.circuit.quantumcircuit as qc
from qiskit.circuit.equivalence import EquivalenceLibrary
from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary
from qiskit.circuit.library.standard_gates.equivalence_library import (
StandardEquivalenceLibrary,
)
SessionEquivalenceLibrary = EquivalenceLibrary(base=StandardEquivalenceLibrary)
# https://github.com/Qiskit/qiskit-terra/blob/main/qiskit/circuit/library/standard_gates/equivalence_library.py
from qiskit.quantum_info.operators import Operator
circuit = qc.QuantumCircuit(2, name="rootswap")
cx = Operator(
[
[1, 0, 0, 0],
[0, 0.5 * (1 + 1j), 0.5 * (1 - 1j), 0],
[0, 0.5 * (1 - 1j), 0.5 * (1 + 1j), 0],
[0, 0, 0, 1],
]
)
circuit.unitary(cx, [0, 1])
rootSwap = circuit.to_gate()
# define rootiswap
circuit = qc.QuantumCircuit(2, name="rootiswap")
cx = Operator(
[
[1, 0, 0, 0],
[0, 1 / np.sqrt(2), 1j / np.sqrt(2), 0],
[0, 1j / np.sqrt(2), 1 / np.sqrt(2), 0],
[0, 0, 0, 1],
]
)
circuit.unitary(cx, [0, 1])
rootiSwap = circuit.to_gate()
def iswap(alpha):
return np.matrix(
[
[1, 0, 0, 0],
[0, np.cos(np.pi * alpha / 2), 1j * np.sin(np.pi * alpha / 2), 0],
[0, 1j * np.sin(np.pi * alpha / 2), np.cos(np.pi * alpha / 2), 0],
[0, 0, 0, 1],
]
)
# class rootiswap_gate(qe.UnitaryGate):
# def __init__(self):
# super().__init__(
# data=np.array(
# [
# [1, 0, 0, 0],
# [0, 1 / np.sqrt(2), 1j / np.sqrt(2), 0],
# [0, 1j / np.sqrt(2), 1 / np.sqrt(2), 0],
# [0, 0, 0, 1],
# ]
# ),
# label=r"rootiswap",
# )
# SWAP out of rootSWAP
_rootSwapEquiv = qc.QuantumCircuit(2)
_rootSwapEquiv.append(rootSwap, [0, 1])
_rootSwapEquiv.append(rootSwap, [0, 1])
SessionEquivalenceLibrary.add_equivalence(g.SwapGate(), _rootSwapEquiv)
# CX out of rootSWAP
_cxEquiv = qc.QuantumCircuit(2)
_cxEquiv.ry(np.pi / 2, 1)
_cxEquiv.append(rootSwap, [0, 1])
_cxEquiv.z(0)
_cxEquiv.append(rootSwap, [0, 1])
_cxEquiv.rz(-np.pi / 2, 0)
_cxEquiv.rz(-np.pi / 2, 1)
_cxEquiv.ry(-np.pi / 2, 1)
SessionEquivalenceLibrary.add_equivalence(g.CXGate(), _cxEquiv)
# rootSWAP out of CX
_rootSwapEquiv = qc.QuantumCircuit(2)
_rootSwapEquiv.cx(0, 1)
_rootSwapEquiv.h(0)
_rootSwapEquiv.rz(np.pi / 4, 0)
_rootSwapEquiv.rz(-np.pi / 4, 1)
_rootSwapEquiv.h(0)
_rootSwapEquiv.h(1)
_rootSwapEquiv.cx(0, 1)
_rootSwapEquiv.h(0)
_rootSwapEquiv.h(1)
_rootSwapEquiv.rz(-np.pi / 4, 0)
_rootSwapEquiv.h(0)
_rootSwapEquiv.cx(0, 1)
_rootSwapEquiv.rz(-np.pi / 2, 0)
_rootSwapEquiv.rz(np.pi / 2, 1)
SessionEquivalenceLibrary.add_equivalence(rootSwap, _rootSwapEquiv)
# add decomp rule for CZ out of Cphase
_czEquiv = qc.QuantumCircuit(2)
_czEquiv.append(g.CPhaseGate(np.pi), [0, 1])
SessionEquivalenceLibrary.add_equivalence(g.CZGate(), _czEquiv)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
circ.measure(0, 0)
circ.measure(1, 1)
circ.draw('mpl')
from qiskit import pulse
from qiskit.pulse.library import Gaussian
from qiskit.providers.fake_provider import FakeValencia
backend = FakeValencia()
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0))
h_q0.draw()
circ.add_calibration('h', [0], h_q0)
from qiskit import transpile
from qiskit.providers.fake_provider import FakeHanoi
backend = FakeHanoi()
circ = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ.draw('mpl', idle_wires=False)
from qiskit import QuantumCircuit
from qiskit.circuit import Gate
circ = QuantumCircuit(1, 1)
custom_gate = Gate('my_custom_gate', 1, [3.14, 1])
# 3.14 is an arbitrary parameter for demonstration
circ.append(custom_gate, [0])
circ.measure(0, 0)
circ.draw('mpl')
with pulse.build(backend, name='custom') as my_schedule:
pulse.play(Gaussian(duration=64, amp=0.2, sigma=8), pulse.drive_channel(0))
circ.add_calibration('my_custom_gate', [0], my_schedule, [3.14, 1])
# Alternatively: circ.add_calibration(custom_gate, [0], my_schedule)
circ = transpile(circ, backend)
circ.draw('mpl', idle_wires=False)
circ = QuantumCircuit(2, 2)
circ.append(custom_gate, [1])
from qiskit import QiskitError
try:
circ = transpile(circ, backend)
except QiskitError as e:
print(e)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
from qiskit import *
def Uf_c(n):
qr = QuantumRegister(n+1); qc = QuantumCircuit(qr, name = 'Uf_c')
qc.x(qr[n])
return qc
qc = Uf_c(3); qc.draw()
def Uf_b(n):
qr = QuantumRegister(n+1); qc = QuantumCircuit(qr, name = 'Uf_b')
qc.cx(qr[n-1],qr[n])
return qc
qc = Uf_b(3); qc.draw()
def deutsch_jozsa(n, typ):
qr = QuantumRegister(n+1); cr = ClassicalRegister(n); qc = QuantumCircuit(qr,cr)
qc.x(qr[n])
for j in range(0,n+1):
qc.h(qr[j])
qc.barrier()
qrs = []
for j in range(0,n+1):
qrs.append(qr[j])
if typ == 'c':
qc_uf = Uf_c(n); qc.append(qc_uf, qrs)
elif typ == 'b':
qc_uf = Uf_b(n); qc.append(qc_uf, qrs)
qc.barrier()
for j in range(0,n):
qc.h(qr[j])
for j in range(0,n):
qc.measure(qr[j], cr[j])
return qc
qc = deutsch_jozsa(3, 'c'); qc.draw() # exemplo pra funcao constante
simulator = Aer.get_backend('qasm_simulator')
nshots = 8192
result = execute(qc, backend = simulator, shots = nshots).result()
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(qc))
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_belem')
from qiskit.tools.monitor import backend_overview, backend_monitor
job = execute(qc, backend = device, shots = nshots)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result = job.result(); plot_histogram(result.get_counts(qc))
qc = deutsch_jozsa(3, 'b'); qc.draw() # exemplo de funcao balanceada
result = execute(qc, backend = simulator, shots = nshots).result()
plot_histogram(result.get_counts(qc))
job = execute(qc, backend = device, shots = nshots)
job_monitor(job)
result = job.result(); plot_histogram(result.get_counts(qc))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver()
problem = driver.run()
print(problem)
from qiskit_nature.second_q.problems import ElectronicBasis
driver.run_pyscf()
problem = driver.to_problem(basis=ElectronicBasis.MO, include_dipole=True)
print(problem.basis)
ao_problem = driver.to_problem(basis=ElectronicBasis.AO)
print(ao_problem.basis)
from qiskit_nature.second_q.formats.qcschema_translator import qcschema_to_problem
qcschema = driver.to_qcschema()
ao_problem = qcschema_to_problem(qcschema, basis=ElectronicBasis.AO)
from qiskit_nature.second_q.formats.qcschema_translator import get_ao_to_mo_from_qcschema
basis_transformer = get_ao_to_mo_from_qcschema(qcschema)
mo_problem = basis_transformer.transform(ao_problem)
print(mo_problem.basis)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.cx(0, 1)
qc.draw("mpl")
|
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
|
PacktPublishing
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created Nov 2020
@author: hassi
"""
from qiskit import QuantumCircuit, execute
from qiskit import IBMQ
from qiskit.tools.monitor import job_monitor
from IPython.core.display import display
print("Getting provider...")
if not IBMQ.active_account():
IBMQ.load_account()
provider = IBMQ.get_provider()
print("Ch 4: Quantum coin toss on IBM Q backend")
print("----------------------------------------")
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0,1)
qc.measure([0,1],[0,1])
display(qc.draw('mpl'))
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(n_qubits=5, operational=True, simulator=False))
print(backend.name())
job = execute(qc, backend, shots=1000)
job_monitor(job)
result = job.result()
print(result)
counts = result.get_counts(qc)
from qiskit.tools.visualization import plot_histogram
display(plot_histogram(counts))
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
s = '11'
# Creating registers
# qubits for querying the oracle and finding the hidden period s
qr = QuantumRegister(2*len(str(s)))
# classical registers for recording the measurement from qr
cr = ClassicalRegister(2*len(str(s)))
simonCircuit = QuantumCircuit(qr, cr)
barriers = True
# Apply Hadamard gates before querying the oracle
for i in range(len(str(s))):
simonCircuit.h(qr[i])
# Apply barrier
if barriers:
simonCircuit.barrier()
# Apply the query function
## 2-qubit oracle for s = 11
simonCircuit.cx(qr[0], qr[len(str(s)) + 0])
simonCircuit.cx(qr[0], qr[len(str(s)) + 1])
simonCircuit.cx(qr[1], qr[len(str(s)) + 0])
simonCircuit.cx(qr[1], qr[len(str(s)) + 1])
# Apply barrier
if barriers:
simonCircuit.barrier()
# Measure ancilla qubits
for i in range(len(str(s)), 2*len(str(s))):
simonCircuit.measure(qr[i], cr[i])
# Apply barrier
if barriers:
simonCircuit.barrier()
# Apply Hadamard gates to the input register
for i in range(len(str(s))):
simonCircuit.h(qr[i])
# Apply barrier
if barriers:
simonCircuit.barrier()
# Measure input register
for i in range(len(str(s))):
simonCircuit.measure(qr[i], cr[i])
simonCircuit.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(simonCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
# Categorize measurements by input register values
answer_plot = {}
for measresult in answer.keys():
measresult_input = measresult[len(str(s)):]
if measresult_input in answer_plot:
answer_plot[measresult_input] += answer[measresult]
else:
answer_plot[measresult_input] = answer[measresult]
# Plot the categorized results
print( answer_plot )
plot_histogram(answer_plot)
# Calculate the dot product of the results
def sdotz(a, b):
accum = 0
for i in range(len(a)):
accum += int(a[i]) * int(b[i])
return (accum % 2)
print('s, z, s.z (mod 2)')
for z_rev in answer_plot:
z = z_rev[::-1]
print( '{}, {}, {}.{}={}'.format(s, z, s,z,sdotz(s,z)) )
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits
IBMQ.load_account()
IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(simonCircuit, backend=backend, shots=shots)
job_monitor(job, interval = 2)
# Categorize measurements by input register values
answer_plot = {}
for measresult in answer.keys():
measresult_input = measresult[len(str(s)):]
if measresult_input in answer_plot:
answer_plot[measresult_input] += answer[measresult]
else:
answer_plot[measresult_input] = answer[measresult]
# Plot the categorized results
print( answer_plot )
plot_histogram(answer_plot)
# Calculate the dot product of the most significant results
print('s, z, s.z (mod 2)')
for z_rev in answer_plot:
if answer_plot[z_rev] >= 0.1*shots:
z = z_rev[::-1]
print( '{}, {}, {}.{}={}'.format(s, z, s,z,sdotz(s,z)) )
import qiskit
qiskit.__qiskit_version__
|
https://github.com/urwin419/QiskitChecker
|
urwin419
|
import qiskit
#Code based on Qiskit offcial Textbook
#Create the circuit for the Bernstein-Vazirani algorithm
def bv_algorithm(bitstring: str, num_qubits: int) -> qiskit.QuantumCircuit:
#Create the quantum circuit
bv_circuit = qiskit.QuantumCircuit(num_qubits + 1, num_qubits)
#Apply H-gate to the output qubit
bv_circuit.h(num_qubits)
#Apply Z-gate to the output qubit
bv_circuit.z(num_qubits)
#Apply H-gates to all qubits
for qubit in range(num_qubits):
bv_circuit.h(qubit)
#Reverse the order of the bitstring
s = bitstring[::-1]
for qubit in range(num_qubits):
if s[qubit] == '0':
#If the position equals to 0, apply an I-gate
bv_circuit.i(qubit)
else:
#Else, apply CX-gates
bv_circuit.cx(qubit, num_qubits)
#Apply H-gates to all qubits
for qubit in range(num_qubits):
bv_circuit.h(qubit)
#Measure all the qubits
for qubit in range(num_qubits):
bv_circuit.measure(qubit, qubit)
return bv_circuit
#Run the simulation with the given circuit
def bernstein_azirani(bitstring: str, num_qubits: int) -> qiskit.QuantumCircuit:
#Get the simulator
simulator = qiskit.Aer.get_backend('qasm_simulator')
#Get the circuit
circuit = bv_algorithm(bitstring, num_qubits)
#Execute the Bernstein-Vazirani algorithm
job = qiskit.execute(circuit, simulator, shots=1000)
#Get results
result = job.result().get_counts()
return result
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Test qclib.gate.mc_gate """
from unittest import TestCase
import numpy as np
from scipy.stats import unitary_group
import qiskit
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import MCXGate
import qclib.util
from qclib.gates.ldmcu import Ldmcu
class TestLinearToffoli(TestCase):
""" Testing qclib.gate.toffoli """
def test_controlled_gate(self):
""" Testing multi controlled gate """
gate_u = unitary_group.rvs(2)
controls = QuantumRegister(4)
target = QuantumRegister(1)
circuit = qiskit.QuantumCircuit(controls, target)
circuit.x(0)
circuit.x(1)
circuit.x(2)
circuit.x(3)
Ldmcu.ldmcu(circuit, gate_u, controls, target)
state = qclib.util.get_state(circuit)
self.assertTrue(np.isclose(state[15], gate_u[0, 0]))
self.assertTrue(np.isclose(state[31], gate_u[1, 0]))
controls2 = QuantumRegister(4)
target2 = QuantumRegister(1)
circuit2 = QuantumCircuit(controls2, target2)
circuit2.x(0)
circuit2.x(1)
circuit2.x(2)
circuit2.x(3)
circuit2.x(4)
Ldmcu.ldmcu(circuit2, gate_u, controls2, target2)
state = qclib.util.get_state(circuit2)
self.assertTrue(np.isclose(state[15], gate_u[0, 1]))
self.assertTrue(np.isclose(state[31], gate_u[1, 1]))
def test_linear_toffoli3(self):
""" Testing Toffoli control 111"""
gate_x = np.array([[0, 1], [1, 0]])
controls = QuantumRegister(3)
target = QuantumRegister(1)
circuit = QuantumCircuit(controls, target)
circuit.x(1)
circuit.x(2)
circuit.x(3)
circuit.x(0)
Ldmcu.ldmcu(circuit, gate_x, controls, target)
state = qclib.util.get_state(circuit)
exp_state = np.zeros(16, dtype=complex)
exp_state[7] = 1
self.assertTrue(np.allclose(state, exp_state))
def test_linear_toffoli2(self):
""" Testing Toffoli control 110"""
gate_x = np.array([[0, 1], [1, 0]])
controls2 = QuantumRegister(3)
target2 = QuantumRegister(1)
circuit2 = QuantumCircuit(controls2, target2)
circuit2 = qiskit.QuantumCircuit(4)
circuit2.x(2)
circuit2.x(3)
circuit2.x(0)
state1 = qclib.util.get_state(circuit2)
controls1 = QuantumRegister(3)
target1 = QuantumRegister(1)
circuit1 = qiskit.QuantumCircuit(controls1, target1)
Ldmcu.ldmcu(circuit1, gate_x, controls1, target1, ctrl_state='110')
circuit2.compose(circuit1, circuit2.qubits, inplace=True)
state2 = qclib.util.get_state(circuit2)
self.assertTrue(np.allclose(state1, state2))
def test_linear_toffoli1(self):
""" Testing Toffoli control 100"""
gate_x = np.array([[0, 1], [1, 0]])
circuit2 = qiskit.QuantumCircuit(4)
circuit2.x(0)
state1 = qclib.util.get_state(circuit2)
controls = QuantumRegister(3)
target = QuantumRegister(1)
circuit = qiskit.QuantumCircuit(controls, target)
Ldmcu.ldmcu(circuit, gate_x, controls, target, ctrl_state='100')
circuit2.compose(circuit, circuit2.qubits, inplace=True)
state2 = qclib.util.get_state(circuit2)
self.assertTrue(np.allclose(state1, state2))
def test_linear_toffoli0(self):
""" Testing Toffoli control 000"""
gate_x = np.array([[0, 1], [1, 0]])
controls = QuantumRegister(3)
target = QuantumRegister(1)
mcgate_circuit = qiskit.QuantumCircuit(controls, target)
Ldmcu.ldmcu(mcgate_circuit, gate_x, controls, target, ctrl_state="000")
controls_2 = QuantumRegister(3)
target_2 = QuantumRegister(1)
qiskit_circuit = QuantumCircuit(controls_2, target_2)
qiskit_circuit.append(MCXGate(len(controls_2), ctrl_state='000'),
[*controls_2, target_2])
state_qiskit = qclib.util.get_state(qiskit_circuit)
state_mcgate = qclib.util.get_state(mcgate_circuit)
self.assertTrue(np.allclose(state_qiskit, state_mcgate))
def test_mct_toffoli(self):
""" compare qiskit.mct and toffoli depth with 7 qubits """
gate_x = np.array([[0, 1], [1, 0]])
qcirc1 = qiskit.QuantumCircuit(6)
qcirc1.mcx([0, 1, 2, 3, 4], 5)
t_qcirc1 = qiskit.transpile(qcirc1, basis_gates=['u', 'cx'])
controls = QuantumRegister(5)
target = QuantumRegister(1)
qcirc2 = qiskit.QuantumCircuit(controls, target)
Ldmcu.ldmcu(qcirc2, gate_x, controls, target)
t_qcirc2 = qiskit.transpile(qcirc2, basis_gates=['u', 'cx'])
self.assertTrue(t_qcirc2.depth() < t_qcirc1.depth())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import pulse
d0 = pulse.DriveChannel(0)
x90 = pulse.Gaussian(10, 0.1, 3)
x180 = pulse.Gaussian(10, 0.2, 3)
def udd10_pos(j):
return np.sin(np.pi*j/(2*10 + 2))**2
with pulse.build() as udd_sched:
pulse.play(x90, d0)
with pulse.align_func(duration=300, func=udd10_pos):
for _ in range(10):
pulse.play(x180, d0)
pulse.play(x90, d0)
udd_sched.draw()
|
https://github.com/theflyingrahul/qiskitsummerschool2020
|
theflyingrahul
|
!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/kdk/qiskit-timeline-debugger
|
kdk
|
from qiskit import QuantumCircuit
from qiskit.test.mock import FakeCasablanca
from qiskit_trebugger import Debugger
import warnings
warnings.simplefilter('ignore')
debugger = Debugger()
backend = FakeCasablanca()
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0,1)
circuit.measure_all()
# replace transpile call
debugger.debug(circuit, backend = backend, initial_layout = [0,1])
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
import numpy as np
np.random.seed(999999)
target_distr = np.random.rand(2)
# We now convert the random vector into a valid probability vector
target_distr /= sum(target_distr)
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
def get_var_form(params):
qr = QuantumRegister(1, name="q")
cr = ClassicalRegister(1, name='c')
qc = QuantumCircuit(qr, cr)
qc.u3(params[0], params[1], params[2], qr[0])
qc.measure(qr, cr[0])
return qc
from qiskit import Aer, execute
backend = Aer.get_backend("qasm_simulator")
NUM_SHOTS = 10000
def get_probability_distribution(counts):
output_distr = [v / NUM_SHOTS for v in counts.values()]
if len(output_distr) == 1:
output_distr.append(0)
return output_distr
def objective_function(params):
# Obtain a quantum circuit instance from the paramters
qc = get_var_form(params)
# Execute the quantum circuit to obtain the probability distribution associated with the current parameters
result = execute(qc, backend, shots=NUM_SHOTS).result()
# Obtain the counts for each measured state, and convert those counts into a probability vector
output_distr = get_probability_distribution(result.get_counts(qc))
# Calculate the cost as the distance between the output distribution and the target distribution
cost = sum([np.abs(output_distr[i] - target_distr[i]) for i in range(2)])
return cost
from qiskit.aqua.components.optimizers import COBYLA
# Initialize the COBYLA optimizer
optimizer = COBYLA(maxiter=500, tol=0.0001)
# Create the initial parameters (noting that our single qubit variational form has 3 parameters)
params = np.random.rand(3)
ret = optimizer.optimize(num_vars=3, objective_function=objective_function, initial_point=params)
# Obtain the output distribution using the final parameters
qc = get_var_form(ret[0])
counts = execute(qc, backend, shots=NUM_SHOTS).result().get_counts(qc)
output_distr = get_probability_distribution(counts)
print("Target Distribution:", target_distr)
print("Obtained Distribution:", output_distr)
print("Output Error (Manhattan Distance):", ret[1])
print("Parameters Found:", ret[0])
from qiskit.aqua.components.variational_forms import RYRZ
entanglements = ["linear", "full"]
for entanglement in entanglements:
form = RYRZ(num_qubits=4, depth=1, entanglement=entanglement)
if entanglement == "linear":
print("=============Linear Entanglement:=============")
else:
print("=============Full Entanglement:=============")
# We initialize all parameters to 0 for this demonstration
print(form.construct_circuit([0] * form.num_parameters).draw(line_length=100))
print()
from qiskit.aqua.algorithms import VQE, ExactEigensolver
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit.chemistry.aqua_extensions.components.variational_forms import UCCSD
from qiskit.aqua.components.variational_forms import RYRZ
from qiskit.chemistry.aqua_extensions.components.initial_states import HartreeFock
from qiskit.aqua.components.optimizers import COBYLA, SPSA, SLSQP
from qiskit import IBMQ, BasicAer, Aer
from qiskit.chemistry.drivers import PySCFDriver, UnitsType
from qiskit.chemistry import FermionicOperator
from qiskit import IBMQ
from qiskit.providers.aer import noise
from qiskit.aqua import QuantumInstance
from qiskit.ignis.mitigation.measurement import CompleteMeasFitter
def get_qubit_op(dist):
driver = PySCFDriver(atom="Li .0 .0 .0; H .0 .0 " + str(dist), unit=UnitsType.ANGSTROM,
charge=0, spin=0, basis='sto3g')
molecule = driver.run()
freeze_list = [0]
remove_list = [-3, -2]
repulsion_energy = molecule.nuclear_repulsion_energy
num_particles = molecule.num_alpha + molecule.num_beta
num_spin_orbitals = molecule.num_orbitals * 2
remove_list = [x % molecule.num_orbitals for x in remove_list]
freeze_list = [x % molecule.num_orbitals for x in freeze_list]
remove_list = [x - len(freeze_list) for x in remove_list]
remove_list += [x + molecule.num_orbitals - len(freeze_list) for x in remove_list]
freeze_list += [x + molecule.num_orbitals for x in freeze_list]
ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals)
ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list)
num_spin_orbitals -= len(freeze_list)
num_particles -= len(freeze_list)
ferOp = ferOp.fermion_mode_elimination(remove_list)
num_spin_orbitals -= len(remove_list)
qubitOp = ferOp.mapping(map_type='parity', threshold=0.00000001)
qubitOp = qubitOp.two_qubit_reduced_operator(num_particles)
shift = energy_shift + repulsion_energy
return qubitOp, num_particles, num_spin_orbitals, shift
backend = BasicAer.get_backend("statevector_simulator")
distances = np.arange(0.5, 4.0, 0.1)
exact_energies = []
vqe_energies = []
optimizer = SLSQP(maxiter=5)
for dist in distances:
qubitOp, num_particles, num_spin_orbitals, shift = get_qubit_op(dist)
result = ExactEigensolver(qubitOp).run()
exact_energies.append(result['energy'] + shift)
initial_state = HartreeFock(
qubitOp.num_qubits,
num_spin_orbitals,
num_particles,
'parity'
)
var_form = UCCSD(
qubitOp.num_qubits,
depth=1,
num_orbitals=num_spin_orbitals,
num_particles=num_particles,
initial_state=initial_state,
qubit_mapping='parity'
)
vqe = VQE(qubitOp, var_form, optimizer, 'matrix')
results = vqe.run(backend)['energy'] + shift
vqe_energies.append(results)
print("Interatomic Distance:", np.round(dist, 2), "VQE Result:", results, "Exact Energy:", exact_energies[-1])
print("All energies have been calculated")
plt.plot(distances, exact_energies, label="Exact Energy")
plt.plot(distances, vqe_energies, label="VQE Energy")
plt.xlabel('Atomic distance (Angstrom)')
plt.ylabel('Energy')
plt.legend()
plt.show()
driver = PySCFDriver(atom='H .0 .0 -0.3625; H .0 .0 0.3625', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g')
molecule = driver.run()
num_particles = molecule.num_alpha + molecule.num_beta
qubitOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals).mapping(map_type='parity')
qubitOp = qubitOp.two_qubit_reduced_operator(num_particles)
IBMQ.load_account()
IBMQ.get_provider(hub='ibm-q')
backend = Aer.get_backend("qasm_simulator")
device = provider.get_backend("ibmqx4")
coupling_map = device.configuration().coupling_map
noise_model = noise.device.basic_device_noise_model(device.properties())
quantum_instance = QuantumInstance(backend=backend, shots=1000,
noise_model=noise_model,
coupling_map=coupling_map,
measurement_error_mitigation_cls=CompleteMeasFitter,
cals_matrix_refresh_period=30,)
exact_solution = ExactEigensolver(qubitOp).run()
print("Exact Result:", exact_solution['energy'])
optimizer = SPSA(max_trials=100)
var_form = RYRZ(qubitOp.num_qubits, depth=1, entanglement="linear")
vqe = VQE(qubitOp, var_form, optimizer=optimizer, operator_mode="grouped_paulis")
ret = vqe.run(quantum_instance)
print("VQE Result:", ret['energy'])
|
https://github.com/theflyingrahul/qiskitsummerschool2020
|
theflyingrahul
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
list_bin = []
for j in range(0,2**4):
b = "{:04b}".format(j)
list_bin.append(b)
print(list_bin)
list_int = []
for j in range(0,2**4):
list_int.append(int(list_bin[j],2))
print(list_int)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# 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.
"""
Quantum teleportation example.
Note: if you have only cloned the Qiskit repository but not
used `pip install`, the examples only work from the root directory.
"""
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import BasicAer
from qiskit import execute
###############################################################
# Set the backend name and coupling map.
###############################################################
coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]]
backend = BasicAer.get_backend("qasm_simulator")
###############################################################
# Make a quantum program for quantum teleportation.
###############################################################
q = QuantumRegister(3, "q")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
c2 = ClassicalRegister(1, "c2")
qc = QuantumCircuit(q, c0, c1, c2, name="teleport")
# Prepare an initial state
qc.u(0.3, 0.2, 0.1, q[0])
# Prepare a Bell pair
qc.h(q[1])
qc.cx(q[1], q[2])
# Barrier following state preparation
qc.barrier(q)
# Measure in the Bell basis
qc.cx(q[0], q[1])
qc.h(q[0])
qc.measure(q[0], c0[0])
qc.measure(q[1], c1[0])
# Apply a correction
qc.barrier(q)
qc.z(q[2]).c_if(c0, 1)
qc.x(q[2]).c_if(c1, 1)
qc.measure(q[2], c2[0])
###############################################################
# Execute.
# Experiment does not support feedback, so we use the simulator
###############################################################
# First version: not mapped
initial_layout = {q[0]: 0, q[1]: 1, q[2]: 2}
job = execute(qc, backend=backend, coupling_map=None, shots=1024, initial_layout=initial_layout)
result = job.result()
print(result.get_counts(qc))
# Second version: mapped to 2x8 array coupling graph
job = execute(
qc, backend=backend, coupling_map=coupling_map, shots=1024, initial_layout=initial_layout
)
result = job.result()
print(result.get_counts(qc))
# Both versions should give the same distribution
|
https://github.com/HayleySummer/Qiskit_Hackathon_Europe
|
HayleySummer
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
# Board A. Only valid move is first Tile
# 011
# 111
# 111
boardA = [ 0, 1, 1, 1, 1, 1, 1, 1, 1]
# Board B. Has Seven Valid moves
#000
#010
#010
boardB = [ 0, 0, 0, 0, 1, 0, 0, 1, 0]
# Board C. Has 5 Valid moves
# 000
# 000
# 010
boardC = [ 0, 0, 0, 0, 0, 0, 0, 1, 0]
# Board D. Has 2 Valid moves
# 001
# 111
# 111
boardD = [ 0, 0, 1, 1, 1, 1, 1, 1, 1]
# Params : circuit, BoardState, Auxillary Qubits, oracle
def othello_3x3_oracle(qc, boardQ, auxillary, oracle):
#Compute the search for the valid moves
# Start with contrived solution, Use a board with only 1 free space. The only valid answer is of the form 100 000 000
#qc.cx(auxillary[0],boardQ[0])
qc.cx(auxillary,boardQ)
qc.mct(boardQ, oracle) ### If the board is solved flip the output bit.
#Phase kickback because output_qubit is in superposition
#Uncompute the search for the valid moves
#qc.cx(auxillary[0],boardQ[0])
qc.cx(auxillary,boardQ)
return
def diffuser(nqubits):
qcDiff = QuantumCircuit(nqubits)
# Apply transformation |s> -> |00..0> (H-gates)
for qubit in range(nqubits):
qcDiff.h(qubit)
# Apply transformation |00..0> -> |11..1> (X-gates)
for qubit in range(nqubits):
qcDiff.x(qubit)
# Do multi-controlled-Z gate
qcDiff.h(nqubits-1)
qcDiff.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli
qcDiff.h(nqubits-1)
# Apply transformation |11..1> -> |00..0>
for qubit in range(nqubits):
qcDiff.x(qubit)
# Apply transformation |00..0> -> |s>
for qubit in range(nqubits):
qcDiff.h(qubit)
# We will return the diffuser as a gate
U_s = qcDiff.to_gate()
U_s.name = "$U_s$"
return U_s
def othelloMoveSearch ( boardRepresentation ):
# Create a 9 Qubit Register for the Quantum represntation of the board.
boardQ = QuantumRegister(9)
# Create a 9 Qubit Register for Auxillary Qubits for Grover Search
auxillary = QuantumRegister(9)
# Create a single Qubit Register for the Grover Search Oracle
oracle = QuantumRegister(1)
# Create a 2 Qubit Quantum Register [Not used yet]
qr = QuantumRegister(2)
# Create a 9 Bit Classical Register for the output
cr = ClassicalRegister(9)
# Create a quantum circuit containing the registers above
qc = QuantumCircuit(boardQ, auxillary, oracle, qr, cr)
# Put the Auxillary Qubits into SuperPosition of the Results.
qc.h(auxillary[:])
# Prepare the Oracle Qubit
qc.x(oracle[0])
qc.h(oracle[0])
# Set up the Quantum Representation of the board to match the current state of the board
for x in range(len( boardRepresentation )):
if boardRepresentation[x] > 0 :
qc.x(boardQ[x])
# Call the Grover Algorithm and Diffuser 16 times [Number of iterations varies according to search]
for i in range (16) :
othello_3x3_oracle(qc, boardQ, auxillary, oracle)
qc.append(diffuser(9), [9,10,11,12,13,14,15,16,17])
# Measure the status of the Quantum Board to verify the setup has worked.
qc.measure(auxillary,cr)
# Change the endian
qc = qc.reverse_bits()
#print ("Diagnostic Log 001")
return qc
# Create the circuit and print it on screen
qc1 = othelloMoveSearch( boardA )
qc1.draw(output="mpl")
#backend = BasicAer.get_backend('qasm_simulator')
backend = Aer.get_backend('qasm_simulator')
shots = 1024
results = execute(qc1, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer, number_to_keep=6)
|
https://github.com/rickapocalypse/final_paper_qiskit_sat
|
rickapocalypse
|
from qiskit import *
import matplotlib.pyplot as plt
from qiskit.tools.visualization import plot_histogram
secretnumber = '10000100001'
circuit = QuantumCircuit(len(secretnumber) + 1,len(secretnumber))
circuit.h(range(len(secretnumber)))
circuit.x(len(secretnumber))
circuit.h(len(secretnumber))
# circuit.draw(output ='mpl')
# plt.show()
circuit.barrier()
# circuit.draw(output ='mpl')
# plt.show()
for i in range(len(secretnumber)):
if secretnumber[i] == '1':
circuit.cx(len(secretnumber) - 1 - i, len(secretnumber))
# circuit.draw(output ='mpl')
# plt.show()
circuit.barrier()
circuit.h(range(len(secretnumber)))
# circuit.draw(output ='mpl')
# plt.show()
circuit.barrier()
circuit.measure(range(len(secretnumber)),range(len(secretnumber)))
circuit.draw(output ='mpl')
plt.show()
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend = simulator, shots = 1).result()
counts = result.get_counts()
print(counts)
|
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
qreg = QuantumRegister(4) # quantum register with 4 qubits
creg = ClassicalRegister(4) # classical register with 4 bits
mycircuit = QuantumCircuit(qreg,creg) # quantum circuit with quantum and classical registers
# apply h-gate (Hadamard) to each qubit
for i in range(4):
mycircuit.h(qreg[i])
# measure all qubits
mycircuit.measure(qreg,creg)
# execute the circuit 1600 times, and print the outcomes
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1600)
counts = job.result().get_counts(mycircuit)
for outcome in counts:
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print(reverse_outcome,"is observed",counts[outcome],"times")
# include our predefined functions
%run qlatvia.py
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import acos, pi
# after Hadamard operators
u = [(13/16)**0.5,(3/16)**0.5]
def angle_between_two_states(u1,u2):
dot_product = u1[0]*u2[0]+u1[1]*u2[1]
return acos(dot_product)
theta = angle_between_two_states(u,[1,0])
all_visited_quantum_states =[]
qreg2 = QuantumRegister(1) # quantum register with 1 qubit
creg2 = ClassicalRegister(1) # classical register with 1 bit
mycircuit2 = QuantumCircuit(qreg2,creg2) # quantum circuit with quantum and classical registers
# set the qubit to |u> by rotating it by theta
mycircuit2.ry(2*theta,qreg2[0])
# read and store the current quantum state
current_state = execute(mycircuit2,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit2)
[x,y] = [current_state[0].real,current_state[1].real]
all_visited_quantum_states.append([x,y,'u'])
# the first reflection
theta = angle_between_two_states([x,y],[1,0])
mycircuit2.ry(2*(-2*theta),qreg2[0])
# read and store the current quantum state
current_state = execute(mycircuit2,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit2)
[x,y] = [current_state[0].real,current_state[1].real]
all_visited_quantum_states.append([x,y,'r'])
# the second reflection
theta = angle_between_two_states(u,[x,y])
mycircuit2.ry(2*(2*theta),qreg2[0])
# read and store the current quantum state
current_state = execute(mycircuit2,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit2)
[x,y] = [current_state[0].real,current_state[1].real]
all_visited_quantum_states.append([x,y,'n'])
# measure the qubit
mycircuit2.measure(qreg2,creg2)
# execute the circuit 100 times, and print the outcomes
job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=100)
counts2 = job.result().get_counts(mycircuit2)
print(counts2)
# visualization
draw_qubit()
for quantum_state in all_visited_quantum_states:
draw_quantum_state(quantum_state[0],quantum_state[1],quantum_state[2])
# include our predefined functions
%run qlatvia.py
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import acos, pi
# after Hadamard operators
u = [(63/64)**0.5,(1/64)**0.5]
def angle_between_two_states(u1,u2):
dot_product = u1[0]*u2[0]+u1[1]*u2[1]
return acos(dot_product)
theta = angle_between_two_states(u,[1,0])
all_visited_quantum_states =[]
qreg3 = QuantumRegister(1) # quantum register with 1 qubit
creg3 = ClassicalRegister(1) # classical register with 1 bit
mycircuit3 = QuantumCircuit(qreg3,creg3) # quantum circuit with quantum and classical registers
# set the qubit to |u> by rotating it by theta
mycircuit3.ry(2*theta,qreg3[0])
# read and store the current quantum state
current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3)
[x,y] = [current_state[0].real,current_state[1].real]
all_visited_quantum_states.append([x,y,'u'])
# three iterations
for i in range(3): # 4,5,6,7,8,9,10
# the first reflection
theta = angle_between_two_states([x,y],[1,0])
mycircuit3.ry(2*(-2*theta),qreg3[0])
# read and store the current quantum state
current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3)
[x,y] = [current_state[0].real,current_state[1].real]
all_visited_quantum_states.append([x,y,'r'+str(i+1)])
# the second reflection
theta = angle_between_two_states(u,[x,y])
mycircuit3.ry(2*(2*theta),qreg3[0])
# read and store the current quantum state
current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3)
[x,y] = [current_state[0].real,current_state[1].real]
all_visited_quantum_states.append([x,y,'n'+str(i+1)])
# measure the qubit
mycircuit3.measure(qreg3,creg3)
# execute the circuit 100 times, and print the outcomes
job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=100)
counts3 = job.result().get_counts(mycircuit3)
print(counts3)
# visualization
draw_qubit()
for quantum_state in all_visited_quantum_states:
draw_quantum_state(quantum_state[0],quantum_state[1],quantum_state[2])
# include our predefined functions
%run qlatvia.py
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import acos, pi
# after Hadamard operators
u = [(4/16)**0.5,(12/16)**0.5]
def angle_between_two_states(u1,u2):
dot_product = u1[0]*u2[0]+u1[1]*u2[1]
return acos(dot_product)
theta = angle_between_two_states(u,[1,0])
all_visited_quantum_states = []
qreg3 = QuantumRegister(1) # quantum register with 1 qubit
creg3 = ClassicalRegister(1) # classical register with 1 bit
mycircuit3 = QuantumCircuit(qreg3,creg3) # quantum circuit with quantum and classical registers
# set the qubit to |u> by rotating it by theta
mycircuit3.ry(2*theta,qreg3[0])
# read and store the current quantum state
current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3)
[x,y] = [current_state[0].real,current_state[1].real]
all_visited_quantum_states.append([x,y,'u'])
# three iterations
number_of_iterations = 1 # 2, 3, and 4
for i in range(number_of_iterations):
# the first reflection
theta = angle_between_two_states([x,y],[1,0])
mycircuit3.ry(2*(-2*theta),qreg3[0])
# read and store the current quantum state
current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3)
[x,y] = [current_state[0].real,current_state[1].real]
if i == number_of_iterations -1: all_visited_quantum_states.append([x,y,'r'+str(i+1)])
# the second reflection
theta = angle_between_two_states(u,[x,y])
mycircuit3.ry(2*(2*theta),qreg3[0])
# read and store the current quantum state
current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3)
[x,y] = [current_state[0].real,current_state[1].real]
if i == number_of_iterations -1: all_visited_quantum_states.append([x,y,'n'+str(i+1)])
# measure the qubit
mycircuit3.measure(qreg3,creg3)
# execute the circuit 100 times, and print the outcomes
job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=100)
counts3 = job.result().get_counts(mycircuit3)
print(counts3)
# visualization
draw_qubit()
for quantum_state in all_visited_quantum_states:
draw_quantum_state(quantum_state[0],quantum_state[1],quantum_state[2])
|
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.
"""Tests for quantum channel representation transformations."""
import unittest
import numpy as np
from qiskit import QiskitError
from qiskit.quantum_info.states import DensityMatrix
from qiskit.quantum_info.operators.predicates import matrix_equal
from qiskit.quantum_info.operators.operator import Operator
from qiskit.quantum_info.operators.channel.choi import Choi
from qiskit.quantum_info.operators.channel.superop import SuperOp
from qiskit.quantum_info.operators.channel.kraus import Kraus
from qiskit.quantum_info.operators.channel.stinespring import Stinespring
from qiskit.quantum_info.operators.channel.ptm import PTM
from qiskit.quantum_info.operators.channel.chi import Chi
from .channel_test_case import ChannelTestCase
class TestTransformations(ChannelTestCase):
"""Tests for Operator channel representation."""
unitary_mat = [
ChannelTestCase.UI,
ChannelTestCase.UX,
ChannelTestCase.UY,
ChannelTestCase.UZ,
ChannelTestCase.UH,
]
unitary_choi = [
ChannelTestCase.choiI,
ChannelTestCase.choiX,
ChannelTestCase.choiY,
ChannelTestCase.choiZ,
ChannelTestCase.choiH,
]
unitary_chi = [
ChannelTestCase.chiI,
ChannelTestCase.chiX,
ChannelTestCase.chiY,
ChannelTestCase.chiZ,
ChannelTestCase.chiH,
]
unitary_sop = [
ChannelTestCase.sopI,
ChannelTestCase.sopX,
ChannelTestCase.sopY,
ChannelTestCase.sopZ,
ChannelTestCase.sopH,
]
unitary_ptm = [
ChannelTestCase.ptmI,
ChannelTestCase.ptmX,
ChannelTestCase.ptmY,
ChannelTestCase.ptmZ,
ChannelTestCase.ptmH,
]
def test_operator_to_operator(self):
"""Test Operator to Operator transformation."""
# Test unitary channels
for mat in self.unitary_mat:
chan1 = Operator(mat)
chan2 = Operator(chan1)
self.assertEqual(chan1, chan2)
def test_operator_to_choi(self):
"""Test Operator to Choi transformation."""
# Test unitary channels
for mat, choi in zip(self.unitary_mat, self.unitary_choi):
chan1 = Choi(choi)
chan2 = Choi(Operator(mat))
self.assertEqual(chan1, chan2)
def test_operator_to_superop(self):
"""Test Operator to SuperOp transformation."""
# Test unitary channels
for mat, sop in zip(self.unitary_mat, self.unitary_sop):
chan1 = SuperOp(sop)
chan2 = SuperOp(Operator(mat))
self.assertEqual(chan1, chan2)
def test_operator_to_kraus(self):
"""Test Operator to Kraus transformation."""
# Test unitary channels
for mat in self.unitary_mat:
chan1 = Kraus(mat)
chan2 = Kraus(Operator(mat))
self.assertEqual(chan1, chan2)
def test_operator_to_stinespring(self):
"""Test Operator to Stinespring transformation."""
# Test unitary channels
for mat in self.unitary_mat:
chan1 = Stinespring(mat)
chan2 = Stinespring(Operator(chan1))
self.assertEqual(chan1, chan2)
def test_operator_to_chi(self):
"""Test Operator to Chi transformation."""
# Test unitary channels
for mat, chi in zip(self.unitary_mat, self.unitary_chi):
chan1 = Chi(chi)
chan2 = Chi(Operator(mat))
self.assertEqual(chan1, chan2)
def test_operator_to_ptm(self):
"""Test Operator to PTM transformation."""
# Test unitary channels
for mat, ptm in zip(self.unitary_mat, self.unitary_ptm):
chan1 = PTM(ptm)
chan2 = PTM(Operator(mat))
self.assertEqual(chan1, chan2)
def test_choi_to_operator(self):
"""Test Choi to Operator transformation."""
# Test unitary channels
for mat, choi in zip(self.unitary_mat, self.unitary_choi):
chan1 = Operator(mat)
chan2 = Operator(Choi(choi))
self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True))
def test_choi_to_choi(self):
"""Test Choi to Choi transformation."""
# Test unitary channels
for choi in self.unitary_choi:
chan1 = Choi(choi)
chan2 = Choi(chan1)
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Choi(self.depol_choi(p))
chan2 = Choi(chan1)
self.assertEqual(chan1, chan2)
def test_choi_to_superop(self):
"""Test Choi to SuperOp transformation."""
# Test unitary channels
for choi, sop in zip(self.unitary_choi, self.unitary_sop):
chan1 = SuperOp(sop)
chan2 = SuperOp(Choi(choi))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = SuperOp(self.depol_sop(p))
chan2 = SuperOp(Choi(self.depol_choi(p)))
self.assertEqual(chan1, chan2)
def test_choi_to_kraus(self):
"""Test Choi to Kraus transformation."""
# Test unitary channels
for mat, choi in zip(self.unitary_mat, self.unitary_choi):
chan1 = Kraus(mat)
chan2 = Kraus(Choi(choi))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Kraus(self.depol_kraus(p)))
output = rho.evolve(Kraus(Choi(self.depol_choi(p))))
self.assertEqual(output, target)
def test_choi_to_stinespring(self):
"""Test Choi to Stinespring transformation."""
# Test unitary channels
for mat, choi in zip(self.unitary_mat, self.unitary_choi):
chan1 = Kraus(mat)
chan2 = Kraus(Choi(choi))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Stinespring(self.depol_stine(p)))
output = rho.evolve(Stinespring(Choi(self.depol_choi(p))))
self.assertEqual(output, target)
def test_choi_to_chi(self):
"""Test Choi to Chi transformation."""
# Test unitary channels
for choi, chi in zip(self.unitary_choi, self.unitary_chi):
chan1 = Chi(chi)
chan2 = Chi(Choi(choi))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Chi(self.depol_chi(p))
chan2 = Chi(Choi(self.depol_choi(p)))
self.assertEqual(chan1, chan2)
def test_choi_to_ptm(self):
"""Test Choi to PTM transformation."""
# Test unitary channels
for choi, ptm in zip(self.unitary_choi, self.unitary_ptm):
chan1 = PTM(ptm)
chan2 = PTM(Choi(choi))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = PTM(self.depol_ptm(p))
chan2 = PTM(Choi(self.depol_choi(p)))
self.assertEqual(chan1, chan2)
def test_superop_to_operator(self):
"""Test SuperOp to Operator transformation."""
for mat, sop in zip(self.unitary_mat, self.unitary_sop):
chan1 = Operator(mat)
chan2 = Operator(SuperOp(sop))
self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True))
self.assertRaises(QiskitError, Operator, SuperOp(self.depol_sop(0.5)))
def test_superop_to_choi(self):
"""Test SuperOp to Choi transformation."""
# Test unitary channels
for choi, sop in zip(self.unitary_choi, self.unitary_sop):
chan1 = Choi(choi)
chan2 = Choi(SuperOp(sop))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0, 0.25, 0.5, 0.75, 1]:
chan1 = Choi(self.depol_choi(p))
chan2 = Choi(SuperOp(self.depol_sop(p)))
self.assertEqual(chan1, chan2)
def test_superop_to_superop(self):
"""Test SuperOp to SuperOp transformation."""
# Test unitary channels
for sop in self.unitary_sop:
chan1 = SuperOp(sop)
chan2 = SuperOp(chan1)
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0, 0.25, 0.5, 0.75, 1]:
chan1 = SuperOp(self.depol_sop(p))
chan2 = SuperOp(chan1)
self.assertEqual(chan1, chan2)
def test_superop_to_kraus(self):
"""Test SuperOp to Kraus transformation."""
# Test unitary channels
for mat, sop in zip(self.unitary_mat, self.unitary_sop):
chan1 = Kraus(mat)
chan2 = Kraus(SuperOp(sop))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Kraus(self.depol_kraus(p)))
output = rho.evolve(Kraus(SuperOp(self.depol_sop(p))))
self.assertEqual(output, target)
def test_superop_to_stinespring(self):
"""Test SuperOp to Stinespring transformation."""
# Test unitary channels
for mat, sop in zip(self.unitary_mat, self.unitary_sop):
chan1 = Stinespring(mat)
chan2 = Stinespring(SuperOp(sop))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Stinespring(self.depol_stine(p)))
output = rho.evolve(Stinespring(SuperOp(self.depol_sop(p))))
self.assertEqual(output, target)
def test_superop_to_chi(self):
"""Test SuperOp to Chi transformation."""
# Test unitary channels
for sop, ptm in zip(self.unitary_sop, self.unitary_ptm):
chan1 = PTM(ptm)
chan2 = PTM(SuperOp(sop))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Chi(self.depol_chi(p))
chan2 = Chi(SuperOp(self.depol_sop(p)))
self.assertEqual(chan1, chan2)
def test_superop_to_ptm(self):
"""Test SuperOp to PTM transformation."""
# Test unitary channels
for sop, ptm in zip(self.unitary_sop, self.unitary_ptm):
chan1 = PTM(ptm)
chan2 = PTM(SuperOp(sop))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = PTM(self.depol_ptm(p))
chan2 = PTM(SuperOp(self.depol_sop(p)))
self.assertEqual(chan1, chan2)
def test_kraus_to_operator(self):
"""Test Kraus to Operator transformation."""
for mat in self.unitary_mat:
chan1 = Operator(mat)
chan2 = Operator(Kraus(mat))
self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True))
self.assertRaises(QiskitError, Operator, Kraus(self.depol_kraus(0.5)))
def test_kraus_to_choi(self):
"""Test Kraus to Choi transformation."""
# Test unitary channels
for mat, choi in zip(self.unitary_mat, self.unitary_choi):
chan1 = Choi(choi)
chan2 = Choi(Kraus(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Choi(self.depol_choi(p))
chan2 = Choi(Kraus(self.depol_kraus(p)))
self.assertEqual(chan1, chan2)
def test_kraus_to_superop(self):
"""Test Kraus to SuperOp transformation."""
# Test unitary channels
for mat, sop in zip(self.unitary_mat, self.unitary_sop):
chan1 = SuperOp(sop)
chan2 = SuperOp(Kraus(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = SuperOp(self.depol_sop(p))
chan2 = SuperOp(Kraus(self.depol_kraus(p)))
self.assertEqual(chan1, chan2)
def test_kraus_to_kraus(self):
"""Test Kraus to Kraus transformation."""
# Test unitary channels
for mat in self.unitary_mat:
chan1 = Kraus(mat)
chan2 = Kraus(chan1)
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Kraus(self.depol_kraus(p))
chan2 = Kraus(chan1)
self.assertEqual(chan1, chan2)
def test_kraus_to_stinespring(self):
"""Test Kraus to Stinespring transformation."""
# Test unitary channels
for mat in self.unitary_mat:
chan1 = Stinespring(mat)
chan2 = Stinespring(Kraus(mat))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Stinespring(self.depol_stine(p)))
output = rho.evolve(Stinespring(Kraus(self.depol_kraus(p))))
self.assertEqual(output, target)
def test_kraus_to_chi(self):
"""Test Kraus to Chi transformation."""
# Test unitary channels
for mat, chi in zip(self.unitary_mat, self.unitary_chi):
chan1 = Chi(chi)
chan2 = Chi(Kraus(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Chi(self.depol_chi(p))
chan2 = Chi(Kraus(self.depol_kraus(p)))
self.assertEqual(chan1, chan2)
def test_kraus_to_ptm(self):
"""Test Kraus to PTM transformation."""
# Test unitary channels
for mat, ptm in zip(self.unitary_mat, self.unitary_ptm):
chan1 = PTM(ptm)
chan2 = PTM(Kraus(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = PTM(self.depol_ptm(p))
chan2 = PTM(Kraus(self.depol_kraus(p)))
self.assertEqual(chan1, chan2)
def test_stinespring_to_operator(self):
"""Test Stinespring to Operator transformation."""
for mat in self.unitary_mat:
chan1 = Operator(mat)
chan2 = Operator(Stinespring(mat))
self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True))
self.assertRaises(QiskitError, Operator, Stinespring(self.depol_stine(0.5)))
def test_stinespring_to_choi(self):
"""Test Stinespring to Choi transformation."""
# Test unitary channels
for mat, choi in zip(self.unitary_mat, self.unitary_choi):
chan1 = Choi(choi)
chan2 = Choi(Stinespring(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Choi(self.depol_choi(p))
chan2 = Choi(Stinespring(self.depol_stine(p)))
self.assertEqual(chan1, chan2)
def test_stinespring_to_superop(self):
"""Test Stinespring to SuperOp transformation."""
# Test unitary channels
for mat, sop in zip(self.unitary_mat, self.unitary_sop):
chan1 = SuperOp(sop)
chan2 = SuperOp(Kraus(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = SuperOp(self.depol_sop(p))
chan2 = SuperOp(Stinespring(self.depol_stine(p)))
self.assertEqual(chan1, chan2)
def test_stinespring_to_kraus(self):
"""Test Stinespring to Kraus transformation."""
# Test unitary channels
for mat in self.unitary_mat:
chan1 = Kraus(mat)
chan2 = Kraus(Stinespring(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Kraus(self.depol_kraus(p))
chan2 = Kraus(Stinespring(self.depol_stine(p)))
self.assertEqual(chan1, chan2)
def test_stinespring_to_stinespring(self):
"""Test Stinespring to Stinespring transformation."""
# Test unitary channels
for mat in self.unitary_mat:
chan1 = Stinespring(mat)
chan2 = Stinespring(chan1)
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Stinespring(self.depol_stine(p))
chan2 = Stinespring(chan1)
self.assertEqual(chan1, chan2)
def test_stinespring_to_chi(self):
"""Test Stinespring to Chi transformation."""
# Test unitary channels
for mat, chi in zip(self.unitary_mat, self.unitary_chi):
chan1 = Chi(chi)
chan2 = Chi(Stinespring(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Chi(self.depol_chi(p))
chan2 = Chi(Stinespring(self.depol_stine(p)))
self.assertEqual(chan1, chan2)
def test_stinespring_to_ptm(self):
"""Test Stinespring to PTM transformation."""
# Test unitary channels
for mat, ptm in zip(self.unitary_mat, self.unitary_ptm):
chan1 = PTM(ptm)
chan2 = PTM(Stinespring(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = PTM(self.depol_ptm(p))
chan2 = PTM(Stinespring(self.depol_stine(p)))
self.assertEqual(chan1, chan2)
def test_chi_to_operator(self):
"""Test Chi to Operator transformation."""
for mat, chi in zip(self.unitary_mat, self.unitary_chi):
chan1 = Operator(mat)
chan2 = Operator(Chi(chi))
self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True))
self.assertRaises(QiskitError, Operator, Chi(self.depol_chi(0.5)))
def test_chi_to_choi(self):
"""Test Chi to Choi transformation."""
# Test unitary channels
for chi, choi in zip(self.unitary_chi, self.unitary_choi):
chan1 = Choi(choi)
chan2 = Choi(Chi(chi))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Choi(self.depol_choi(p))
chan2 = Choi(Chi(self.depol_chi(p)))
self.assertEqual(chan1, chan2)
def test_chi_to_superop(self):
"""Test Chi to SuperOp transformation."""
# Test unitary channels
for chi, sop in zip(self.unitary_chi, self.unitary_sop):
chan1 = SuperOp(sop)
chan2 = SuperOp(Chi(chi))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = SuperOp(self.depol_sop(p))
chan2 = SuperOp(Chi(self.depol_chi(p)))
self.assertEqual(chan1, chan2)
def test_chi_to_kraus(self):
"""Test Chi to Kraus transformation."""
# Test unitary channels
for mat, chi in zip(self.unitary_mat, self.unitary_chi):
chan1 = Kraus(mat)
chan2 = Kraus(Chi(chi))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Kraus(self.depol_kraus(p)))
output = rho.evolve(Kraus(Chi(self.depol_chi(p))))
self.assertEqual(output, target)
def test_chi_to_stinespring(self):
"""Test Chi to Stinespring transformation."""
# Test unitary channels
for mat, chi in zip(self.unitary_mat, self.unitary_chi):
chan1 = Kraus(mat)
chan2 = Kraus(Chi(chi))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Stinespring(self.depol_stine(p)))
output = rho.evolve(Stinespring(Chi(self.depol_chi(p))))
self.assertEqual(output, target)
def test_chi_to_chi(self):
"""Test Chi to Chi transformation."""
# Test unitary channels
for chi in self.unitary_chi:
chan1 = Chi(chi)
chan2 = Chi(chan1)
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Chi(self.depol_chi(p))
chan2 = Chi(chan1)
self.assertEqual(chan1, chan2)
def test_chi_to_ptm(self):
"""Test Chi to PTM transformation."""
# Test unitary channels
for chi, ptm in zip(self.unitary_chi, self.unitary_ptm):
chan1 = PTM(ptm)
chan2 = PTM(Chi(chi))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = PTM(self.depol_ptm(p))
chan2 = PTM(Chi(self.depol_chi(p)))
self.assertEqual(chan1, chan2)
def test_ptm_to_operator(self):
"""Test PTM to Operator transformation."""
for mat, ptm in zip(self.unitary_mat, self.unitary_ptm):
chan1 = Operator(mat)
chan2 = Operator(PTM(ptm))
self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True))
self.assertRaises(QiskitError, Operator, PTM(self.depol_ptm(0.5)))
def test_ptm_to_choi(self):
"""Test PTM to Choi transformation."""
# Test unitary channels
for ptm, choi in zip(self.unitary_ptm, self.unitary_choi):
chan1 = Choi(choi)
chan2 = Choi(PTM(ptm))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Choi(self.depol_choi(p))
chan2 = Choi(PTM(self.depol_ptm(p)))
self.assertEqual(chan1, chan2)
def test_ptm_to_superop(self):
"""Test PTM to SuperOp transformation."""
# Test unitary channels
for ptm, sop in zip(self.unitary_ptm, self.unitary_sop):
chan1 = SuperOp(sop)
chan2 = SuperOp(PTM(ptm))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = SuperOp(self.depol_sop(p))
chan2 = SuperOp(PTM(self.depol_ptm(p)))
self.assertEqual(chan1, chan2)
def test_ptm_to_kraus(self):
"""Test PTM to Kraus transformation."""
# Test unitary channels
for mat, ptm in zip(self.unitary_mat, self.unitary_ptm):
chan1 = Kraus(mat)
chan2 = Kraus(PTM(ptm))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Kraus(self.depol_kraus(p)))
output = rho.evolve(Kraus(PTM(self.depol_ptm(p))))
self.assertEqual(output, target)
def test_ptm_to_stinespring(self):
"""Test PTM to Stinespring transformation."""
# Test unitary channels
for mat, ptm in zip(self.unitary_mat, self.unitary_ptm):
chan1 = Kraus(mat)
chan2 = Kraus(PTM(ptm))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Stinespring(self.depol_stine(p)))
output = rho.evolve(Stinespring(PTM(self.depol_ptm(p))))
self.assertEqual(output, target)
def test_ptm_to_chi(self):
"""Test PTM to Chi transformation."""
# Test unitary channels
for chi, ptm in zip(self.unitary_chi, self.unitary_ptm):
chan1 = Chi(chi)
chan2 = Chi(PTM(ptm))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Chi(self.depol_chi(p))
chan2 = Chi(PTM(self.depol_ptm(p)))
self.assertEqual(chan1, chan2)
def test_ptm_to_ptm(self):
"""Test PTM to PTM transformation."""
# Test unitary channels
for ptm in self.unitary_ptm:
chan1 = PTM(ptm)
chan2 = PTM(chan1)
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = PTM(self.depol_ptm(p))
chan2 = PTM(chan1)
self.assertEqual(chan1, chan2)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
import numpy as np
from qiskit.circuit import ParameterVector
from qiskit.circuit.library import TwoLocal
from qiskit.quantum_info import Statevector
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.applications.estimation import EuropeanCallPricing
from qiskit_finance.circuit.library import NormalDistribution
# Set upper and lower data values
bounds = np.array([0.0, 7.0])
# Set number of qubits used in the uncertainty model
num_qubits = 3
# Load the trained circuit parameters
g_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225]
# Set an initial state for the generator circuit
init_dist = NormalDistribution(num_qubits, mu=1.0, sigma=1.0, bounds=bounds)
# construct the variational form
var_form = TwoLocal(num_qubits, "ry", "cz", entanglement="circular", reps=1)
# keep a list of the parameters so we can associate them to the list of numerical values
# (otherwise we need a dictionary)
theta = var_form.ordered_parameters
# compose the generator circuit, this is the circuit loading the uncertainty model
g_circuit = init_dist.compose(var_form)
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price = 2
# set the approximation scaling for the payoff function
c_approx = 0.25
# Evaluate trained probability distribution
values = [
bounds[0] + (bounds[1] - bounds[0]) * x / (2**num_qubits - 1) for x in range(2**num_qubits)
]
uncertainty_model = g_circuit.assign_parameters(dict(zip(theta, g_params)))
amplitudes = Statevector.from_instruction(uncertainty_model).data
x = np.array(values)
y = np.abs(amplitudes) ** 2
# Sample from target probability distribution
N = 100000
log_normal = np.random.lognormal(mean=1, sigma=1, size=N)
log_normal = np.round(log_normal)
log_normal = log_normal[log_normal <= 7]
log_normal_samples = []
for i in range(8):
log_normal_samples += [np.sum(log_normal == i)]
log_normal_samples = np.array(log_normal_samples / sum(log_normal_samples))
# Plot distributions
plt.bar(x, y, width=0.2, label="trained distribution", color="royalblue")
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.grid()
plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15)
plt.ylabel("Probability ($\%$)", size=15)
plt.plot(
log_normal_samples,
"-o",
color="deepskyblue",
label="target distribution",
linewidth=4,
markersize=12,
)
plt.legend(loc="best")
plt.show()
# Evaluate payoff for different distributions
payoff = np.array([0, 0, 0, 1, 2, 3, 4, 5])
ep = np.dot(log_normal_samples, payoff)
print("Analytically calculated expected payoff w.r.t. the target distribution: %.4f" % ep)
ep_trained = np.dot(y, payoff)
print("Analytically calculated expected payoff w.r.t. the trained distribution: %.4f" % ep_trained)
# Plot exact payoff function (evaluated on the grid of the trained uncertainty model)
x = np.array(values)
y_strike = np.maximum(0, x - strike_price)
plt.plot(x, y_strike, "ro-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# construct circuit for payoff function
european_call_pricing = EuropeanCallPricing(
num_qubits,
strike_price=strike_price,
rescaling_factor=c_approx,
bounds=bounds,
uncertainty_model=uncertainty_model,
)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = european_call_pricing.to_estimation_problem()
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % ep_trained)
print("Estimated value: \t%.4f" % (result.estimation_processed))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
import qiskit
from qiskit import Aer, QuantumCircuit
from qiskit.utils import QuantumInstance
from qiskit.opflow import AerPauliExpectation
from qiskit.circuit import Parameter
from qiskit_machine_learning.neural_networks import CircuitQNN
from qiskit_machine_learning.connectors import TorchConnector
qi = QuantumInstance(Aer.get_backend('statevector_simulator'))
qiskit.__qiskit_version__
import numpy as np
from numpy import pi
import matplotlib.pyplot as plt
from sklearn.utils import shuffle
from pandas.core.common import flatten
import torch
from torch import Tensor
from torch.nn import Linear, CrossEntropyLoss, MSELoss
from torch.optim import LBFGS, SGD,Adam
import torch.optim as optim
torch.cuda.is_available()
# import the example dataset from the folder
# data = array([x1,y1],[x2,y2],[x3,y3],.....,[x1500,y1500])
# label = array([0,0,0,....,1,1,1])
data0Path = r'data.txt'
data0Label = r'datalabel.txt'
dataCoords = np.loadtxt(data0Path)
dataLabels = np.loadtxt(data0Label)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2],
np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o')
ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2],
np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o')
# Change the data structure for shuffling
# We are taking 100 data to train the model
np.random.seed(2)
data1 = list(zip(dataCoords, dataLabels))
data_ixs = np.random.choice(len(data1), size=100)
# Transform the data to work with the pytorch optimizer.
# data coordinate X is [x1,y1,x1,y1] to embed in four-qubit circuit.
X= [np.array(list(flatten([data1[j][0],data1[j][0]]))) for j in data_ixs]
y01 = [data1[j][1] for j in data_ixs]
X_ = Tensor(X)
y01_ = Tensor(y01).reshape(len(y01)).long()
n=4;
feature_map = QuantumCircuit(n, name='Embed')
feature_map.rx(Parameter('x[0]'),0)
feature_map.rx(Parameter('x[1]'),1)
feature_map.rx(Parameter('x[2]'),2)
feature_map.rx(Parameter('x[3]'),3)
for i in range(n):
feature_map.ry(pi/4,i)
for i in range(n):
feature_map.rz(pi/4,i)
feature_map.draw('mpl')
param_y=[];
for i in range(8):
param_y.append((Parameter('θ'+str(i))))
ansatz = QuantumCircuit(n, name='PQC')
for i in range(n):
ansatz.ry(param_y[i],i)
for i in range(n):
ansatz.rz(param_y[i+4],i)
ansatz.draw('mpl')
def binary(x):
return ('0'*(4-len('{:b}'.format(x) ))+'{:b}'.format(x))
def firsttwo(x):
return x[:2]
parity = lambda x: firsttwo(binary(x)).count('1') % 2
[parity(i) for i in range(16)]
qc = QuantumCircuit(n)
qc.append(feature_map, range(n))
qc.append(ansatz, range(n))
qc.draw('mpl')
# Model for LBFGS
# Combining the circuit together with CircuitQNN
np.random.seed(3)
qnn2 = CircuitQNN(qc, input_params=feature_map.parameters, weight_params=ansatz.parameters,
interpret=parity, output_shape=2, quantum_instance=qi)
initial_weights = 0.1*(2*np.random.rand(qnn2.num_weights) - 1)
model2 = TorchConnector(qnn2, initial_weights)
# Model for Adam
np.random.seed(3)
qnn3 = CircuitQNN(qc, input_params=feature_map.parameters, weight_params=ansatz.parameters,
interpret=parity, output_shape=2, quantum_instance=qi)
initial_weights = 0.1*(2*np.random.rand(qnn3.num_weights) - 1)
model3 = TorchConnector(qnn3, initial_weights)
# define optimizer and loss function
optimizer = LBFGS(model2.parameters(),lr=0.01)
f_loss = CrossEntropyLoss()
# start training
model2.train() # set model to training mode
# define objective function
def closure():
optimizer.zero_grad() # initialize gradient
loss = 0.0 # initialize loss
for x, y_target in zip(X, y01): # evaluate batch loss
output = model2(Tensor(x)).reshape(1, 2) # forward pass
loss += f_loss(output, Tensor([y_target]).long())
loss.backward() # backward pass
print(loss.item()) # print loss
return loss
# run optimizer
optimizer.step(closure)
# evaluate model and compute accuracy
y_predict = []
for x in X:
output = model2(Tensor(x))
y_predict += [np.argmax(output.detach().numpy())]
print('Accuracy:', sum(y_predict == np.array(y01))/len(np.array(y01)))
# plot results
# red == wrongly classified
for x, y_target, y_ in zip(X, y01, y_predict):
if y_target == 1:
plt.plot(x[0], x[1], 'bo')
else:
plt.plot(x[0], x[1], 'go')
if y_target != y_:
plt.scatter(x[0], x[1], s=200, facecolors='none', edgecolors='r', linewidths=2)
plt.show()
for x, y_target, y_ in zip(X, y01, y_predict):
if y_target == 1:
plt.plot(x[0], x[1], 'bo')
else:
plt.plot(x[0], x[1], 'go')
X1 = np.linspace(0, 1, num=10)
Z1 = np.zeros((len(X1), len(X1)))
# Contour map
for j in range(len(X1)):
for k in range(len(X1)):
# Fill Z with the labels (numerical values)
# the inner loop goes over the columns of Z,
# which corresponds to sweeping x-values
# Therefore, the role of j,k is flipped in the signature
Z1[j, k] = np.argmax(model2(Tensor([X1[k],X1[j],X1[k],X1[j]])).detach().numpy())
plt.contourf(X1, X1, Z1, cmap='bwr', levels=30)
# Converged paramter for the PQC
for p in model2.parameters():
print(p.data)
optimizer = optim.Adam(model3.parameters(),lr=0.05)
f_loss = MSELoss(reduction='mean')
model3.train()
epochs = 10 # set number of epochs
for epoch in range(epochs):
optimizer.zero_grad()
loss = 0.0
for x, y_target in zip(X, y01):
output = model3(Tensor(x)).reshape(1, 2)
targets=Tensor([y_target]).long()
targets = targets.to(torch.float32)
loss += f_loss(output, targets)
loss.backward()
print(loss.item())
optimizer.step()
y_predict = []
for x in X:
output = model3(Tensor(x))
y_predict += [np.argmax(output.detach().numpy())]
print('Accuracy:', sum(y_predict == np.array(y01))/len(np.array(y01)))
for x, y_target, y_ in zip(X, y01, y_predict):
if y_target == 1:
plt.plot(x[0], x[1], 'bo')
else:
plt.plot(x[0], x[1], 'go')
if y_target != y_:
plt.scatter(x[0], x[1], s=200, facecolors='none', edgecolors='r', linewidths=2)
plt.show()
for x, y_target, y_ in zip(X, y01, y_predict):
if y_target == 1:
plt.plot(x[0], x[1], 'bo')
else:
plt.plot(x[0], x[1], 'go')
X1 = np.linspace(0, 1, num=10)
Z1 = np.zeros((len(X1), len(X1)))
for j in range(len(X1)):
for k in range(len(X1)):
Z1[j, k] = np.argmax(model3(Tensor([X1[k],X1[j],X1[k],X1[j]])).detach().numpy())
plt.contourf(X1, X1, Z1, cmap='bwr', levels=30)
for p in model3.parameters():
print(p.data)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import QuantumCircuit
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit.circuit.library import LinearAmplitudeFunction
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import LogNormalDistribution
# number of qubits to represent the uncertainty
num_uncertainty_qubits = 3
# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity
# resulting parameters for log-normal distribution
mu = (r - 0.5 * vol**2) * T + np.log(S)
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2 / 2)
variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3 * stddev)
high = mean + 3 * stddev
# construct A operator for QAE for the payoff function by
# composing the uncertainty model and the objective
uncertainty_model = LogNormalDistribution(
num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high)
)
# plot probability distribution
x = uncertainty_model.values
y = uncertainty_model.probabilities
plt.bar(x, y, width=0.2)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.grid()
plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15)
plt.ylabel("Probability ($\%$)", size=15)
plt.show()
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price = 1.896
# set the approximation scaling for the payoff function
c_approx = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [low, strike_price]
slopes = [0, 1]
offsets = [0, 0]
f_min = 0
f_max = high - strike_price
european_call_objective = LinearAmplitudeFunction(
num_uncertainty_qubits,
slopes,
offsets,
domain=(low, high),
image=(f_min, f_max),
breakpoints=breakpoints,
rescaling_factor=c_approx,
)
# construct A operator for QAE for the payoff function by
# composing the uncertainty model and the objective
num_qubits = european_call_objective.num_qubits
european_call = QuantumCircuit(num_qubits)
european_call.append(uncertainty_model, range(num_uncertainty_qubits))
european_call.append(european_call_objective, range(num_qubits))
# draw the circuit
european_call.draw()
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = uncertainty_model.values
y = np.maximum(0, x - strike_price)
plt.plot(x, y, "ro-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value (normalized to the [0, 1] interval)
exact_value = np.dot(uncertainty_model.probabilities, y)
exact_delta = sum(uncertainty_model.probabilities[x >= strike_price])
print("exact expected value:\t%.4f" % exact_value)
print("exact delta value: \t%.4f" % exact_delta)
european_call.draw()
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=european_call,
objective_qubits=[3],
post_processing=european_call_objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % exact_value)
print("Estimated value: \t%.4f" % (result.estimation_processed))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
from qiskit_finance.applications.estimation import EuropeanCallPricing
european_call_pricing = EuropeanCallPricing(
num_state_qubits=num_uncertainty_qubits,
strike_price=strike_price,
rescaling_factor=c_approx,
bounds=(low, high),
uncertainty_model=uncertainty_model,
)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = european_call_pricing.to_estimation_problem()
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % exact_value)
print("Estimated value: \t%.4f" % (european_call_pricing.interpret(result)))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
from qiskit_finance.applications.estimation import EuropeanCallDelta
european_call_delta = EuropeanCallDelta(
num_state_qubits=num_uncertainty_qubits,
strike_price=strike_price,
bounds=(low, high),
uncertainty_model=uncertainty_model,
)
european_call_delta._objective.decompose().draw()
european_call_delta_circ = QuantumCircuit(european_call_delta._objective.num_qubits)
european_call_delta_circ.append(uncertainty_model, range(num_uncertainty_qubits))
european_call_delta_circ.append(
european_call_delta._objective, range(european_call_delta._objective.num_qubits)
)
european_call_delta_circ.draw()
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = european_call_delta.to_estimation_problem()
# construct amplitude estimation
ae_delta = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_delta = ae_delta.estimate(problem)
conf_int = np.array(result_delta.confidence_interval_processed)
print("Exact delta: \t%.4f" % exact_delta)
print("Esimated value: \t%.4f" % european_call_delta.interpret(result_delta))
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
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)
return qc
def decode_message(qc):
qc.cx(1, 0)
### removed h gate ###
return qc
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
| |
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for the converters."""
import unittest
from qiskit.converters import dag_to_circuit, circuit_to_dag
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
class TestCircuitToDag(QiskitTestCase):
"""Test Circuit to DAG."""
def test_circuit_and_dag(self):
"""Check convert to dag and back"""
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit_in = QuantumCircuit(qr, cr)
circuit_in.h(qr[0])
circuit_in.h(qr[1])
circuit_in.measure(qr[0], cr[0])
circuit_in.measure(qr[1], cr[1])
circuit_in.x(qr[0]).c_if(cr, 0x3)
circuit_in.measure(qr[0], cr[0])
circuit_in.measure(qr[1], cr[1])
circuit_in.measure(qr[2], cr[2])
dag = circuit_to_dag(circuit_in)
circuit_out = dag_to_circuit(dag)
self.assertEqual(circuit_out, circuit_in)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
https://github.com/Qiskit/feedback
|
Qiskit
|
from qiskit.circuit import *
qreg, creg = QuantumRegister(5, "q"), ClassicalRegister(2, "c")
body = QuantumCircuit(3, 1)
loop_parameter = Parameter("foo")
indexset = range(0, 10, 2)
body.rx(loop_parameter, [0, 1, 2])
circuit = QuantumCircuit(qreg, creg)
circuit.for_loop(indexset, loop_parameter, body, [1, 2, 3], [1])
print(circuit.draw())
from qiskit.qasm3 import dumps
print(dumps(circuit))
from qiskit.transpiler.passes import UnrollForLoops
circuit_unroll = UnrollForLoops()(circuit)
print(dumps(circuit_unroll))
circuit_unroll.draw()
print(dumps(UnrollForLoops(max_target_depth=4)(circuit)))
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
pass_manager = generate_preset_pass_manager(1)
pass_manager.run(circuit).draw()
pass_manager.pre_optimization.append(UnrollForLoops())
pass_manager.run(circuit).draw()
# skip when continue and break
import math
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, 1)
with qc.for_loop(range(5)) as i:
qc.rx(i * math.pi/4, 0)
qc.cx(0, 1)
qc.measure(0, 0)
qc.break_loop().c_if(0, True)
print(dumps(qc))
print(dumps(UnrollForLoops()(qc)))
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# Copyright (C) Unitary Fund
#
# This source code is licensed under the GPL license (v3) found in the
# LICENSE file in the root directory of this source tree.
"""Tests for mitiq.pec.sampling functions."""
import cirq
import numpy as np
import pytest
from cirq import (
Circuit,
Gate,
LineQubit,
NamedQubit,
depolarize,
measure,
measure_each,
ops,
)
from pyquil import Program, gates
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from mitiq.pec import (
NoisyOperation,
OperationRepresentation,
represent_operation_with_global_depolarizing_noise,
sample_circuit,
sample_sequence,
)
from mitiq.pec.channels import _circuit_to_choi, _operation_to_choi
from mitiq.pec.representations import (
represent_operation_with_local_depolarizing_noise,
represent_operations_in_circuit_with_local_depolarizing_noise,
)
from mitiq.utils import _equal
xcirq = Circuit(cirq.X(cirq.LineQubit(0)))
zcirq = Circuit(cirq.Z(cirq.LineQubit(0)))
cnotcirq = Circuit(cirq.CNOT(cirq.LineQubit(0), cirq.LineQubit(1)))
czcirq = Circuit(cirq.CZ(cirq.LineQubit(0), cirq.LineQubit(1)))
def test_sample_sequence_cirq():
circuit = Circuit(cirq.H(LineQubit(0)))
circuit.append(measure(LineQubit(0)))
rep = OperationRepresentation(
ideal=circuit,
noisy_operations=[NoisyOperation(xcirq), NoisyOperation(zcirq)],
coeffs=[0.5, -0.5],
)
for _ in range(5):
seqs, signs, norm = sample_sequence(circuit, representations=[rep])
assert isinstance(seqs[0], Circuit)
assert signs[0] in {1, -1}
assert norm == 1.0
def test_sample_sequence_qiskit():
qreg = QuantumRegister(1)
circuit = QuantumCircuit(qreg)
_ = circuit.h(qreg)
xcircuit = QuantumCircuit(qreg)
_ = xcircuit.x(qreg)
zcircuit = QuantumCircuit(qreg)
_ = zcircuit.z(qreg)
noisy_xop = NoisyOperation(xcircuit)
noisy_zop = NoisyOperation(zcircuit)
rep = OperationRepresentation(
ideal=circuit,
noisy_operations=[noisy_xop, noisy_zop],
coeffs=[0.5, -0.5],
)
for _ in range(5):
seqs, signs, norm = sample_sequence(circuit, representations=[rep])
assert isinstance(seqs[0], QuantumCircuit)
assert signs[0] in {1, -1}
assert norm == 1.0
def test_sample_sequence_pyquil():
circuit = Program(gates.H(0))
noisy_xop = NoisyOperation(Program(gates.X(0)))
noisy_zop = NoisyOperation(Program(gates.Z(0)))
rep = OperationRepresentation(
ideal=circuit,
noisy_operations=[noisy_xop, noisy_zop],
coeffs=[0.5, -0.5],
)
for _ in range(50):
seqs, signs, norm = sample_sequence(circuit, representations=[rep])
assert isinstance(seqs[0], Program)
assert signs[0] in {1, -1}
assert norm == 1.0
@pytest.mark.parametrize("seed", (1, 2, 3, 5))
def test_sample_sequence_cirq_random_state(seed):
circuit = Circuit(cirq.H.on(LineQubit(0)))
rep = OperationRepresentation(
ideal=circuit,
noisy_operations=[NoisyOperation(xcirq), NoisyOperation(zcirq)],
coeffs=[0.5, -0.5],
)
sequences, signs, norm = sample_sequence(
circuit, [rep], random_state=np.random.RandomState(seed)
)
for _ in range(20):
new_sequences, new_signs, new_norm = sample_sequence(
circuit, [rep], random_state=np.random.RandomState(seed)
)
assert _equal(new_sequences[0], sequences[0])
assert new_signs[0] == signs[0]
assert np.isclose(new_norm, norm)
def test_qubit_independent_representation_cirq():
"""Test that an OperationRepresentation defined for some qubits can
(optionally) be used to mitigate gates acting on different qubits."""
circuit = Circuit([cirq.I.on(LineQubit(0)), cirq.H.on(LineQubit(1))])
circuit.append(measure_each(*LineQubit.range(2)))
rep = OperationRepresentation(
ideal=Circuit(cirq.H.on(LineQubit(0))),
noisy_operations=[NoisyOperation(xcirq), NoisyOperation(zcirq)],
coeffs=[0.5, -0.5],
is_qubit_dependent=False,
)
expected_a = Circuit([cirq.I.on(LineQubit(0)), cirq.X.on(LineQubit(1))])
expected_a.append(measure_each(*LineQubit.range(2)))
expected_b = Circuit([cirq.I.on(LineQubit(0)), cirq.Z.on(LineQubit(1))])
expected_b.append(measure_each(*LineQubit.range(2)))
for _ in range(5):
seqs, signs, norm = sample_circuit(circuit, representations=[rep])
assert seqs[0] in [expected_a, expected_b]
assert signs[0] in {1, -1}
assert norm == 1.0
def test_qubit_independent_representation_qiskit():
"""Test that an OperationRepresentation defined for some qubits can
(optionally) be used to mitigate gates acting on different qubits."""
different_qreg = QuantumRegister(2, name="q")
circuit_to_mitigate = QuantumCircuit(different_qreg)
_ = circuit_to_mitigate.cx(*different_qreg)
qreg = QuantumRegister(2, name="rep_register")
xcircuit = QuantumCircuit(qreg)
_ = xcircuit.x(qreg)
zcircuit = QuantumCircuit(qreg)
_ = zcircuit.z(qreg)
noisy_xop = NoisyOperation(xcircuit)
noisy_zop = NoisyOperation(zcircuit)
ideal_op = QuantumCircuit(qreg)
_ = ideal_op.cx(*qreg)
rep = OperationRepresentation(
ideal=ideal_op,
noisy_operations=[noisy_xop, noisy_zop],
coeffs=[0.5, -0.5],
is_qubit_dependent=False,
)
# Expected outcomes
xcircuit_different = QuantumCircuit(different_qreg)
xcircuit_different.x(different_qreg)
zcircuit_different = QuantumCircuit(different_qreg)
zcircuit_different.z(different_qreg)
for _ in range(5):
seqs, signs, norm = sample_sequence(
circuit_to_mitigate, representations=[rep]
)
assert seqs[0] in [xcircuit_different, zcircuit_different]
assert signs[0] in {1, -1}
assert norm == 1.0
def test_qubit_independent_representation_pyquil():
"""Test that an OperationRepresentation defined for some qubits can
(optionally) be used to mitigate gates acting on different qubits."""
circuit_to_mitigate = Program(gates.H(1))
noisy_xop = NoisyOperation(Program(gates.X(0)))
noisy_zop = NoisyOperation(Program(gates.Z(0)))
rep = OperationRepresentation(
ideal=Program(gates.H(0)),
noisy_operations=[noisy_xop, noisy_zop],
coeffs=[0.5, -0.5],
is_qubit_dependent=False,
)
for _ in range(50):
seqs, signs, norm = sample_sequence(
circuit_to_mitigate, representations=[rep]
)
assert seqs[0] in [Program(gates.X(1)), Program(gates.Z(1))]
assert signs[0] in {1, -1}
assert norm == 1.0
@pytest.mark.parametrize(
"reps",
[
[],
[
OperationRepresentation(
Circuit(cirq.H.on(LineQubit(0))),
[NoisyOperation(xcirq), NoisyOperation(zcirq)],
[0.5, -0.5],
)
],
],
)
def test_sample_sequence_no_representation(reps):
circuit = Circuit(cirq.H.on(LineQubit(0)), cirq.H.on(LineQubit(1)))
circuit.append(measure_each(*LineQubit.range(2)))
with pytest.warns(UserWarning, match="No representation found for"):
sequences, signs, norm = sample_sequence(circuit, reps)
assert _equal(sequences[0], circuit, require_qubit_equality=True)
assert signs == [1]
assert norm == 1
@pytest.mark.parametrize("measure", [True, False])
def test_sample_circuit_cirq(measure):
circuit = Circuit(
ops.H.on(LineQubit(0)),
ops.CNOT.on(*LineQubit.range(2)),
)
if measure:
circuit.append(measure_each(*LineQubit.range(2)))
h_rep = OperationRepresentation(
circuit[:1],
[NoisyOperation(xcirq), NoisyOperation(zcirq)],
[0.6, -0.6],
)
cnot_rep = OperationRepresentation(
circuit[1:2],
[NoisyOperation(cnotcirq), NoisyOperation(czcirq)],
[0.7, -0.7],
)
for _ in range(50):
sampled_circuits, signs, norm = sample_circuit(
circuit, representations=[h_rep, cnot_rep]
)
assert isinstance(sampled_circuits[0], Circuit)
assert signs[0] in (-1, 1)
assert norm >= 1
if measure:
assert len(sampled_circuits[0]) == 3
assert cirq.is_measurement(
list(sampled_circuits[0].all_operations())[-1] # last gate
)
else:
assert len(sampled_circuits[0]) == 2
def test_sample_circuit_partial_representations():
circuit = Circuit(
ops.H.on(LineQubit(0)),
ops.CNOT.on(*LineQubit.range(2)),
)
cnot_rep = OperationRepresentation(
circuit[1:2],
[NoisyOperation(cnotcirq), NoisyOperation(czcirq)],
[0.7, -0.7],
)
for _ in range(10):
with pytest.warns(UserWarning, match="No representation found for"):
sampled_circuits, signs, norm = sample_circuit(
circuit, representations=[cnot_rep]
)
assert isinstance(sampled_circuits[0], Circuit)
assert len(sampled_circuits[0]) == 2
assert signs[0] in (-1, 1)
assert norm >= 1
def test_sample_circuit_pyquil():
circuit = Program(gates.H(0), gates.CNOT(0, 1))
h_rep = OperationRepresentation(
circuit[:1],
[
NoisyOperation(Program(gates.X(0))),
NoisyOperation(Program(gates.Z(0))),
],
[0.6, -0.6],
)
cnot_rep = OperationRepresentation(
circuit[1:],
[
NoisyOperation(Program(gates.CNOT(0, 1))),
NoisyOperation(Program(gates.CZ(0, 1))),
],
[0.7, -0.7],
)
for _ in range(50):
sampled_circuits, signs, norm = sample_circuit(
circuit, representations=[h_rep, cnot_rep]
)
assert isinstance(sampled_circuits[0], Program)
assert len(sampled_circuits[0]) == 2
assert signs[0] in (-1, 1)
assert norm >= 1
def test_sample_circuit_with_seed():
circ = Circuit([cirq.X.on(LineQubit(0)) for _ in range(10)])
rep = OperationRepresentation(
ideal=Circuit(cirq.X.on(LineQubit(0))),
noisy_operations=[NoisyOperation(zcirq), NoisyOperation(xcirq)],
coeffs=[1.0, -1.0],
)
expected_circuits, expected_signs, expected_norm = sample_circuit(
circ, [rep], random_state=4
)
# Check we're not sampling the same operation every call to sample_sequence
assert len(set(expected_circuits[0].all_operations())) > 1
for _ in range(10):
sampled_circuits, sampled_signs, sampled_norm = sample_circuit(
circ, [rep], random_state=4
)
assert _equal(sampled_circuits[0], expected_circuits[0])
assert sampled_signs[0] == expected_signs[0]
assert sampled_norm == expected_norm
def test_sample_circuit_trivial_decomposition():
circuit = Circuit(ops.H.on(NamedQubit("Q")))
rep = OperationRepresentation(
ideal=circuit,
noisy_operations=[NoisyOperation(circuit)],
coeffs=[1.0],
)
sampled_circuits, signs, norm = sample_circuit(
circuit, [rep], random_state=1
)
assert _equal(sampled_circuits[0], circuit)
assert signs[0] == 1
assert np.isclose(norm, 1)
BASE_NOISE = 0.02
qreg = LineQubit.range(2)
@pytest.mark.parametrize("gate", [cirq.Y, cirq.CNOT])
def test_sample_sequence_choi(gate: Gate):
"""Tests the sample_sequence by comparing the exact Choi matrices."""
qreg = LineQubit.range(gate.num_qubits())
ideal_op = gate.on(*qreg)
ideal_circ = Circuit(ideal_op)
noisy_op_tree = [ideal_op] + [depolarize(BASE_NOISE)(q) for q in qreg]
ideal_choi = _operation_to_choi(ideal_op)
noisy_choi = _operation_to_choi(noisy_op_tree)
representation = represent_operation_with_local_depolarizing_noise(
ideal_circ,
BASE_NOISE,
)
choi_unbiased_estimates = []
rng = np.random.RandomState(1)
for _ in range(500):
imp_seqs, signs, norm = sample_sequence(
ideal_circ, [representation], random_state=rng
)
noisy_sequence = imp_seqs[0].with_noise(depolarize(BASE_NOISE))
sequence_choi = _circuit_to_choi(noisy_sequence)
choi_unbiased_estimates.append(norm * signs[0] * sequence_choi)
choi_pec_estimate = np.average(choi_unbiased_estimates, axis=0)
noise_error = np.linalg.norm(ideal_choi - noisy_choi)
pec_error = np.linalg.norm(ideal_choi - choi_pec_estimate)
assert pec_error < noise_error
assert np.allclose(ideal_choi, choi_pec_estimate, atol=0.05)
def test_sample_circuit_choi():
"""Tests the sample_circuit by comparing the exact Choi matrices."""
# A simple 2-qubit circuit
qreg = LineQubit.range(2)
ideal_circ = Circuit(
cirq.X.on(qreg[0]),
cirq.I.on(qreg[1]),
cirq.CNOT.on(*qreg),
)
noisy_circuit = ideal_circ.with_noise(depolarize(BASE_NOISE))
ideal_choi = _circuit_to_choi(ideal_circ)
noisy_choi = _operation_to_choi(noisy_circuit)
rep_list = represent_operations_in_circuit_with_local_depolarizing_noise(
ideal_circuit=ideal_circ,
noise_level=BASE_NOISE,
)
choi_unbiased_estimates = []
rng = np.random.RandomState(1)
for _ in range(500):
imp_circs, signs, norm = sample_circuit(
ideal_circ, rep_list, random_state=rng
)
noisy_imp_circ = imp_circs[0].with_noise(depolarize(BASE_NOISE))
sequence_choi = _circuit_to_choi(noisy_imp_circ)
choi_unbiased_estimates.append(norm * signs[0] * sequence_choi)
choi_pec_estimate = np.average(choi_unbiased_estimates, axis=0)
noise_error = np.linalg.norm(ideal_choi - noisy_choi)
pec_error = np.linalg.norm(ideal_choi - choi_pec_estimate)
assert pec_error < noise_error
assert np.allclose(ideal_choi, choi_pec_estimate, atol=0.05)
def test_conversions_in_sample_circuit():
"""Tests sample_circuit preserves idle qubits and quantum registers."""
qreg = QuantumRegister(3, name="Q")
creg = ClassicalRegister(2, name="C")
circuit = QuantumCircuit(qreg, creg)
circuit.h(qreg[0])
circuit.cx(qreg[0], qreg[1])
circuit.measure(0, 0)
cnot_circuit = QuantumCircuit(qreg)
cnot_circuit.cx(qreg[0], qreg[1])
rep = represent_operation_with_global_depolarizing_noise(
cnot_circuit,
noise_level=0.0,
)
out_circuits, signs, norm = sample_circuit(circuit, [rep], num_samples=3)
for out_circ in out_circuits:
out_circ == circuit
assert len(signs) == 3
assert set(signs).issubset({1.0, -1.0})
assert np.isclose(norm, 1.0)
|
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
|
mnp-club
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import *
from qiskit.compiler import *
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import numpy as np
import qiskit.quantum_info as qi
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
#This cell is just for seeing what the U tilde matrix looks like
a, b, c, d = np.cos(np.pi/8), np.sin(np.pi/8), -np.sin(np.pi/8), np.cos(np.pi/8)
u_tilde = np.array([[a,c],[b,d]]).reshape(2,2)
print(u_tilde)
#This cell defines the controlled variant of the U tilde matrix
qc_for_u = QuantumCircuit(1)
qc_for_u.ry(np.pi/4, 0)
qc_for_u.name = "U"
controlled_u_tilde = qc_for_u.to_gate().control(2)
qc1 = QuantumCircuit(3)
qc1.x(0)
qc1.x(1)
qc1.toffoli(0,1,2)#Flipping the third bit if the first two are zero
qc1.x(0) #Essentially 000 -> 001
qc1.x(1)
qc1.x(0)
qc1.toffoli(0,2,1)#Flipping the second bit if the first bit is zero and the third is one
qc1.x(0) #Essentially 001 -> 011
qc1.append(controlled_u_tilde, [1, 2, 0])
qc1.x(0)
qc1.toffoli(0,2,1)#Undoing the flip from before
qc1.x(0)
qc1.x(0)
qc1.x(1)
qc1.toffoli(0,1,2)#Undoing the flip from before
qc1.x(0)
qc1.x(1)
qc1.draw('mpl')
U_circ = qi.Operator(qc1).data
print(U_circ)
qc2 = QuantumCircuit(3)
#Code for executing U
qc2.x(0)
qc2.x(1)
qc2.toffoli(0,1,2)#Flipping the third bit if the first two are zero
qc2.x(0) #Essentially 000 -> 001
qc2.x(1)
qc2.x(0)
qc2.toffoli(0,2,1)#Flipping the second bit if the first bit is zero and the third is one
qc2.x(0) #Essentially 001 -> 011
qc2.append(controlled_u_tilde, [1, 2, 0])
qc2.x(0)
qc2.toffoli(0,2,1)#Undoing the flip from before
qc2.x(0)
qc2.x(0)
qc2.x(1)
qc2.toffoli(0,1,2)#Undoing the flip from before
qc2.x(0)
qc2.x(1)
#Code for executing V
qc2.x(0)
qc2.toffoli(0,1,2)#Flipping the third bit if the first is zero and second is one
qc2.x(0) #Essentially 010 -> 011
qc2.toffoli(1,2,0)
qc2.x(0)
qc2.toffoli(0,1,2)#Undoing the flip from before
qc2.x(0)
qc2.draw('mpl')
def without_global_phase(matrix: np.ndarray, atol: float = 1e-8) :
phases1 = np.angle(matrix[abs(matrix) > atol].ravel(order='F'))
if len(phases1) > 0:
matrix = np.exp(-1j * phases1[0]) * matrix
return matrix
V_circ = without_global_phase(qi.Operator(qc2).data)
print(V_circ)
#Function just returns norm ignoring global phase between unitaries
def norm(unitary_a: np.ndarray, unitary_b: np.ndarray) :
return np.linalg.norm(without_global_phase(unitary_b)-without_global_phase(unitary_a), ord=2)
#Make the Pauli Y gate
qcy = QuantumCircuit(1)
qcy.t(0)
qcy.t(0)
qcy.t(0)
qcy.t(0)
qcy.h(0)
qcy.t(0)
qcy.t(0)
qcy.t(0)
qcy.t(0)
qcy.h(0)# Essentially XZ is being applied since T^4 = X and HXH = Z and XZ = iY but global phase is ignored
Y_circ = qi.Operator(qcy).data
Y = np.array([[0,-1j],[1j,0]])
print(norm(Y_circ,Y))
uni_q = np.array([[-0.25+0.60355339j, 0.60355339+0.45710678j],
[0.60355339-0.45710678j, 0.25+0.60355339j]]).reshape(2,2)
qc3 = QuantumCircuit(1)
qc_min = 1000
while(True):
parameters = np.random.randint(8, size=6) #Samling integers from 0 to 7 and getting 6 of them
for i in parameters[0:5]:
for j in range(i):
qc3.t(0)
qc3.h(0)
for j in range(parameters[-1]):
qc3.t(0)
if norm(qi.Operator(qc3).data,uni_q) <= 1e-8:#Break if we have reached the right combination
print(parameters)
break
qc_min = np.sum(parameters)
qc3 = QuantumCircuit(1)#Reinitiallize circuit
uni_q_circ = qi.Operator(qc3).data
print(norm(uni_q_circ,uni_q))
qc3.draw('mpl')#Drawing the actual solution
#Note that there are multiple solutions so as long as your norm
#was of order 1.65e-9 you are correct. The reason of these multiple
#solutions is because there are commutativity relations that we
#havent bothered calculating
#There are better ways and many of you probably did use them. This is the best circuit we found
#If you search amongst all the possibilities or iterate the right way this will be the solution you find
#The difference between this cell and the one above is that the one above came from a random number generator
qc3 = QuantumCircuit(1)
qc3.t(0)
qc3.h(0)
qc3.t(0)
qc3.t(0)
qc3.t(0)
qc3.h(0)
qc3.t(0)
qc3.h(0)
qc3.t(0)
qc3.h(0)
qc3.t(0)
qc3.t(0)
qc3.h(0)
qc3.draw('mpl')
#Defining the gate as controlled_irx
from qiskit.extensions import *
pi_alpha = np.arccos(0.6)
qc_for_irx = QuantumCircuit(1)
irx = np.array([[1j*np.cos(pi_alpha/2),np.sin(pi_alpha/2)],[np.sin(pi_alpha/2),1j*np.cos(pi_alpha/2)]]).reshape(2,2)
g_irx = UnitaryGate(data=irx,label=None)
controlled_irx = g_irx.control(2)
alpha = pi_alpha/np.pi
i = 0
while(True):
if abs((alpha*i)%2 - 0.5) <= 0.001:
print(i)
break
i += 1
i = 1
while(True):
if abs((alpha*i)%2) <= 0.013 and (i%4 == 2):
print(i)
break
i += 1
n = 4
qcb = QuantumCircuit(n,n)
qcb.x(0)#Ancilla
qcb.x(1)#Ancilla You can use these two as control to use the controlled_irx gate
#Doing the Rx(pi/2)
for i in range(476):
qcb.append(controlled_irx,[0,1,2])
#Controlled not off first qubit (here first qubit is actually the third one cause we have two ancillas)
qcb.cx(2,3)
#Doing the Rx(3pi/2) which is Rx(-pi/2) essentially
qcb.x(2)
for i in range(476):
qcb.append(controlled_irx,[0,1,2])
# This makes the state |11> flip sign if third and fourth qubit is 1
#so that way we know that fourth qubit has |+> state always
qcb.x(0)#reset ancillas
qcb.x(1)#reset ancillas
qcb.cx(2,0)
qcb.cx(3,1)
for i in range(122):
qcb.append(controlled_irx,[0,1,3])
qcb.cx(3,1)
qcb.cx(2,0)
#Get state of qubit which should have the |+> state using the backend simulator
i = 3#Index for the qubit at |+> state
qcb.h(i)#Puts the |+> state to |0>
qcb.measure(i, i)
def run_circuit(qcb):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qcb, backend, shots = 2000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qcb)
print(counts)
plot_histogram(counts)
|
https://github.com/lynnlangit/learning-quantum
|
lynnlangit
|
# Importing Libraries
import torch
from torch import cat, no_grad, manual_seed
from torch.utils.data import DataLoader
from torchvision import transforms
import torch.optim as optim
from torch.nn import (
Module,
Conv2d,
Linear,
Dropout2d,
NLLLoss
)
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from qiskit_machine_learning.neural_networks import EstimatorQNN
from qiskit_machine_learning.connectors import TorchConnector
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from qiskit import QuantumCircuit
from qiskit.visualization import circuit_drawer
# Imports for CIFAR-10s
from torchvision.datasets import CIFAR10
from torchvision import transforms
def prepare_data(X, labels_to_keep, batch_size):
# Filtering out labels (originally 0-9), leaving only labels 0 and 1
filtered_indices = [i for i in range(len(X.targets)) if X.targets[i] in labels_to_keep]
X.data = X.data[filtered_indices]
X.targets = [X.targets[i] for i in filtered_indices]
# Defining dataloader with filtered data
loader = DataLoader(X, batch_size=batch_size, shuffle=True)
return loader
# Set seed for reproducibility
manual_seed(42)
# CIFAR-10 data transformation
transform = transforms.Compose([
transforms.ToTensor(), # convert the images to tensors
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) # Normalization usign mean and std.
])
labels_to_keep = [0, 1]
batch_size = 1
# Preparing Train Data
X_train = CIFAR10(root="./data", train=True, download=True, transform=transform)
train_loader = prepare_data(X_train, labels_to_keep, batch_size)
# Preparing Test Data
X_test = CIFAR10(root="./data", train=False, download=True, transform=transform)
test_loader = prepare_data(X_test, labels_to_keep, batch_size)
print(f"Training dataset size: {len(train_loader.dataset)}")
print(f"Test dataset size: {len(test_loader.dataset)}")
# Defining and creating QNN
def create_qnn():
feature_map = ZZFeatureMap(2) # ZZFeatureMap with 2 bits, entanglement between qubits based on the pairwise product of input features.
ansatz = RealAmplitudes(2, reps=1) # parameters (angles, in the case of RealAmplitudes) that are adjusted during the training process to optimize the quantum model for a specific task.
qc = QuantumCircuit(2)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
qnn = EstimatorQNN(
circuit=qc,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
input_gradients=True,
)
return qnn
qnn = create_qnn()
# Visualizing the QNN circuit
circuit_drawer(qnn.circuit, output='mpl')
# Defining torch NN module
class Net(Module):
def __init__(self, qnn):
super().__init__()
self.conv1 = Conv2d(3, 16, kernel_size=3, padding=1)
self.conv2 = Conv2d(16, 32, kernel_size=3, padding=1)
self.dropout = Dropout2d()
self.fc1 = Linear(32 * 8 * 8, 64)
self.fc2 = Linear(64, 2) # 2-dimensional input to QNN
self.qnn = TorchConnector(qnn)
self.fc3 = Linear(1, 1) # 1-dimensional output from QNN
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(x.shape[0], -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.qnn(x)
x = self.fc3(x)
return cat((x, 1 - x), -1)
# Creating model
model = Net(qnn)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
# Defining model, optimizer, and loss function
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = NLLLoss()
# Starting training
epochs = 10
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device) # Move data to GPU
optimizer.zero_grad(set_to_none=True)
output = model(data)
loss = loss_func(output, target)
loss.backward()
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss) / len(total_loss))
print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1]))
# Plotting loss convergence
plt.plot(loss_list)
plt.title("Hybrid NN Training Convergence")
plt.xlabel("Training Iterations")
plt.ylabel("Neg. Log Likelihood Loss")
plt.show()
# Saving the model
torch.save( model.state_dict(), "model_cifar10_10EPOCHS.pt")
# Loading the model
qnn_cifar10 = create_qnn()
model_cifar10 = Net(qnn_cifar10)
model_cifar10.load_state_dict(torch.load("model_cifar10.pt"))
correct = 0
total = 0
model_cifar10.eval()
with torch.no_grad():
for data, target in test_loader:
output = model_cifar10(data)
_, predicted = torch.max(output.data, 1)
total += target.size(0)
correct += (predicted == target).sum().item()
# Calculating and print test accuracy
test_accuracy = correct / total * 100
print(f"Test Accuracy: {test_accuracy:.2f}%")
# Plotting predicted labels
n_samples_show = 6
count = 0
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
model_cifar10.eval()
with no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
if count == n_samples_show:
break
output = model_cifar10(data)
if len(output.shape) == 1:
output = output.reshape(1, *output.shape)
pred = output.argmax(dim=1, keepdim=True)
axes[count].imshow(np.transpose(data[0].numpy(), (1, 2, 0)))
axes[count].set_xticks([])
axes[count].set_yticks([])
axes[count].set_title("Predicted {0}\n Actual {1}".format(pred.item(), target.item()))
count += 1
plt.show()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import BasicAer
from qiskit_aqua.algorithms import AmplitudeEstimation
from qiskit_aqua.components.random_distributions import MultivariateNormalDistribution
from qiskit_aqua.components.uncertainty_problems import FixedIncomeExpectedValue
# can be used in case a principal component analysis has been done to derive the uncertainty model, ignored in this example.
A = np.eye(2)
b = np.zeros(2)
# specify the number of qubits that are used to represent the different dimenions of the uncertainty model
num_qubits = [2, 2]
# specify the lower and upper bounds for the different dimension
low = [0, 0]
high = [0.12, 0.24]
mu = [0.12, 0.24]
sigma = 0.01*np.eye(2)
# construct corresponding distribution
u = MultivariateNormalDistribution(num_qubits, low, high, mu, sigma)
# plot contour of probability density function
x = np.linspace(low[0], high[0], 2**num_qubits[0])
y = np.linspace(low[1], high[1], 2**num_qubits[1])
z = u.probabilities.reshape(2**num_qubits[0], 2**num_qubits[1])
plt.contourf(x, y, z)
plt.xticks(x, size=15)
plt.yticks(y, size=15)
plt.grid()
plt.xlabel('$r_1$ (%)', size=15)
plt.ylabel('$r_2$ (%)', size=15)
plt.colorbar()
plt.show()
# specify cash flow
cf = [1.0, 2.0]
periods = range(1, len(cf)+1)
# plot cash flow
plt.bar(periods, cf)
plt.xticks(periods, size=15)
plt.yticks(size=15)
plt.grid()
plt.xlabel('periods', size=15)
plt.ylabel('cashflow ($)', size=15)
plt.show()
# estimate real value
cnt = 0
exact_value = 0.0
for x1 in np.linspace(low[0], high[0], pow(2, num_qubits[0])):
for x2 in np.linspace(low[1], high[1], pow(2, num_qubits[1])):
prob = u.probabilities[cnt]
for t in range(len(cf)):
# evaluate linear approximation of real value w.r.t. interest rates
exact_value += prob * (cf[t]/pow(1 + b[t], t+1) - (t+1)*cf[t]*np.dot(A[:, t], np.asarray([x1, x2]))/pow(1 + b[t], t+2))
cnt += 1
print('Exact value: \t%.4f' % exact_value)
# specify approximation factor
c_approx = 0.125
# get fixed income circuit appfactory
fixed_income = FixedIncomeExpectedValue(u, A, b, cf, c_approx)
# set number of evaluation qubits (samples)
m = 5
# construct amplitude estimation
ae = AmplitudeEstimation(m, fixed_income)
# result = ae.run(quantum_instance=BasicAer.get_backend('qasm_simulator'), shots=100)
result = ae.run(quantum_instance=BasicAer.get_backend('statevector_simulator'))
print('Exact value: \t%.4f' % exact_value)
print('Estimated value:\t%.4f' % result['estimation'])
print('Probability: \t%.4f' % result['max_probability'])
# plot estimated values for "a" (direct result of amplitude estimation, not rescaled yet)
plt.bar(result['values'], result['probabilities'], width=0.5/len(result['probabilities']))
plt.xticks([0, 0.25, 0.5, 0.75, 1], size=15)
plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15)
plt.title('"a" Value', size=15)
plt.ylabel('Probability', size=15)
plt.xlim((0,1))
plt.ylim((0,1))
plt.grid()
plt.show()
# plot estimated values for fixed-income asset (after re-scaling and reversing the c_approx-transformation)
plt.bar(result['mapped_values'], result['probabilities'], width=3/len(result['probabilities']))
plt.plot([exact_value, exact_value], [0,1], 'r--', linewidth=2)
plt.xticks(size=15)
plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15)
plt.title('Estimated Option Price', size=15)
plt.ylabel('Probability', size=15)
plt.ylim((0,1))
plt.grid()
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import datetime
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.rcParams.update({"text.usetex": True})
plt.rcParams["figure.figsize"] = (6,4)
mpl.rcParams["figure.dpi"] = 200
from qiskit_ibm_runtime import Estimator, Session, QiskitRuntimeService, Options
from qiskit.quantum_info import SparsePauliOp
from qiskit import QuantumCircuit
service = QiskitRuntimeService()
backend_simulator = "backend_simulator"
backend = "ibmq_montreal"
qubits = 4
trotter_layer = QuantumCircuit(qubits)
trotter_layer.rx(0.1, range(qubits))
trotter_layer.cx(0, 1)
trotter_layer.cx(2, 3)
trotter_layer.rz(-0.2, [1, 3])
trotter_layer.cx(0, 1)
trotter_layer.cx(2, 3)
trotter_layer.cx(1, 2)
trotter_layer.rz(-0.2, 2)
trotter_layer.cx(1, 2)
num_steps = 6
trotter_circuit_list = []
for i in range(1, num_steps):
trotter_circuit = QuantumCircuit(qubits)
for _ in range(i):
trotter_circuit = trotter_circuit.compose(trotter_layer)
trotter_circuit_list.append(trotter_circuit)
print(f'Trotter circuit with {i} Trotter steps`)
display(trotter_circuit.draw(fold=-1))
obs = SparsePauliOp("Z"*qubits)
obs_list = [obs]*len(trotter_circuit_list)
options = Options()
options.execution.shots = 1000
options.optimization_level = 0 # No optimization
options.resilience_level = 0 # No mitigation
with Session(service=service, backend=backend_simulator) as session:
estimator_sim = Estimator(session=session, options=options)
job_sim = estimator_sim.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_sim.job_id)
print(job_sim.result())
expvals_ideal = job_sim.result().values
expvals_ideal_variance = [metadata['variance']/metadata['shots'] for metadata in job_sim.result().metadata]
std_error_ideal = np.sqrt(expvals_ideal_variance)
options = Options()
options.execution.shots = 1000
options.optimization_level = 0 # No optimization
options.resilience_level = 0 # No error mitigation
with Session(service=service, backend=backend) as session:
estimator = Estimator(session=session, options=options)
job = estimator.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job.job_id)
print(job.result())
expvals_unmit = job.result().values
expvals_unmit_variance = [metadata['variance']/metadata['shots'] for metadata in job.result().metadata]
std_error_unmit = np.sqrt(expvals_unmit_variance)
options = Options()
options.execution.shots = 1000
options.optimization_level = 3 # Dynamical decoupling
options.resilience_level = 0 # No error mitigation
with Session(service=service, backend=backend) as session:
estimator = Estimator(session=session, options=options)
job_dd = estimator.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_dd.job_id)
print(job_dd.result())
expvals_unmit_dd = job_dd.result().values
expvals_unmit_dd_variance = [metadata['variance']/metadata['shots'] for metadata in job_dd.result().metadata]
std_error_dd = np.sqrt(expvals_unmit_dd_variance)
plt.title('Trotter circuits expectation value')
plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal')
plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation')
plt.errorbar(range(1, num_steps), expvals_unmit_dd, std_error_dd, fmt = 'o', linestyle = '-', capsize=4, c='blue', label='Dynamical decoupling')
plt.ylabel(f"$\langle ZZZZ \\rangle$")
plt.xlabel('No. Trotter Steps')
plt.xticks([1, 2, 3, 4, 5])
plt.legend()
plt.show()
options = Options()
options.resilience_level = 1 # T-REx
options.optimization_level = 0 # No optimization
options.execution.shots = 1000
with Session(service=service, backend=backend) as session:
estimator = Estimator(session=session, options=options)
job_trex = estimator.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_trex.job_id)
print(job_trex.result())
expvals_unmit_trex = job_trex.result().values
expvals_unmit_trex_variance = [metadata['variance']/metadata['shots'] for metadata in job_trex.result().metadata]
std_error_trex = np.sqrt(expvals_unmit_trex_variance)
plt.title('Trotter circuits expectation value')
plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal')
plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation')
plt.errorbar(range(1, num_steps), expvals_unmit_trex, std_error_trex, fmt = 'o', linestyle = '-', capsize=4, c='violet', label='T-REx')
plt.ylabel(f"$\langle ZZZZ \\rangle$")
plt.xlabel('No. Trotter Steps')
plt.xticks([1, 2, 3, 4, 5])
plt.legend()
plt.show()
options = Options()
options.execution.shots = 1000
options.optimization_level = 0 # No optimization
options.resilience_level = 2 # ZNE
with Session(service=service, backend=backend) as session:
estimator = Estimator(session=session, options=options)
job_zne = estimator.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_zne.job_id)
print(job_zne.result())
expvals_unmit_zne = job_zne.result().values
# Standard error: coming soon!
plt.title('Trotter circuits expectation value')
plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal')
plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation')
plt.errorbar(range(1, num_steps), expvals_unmit_zne, [0]*(num_steps-1), fmt = 'o', linestyle = '-', capsize=4, c='cyan', label='ZNE')
plt.xlabel('No. Trotter Steps')
plt.ylabel(f"$\langle ZZZZ \\rangle$")
plt.xticks([1, 2, 3, 4, 5])
plt.legend()
plt.show()
def interim_results_callback(job_id, result):
now = datetime.datetime.now()
print(now, "*** Callback ***", result, "\n")
options = Options()
options.optimization_level = 0 # No optimization
options.execution.shots = 100
options.resilience_level = 3 # PEC
options.environment.callback = interim_results_callback
with Session(service=service, backend=backend) as session:
estimator_pec = Estimator(session=session, options=options)
job_pec = estimator_pec.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_pec.job_id)
expvals_pec = job_pec.result().values
std_error_pec = [metadata['standard_error'] for metadata in job_pec.result().metadata]
plt.title('Trotter circuits expectation value')
plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal')
plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation')
plt.errorbar(range(1, num_steps), expvals_pec, std_error_pec, fmt = 'd', linestyle = '-', capsize=4, c='orange', label='PEC')
plt.ylabel(f"$\langle ZZZZ \\rangle$")
plt.xlabel('No. Trotter Steps')
plt.xticks([1, 2, 3, 4, 5])
plt.legend()
plt.show()
print(job_pec.result())
pec_metadata = job_pec.result().metadata
fig, ax = plt.subplots()
fig.subplots_adjust(right=0.75)
twin1 = ax.twinx()
twin2 = ax.twinx()
twin3 = ax.twinx()
twin2.spines.right.set_position(("axes", 1.2))
twin3.spines.right.set_position(("axes", 1.4))
p1, = ax.plot(range(1, num_steps), [m["total_mitigated_layers"] for m in pec_metadata] , "b-", label="Total mitigated layers")
p2, = twin1.plot(range(1, num_steps), [m["sampling_overhead"] for m in pec_metadata], "r-", label="Sampling overhead")
p3, = twin2.plot(range(1, num_steps), [m["samples"] for m in pec_metadata], "g-", label="Samples")
p4, = twin3.plot(range(1, num_steps), [m["shots"] for m in pec_metadata], "c-", label="Shots")
ax.set_ylim(0, 20)
twin1.set_ylim(0, 2.8)
twin2.set_ylim(0, 300)
twin3.set_ylim(0, 35000)
ax.set_xlabel("No. Trotter Steps")
ax.set_ylabel("Total mitigated layers")
twin1.set_ylabel("Sampling overhead")
twin2.set_ylabel("Samples")
twin3.set_ylabel("Shots")
ax.yaxis.label.set_color(p1.get_color())
twin1.yaxis.label.set_color(p2.get_color())
twin2.yaxis.label.set_color(p3.get_color())
twin3.yaxis.label.set_color(p4.get_color())
tkw = dict(size=4, width=1.5)
ax.tick_params(axis='y', colors=p1.get_color(), **tkw)
twin1.tick_params(axis='y', colors=p2.get_color(), **tkw)
twin2.tick_params(axis='y', colors=p3.get_color(), **tkw)
twin3.tick_params(axis='y', colors=p4.get_color(), **tkw)
plt.xticks([1, 2, 3, 4, 5])
ax.legend(handles=[p1, p2, p3, p4])
plt.title('PEC metadata')
plt.show()
from matplotlib.pyplot import figure
plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal')
plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation')
plt.errorbar(range(1, num_steps), expvals_unmit_trex, std_error_trex, fmt = 'o', linestyle = '-', capsize=4, c='violet', label='T-REx')
plt.errorbar(range(1, num_steps), expvals_unmit_zne, [0]*(num_steps-1), fmt = 'o', linestyle = '-', capsize=4, c='cyan', label='ZNE')
plt.errorbar(range(1, num_steps), expvals_pec, std_error_pec, fmt = 'd', linestyle = '-', capsize=4, c='orange', label='PEC')
plt.title('Trotter circuits expectation value')
plt.ylabel(f"$\langle ZZZZ \\rangle$")
plt.xlabel('No. Trotter Steps')
plt.xticks([1, 2, 3, 4, 5])
plt.legend()
plt.show()
options = Options()
options.execution.shots = 1000
options.optimization_level = 0 # no optimization
options.resilience_level = 2 # ZNE
options.resilience.noise_factors = [1, 2, 3, 4]
options.resilience.noise_amplifier = "LocalFoldingAmplifier"
options.resilience.extrapolator = "QuadraticExtrapolator"
with Session(service=service, backend='ibmq_montreal') as session:
estimator = Estimator(session=session, options=options)
job_zne_options = estimator.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_zne_options.job_id)
print(job_zne_options.result())
from qiskit.tools import jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
input_3sat_instance = '''
c example DIMACS-CNF 3-SAT
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
'''
import os
import tempfile
from qiskit.exceptions import MissingOptionalLibraryError
from qiskit.circuit.library.phase_oracle import PhaseOracle
fp = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
fp.write(input_3sat_instance)
file_name = fp.name
fp.close()
oracle = None
try:
oracle = PhaseOracle.from_dimacs_file(file_name)
except MissingOptionalLibraryError as ex:
print(ex)
finally:
os.remove(file_name)
from qiskit.algorithms import AmplificationProblem
problem = None
if oracle is not None:
problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring)
from qiskit.algorithms import Grover
from qiskit.primitives import Sampler
grover = Grover(sampler=Sampler())
result = None
if problem is not None:
result = grover.amplify(problem)
print(result.assignment)
from qiskit.tools.visualization import plot_histogram
if result is not None:
display(plot_histogram(result.circuit_results[0]))
expression = '(w ^ x) & ~(y ^ z) & (x & y & z)'
try:
oracle = PhaseOracle(expression)
problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring)
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
display(plot_histogram(result.circuit_results[0]))
except MissingOptionalLibraryError as ex:
print(ex)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Qiskit/feedback
|
Qiskit
|
# based on https://github.com/Qiskit-Extensions/qiskit-alt/blob/main/bench/jordan_wigner_nature_time.py
from timeit import timeit
from qiskit import __qiskit_version__
from qiskit_nature.drivers import UnitsType, Molecule
from qiskit_nature.drivers.second_quantization import (
ElectronicStructureDriverType,
ElectronicStructureMoleculeDriver,
)
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
from qiskit_nature.operators.second_quantization import FermionicOp
geometry = {
"h2": [["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]],
"h2o": [["O", [0.0, 0.0, 0.0]], ["H", [0.757, 0.586, 0.0]], ["H", [-0.757, 0.586, 0.0]]],
}
def setup(basis, geom):
molecule = Molecule(geometry=geom, charge=0, multiplicity=1)
driver = ElectronicStructureMoleculeDriver(
molecule, basis=basis, driver_type=ElectronicStructureDriverType.PYSCF
)
es_problem = ElectronicStructureProblem(driver)
second_q_op = es_problem.second_q_ops()
qubit_converter = QubitConverter(mapper=JordanWignerMapper())
hamiltonian = second_q_op[0].reduce()
return qubit_converter, hamiltonian
def run_one_basis(basis, molecule, num_repetitions):
qubit_converter, hamiltonian = setup(basis, geometry[molecule])
time = timeit(lambda: qubit_converter.convert(hamiltonian), number=num_repetitions)
t = 1000 * time / num_repetitions
print(f"geometry={molecule}, basis={basis}, size={len(hamiltonian)}, time={t:0.2f} ms")
return t
print(__qiskit_version__)
for basis, molecule, num_repetitions in [
("sto3g", "h2", 10),
("631g", "h2", 10),
("631++g", "h2", 5),
("sto3g", "h2o", 5),
("631g", "h2o", 1),
]:
run_one_basis(basis, molecule, num_repetitions)
# Pure-Python PoC of unique
# https://github.com/Qiskit/qiskit-terra/pull/7656/commits/7e886dde94a7c2e46345d85b97b8bb4f7c928fc0
def _unique(array):
# This function corresponds to
# _, indexes, inverses = np.unique(array, return_index=True, return_inverse=True, axis=0)
table = {}
indexes = []
inverses = np.empty(array.shape[0], dtype=int)
for i, ary in enumerate(array):
b = ary.data.tobytes()
if b in table:
inverses[i] = table[b]
else:
inverses[i] = table[b] = len(table)
indexes.append(i)
return indexes, inverses
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
### replaced x gate ###
qc.x(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)
return qc
def decode_message(qc):
qc.cx(1, 0)
### replaced x gate ###
qc.x(1)
return qc
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# 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.
"""Test cases for the circuit qasm_file and qasm_string method."""
import os
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit import Gate, Parameter
from qiskit.exceptions import QiskitError
from qiskit.test import QiskitTestCase
from qiskit.transpiler.passes import Unroller
from qiskit.converters.circuit_to_dag import circuit_to_dag
class LoadFromQasmTest(QiskitTestCase):
"""Test circuit.from_qasm_* set of methods."""
def setUp(self):
super().setUp()
self.qasm_file_name = "entangled_registers.qasm"
self.qasm_dir = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm"
)
self.qasm_file_path = os.path.join(self.qasm_dir, self.qasm_file_name)
def test_qasm_file(self):
"""
Test qasm_file and get_circuit.
If all is correct we should get the qasm file loaded in _qasm_file_path
"""
q_circuit = QuantumCircuit.from_qasm_file(self.qasm_file_path)
qr_a = QuantumRegister(4, "a")
qr_b = QuantumRegister(4, "b")
cr_c = ClassicalRegister(4, "c")
cr_d = ClassicalRegister(4, "d")
q_circuit_2 = QuantumCircuit(qr_a, qr_b, cr_c, cr_d)
q_circuit_2.h(qr_a)
q_circuit_2.cx(qr_a, qr_b)
q_circuit_2.barrier(qr_a)
q_circuit_2.barrier(qr_b)
q_circuit_2.measure(qr_a, cr_c)
q_circuit_2.measure(qr_b, cr_d)
self.assertEqual(q_circuit, q_circuit_2)
def test_loading_all_qelib1_gates(self):
"""Test setting up a circuit with all gates defined in qiskit/qasm/libs/qelib1.inc."""
from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate, UGate
all_gates_qasm = os.path.join(self.qasm_dir, "all_gates.qasm")
qasm_circuit = QuantumCircuit.from_qasm_file(all_gates_qasm)
ref_circuit = QuantumCircuit(3, 3)
# abstract gates (legacy)
ref_circuit.append(UGate(0.2, 0.1, 0.6), [0])
ref_circuit.cx(0, 1)
# the hardware primitives
ref_circuit.append(U3Gate(0.2, 0.1, 0.6), [0])
ref_circuit.append(U2Gate(0.1, 0.6), [0])
ref_circuit.append(U1Gate(0.6), [0])
ref_circuit.id(0)
ref_circuit.cx(0, 1)
# the standard single qubit gates
ref_circuit.u(0.2, 0.1, 0.6, 0)
ref_circuit.p(0.6, 0)
ref_circuit.x(0)
ref_circuit.y(0)
ref_circuit.z(0)
ref_circuit.h(0)
ref_circuit.s(0)
ref_circuit.t(0)
ref_circuit.sdg(0)
ref_circuit.tdg(0)
ref_circuit.sx(0)
ref_circuit.sxdg(0)
# the standard rotations
ref_circuit.rx(0.1, 0)
ref_circuit.ry(0.1, 0)
ref_circuit.rz(0.1, 0)
# the barrier
ref_circuit.barrier()
# the standard user-defined gates
ref_circuit.swap(0, 1)
ref_circuit.cswap(0, 1, 2)
ref_circuit.cy(0, 1)
ref_circuit.cz(0, 1)
ref_circuit.ch(0, 1)
ref_circuit.csx(0, 1)
ref_circuit.append(CU1Gate(0.6), [0, 1])
ref_circuit.append(CU3Gate(0.2, 0.1, 0.6), [0, 1])
ref_circuit.cp(0.6, 0, 1)
ref_circuit.cu(0.2, 0.1, 0.6, 0, 0, 1)
ref_circuit.ccx(0, 1, 2)
ref_circuit.crx(0.6, 0, 1)
ref_circuit.cry(0.6, 0, 1)
ref_circuit.crz(0.6, 0, 1)
ref_circuit.rxx(0.2, 0, 1)
ref_circuit.rzz(0.2, 0, 1)
ref_circuit.measure([0, 1, 2], [0, 1, 2])
self.assertEqual(qasm_circuit, ref_circuit)
def test_fail_qasm_file(self):
"""
Test fail_qasm_file.
If all is correct we should get a QiskitError
"""
self.assertRaises(QiskitError, QuantumCircuit.from_qasm_file, "")
def test_qasm_text(self):
"""
Test qasm_text and get_circuit.
If all is correct we should get the qasm file loaded from the string
"""
qasm_string = "// A simple 8 qubit example\nOPENQASM 2.0;\n"
qasm_string += 'include "qelib1.inc";\nqreg a[4];\n'
qasm_string += "qreg b[4];\ncreg c[4];\ncreg d[4];\nh a;\ncx a, b;\n"
qasm_string += "barrier a;\nbarrier b;\nmeasure a[0]->c[0];\n"
qasm_string += "measure a[1]->c[1];\nmeasure a[2]->c[2];\n"
qasm_string += "measure a[3]->c[3];\nmeasure b[0]->d[0];\n"
qasm_string += "measure b[1]->d[1];\nmeasure b[2]->d[2];\n"
qasm_string += "measure b[3]->d[3];"
q_circuit = QuantumCircuit.from_qasm_str(qasm_string)
qr_a = QuantumRegister(4, "a")
qr_b = QuantumRegister(4, "b")
cr_c = ClassicalRegister(4, "c")
cr_d = ClassicalRegister(4, "d")
ref = QuantumCircuit(qr_a, qr_b, cr_c, cr_d)
ref.h(qr_a[3])
ref.cx(qr_a[3], qr_b[3])
ref.h(qr_a[2])
ref.cx(qr_a[2], qr_b[2])
ref.h(qr_a[1])
ref.cx(qr_a[1], qr_b[1])
ref.h(qr_a[0])
ref.cx(qr_a[0], qr_b[0])
ref.barrier(qr_b)
ref.measure(qr_b, cr_d)
ref.barrier(qr_a)
ref.measure(qr_a, cr_c)
self.assertEqual(len(q_circuit.cregs), 2)
self.assertEqual(len(q_circuit.qregs), 2)
self.assertEqual(q_circuit, ref)
def test_qasm_text_conditional(self):
"""
Test qasm_text and get_circuit when conditionals are present.
"""
qasm_string = (
"\n".join(
[
"OPENQASM 2.0;",
'include "qelib1.inc";',
"qreg q[1];",
"creg c0[4];",
"creg c1[4];",
"x q[0];",
"if(c1==4) x q[0];",
]
)
+ "\n"
)
q_circuit = QuantumCircuit.from_qasm_str(qasm_string)
qr = QuantumRegister(1, "q")
cr0 = ClassicalRegister(4, "c0")
cr1 = ClassicalRegister(4, "c1")
ref = QuantumCircuit(qr, cr0, cr1)
ref.x(qr[0])
ref.x(qr[0]).c_if(cr1, 4)
self.assertEqual(len(q_circuit.cregs), 2)
self.assertEqual(len(q_circuit.qregs), 1)
self.assertEqual(q_circuit, ref)
def test_opaque_gate(self):
"""
Test parse an opaque gate
See https://github.com/Qiskit/qiskit-terra/issues/1566.
"""
qasm_string = (
"\n".join(
[
"OPENQASM 2.0;",
'include "qelib1.inc";',
"opaque my_gate(theta,phi,lambda) a,b;",
"qreg q[3];",
"my_gate(1,2,3) q[1],q[2];",
]
)
+ "\n"
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
qr = QuantumRegister(3, "q")
expected = QuantumCircuit(qr)
expected.append(Gate(name="my_gate", num_qubits=2, params=[1, 2, 3]), [qr[1], qr[2]])
self.assertEqual(circuit, expected)
def test_qasm_example_file(self):
"""Loads qasm/example.qasm."""
qasm_filename = os.path.join(self.qasm_dir, "example.qasm")
expected_circuit = QuantumCircuit.from_qasm_str(
"\n".join(
[
"OPENQASM 2.0;",
'include "qelib1.inc";',
"qreg q[3];",
"qreg r[3];",
"creg c[3];",
"creg d[3];",
"h q[2];",
"cx q[2],r[2];",
"measure r[2] -> d[2];",
"h q[1];",
"cx q[1],r[1];",
"measure r[1] -> d[1];",
"h q[0];",
"cx q[0],r[0];",
"measure r[0] -> d[0];",
"barrier q[0],q[1],q[2];",
"measure q[2] -> c[2];",
"measure q[1] -> c[1];",
"measure q[0] -> c[0];",
]
)
+ "\n"
)
q_circuit = QuantumCircuit.from_qasm_file(qasm_filename)
self.assertEqual(q_circuit, expected_circuit)
self.assertEqual(len(q_circuit.cregs), 2)
self.assertEqual(len(q_circuit.qregs), 2)
def test_qasm_qas_string_order(self):
"""Test that gates are returned in qasm in ascending order."""
expected_qasm = (
"\n".join(
[
"OPENQASM 2.0;",
'include "qelib1.inc";',
"qreg q[3];",
"h q[0];",
"h q[1];",
"h q[2];",
]
)
+ "\n"
)
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
h q;"""
q_circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(q_circuit.qasm(), expected_qasm)
def test_from_qasm_str_custom_gate1(self):
"""Test load custom gates (simple case)"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate rinv q {sdg q; h q; sdg q; h q; }
qreg qr[1];
rinv qr[0];"""
circuit = QuantumCircuit.from_qasm_str(qasm_string)
rinv_q = QuantumRegister(1, name="q")
rinv_gate = QuantumCircuit(rinv_q, name="rinv")
rinv_gate.sdg(rinv_q)
rinv_gate.h(rinv_q)
rinv_gate.sdg(rinv_q)
rinv_gate.h(rinv_q)
rinv = rinv_gate.to_instruction()
qr = QuantumRegister(1, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.append(rinv, [qr[0]])
self.assertEqualUnroll(["sdg", "h"], circuit, expected)
def test_from_qasm_str_custom_gate2(self):
"""Test load custom gates (no so simple case, different bit order)
See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate swap2 a,b {
cx a,b;
cx b,a; // different bit order
cx a,b;
}
qreg qr[3];
swap2 qr[0], qr[1];
swap2 qr[1], qr[2];"""
circuit = QuantumCircuit.from_qasm_str(qasm_string)
ab_args = QuantumRegister(2, name="ab")
swap_gate = QuantumCircuit(ab_args, name="swap2")
swap_gate.cx(ab_args[0], ab_args[1])
swap_gate.cx(ab_args[1], ab_args[0])
swap_gate.cx(ab_args[0], ab_args[1])
swap = swap_gate.to_instruction()
qr = QuantumRegister(3, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.append(swap, [qr[0], qr[1]])
expected.append(swap, [qr[1], qr[2]])
self.assertEqualUnroll(["cx"], expected, circuit)
def test_from_qasm_str_custom_gate3(self):
"""Test load custom gates (no so simple case, different bit count)
See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate cswap2 a,b,c
{
cx c,b; // different bit count
ccx a,b,c; //previously defined gate
cx c,b;
}
qreg qr[3];
cswap2 qr[1], qr[0], qr[2];"""
circuit = QuantumCircuit.from_qasm_str(qasm_string)
abc_args = QuantumRegister(3, name="abc")
cswap_gate = QuantumCircuit(abc_args, name="cswap2")
cswap_gate.cx(abc_args[2], abc_args[1])
cswap_gate.ccx(abc_args[0], abc_args[1], abc_args[2])
cswap_gate.cx(abc_args[2], abc_args[1])
cswap = cswap_gate.to_instruction()
qr = QuantumRegister(3, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.append(cswap, [qr[1], qr[0], qr[2]])
self.assertEqualUnroll(["cx", "h", "tdg", "t"], circuit, expected)
def test_from_qasm_str_custom_gate4(self):
"""Test load custom gates (parameterized)
See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate my_gate(phi,lambda) q {u(1.5707963267948966,phi,lambda) q;}
qreg qr[1];
my_gate(pi, pi) qr[0];"""
circuit = QuantumCircuit.from_qasm_str(qasm_string)
my_gate_circuit = QuantumCircuit(1, name="my_gate")
phi = Parameter("phi")
lam = Parameter("lambda")
my_gate_circuit.u(1.5707963267948966, phi, lam, 0)
my_gate = my_gate_circuit.to_gate()
qr = QuantumRegister(1, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.append(my_gate, [qr[0]])
expected = expected.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793})
self.assertEqualUnroll("u", circuit, expected)
def test_from_qasm_str_custom_gate5(self):
"""Test load custom gates (parameterized, with biop and constant)
See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate my_gate(phi,lambda) q {u(pi/2,phi,lambda) q;} // biop with pi
qreg qr[1];
my_gate(pi, pi) qr[0];"""
circuit = QuantumCircuit.from_qasm_str(qasm_string)
my_gate_circuit = QuantumCircuit(1, name="my_gate")
phi = Parameter("phi")
lam = Parameter("lambda")
my_gate_circuit.u(1.5707963267948966, phi, lam, 0)
my_gate = my_gate_circuit.to_gate()
qr = QuantumRegister(1, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.append(my_gate, [qr[0]])
expected = expected.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793})
self.assertEqualUnroll("u", circuit, expected)
def test_from_qasm_str_custom_gate6(self):
"""Test load custom gates (parameters used in expressions)
See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-591668924
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate my_gate(phi,lambda) q
{rx(phi+pi) q; ry(lambda/2) q;} // parameters used in expressions
qreg qr[1];
my_gate(pi, pi) qr[0];"""
circuit = QuantumCircuit.from_qasm_str(qasm_string)
my_gate_circuit = QuantumCircuit(1, name="my_gate")
phi = Parameter("phi")
lam = Parameter("lambda")
my_gate_circuit.rx(phi + 3.141592653589793, 0)
my_gate_circuit.ry(lam / 2, 0)
my_gate = my_gate_circuit.to_gate()
qr = QuantumRegister(1, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.append(my_gate, [qr[0]])
expected = expected.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793})
self.assertEqualUnroll(["rx", "ry"], circuit, expected)
def test_from_qasm_str_custom_gate7(self):
"""Test load custom gates (build in functions)
See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-592208951
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate my_gate(phi,lambda) q
{u(asin(cos(phi)/2), phi+pi, lambda/2) q;} // build func
qreg qr[1];
my_gate(pi, pi) qr[0];"""
circuit = QuantumCircuit.from_qasm_str(qasm_string)
qr = QuantumRegister(1, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.u(-0.5235987755982988, 6.283185307179586, 1.5707963267948966, qr[0])
self.assertEqualUnroll("u", circuit, expected)
def test_from_qasm_str_nested_custom_gate(self):
"""Test chain of custom gates
See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-592261942
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate my_other_gate(phi,lambda) q
{u(asin(cos(phi)/2), phi+pi, lambda/2) q;}
gate my_gate(phi) r
{my_other_gate(phi, phi+pi) r;}
qreg qr[1];
my_gate(pi) qr[0];"""
circuit = QuantumCircuit.from_qasm_str(qasm_string)
qr = QuantumRegister(1, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.u(-0.5235987755982988, 6.283185307179586, 3.141592653589793, qr[0])
self.assertEqualUnroll("u", circuit, expected)
def test_from_qasm_str_delay(self):
"""Test delay instruction/opaque-gate
See: https://github.com/Qiskit/qiskit-terra/issues/6510
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
opaque delay(time) q;
qreg q[1];
delay(172) q[0];"""
circuit = QuantumCircuit.from_qasm_str(qasm_string)
qr = QuantumRegister(1, name="q")
expected = QuantumCircuit(qr, name="circuit")
expected.delay(172, qr[0])
self.assertEqualUnroll("u", circuit, expected)
def test_definition_with_u_cx(self):
"""Test that gate-definition bodies can use U and CX."""
qasm_string = """
OPENQASM 2.0;
gate bell q0, q1 { U(pi/2, 0, pi) q0; CX q0, q1; }
qreg q[2];
bell q[0], q[1];
"""
circuit = QuantumCircuit.from_qasm_str(qasm_string)
qr = QuantumRegister(2, "q")
expected = QuantumCircuit(qr)
expected.h(0)
expected.cx(0, 1)
self.assertEqualUnroll(["u", "cx"], circuit, expected)
def assertEqualUnroll(self, basis, circuit, expected):
"""Compares the dags after unrolling to basis"""
circuit_dag = circuit_to_dag(circuit)
expected_dag = circuit_to_dag(expected)
circuit_result = Unroller(basis).run(circuit_dag)
expected_result = Unroller(basis).run(expected_dag)
self.assertEqual(circuit_result, expected_result)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
from qiskit import BasicAer
π = np.pi
q = QuantumRegister(3, 'q')
c = ClassicalRegister(1, 'c')
qft = QuantumCircuit(q, c)
qft.h(q[0])
qft.cu1(π/2, q[1], q[0])
qft.h(q[1])
qft.cu1(π/4, q[2], q[0])
qft.cu1(π/2, q[2], q[1])
qft.h(q[2]);
from qiskit.tools.visualization import circuit_drawer
circuit_drawer(qft)
qpe = QuantumCircuit(q, c)
qpe.h(q[0])
qpe.h(q[1]);
# Controlled-U0
qpe.cu3(-π / 2, -π / 2, π / 2, q[1], q[2])
qpe.cu1(3 * π / 4, q[1], q[2])
qpe.cx(q[1], q[2])
qpe.cu1(3 * π / 4, q[1], q[2])
qpe.cx(q[1], q[2])
# Controlled-U1
qpe.cx(q[0], q[2]);
qpe.swap(q[0], q[1])
qpe.h(q[1])
qpe.cu1(-π / 2, q[0], q[1])
qpe.h(q[0]);
circuit_drawer(qpe)
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%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
|
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.visualization import dag_drawer
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)
dag_drawer(dag)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_optimization.problems import QuadraticProgram
# define a problem
qp = QuadraticProgram()
qp.binary_var("x")
qp.integer_var(name="y", lowerbound=-1, upperbound=4)
qp.maximize(quadratic={("x", "y"): 1})
qp.linear_constraint({"x": 1, "y": -1}, "<=", 0)
print(qp.prettyprint())
from qiskit_optimization.algorithms import CplexOptimizer, GurobiOptimizer
cplex_result = CplexOptimizer().solve(qp)
gurobi_result = GurobiOptimizer().solve(qp)
print("cplex")
print(cplex_result.prettyprint())
print()
print("gurobi")
print(gurobi_result.prettyprint())
result = CplexOptimizer(disp=True, cplex_parameters={"threads": 1, "timelimit": 0.1}).solve(qp)
print(result.prettyprint())
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_aer import Aer
from qiskit.algorithms.minimum_eigensolvers import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
meo = MinimumEigenOptimizer(QAOA(sampler=Sampler(), optimizer=COBYLA(maxiter=100)))
result = meo.solve(qp)
print(result.prettyprint())
print("\ndisplay the best 5 solution samples")
for sample in result.samples[:5]:
print(sample)
# docplex model
from docplex.mp.model import Model
docplex_model = Model("docplex")
x = docplex_model.binary_var("x")
y = docplex_model.integer_var(-1, 4, "y")
docplex_model.maximize(x * y)
docplex_model.add_constraint(x <= y)
docplex_model.prettyprint()
# gurobi model
import gurobipy as gp
gurobipy_model = gp.Model("gurobi")
x = gurobipy_model.addVar(vtype=gp.GRB.BINARY, name="x")
y = gurobipy_model.addVar(vtype=gp.GRB.INTEGER, lb=-1, ub=4, name="y")
gurobipy_model.setObjective(x * y, gp.GRB.MAXIMIZE)
gurobipy_model.addConstr(x - y <= 0)
gurobipy_model.update()
gurobipy_model.display()
from qiskit_optimization.translators import from_docplex_mp, from_gurobipy
qp = from_docplex_mp(docplex_model)
print("QuadraticProgram obtained from docpblex")
print(qp.prettyprint())
print("-------------")
print("QuadraticProgram obtained from gurobipy")
qp2 = from_gurobipy(gurobipy_model)
print(qp2.prettyprint())
from qiskit_optimization.translators import to_gurobipy, to_docplex_mp
gmod = to_gurobipy(from_docplex_mp(docplex_model))
print("convert docplex to gurobipy via QuadraticProgram")
gmod.display()
dmod = to_docplex_mp(from_gurobipy(gurobipy_model))
print("\nconvert gurobipy to docplex via QuadraticProgram")
print(dmod.export_as_lp_string())
ind_mod = Model("docplex")
x = ind_mod.binary_var("x")
y = ind_mod.integer_var(-1, 2, "y")
z = ind_mod.integer_var(-1, 2, "z")
ind_mod.maximize(3 * x + y - z)
ind_mod.add_indicator(x, y >= z, 1)
print(ind_mod.export_as_lp_string())
qp = from_docplex_mp(ind_mod)
result = meo.solve(qp) # apply QAOA to QuadraticProgram
print("QAOA")
print(result.prettyprint())
print("-----\nCPLEX")
print(ind_mod.solve()) # apply CPLEX directly to the Docplex model
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""
CCXMöttönen
============
.. currentmodule:: dc_qiskit_qml.distance_based.hadamard.state.cnot._CCXMöttönen
This module implements a :py:class:`CCXFactory` to create a multi-controlled X-gate (or NOT gate) to a circuit
using the uniform rotations as described by Möttönen et al. (http://dl.acm.org/citation.cfm?id=2011670.2011675).
.. autosummary::
:nosignatures:
CCXMöttönen
CCXMöttönen
#############
.. autoclass:: CCXMöttönen
:members:
"""
import logging
from typing import List, Union, Tuple
from dc_qiskit_algorithms.UniformRotation import ccx_uni_rot
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.register import Register
from . import CCXFactory
log = logging.getLogger(__name__)
class CCXMottonen(CCXFactory):
"""
cc-X gate implemented via the uniform rotation scheme (Möttönen et al. 2005)
"""
def ccx(self, qc, conditial_case, control_qubits, tgt):
# type: (CCXFactory, QuantumCircuit, int, Union[List[Tuple[Register, int]], QuantumRegister], Union[Tuple[Register, int], QuantumRegister]) ->QuantumCircuit
"""
Using the Möttönen uniform rotation, one can create multi-controlled NOT gate
(along with other arbitrary rotations). The routine has exponential (w.r.t. number of qubits) gate usage.
:param qc: the circuit to apply this operation to
:param conditial_case: an integer whose binary representation signifies the branch to controll on
:param control_qubits: the qubits that hold the desired conditional case
:param tgt: the target to be applied the controlled X gate on
:return: the circuit after application of the gate
"""
ccx_uni_rot(qc, conditial_case, control_qubits, tgt)
return qc
|
https://github.com/WhenTheyCry96/qiskitHackathon2022
|
WhenTheyCry96
|
%load_ext autoreload
%autoreload 2
import os
import warnings
import numpy as np
import pyEPR as epr
import qiskit_metal as metal
from collections import OrderedDict
import scqubits as scq
from scipy.constants import c, h, pi, hbar, e
from qiskit_metal import designs, draw, MetalGUI, Dict, Headings
from qiskit_metal.qlibrary.tlines.meandered import RouteMeander
from qiskit_metal.qlibrary.tlines.anchored_path import RouteAnchors
from qiskit_metal.analyses.quantization import LOManalysis, EPRanalysis
from qiskit_metal.analyses.em.cpw_calculations import guided_wavelength
from qiskit_metal.qlibrary.qubits.transmon_pocket_cl import TransmonPocketCL
from qiskit_metal.qlibrary.lumped.cap_3_interdigital import Cap3Interdigital
from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled
from qiskit_metal.analyses.quantization.lumped_capacitive import load_q3d_capacitance_matrix
from qiskit_metal.analyses.quantization.lom_core_analysis import CompositeSystem, Cell, Subsystem, QuantumSystemRegistry
ws_path = os.getcwd()
warnings.filterwarnings("ignore")
design = designs.DesignPlanar()
design.overwrite_enabled = True
#constants:
phi0 = h/(2*e)
varphi0 = phi0/(2*pi)
# project target parameters
f_qList = np.around(np.linspace(5.25, 5.75, 4),2) # GHz
f_rList = f_qList + 1.8 # GHz
L_JJList = np.around(varphi0**2/((f_qList*1e9+300e6)**2/(8*300e6))/h*1e9, 2) # nH
# initial CPW readout lengths
def find_resonator_length(frequency, line_width, line_gap, N):
#frequency in GHz
#line_width/line_gap in um
#N -> 2 for lambda/2, 4 for lambda/4
[lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6,
line_gap*10**-6, 750*10**-6, 200*10**-9)
return str(lambdaG/N*10**3)+" mm"
find_resonator_length(f_rList, 10, 6, 2)
design.chips.main.size_x = '12mm'
design.chips.main.size_y = '10mm'
gui = MetalGUI(design)
design.delete_all_components()
design_span_x = 5
design_span_y = 3
half_chip_width = design_span_x / 2
half_chip_height = design_span_y / 2
connection_pads_options = dict(
a = dict(loc_W=1, loc_H=-1),
b = dict(loc_W=1, loc_H=1),
c = dict(loc_W=-1, loc_H=-1)
)
connection23_pads_options = dict(
a = dict(loc_W=1, loc_H=-1),
c = dict(loc_W=-1, loc_H=-1)
)
transmons = []
transmons.append(TransmonPocketCL(design, 'Q1',
options=dict(pos_x=f'-{half_chip_width}mm',
pos_y=f'{-half_chip_height}mm',
connection_pads=dict(**connection_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q2',
options=dict(pos_x=f'0mm',
pos_y=f'{half_chip_height}mm',
orientation=-90,
connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection23_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q3',
options=dict(pos_x=f'0mm',
pos_y=f'{-half_chip_height}mm',
orientation=90,
connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection23_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q4',
options=dict(pos_x=f'{half_chip_width}mm',
pos_y=f'{half_chip_height}mm',
orientation=180,
connection_pads=dict(**connection_pads_options))))
gui.rebuild()
gui.autoscale()
fillet='99.99um'
options = Dict(
meander=Dict(
lead_start='0.1mm',
lead_end='0.1mm',
asymmetry='0 um')
)
def connect(component_name: str, component1: str, pin1: str, component2: str, pin2: str,
length: str,
asymmetry='0 um', start_strght='0 um', end_strght='0 um', flip=False):
"""Connect two pins with a CPW."""
myoptions = Dict(
pin_inputs=Dict(
start_pin=Dict(
component=component1,
pin=pin1),
end_pin=Dict(
component=component2,
pin=pin2)),
lead=Dict(
start_straight=start_strght,
end_straight=end_strght
),
total_length=length,
fillet = '99.9um')
myoptions.update(options)
myoptions.meander.asymmetry = asymmetry
myoptions.meander.lead_direction_inverted = 'true' if flip else 'false'
return RouteMeander(design, component_name, myoptions)
asym_h = 100
asym_v = 100
cpw = []
cpw.append(connect('cpw1', 'Q1', 'b', 'Q2', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw3', 'Q4', 'b', 'Q3', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw4', 'Q3', 'd', 'Q1', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw5', 'Q2', 'd', 'Q4', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm'))
gui.rebuild()
gui.autoscale()
readouts_lwc = []
control_lwc = []
offset_x = 0
offset_y = 1
#Readouts
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R1',
options = dict(
pos_x = '-5mm',
pos_y = f'-{half_chip_height+offset_y}mm',
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R2',
options = dict(
pos_x = '-1mm',
pos_y = '4mm',
orientation = -90,
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R3',
options = dict(
pos_x = '1mm',
pos_y = '-4mm',
orientation = 90,
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R4',
options = dict(
pos_x = '5mm',
pos_y = f'{half_chip_height+offset_y}mm',
orientation = 180,
lead_length = '30um')))
#Controls
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL1',
options = dict(
pos_x = '-5mm',
pos_y = '2mm',
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL2',
options = dict(
pos_x = '4mm',
pos_y = '4mm',
orientation = -90,
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL3',
options = dict(
pos_x = '-4mm',
pos_y = '-4mm',
orientation = 90,
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL4',
options = dict(
pos_x = '5mm',
pos_y = '-2mm',
orientation = 180,
lead_length = '30um')))
gui.rebuild()
gui.autoscale()
readout_lines = []
asym_14 = 700
asym_23 = 700
options = Dict(
lead=Dict(
start_straight='330um',
end_straight='0um'),
fillet='99.99um')
readout_lines.append(connect('ol1', 'Q1', 'c', 'R1', 'tie', '8 mm', f'{asym_14}um'))
options = Dict(
lead=Dict(
start_straight='430um',
end_straight='0um'),
fillet='99.99um')
readout_lines.append(connect('ol2', 'Q2', 'c', 'R2', 'tie', '8 mm', f'{asym_23}um'))
readout_lines.append(connect('ol3', 'Q3', 'c', 'R3', 'tie', '8 mm', f'{asym_23}um'))
readout_lines.append(connect('ol4', 'Q4', 'c', 'R4', 'tie', '8 mm', f'{asym_14}um'))
gui.rebuild()
gui.autoscale()
control_lines = []
def connectRouteAnchor(name: str,
component1: str, pin1: str, component2: str, pin2: str,
anchor_points: OrderedDict) -> RouteAnchors:
options_line_cl = dict(
pin_inputs = dict(start_pin = dict(component = component1, pin = pin1),
end_pin = dict(component = component2, pin = pin2)),
anchors = anchor_points,
lead = dict(start_straight = '200um',
end_straight = '225um'),
fillet = fillet
)
return RouteAnchors(design, name, options_line_cl)
anchors1c = OrderedDict()
anchors1c[0] = np.array([-4, -1.42])
anchors1c[1] = np.array([-4, 2])
control_lines.append(connectRouteAnchor('line_cl1', 'Q1', 'Charge_Line', 'CL1', 'tie', anchors1c))
anchors2c = OrderedDict()
anchors2c[0] = np.array([0.08, 3.25])
anchors2c[1] = np.array([4, 3.25])
control_lines.append(connectRouteAnchor('line_cl2', 'Q2', 'Charge_Line', 'CL2', 'tie', anchors2c))
anchors3c = OrderedDict()
anchors3c[0] = np.array([-0.08, -3.25])
anchors3c[1] = np.array([-4, -3.25])
control_lines.append(connectRouteAnchor('line_cl3', 'Q3', 'Charge_Line', 'CL3', 'tie', anchors3c))
anchors4c = OrderedDict()
anchors4c[0] = np.array([4, 1.42])
anchors4c[1] = np.array([4, -2])
control_lines.append(connectRouteAnchor('line_cl4', 'Q4', 'Charge_Line', 'CL4', 'tie', anchors4c))
gui.rebuild()
gui.autoscale()
gui.screenshot(name="full_design.png")
# constants:
phi0 = h/(2*e)
varphi0 = phi0/(2*pi)
# project target parameters
f_qList = np.around(np.linspace(5.25, 5.75, 4),2) # GHz
f_rList = f_qList + 1.8 # GHz
L_JJList = np.around(varphi0**2/((f_qList*1e9+300e6)**2/(8*300e6))/h*1e9, 2) # nH
# initial CPW readout lengths
def find_resonator_length(frequency, line_width, line_gap, N):
#frequency in GHz
#line_width/line_gap in um
#N -> 2 for lambda/2, 4 for lambda/4
[lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6,
line_gap*10**-6, 750*10**-6, 200*10**-9)
return str(lambdaG/N*10**3)+" mm"
find_resonator_length(f_rList, 10, 6, 2)
# CPW busline length is determined to be 7 mm
cpw[0].options.total_length = '7.0mm'
cpw[1].options.total_length = '7.0mm'
cpw[2].options.total_length = '7.0mm'
cpw[3].options.total_length = '7.0mm'
gui.rebuild()
gui.autoscale()
# qubit 1 design target f: 5.25 GHz
# readout resonator target f: 7.05 GHz
# qubit 2 design target f: 5.42 GHz
# readout resonator target f: 7.22 GHz
transmons[1].options.pad_gap = '40um'
transmons[1].options.pad_width = '390um' # 405
transmons[1].options.pad_height = '120um'
transmons[1].options.connection_pads.d.pad_gap='8um'
transmons[1].options.connection_pads.a.pad_gap='8um'
transmons[1].options.connection_pads.c.pad_gap='8um'
transmons[1].options.connection_pads.d.pad_width='140um'
transmons[1].options.connection_pads.a.pad_width='140um'
transmons[1].options.connection_pads.c.pad_width='150um'
transmons[1].options.connection_pads.d.pad_gap
# qubit 3 design target f: 5.58 GHz
# readout resonator target f: 7.38 GHz
transmons[2].options.pad_gap = '40um'
transmons[2].options.pad_width = '370um' # 405
transmons[2].options.pad_height = '120um'
transmons[2].options.connection_pads.d.pad_gap='10um'
transmons[2].options.connection_pads.a.pad_gap='10um'
transmons[2].options.connection_pads.c.pad_gap='10um'
# qubit 4 design target f: 5.75 GHz
# readout resonator target f: 7.55 GHz
# tuning parameters
C_JJ4f = 2
L_JJ4f = 9.8
C_JJ4 = str(C_JJ4f)+' fF'
L_JJ4 = str(L_JJ4f)+' nH'
transmons[3].options.pad_gap = '35um'
transmons[3].options.pad_width = '510um'
transmons[3].options.pad_height = '125um'
transmons[3].options.connection_pads.c.pad_gap = '30um'
transmons[3].options.connection_pads.a.pad_gap = '15um' # cpw5
transmons[3].options.connection_pads.a.pad_width = '40um' # cpw5
transmons[3].options.connection_pads.b.pad_gap = '15um' # cpw3
transmons[3].options.connection_pads.b.pad_width = '40um' # cpw3
readout_lines[3].options.total_length = '7.5mm'
gui.rebuild()
gui.autoscale()
|
https://github.com/harshdeeps036/QiskitFallFest21-AU
|
harshdeeps036
|
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumRegister, ClassicalRegister, execute
from qiskit import QuantumCircuit, execute, Aer
from qiskit.tools.jupyter import *
import matplotlib.pyplot as plt
import numpy as np
from math import pi
%matplotlib inline
def real_map(value, leftMin, leftMax, rightMin, rightMax):
# Maps one range to another
# Figure out how 'wide' each range is
leftSpan = leftMax - leftMin
rightSpan = rightMax - rightMin
# Convert the left range into a 0-1 range (float)
valueScaled = float(value - leftMin) / float(leftSpan)
# Convert the 0-1 range into a value in the right range.
return rightMin + (valueScaled * rightSpan)
# Quantum Random Number generator
def QRandom(a, b, qubits):
q = QuantumRegister(qubits, 'q')
circ = QuantumCircuit(q)
c0 = ClassicalRegister(1, 'c0')
circ.add_register(c0)
for i in range(qubits):
circ.h(q[i])
for i in range(qubits):
circ.measure(q[i], c0)
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
result = job.result()
output = result.get_statevector(circ, decimals=5)
n1 = 0
n2 = 0
n3 = 0
for i in range( output.size ):
if abs(output[i]) != 0:
n1 = i
n2 = np.real(output[i])
n3 = np.imag(output[i])
y = real_map(n1+n2+n3, -qubits, len(output)-1+qubits, a, b)
return y
y = []
for i in range(20):
y.append(QRandom(0,100,3))
plt.plot(y)
# Example of number of unique random numbers:
# Generating 40 random numbers with our QRNG
y = []
for i in range(40):
y.append(QRandom(0,100,3))
count = 0
z=[]
#Counting the number of unique elements
for num in y:
if num not in z:
count = count+1
z.append(num)
print('The number of unique elements in provided random distribution is:')
print(count)
# Variational Quantum Random Number generator
def VarQRandom(a, b, theta, depth, qubits):
q = QuantumRegister(qubits, 'q')
circ = QuantumCircuit(q)
c0 = ClassicalRegister(2, 'c0')
circ.add_register(c0)
for j in range(depth):
for i in range(qubits):
circ.h(q[i])
#rotating the axis by an angle theta along y-axis
circ.ry(theta, q[i])
#rotating the axis by an angle theta along x-axis
circ.rx(theta, q[i])
for i in range(qubits):
circ.measure(q[i], c0)
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
result = job.result()
output = result.get_statevector(circ, decimals=5)
n1 = 0
n2 = 0
n3 = 0
for i in range( output.size ):
if abs(output[i]) != 0:
n1 = i
n2 = np.real(output[i])
n3 = np.imag(output[i])
y = real_map(n1+n2+n3, -qubits, len(output)-1+qubits, a, b)
return y
#initialization
m=0
length = 0
theta = 0
#taking input from the user
number = int(input('Enter the number of random numbers required'))
low = int(input('Enter lower limit'))
high = int(input('Enter higher limit'))
depth=1
x=[]
n=1
while length!=number:
y = VarQRandom(low,high,theta,depth,3)
while (y in x):
i=i+1
theta = theta + pi/16
y= VarQRandom(low,high,theta,depth,3)
if(i==(16*n)):
depth = depth+1
n=n+1
x.append(y)
length=len(x)
plt.plot(x)
count = 0
z=[]
#Counting the number of unique elements
for num in x:
if num not in z:
count = count+1
z.append(num)
print('The number of unique elements in provided random distribution is:')
print(count)
y2 = []
for i in range(20):
y2.append(QRandom(0,100,2))
plt.plot(y2)
z2=[]
count = 0
#Counting the number of unique elements
for num in y2:
if num not in z2:
count = count+1
z2.append(num)
print('The number of unique elements in provided random distribution is:')
print(count)
#initialization
m=0
length = 0
theta = 0
#taking input from the user
number = int(input('Enter the number of random numbers required'))
low = int(input('Enter lower limit'))
high = int(input('Enter higher limit'))
depth=1
x2=[]
n=1
while length!=number:
y = VarQRandom(low,high,theta,depth,2)
while (y in x2):
i=i+1
theta = theta + pi/16
y= VarQRandom(low,high,theta,depth,2)
if(i==(16*n)):
depth = depth+1
n=n+1
x2.append(y)
length=len(x2)
plt.plot(x2)
z2=[]
count = 0
#Counting the number of unique elements
for num in x2:
if num not in z2:
count = count+1
z2.append(num)
print('The number of unique elements in provided random distribution is:')
print(count)
from datetime import datetime
start_time = datetime.now()
y3 = []
for i in range(100):
y3.append(QRandom(0,100,2))
end_time = datetime.now()
print('Duration: {}'.format(end_time - start_time))
#initialization
m=0
length = 0
theta = 0
#taking input from the user
number = int(input('Enter the number of random numbers required'))
low = int(input('Enter lower limit'))
high = int(input('Enter higher limit'))
depth=1
x2=[]
n=1
start_time = datetime.now()
while length!=number:
y = VarQRandom(low,high,theta,depth,3)
while (y in x2):
i=i+1
theta = theta + pi/16
y= VarQRandom(low,high,theta,depth,3)
if(i==(16*n)):
depth = depth+1
n=n+1
x2.append(y)
length=len(x2)
end_time = datetime.now()
print('Duration: {}'.format(end_time - start_time))
#initialization
m=0
length = 0
theta = 0
#taking input from the user
number = int(input('Enter the number of random numbers required'))
low = int(input('Enter lower limit'))
high = int(input('Enter higher limit'))
depth=1
x4=[]
n=1
start_time = datetime.now()
while length!=number:
y = VarQRandom(low,high,theta,depth,2)
while (y in x2):
i=i+1
theta = theta + pi/16
y= VarQRandom(low,high,theta,depth,2)
if(i==(16*n)):
depth = depth+1
n=n+1
x4.append(y)
length=len(x4)
end_time = datetime.now()
print('Duration: {}'.format(end_time - start_time))
import random
testpy=[]
for i in range(20):
y=random.randint(1,100)
if y not in testpy:
testpy.append(y)
plt.plot(testpy)
#initialization
m=0
length = 0
theta = 0
#taking input from the user
number = int(input('Enter the number of random numbers required'))
low = int(input('Enter lower limit'))
high = int(input('Enter higher limit'))
depth=1
testvc=[]
n=1
while length!=number:
y = VarQRandom(low,high,theta,depth,2)
while (y in testvc):
i=i+1
theta = theta + pi/16
y= VarQRandom(low,high,theta,depth,2)
if(i==(16*n)):
depth = depth+1
n=n+1
testvc.append(y)
length=len(testvc)
plt.plot(testvc)
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
### added h gate ###
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)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/quantumgenetics/quantumgenetics
|
quantumgenetics
|
#!/usr/bin/env python3
import logging
from datetime import datetime
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
logger = logging.getLogger(__name__)
def map_circuit(circuit_qcount, gate_map, measurements):
logger.info('Producing circuit...')
before = datetime.now()
qr = QuantumRegister(circuit_qcount)
cr = ClassicalRegister(circuit_qcount)
circuit = QuantumCircuit(qr, cr)
for m in measurements:
gate_map[m](circuit)
delta = datetime.now() - before
logger.info('Circuit produced ({} s)'.format(delta.total_seconds()))
return circuit
|
https://github.com/QC-Hub/Examples
|
QC-Hub
|
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute
from qiskit import Aer
import numpy as np
import sys
N=int(sys.argv[1])
filename = sys.argv[2]
backend = Aer.get_backend('unitary_simulator')
def GHZ(n):
if n<=0:
return None
circ = QuantumCircuit(n)
# Put your code below
# ----------------------------
circ.h(0)
for x in range(1,n):
circ.cx(x-1,x)
# ----------------------------
return circ
circuit = GHZ(N)
job = execute(circuit, backend, shots=8192)
result = job.result()
array = result.get_unitary(circuit,3)
np.savetxt(filename, array, delimiter=",", fmt = "%0.3f")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.