repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/kurtchahn/QiskitPrx
|
kurtchahn
|
import qiskit as qk
import qiskit_aer as qaer
import numpy as np
import math
sSimulator = qaer.Aer.backends(name="statevector_simulator")[0]
mSimulator = qaer.Aer.backends(name="qasm_simulator")[0]
|
https://github.com/ctuning/ck-qiskit
|
ctuning
|
#!/usr/bin/env python3
import qiskit.tools.apps.optimization
num_of_qubits = 2
circuit_depth = 6
num_params = 2 * num_of_qubits * circuit_depth # make sure you set this correctly to the number of parameters used by the ansatz
## Previously used for Hydrogen VQE in QISKit implementation
#
def universal_ansatz(current_params, entangler_map=None):
if entangler_map==None:
# Which qubits to use (0 to 1 best to avoid qiskit bugs)
entangler_map = {1: [0]}
return qiskit.tools.apps.optimization.trial_circuit_ryrz(num_of_qubits, circuit_depth, current_params, entangler_map, None, False)
|
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 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
This module contains the definition of a base class for quantum fourier transforms.
"""
from abc import abstractmethod
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.aqua import Pluggable, AquaError
class QFT(Pluggable):
"""Base class for QFT.
This method should initialize the module and its configuration, and
use an exception if a component of the module is
available.
Args:
configuration (dict): configuration dictionary
"""
@abstractmethod
def __init__(self, *args, **kwargs):
super().__init__()
@classmethod
def init_params(cls, params):
qft_params = params.get(Pluggable.SECTION_KEY_QFT)
kwargs = {k: v for k, v in qft_params.items() if k != 'name'}
return cls(**kwargs)
@abstractmethod
def _build_matrix(self):
raise NotImplementedError
@abstractmethod
def _build_circuit(self, qubits=None, circuit=None, do_swaps=True):
raise NotImplementedError
def construct_circuit(self, mode='circuit', qubits=None, circuit=None, do_swaps=True):
"""Construct the circuit.
Args:
mode (str): 'matrix' or 'circuit'
qubits (QuantumRegister or qubits): register or qubits to build the circuit on.
circuit (QuantumCircuit): circuit for construction.
do_swaps (bool): include the swaps.
Returns:
The matrix or circuit depending on the specified mode.
"""
if mode == 'circuit':
return self._build_circuit(qubits=qubits, circuit=circuit, do_swaps=do_swaps)
elif mode == 'matrix':
return self._build_matrix()
else:
raise AquaError('Unrecognized mode: {}.'.format(mode))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.compiler import transpile
from qiskit.transpiler import PassManager
circ = QuantumCircuit(3)
circ.ccx(0, 1, 2)
circ.draw(output='mpl')
from qiskit.transpiler.passes import Unroller
pass_ = Unroller(['u1', 'u2', 'u3', 'cx'])
pm = PassManager(pass_)
new_circ = pm.run(circ)
new_circ.draw(output='mpl')
from qiskit.transpiler import passes
[pass_ for pass_ in dir(passes) if pass_[0].isupper()]
from qiskit.transpiler import CouplingMap, Layout
from qiskit.transpiler.passes import BasicSwap, LookaheadSwap, StochasticSwap
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
circuit = QuantumCircuit(7)
circuit.h(3)
circuit.cx(0, 6)
circuit.cx(6, 0)
circuit.cx(0, 1)
circuit.cx(3, 1)
circuit.cx(3, 0)
coupling_map = CouplingMap(couplinglist=coupling)
bs = BasicSwap(coupling_map=coupling_map)
pass_manager = PassManager(bs)
basic_circ = pass_manager.run(circuit)
ls = LookaheadSwap(coupling_map=coupling_map)
pass_manager = PassManager(ls)
lookahead_circ = pass_manager.run(circuit)
ss = StochasticSwap(coupling_map=coupling_map)
pass_manager = PassManager(ss)
stochastic_circ = pass_manager.run(circuit)
circuit.draw(output='mpl')
basic_circ.draw(output='mpl')
lookahead_circ.draw(output='mpl')
stochastic_circ.draw(output='mpl')
import math
from qiskit.providers.fake_provider import FakeTokyo
backend = FakeTokyo() # mimics the tokyo device in terms of coupling map and basis gates
qc = QuantumCircuit(10)
random_state = [
1 / math.sqrt(4) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
0,
0,
0,
0,
0,
0,
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(8) * complex(0, 1),
0,
0,
0,
0,
1 / math.sqrt(4) * complex(1, 0),
1 / math.sqrt(8) * complex(1, 0)]
qc.initialize(random_state, range(4))
qc.draw()
optimized_0 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=0)
print('gates = ', optimized_0.count_ops())
print('depth = ', optimized_0.depth())
optimized_1 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=1)
print('gates = ', optimized_1.count_ops())
print('depth = ', optimized_1.depth())
optimized_2 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=2)
print('gates = ', optimized_2.count_ops())
print('depth = ', optimized_2.depth())
optimized_3 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=3)
print('gates = ', optimized_3.count_ops())
print('depth = ', optimized_3.depth())
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
circ.draw(output='mpl')
from qiskit.converters import circuit_to_dag
from qiskit.tools.visualization import dag_drawer
dag = circuit_to_dag(circ)
dag_drawer(dag)
dag.op_nodes()
node = dag.op_nodes()[3]
print("node name: ", node.name)
print("node op: ", node.op)
print("node qargs: ", node.qargs)
print("node cargs: ", node.cargs)
print("node condition: ", node.op.condition)
from qiskit.circuit.library import HGate
dag.apply_operation_back(HGate(), qargs=[q[0]])
dag_drawer(dag)
from qiskit.circuit.library import CCXGate
dag.apply_operation_front(CCXGate(), qargs=[q[0], q[1], q[2]], cargs=[])
dag_drawer(dag)
from qiskit.circuit.library import CHGate, U2Gate, CXGate
mini_dag = DAGCircuit()
p = QuantumRegister(2, "p")
mini_dag.add_qreg(p)
mini_dag.apply_operation_back(CHGate(), qargs=[p[1], p[0]])
mini_dag.apply_operation_back(U2Gate(0.1, 0.2), qargs=[p[1]])
# substitute the cx node with the above mini-dag
cx_node = dag.op_nodes(op=CXGate).pop()
dag.substitute_node_with_dag(node=cx_node, input_dag=mini_dag, wires=[p[0], p[1]])
dag_drawer(dag)
from qiskit.converters import dag_to_circuit
circuit = dag_to_circuit(dag)
circuit.draw(output='mpl')
from copy import copy
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.transpiler import Layout
from qiskit.circuit.library import SwapGate
class BasicSwap(TransformationPass):
"""Maps (with minimum effort) a DAGCircuit onto a `coupling_map` adding swap gates."""
def __init__(self,
coupling_map,
initial_layout=None):
"""Maps a DAGCircuit onto a `coupling_map` using swap gates.
Args:
coupling_map (CouplingMap): Directed graph represented a coupling map.
initial_layout (Layout): initial layout of qubits in mapping
"""
super().__init__()
self.coupling_map = coupling_map
self.initial_layout = initial_layout
def run(self, dag):
"""Runs the BasicSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
Raises:
TranspilerError: if the coupling map or the layout are not
compatible with the DAG.
"""
new_dag = DAGCircuit()
for qreg in dag.qregs.values():
new_dag.add_qreg(qreg)
for creg in dag.cregs.values():
new_dag.add_creg(creg)
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
if len(dag.qubits) != len(self.initial_layout):
raise TranspilerError('The layout does not match the amount of qubits in the DAG')
if len(self.coupling_map.physical_qubits) != len(self.initial_layout):
raise TranspilerError(
"Mappers require to have the layout to be the same size as the coupling map")
canonical_register = dag.qregs['q']
trivial_layout = Layout.generate_trivial_layout(canonical_register)
current_layout = trivial_layout.copy()
for layer in dag.serial_layers():
subdag = layer['graph']
for gate in subdag.two_qubit_ops():
physical_q0 = current_layout[gate.qargs[0]]
physical_q1 = current_layout[gate.qargs[1]]
if self.coupling_map.distance(physical_q0, physical_q1) != 1:
# Insert a new layer with the SWAP(s).
swap_layer = DAGCircuit()
swap_layer.add_qreg(canonical_register)
path = self.coupling_map.shortest_undirected_path(physical_q0, physical_q1)
for swap in range(len(path) - 2):
connected_wire_1 = path[swap]
connected_wire_2 = path[swap + 1]
qubit_1 = current_layout[connected_wire_1]
qubit_2 = current_layout[connected_wire_2]
# create the swap operation
swap_layer.apply_operation_back(SwapGate(),
qargs=[qubit_1, qubit_2],
cargs=[])
# layer insertion
order = current_layout.reorder_bits(new_dag.qubits)
new_dag.compose(swap_layer, qubits=order)
# update current_layout
for swap in range(len(path) - 2):
current_layout.swap(path[swap], path[swap + 1])
order = current_layout.reorder_bits(new_dag.qubits)
new_dag.compose(subdag, qubits=order)
return new_dag
q = QuantumRegister(7, 'q')
in_circ = QuantumCircuit(q)
in_circ.h(q[0])
in_circ.cx(q[0], q[4])
in_circ.cx(q[2], q[3])
in_circ.cx(q[6], q[1])
in_circ.cx(q[5], q[0])
in_circ.rz(0.1, q[2])
in_circ.cx(q[5], q[0])
from qiskit.transpiler import PassManager
from qiskit.transpiler import CouplingMap
from qiskit import BasicAer
pm = PassManager()
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
coupling_map = CouplingMap(couplinglist=coupling)
pm.append([BasicSwap(coupling_map)])
out_circ = pm.run(in_circ)
in_circ.draw(output='mpl')
out_circ.draw(output='mpl')
import logging
logging.basicConfig(level='DEBUG')
from qiskit.providers.fake_provider import FakeTenerife
log_circ = QuantumCircuit(2, 2)
log_circ.h(0)
log_circ.h(1)
log_circ.h(1)
log_circ.x(1)
log_circ.cx(0, 1)
log_circ.measure([0,1], [0,1])
backend = FakeTenerife()
transpile(log_circ, backend);
logging.getLogger('qiskit.transpiler').setLevel('INFO')
transpile(log_circ, backend);
# Change log level back to DEBUG
logging.getLogger('qiskit.transpiler').setLevel('DEBUG')
# Transpile multiple circuits
circuits = [log_circ, log_circ]
transpile(circuits, backend);
formatter = logging.Formatter('%(name)s - %(processName)-10s - %(levelname)s: %(message)s')
handler = logging.getLogger().handlers[0]
handler.setFormatter(formatter)
transpile(circuits, backend);
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-class-docstring,missing-function-docstring
"""Test Counts class."""
import unittest
import numpy as np
from qiskit.result import counts
from qiskit import exceptions
from qiskit.result import utils
class TestCounts(unittest.TestCase):
def test_just_counts(self):
raw_counts = {"0x0": 21, "0x2": 12}
expected = {"0": 21, "10": 12}
result = counts.Counts(raw_counts)
self.assertEqual(expected, result)
def test_counts_with_exta_formatting_data(self):
raw_counts = {"0x0": 4, "0x2": 10}
expected = {"0 0 00": 4, "0 0 10": 10}
result = counts.Counts(
raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4
)
self.assertEqual(result, expected)
def test_marginal_counts(self):
raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_counts(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_marginal_distribution(self):
raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_distribution(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_marginal_distribution_numpy_indices(self):
raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8}
expected = {"00": 4, "01": 27, "10": 23}
indices = np.asarray([0, 1])
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_distribution(counts_obj, indices)
self.assertEqual(expected, result)
def test_int_outcomes(self):
raw_counts = {"0x0": 21, "0x2": 12, "0x3": 5, "0x2E": 265}
expected = {0: 21, 2: 12, 3: 5, 46: 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.int_outcomes()
self.assertEqual(expected, result)
def test_most_frequent(self):
raw_counts = {"0x0": 21, "0x2": 12, "0x3": 5, "0x2E": 265}
expected = "101110"
counts_obj = counts.Counts(raw_counts)
result = counts_obj.most_frequent()
self.assertEqual(expected, result)
def test_most_frequent_duplicate(self):
raw_counts = {"0x0": 265, "0x2": 12, "0x3": 5, "0x2E": 265}
counts_obj = counts.Counts(raw_counts)
self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent)
def test_hex_outcomes(self):
raw_counts = {"0x0": 21, "0x2": 12, "0x3": 5, "0x2E": 265}
expected = {"0x0": 21, "0x2": 12, "0x3": 5, "0x2e": 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.hex_outcomes()
self.assertEqual(expected, result)
def test_just_int_counts(self):
raw_counts = {0: 21, 2: 12}
expected = {"0": 21, "10": 12}
result = counts.Counts(raw_counts)
self.assertEqual(expected, result)
def test_int_counts_with_exta_formatting_data(self):
raw_counts = {0: 4, 2: 10}
expected = {"0 0 00": 4, "0 0 10": 10}
result = counts.Counts(
raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4
)
self.assertEqual(result, expected)
def test_marginal_int_counts(self):
raw_counts = {0: 4, 1: 7, 2: 10, 6: 5, 9: 11, 13: 9, 14: 8}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_counts(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_marginal_distribution_int_counts(self):
raw_counts = {0: 4, 1: 7, 2: 10, 6: 5, 9: 11, 13: 9, 14: 8}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_distribution(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_marginal_distribution_int_counts_numpy_64_bit(self):
raw_counts = {
0: np.int64(4),
1: np.int64(7),
2: np.int64(10),
6: np.int64(5),
9: np.int64(11),
13: np.int64(9),
14: np.int64(8),
}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_distribution(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_marginal_distribution_int_counts_numpy_8_bit(self):
raw_counts = {
0: np.int8(4),
1: np.int8(7),
2: np.int8(10),
6: np.int8(5),
9: np.int8(11),
13: np.int8(9),
14: np.int8(8),
}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_distribution(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_int_outcomes_with_int_counts(self):
raw_counts = {0: 21, 2: 12, 3: 5, 46: 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.int_outcomes()
self.assertEqual(raw_counts, result)
def test_most_frequent_int_counts(self):
raw_counts = {0: 21, 2: 12, 3: 5, 46: 265}
expected = "101110"
counts_obj = counts.Counts(raw_counts)
result = counts_obj.most_frequent()
self.assertEqual(expected, result)
def test_most_frequent_duplicate_int_counts(self):
raw_counts = {0: 265, 2: 12, 3: 5, 46: 265}
counts_obj = counts.Counts(raw_counts)
self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent)
def test_hex_outcomes_int_counts(self):
raw_counts = {0: 265, 2: 12, 3: 5, 46: 265}
expected = {"0x0": 265, "0x2": 12, "0x3": 5, "0x2e": 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.hex_outcomes()
self.assertEqual(expected, result)
def test_invalid_input_type(self):
self.assertRaises(TypeError, counts.Counts, {2.4: 1024})
def test_just_bitstring_counts(self):
raw_counts = {"0": 21, "10": 12}
expected = {"0": 21, "10": 12}
result = counts.Counts(raw_counts)
self.assertEqual(expected, result)
def test_bistring_counts_with_exta_formatting_data(self):
raw_counts = {"0": 4, "10": 10}
expected = {"0 0 00": 4, "0 0 10": 10}
result = counts.Counts(
raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4
)
self.assertEqual(result, expected)
def test_marginal_bitstring_counts(self):
raw_counts = {"0": 4, "1": 7, "10": 10, "110": 5, "1001": 11, "1101": 9, "1110": 8}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_counts(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_marginal_distribution_bitstring_counts(self):
raw_counts = {"0": 4, "1": 7, "10": 10, "110": 5, "1001": 11, "1101": 9, "1110": 8}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_distribution(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_int_outcomes_with_bitstring_counts(self):
raw_counts = {"0": 21, "10": 12, "11": 5, "101110": 265}
expected = {0: 21, 2: 12, 3: 5, 46: 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.int_outcomes()
self.assertEqual(expected, result)
def test_most_frequent_bitstring_counts(self):
raw_counts = {"0": 21, "10": 12, "11": 5, "101110": 265}
expected = "101110"
counts_obj = counts.Counts(raw_counts)
result = counts_obj.most_frequent()
self.assertEqual(expected, result)
def test_most_frequent_duplicate_bitstring_counts(self):
raw_counts = {"0": 265, "10": 12, "11": 5, "101110": 265}
counts_obj = counts.Counts(raw_counts)
self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent)
def test_hex_outcomes_bitstring_counts(self):
raw_counts = {"0": 265, "10": 12, "11": 5, "101110": 265}
expected = {"0x0": 265, "0x2": 12, "0x3": 5, "0x2e": 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.hex_outcomes()
self.assertEqual(expected, result)
def test_qudit_counts(self):
raw_counts = {
"00": 121,
"01": 109,
"02": 114,
"10": 113,
"11": 106,
"12": 114,
"20": 117,
"21": 104,
"22": 102,
}
result = counts.Counts(raw_counts)
self.assertEqual(raw_counts, result)
def test_qudit_counts_raises_with_format(self):
raw_counts = {
"00": 121,
"01": 109,
"02": 114,
"10": 113,
"11": 106,
"12": 114,
"20": 117,
"21": 104,
"22": 102,
}
self.assertRaises(exceptions.QiskitError, counts.Counts, raw_counts, creg_sizes=[["c0", 4]])
def test_qudit_counts_hex_outcome(self):
raw_counts = {
"00": 121,
"01": 109,
"02": 114,
"10": 113,
"11": 106,
"12": 114,
"20": 117,
"21": 104,
"22": 102,
}
counts_obj = counts.Counts(raw_counts)
self.assertRaises(exceptions.QiskitError, counts_obj.hex_outcomes)
def test_qudit_counts_int_outcome(self):
raw_counts = {
"00": 121,
"01": 109,
"02": 114,
"10": 113,
"11": 106,
"12": 114,
"20": 117,
"21": 104,
"22": 102,
}
counts_obj = counts.Counts(raw_counts)
self.assertRaises(exceptions.QiskitError, counts_obj.int_outcomes)
def test_qudit_counts_most_frequent(self):
raw_counts = {
"00": 121,
"01": 109,
"02": 114,
"10": 113,
"11": 106,
"12": 114,
"20": 117,
"21": 104,
"22": 102,
}
counts_obj = counts.Counts(raw_counts)
self.assertEqual("00", counts_obj.most_frequent())
def test_just_0b_bitstring_counts(self):
raw_counts = {"0b0": 21, "0b10": 12}
expected = {"0": 21, "10": 12}
result = counts.Counts(raw_counts)
self.assertEqual(expected, result)
def test_0b_bistring_counts_with_exta_formatting_data(self):
raw_counts = {"0b0": 4, "0b10": 10}
expected = {"0 0 00": 4, "0 0 10": 10}
result = counts.Counts(
raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4
)
self.assertEqual(result, expected)
def test_marginal_0b_string_counts(self):
raw_counts = {
"0b0": 4,
"0b1": 7,
"0b10": 10,
"0b110": 5,
"0b1001": 11,
"0b1101": 9,
"0b1110": 8,
}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_counts(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_marginal_distribution_0b_string_counts(self):
raw_counts = {
"0b0": 4,
"0b1": 7,
"0b10": 10,
"0b110": 5,
"0b1001": 11,
"0b1101": 9,
"0b1110": 8,
}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_distribution(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_int_outcomes_with_0b_bitstring_counts(self):
raw_counts = {"0b0": 21, "0b10": 12, "0b11": 5, "0b101110": 265}
expected = {0: 21, 2: 12, 3: 5, 46: 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.int_outcomes()
self.assertEqual(expected, result)
def test_most_frequent_0b_bitstring_counts(self):
raw_counts = {"0b0": 21, "0b10": 12, "0b11": 5, "0b101110": 265}
expected = "101110"
counts_obj = counts.Counts(raw_counts)
result = counts_obj.most_frequent()
self.assertEqual(expected, result)
def test_most_frequent_duplicate_0b_bitstring_counts(self):
raw_counts = {"0b0": 265, "0b10": 12, "0b11": 5, "0b101110": 265}
counts_obj = counts.Counts(raw_counts)
self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent)
def test_hex_outcomes_0b_bitstring_counts(self):
raw_counts = {"0b0": 265, "0b10": 12, "0b11": 5, "0b101110": 265}
expected = {"0x0": 265, "0x2": 12, "0x3": 5, "0x2e": 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.hex_outcomes()
self.assertEqual(expected, result)
def test_empty_bitstring_counts(self):
raw_counts = {}
expected = {}
result = counts.Counts(raw_counts)
self.assertEqual(expected, result)
def test_empty_bistring_counts_with_exta_formatting_data(self):
raw_counts = {}
expected = {}
result = counts.Counts(
raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4
)
self.assertEqual(result, expected)
def test_int_outcomes_with_empty_counts(self):
raw_counts = {}
expected = {}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.int_outcomes()
self.assertEqual(expected, result)
def test_most_frequent_empty_bitstring_counts(self):
raw_counts = {}
counts_obj = counts.Counts(raw_counts)
self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent)
def test_hex_outcomes_empty_bitstring_counts(self):
raw_counts = {}
expected = {}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.hex_outcomes()
self.assertEqual(expected, result)
|
https://github.com/QPower-Research/QPowerAlgo
|
QPower-Research
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import *
from qiskit.providers.ibmq import least_busy
from qiskit.tools.visualization import plot_histogram
from IPython.display import display, Math, Latex
def Increment(size):
U = QuantumCircuit(size)
control = [x for x in range(size-1)]
for k in range(size-1):
U.mcx(control, control[-1]+1)
control.pop()
U.x(0)
U = U.to_gate()
U.name = '--->'
ctl_U = U.control()
return ctl_U
def Decrement(size):
U = QuantumCircuit(size)
control = [x for x in range(size-1)]
for k in range(size-1):
U.x(control)
U.mcx(control, control[-1]+1)
U.x(control)
control.pop()
U.x(0)
U = U.to_gate()
U.name = '<---'
ctl_U = U.control()
return ctl_U
n = 2
steps = 2
graph = QuantumRegister(n+1)
mes = ClassicalRegister(n)
mcq = QuantumCircuit(graph, mes)
#define U(t)
for i in range(steps):
mcq.h(n)
mcq.append(Increment(n), [n]+list(range(0, n)))
mcq.x(n)
mcq.append(Decrement(n), [n]+list(range(0, n)))
mcq.x(n)
mcq.measure(range(n), range(n))
#mcq = transpile(mcq, basis_gates=['cx','u3'],optimization_level=3)
mcq.draw('mpl')
backend = BasicAer.get_backend('qasm_simulator')
atp = 1024
res = execute(mcq, backend=backend, shots=atp).result()
ans = res.get_counts()
plot_histogram(ans)
IBMQ.load_account()
provider = IBMQ.get_provider(group='open', project='main')
backend = provider.get_backend('ibmq_16_melbourne')
job = execute(mcq, backend=backend)
ans_quantum = job.result().get_counts()
legend = ['QASM','ibmq_16_melbourne']
plot_histogram([ans,ans_quantum], legend=legend)
|
https://github.com/Chibikuri/Quantum-Othello
|
Chibikuri
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.compiler import transpile
import numpy as np
import collections
import random
import matplotlib.pyplot as plt
import os
plt.ioff()
'''
Function to create folder
'''
def createFolder(directory):
try:
if not os.path.exists(directory):
os.makedirs(directory)
except OSError:
print ('Error: Creating directory. ' + directory)
'''
Define class
'''
class QuantumOthello():
def __init__(self, num, turn):
self.num = num
self.turn = turn
self.qc = QuantumCircuit(num)
self.turnA = int(self.turn/2)
self.turnB = self.turn - self.turnA
self.GateA = self.RandomGate(self.turnA)
self.GateB = self.RandomGate(self.turnB)
self.MeasurementBasis = self.RandomBasis()
def StartTheGame(self):
for i in range(self.num):
if i % 2 == 0:
x = str(input('A, instruction >'))
y = int(input('A #qubit >'))
self.initial(x, y)
else:
x = str(input('B, instruction >'))
y = int(input('B #qubit >'))
self.initial(x, y)
self.end_initial()
#q.get_cir()
print('End of initialization')
for i in range(self.turn):
if i % 2 == 0:
x = str(input('A, instruction >'))
if x == 'CX':
y1 = int(input('Control qubit #> '))
y2 = int(input('target qubit #> '))
self.operation(x, [y1, y2])
else:
y = int(input('A #qubit >'))
self.operation(x, y)
else:
x = str(input('B, instruction >'))
if x == 'CX':
y1 = int(input('Control qubit #> '))
y2 = int(input('target qubit #> '))
self.operation(x, [y1, y2])
else:
y = int(input('B #qubit >'))
self.operation(x, y)
result = self.RuntheGaame()
print(result)
def get_cir(self, trans=False):
createFolder('./fig')
style = { 'showindex': True,
'cregbundle' : True, 'dpi' : 300}
if trans == True:
return transpile(self.qc, basis_gates = ['x', 'h', 'u3', 'cx']).draw(output='mpl', style = style, fold=100)
return self.qc.draw(output='mpl', style = style, fold=100)
def initial(self, instruction, num, vector=None):
''' Normal gate version '''
if instruction == '+':
self.qc.h(num)
elif instruction == '-':
self.qc.x(num)
self.qc.h(num)
elif instruction == '1':
self.qc.x(num)
elif instruction == '0':
None
else:
print('invalid initialize instruction')
def SeqInitial(self, instruction):
for i in range(self.num):
self.initial(instruction[i], i)
def end_initial(self):
self.qc.barrier()
def operation(self, oper, num):
if type(num) == list and len(num) == 2:
num_control = num[0]
num_target = num[1]
if type(num) == list and len(num) == 1:
num = num[0]
if oper == 'H':
self.qc.h(num)
if oper == 'CX':
self.qc.cx(num_control, num_target)
if oper == 'X':
self.qc.x(num)
if oper == 'Z':
self.qc.z(num)
if oper == 'HX':
self.qc.h(num)
self.qc.x(num)
if oper == 'CZ':
self.qc.cz(num_control, num_target)
def RuntheGame(self):
self.qc.barrier()
for i in range(self.num):
if self.MeasurementBasis[i] == 'X':
self.qc.h(i)
elif self.MeasurementBasis[i] == 'Y':
self.qc.sdg(i)
self.qc.h(i)
else:
None
self.qc.measure_all()
self.get_cir().savefig('./fig/Measurment.png')
backend = Aer.get_backend('qasm_simulator') #qasm_simulator
job = execute(self.qc, backend=backend, shots = 8192).result().get_counts()
List = {'0': 0, '1': 0}
for i in job:
if len(collections.Counter(i).most_common()) == 2:
t, t_c = collections.Counter(i).most_common(2)[0]
d, d_c = collections.Counter(i).most_common(2)[1]
if t_c > d_c:
List[t] += job[i]
elif t_c < d_c:
List[d] += job[i]
else:
None
else:
t, _ = collections.Counter(i).most_common(1)[0]
List[t] += job[i]
return List
def RandomBasis(self):
Basis = ['X', 'Z']
return random.choices(Basis, k=self.num)
def RandomGate(self, numTurn):
Gate = ['X', 'Z', 'H', 'HX', 'CX', 'CZ']
return random.choices(Gate, k=numTurn)
def RemoveOper(self, player, gate):
if player == 'A':
self.GateA.remove(gate)
else:
self.GateB.remove(gate)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
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/benkoehlL/Qiskit_Playground
|
benkoehlL
|
from qiskit import *
print("GHZ")
c2 = QuantumCircuit(3,3)
c2.h(0)
c2.h(1)
c2.ccz(0,1,2)
c2.x(2)
c2.ccz(0,1,2)
c2.x(2)
c2.h(1)
c2.h(2)
c2.ccz(0,1,2)
c2.h(2)
c2.measure([i for i in range(3)], [i for i in range(3)])
simulator = Aer.get_backend('qasm_simulator')
result = execute(c2, backend=simulator, shots=1000).result()
answer = result.get_counts()
print(answer)
|
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Clifford, random_clifford
qc = QuantumCircuit(3)
cliff = random_clifford(2)
qc.append(cliff, [0, 1])
qc.ccx(0, 1, 2)
qc.draw('mpl')
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 1量子ビット回路を用意
q = QuantumCircuit(1,1)
# 回路を描画
q.draw(output="mpl")
# 量子ゲートで回路を作成
q.h(0) # Hゲートを0番目の量子ビットに操作します。
# 回路を描画
q.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q, vector_sim )
result = job.result().get_statevector(q, decimals=3)
print(result)
# ブロッホ球での表示
from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(result)
# 数値計算モジュールを導入
import numpy as np
q = QuantumCircuit(1,1) # 1量子ビット回路を用意
q.rx(np.pi/2,0) # x軸を中心にπ/2回転
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q, vector_sim )
result = job.result().get_statevector(q, decimals=3)
print(result)
# ブロッホ球での表示
plot_bloch_multivector(result)
# 2量子ビット回路を用意
q = QuantumCircuit(2,2)
# 回路を描画
q.draw(output="mpl")
# 量子ゲートで回路を作成
q.h(0) # Hゲートを0番目の量子ビットに操作します。
q.h(1) # Hゲートを1番目の量子ビットに操作します。
# 回路を描画
q.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q, vector_sim )
result = job.result().get_statevector(q, decimals=3)
print(result)
q = QuantumCircuit(2,2) # 2量子ビット回路を用意
q.h(0) # Hゲートを0番目の量子ビットに操作します。
q.h(1) # Hゲートを1番目の量子ビットに操作します。
# 回路を測定
q.measure(0,0)
q.measure(1,1)
# 回路を描画
q.draw(output='mpl')
# QASMシミュレーターで実験
simulator = Aer.get_backend('qasm_simulator')
job = execute(q, backend=simulator, shots=1024)
result = job.result()
# 測定された回数を表示
counts = result.get_counts(q)
print(counts)
## ヒストグラムで測定された確率をプロット
from qiskit.visualization import *
plot_histogram( counts )
|
https://github.com/at2005/hodl-qiskit
|
at2005
|
from qiskit import *
from qiskit.visualization import plot_histogram
import re
import subprocess
import os
### define a class to hold hodl oracle code alongside parameters
### this allows many instances of an oracle to be defined --> not limited to
### input-dependent compilation
class HODLOracle:
def __init__(self, func_name, init_params, program):
### accepts body of the oracle, parameters to the oracle in order, and the oracle name
self.program = program
self.params = init_params
self.fname = func_name
### compilation function --> this takes an oracle instance, generates a HODL program,
### invokes the compiler binary, converts the output assembly to a qiskit circuit, and returns it
def to_circ(self,params):
main = "function main() {"
### iterate over each parameter and if a quantum register then declare it as
### a |0>^n register. This initialization is such so that the circuit can be concatenated
## with any desired input register
param_lst = []
for q in params:
if isinstance(q, QuantumRegister):
main += f"\nsuper {q.name} = {2**(q.size)};\nH({q.name});"
param_lst.append(q.name)
else:
param_lst.append(str(q))
main += f"\n{self.fname}({','.join(param_lst)});"
result = self.program + main + "\n}"
f = open("program.hodl", "w")
f.write(result)
f.close()
os.system("hodl --target qasm -o out.qasm program.hodl")
circ = QuantumCircuit.from_qasm_file("out.qasm")
os.remove("program.hodl")
os.remove("out.qasm")
return circ
### takes an oracle and outputs a HODL object
def init_oracle(code):
fname = re.search("function (.*)\(", code).group(1)
params = re.search("\((.*)\)",code).group(1)
params = params.split(",")
### parameter map --> {type: name}
param_dict = {}
for p in params:
p = p.split()
param_dict[p[0]] = p[1]
oracle = HODLOracle(fname, param_dict, code)
return oracle
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test basic simulator."""
import os
import unittest
import numpy as np
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.compiler import transpile, assemble
from qiskit.providers.basic_provider import BasicSimulator
from qiskit.qasm2 import dumps
from test import QiskitTestCase # pylint: disable=wrong-import-order
from . import BasicProviderBackendTestMixin
class TestBasicSimulator(QiskitTestCase, BasicProviderBackendTestMixin):
"""Test the basic provider simulator."""
def setUp(self):
super().setUp()
self.backend = BasicSimulator()
bell = QuantumCircuit(2, 2)
bell.h(0)
bell.cx(0, 1)
bell.measure([0, 1], [0, 1])
self.circuit = bell
self.seed = 88
self.backend = BasicSimulator()
qasm_dir = os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "qasm"
)
qasm_filename = os.path.join(qasm_dir, "example.qasm")
qcirc = QuantumCircuit.from_qasm_file(qasm_filename)
qcirc.name = "test"
self.transpiled_circuit = transpile(qcirc, backend=self.backend)
self.qobj = assemble(self.transpiled_circuit, shots=1000, seed_simulator=self.seed)
def test_basic_simulator_single_shot(self):
"""Test single shot run."""
shots = 1
result = self.backend.run(
self.transpiled_circuit, shots=shots, seed_simulator=self.seed
).result()
self.assertEqual(result.success, True)
def test_measure_sampler_repeated_qubits(self):
"""Test measure sampler if qubits measured more than once."""
shots = 100
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(4, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[1])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
circuit.measure(qr[1], cr[2])
circuit.measure(qr[0], cr[3])
target = {"0110": shots}
job = self.backend.run(
transpile(circuit, self.backend), shots=shots, seed_simulator=self.seed
)
result = job.result()
counts = result.get_counts(0)
self.assertEqual(counts, target)
def test_measure_sampler_single_qubit(self):
"""Test measure sampler if single-qubit is measured."""
shots = 100
num_qubits = 5
qr = QuantumRegister(num_qubits, "qr")
cr = ClassicalRegister(1, "cr")
for qubit in range(num_qubits):
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[qubit])
circuit.measure(qr[qubit], cr[0])
target = {"1": shots}
job = self.backend.run(
transpile(circuit, self.backend), shots=shots, seed_simulator=self.seed
)
result = job.result()
counts = result.get_counts(0)
self.assertEqual(counts, target)
def test_measure_sampler_partial_qubit(self):
"""Test measure sampler if single-qubit is measured."""
shots = 100
num_qubits = 5
qr = QuantumRegister(num_qubits, "qr")
cr = ClassicalRegister(4, "cr")
# ░ ░ ░ ┌─┐ ░
# qr_0: ──────░─────░─────░─┤M├─░────
# ┌───┐ ░ ░ ┌─┐ ░ └╥┘ ░
# qr_1: ┤ X ├─░─────░─┤M├─░──╫──░────
# └───┘ ░ ░ └╥┘ ░ ║ ░
# qr_2: ──────░─────░──╫──░──╫──░────
# ┌───┐ ░ ┌─┐ ░ ║ ░ ║ ░ ┌─┐
# qr_3: ┤ X ├─░─┤M├─░──╫──░──╫──░─┤M├
# └───┘ ░ └╥┘ ░ ║ ░ ║ ░ └╥┘
# qr_4: ──────░──╫──░──╫──░──╫──░──╫─
# ░ ║ ░ ║ ░ ║ ░ ║
# cr: 4/═════════╩═════╩═════╩═════╩═
# 1 0 2 3
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[3])
circuit.x(qr[1])
circuit.barrier(qr)
circuit.measure(qr[3], cr[1])
circuit.barrier(qr)
circuit.measure(qr[1], cr[0])
circuit.barrier(qr)
circuit.measure(qr[0], cr[2])
circuit.barrier(qr)
circuit.measure(qr[3], cr[3])
target = {"1011": shots}
job = self.backend.run(
transpile(circuit, self.backend), shots=shots, seed_simulator=self.seed
)
result = job.result()
counts = result.get_counts(0)
self.assertEqual(counts, target)
def test_basic_simulator(self):
"""Test data counts output for single circuit run against reference."""
result = self.backend.run(
self.transpiled_circuit, shots=1000, seed_simulator=self.seed
).result()
shots = 1024
threshold = 0.04 * shots
counts = result.get_counts("test")
target = {
"100 100": shots / 8,
"011 011": shots / 8,
"101 101": shots / 8,
"111 111": shots / 8,
"000 000": shots / 8,
"010 010": shots / 8,
"110 110": shots / 8,
"001 001": shots / 8,
}
self.assertDictAlmostEqual(counts, target, threshold)
def test_if_statement(self):
"""Test if statements."""
shots = 100
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(3, "cr")
# ┌───┐┌─┐ ┌─┐
# qr_0: ┤ X ├┤M├──────────┤M├──────
# ├───┤└╥┘┌─┐ └╥┘┌─┐
# qr_1: ┤ X ├─╫─┤M├────────╫─┤M├───
# └───┘ ║ └╥┘ ┌───┐ ║ └╥┘┌─┐
# qr_2: ──────╫──╫──┤ X ├──╫──╫─┤M├
# ║ ║ └─╥─┘ ║ ║ └╥┘
# ║ ║ ┌──╨──┐ ║ ║ ║
# cr: 3/══════╩══╩═╡ 0x3 ╞═╩══╩══╩═
# 0 1 └─────┘ 0 1 2
circuit_if_true = QuantumCircuit(qr, cr)
circuit_if_true.x(qr[0])
circuit_if_true.x(qr[1])
circuit_if_true.measure(qr[0], cr[0])
circuit_if_true.measure(qr[1], cr[1])
circuit_if_true.x(qr[2]).c_if(cr, 0x3)
circuit_if_true.measure(qr[0], cr[0])
circuit_if_true.measure(qr[1], cr[1])
circuit_if_true.measure(qr[2], cr[2])
# ┌───┐┌─┐ ┌─┐
# qr_0: ┤ X ├┤M├───────┤M├──────
# └┬─┬┘└╥┘ └╥┘┌─┐
# qr_1: ─┤M├──╫─────────╫─┤M├───
# └╥┘ ║ ┌───┐ ║ └╥┘┌─┐
# qr_2: ──╫───╫──┤ X ├──╫──╫─┤M├
# ║ ║ └─╥─┘ ║ ║ └╥┘
# ║ ║ ┌──╨──┐ ║ ║ ║
# cr: 3/══╩═══╩═╡ 0x3 ╞═╩══╩══╩═
# 1 0 └─────┘ 0 1 2
circuit_if_false = QuantumCircuit(qr, cr)
circuit_if_false.x(qr[0])
circuit_if_false.measure(qr[0], cr[0])
circuit_if_false.measure(qr[1], cr[1])
circuit_if_false.x(qr[2]).c_if(cr, 0x3)
circuit_if_false.measure(qr[0], cr[0])
circuit_if_false.measure(qr[1], cr[1])
circuit_if_false.measure(qr[2], cr[2])
job = self.backend.run(
transpile([circuit_if_true, circuit_if_false], self.backend),
shots=shots,
seed_simulator=self.seed,
)
result = job.result()
counts_if_true = result.get_counts(circuit_if_true)
counts_if_false = result.get_counts(circuit_if_false)
self.assertEqual(counts_if_true, {"111": 100})
self.assertEqual(counts_if_false, {"001": 100})
def test_bit_cif_crossaffect(self):
"""Test if bits in a classical register other than
the single conditional bit affect the conditioned operation."""
# ┌───┐ ┌─┐
# q0_0: ────────┤ H ├──────────┤M├
# ┌───┐ └─╥─┘ ┌─┐ └╥┘
# q0_1: ┤ X ├─────╫──────┤M├────╫─
# ├───┤ ║ └╥┘┌─┐ ║
# q0_2: ┤ X ├─────╫───────╫─┤M├─╫─
# └───┘┌────╨─────┐ ║ └╥┘ ║
# c0: 3/═════╡ c0_0=0x1 ╞═╩══╩══╬═
# └──────────┘ 1 2 ║
# c1: 1/════════════════════════╩═
# 0
shots = 100
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
cr1 = ClassicalRegister(1)
circuit = QuantumCircuit(qr, cr, cr1)
circuit.x([qr[1], qr[2]])
circuit.measure(qr[1], cr[1])
circuit.measure(qr[2], cr[2])
circuit.h(qr[0]).c_if(cr[0], True)
circuit.measure(qr[0], cr1[0])
job = self.backend.run(circuit, shots=shots, seed_simulator=self.seed)
result = job.result().get_counts()
target = {"0 110": 100}
self.assertEqual(result, target)
def test_teleport(self):
"""Test teleportation as in tutorials"""
# ┌─────────┐ ┌───┐ ░ ┌─┐
# qr_0: ┤ Ry(π/4) ├───────■──┤ H ├─░─┤M├────────────────────
# └──┬───┬──┘ ┌─┴─┐└───┘ ░ └╥┘┌─┐
# qr_1: ───┤ H ├─────■──┤ X ├──────░──╫─┤M├─────────────────
# └───┘ ┌─┴─┐└───┘ ░ ║ └╥┘ ┌───┐ ┌───┐ ┌─┐
# qr_2: ───────────┤ X ├───────────░──╫──╫──┤ Z ├──┤ X ├─┤M├
# └───┘ ░ ║ ║ └─╥─┘ └─╥─┘ └╥┘
# ║ ║ ┌──╨──┐ ║ ║
# cr0: 1/═════════════════════════════╩══╬═╡ 0x1 ╞═══╬════╬═
# 0 ║ └─────┘┌──╨──┐ ║
# cr1: 1/════════════════════════════════╩════════╡ 0x1 ╞═╬═
# 0 └─────┘ ║
# cr2: 1/═════════════════════════════════════════════════╩═
# 0
self.log.info("test_teleport")
pi = np.pi
shots = 4000
qr = QuantumRegister(3, "qr")
cr0 = ClassicalRegister(1, "cr0")
cr1 = ClassicalRegister(1, "cr1")
cr2 = ClassicalRegister(1, "cr2")
circuit = QuantumCircuit(qr, cr0, cr1, cr2, name="teleport")
circuit.h(qr[1])
circuit.cx(qr[1], qr[2])
circuit.ry(pi / 4, qr[0])
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.barrier(qr)
circuit.measure(qr[0], cr0[0])
circuit.measure(qr[1], cr1[0])
circuit.z(qr[2]).c_if(cr0, 1)
circuit.x(qr[2]).c_if(cr1, 1)
circuit.measure(qr[2], cr2[0])
job = self.backend.run(
transpile(circuit, self.backend), shots=shots, seed_simulator=self.seed
)
results = job.result()
data = results.get_counts("teleport")
alice = {
"00": data["0 0 0"] + data["1 0 0"],
"01": data["0 1 0"] + data["1 1 0"],
"10": data["0 0 1"] + data["1 0 1"],
"11": data["0 1 1"] + data["1 1 1"],
}
bob = {
"0": data["0 0 0"] + data["0 1 0"] + data["0 0 1"] + data["0 1 1"],
"1": data["1 0 0"] + data["1 1 0"] + data["1 0 1"] + data["1 1 1"],
}
self.log.info("test_teleport: circuit:")
self.log.info(dumps(circuit))
self.log.info("test_teleport: data %s", data)
self.log.info("test_teleport: alice %s", alice)
self.log.info("test_teleport: bob %s", bob)
alice_ratio = 1 / np.tan(pi / 8) ** 2
bob_ratio = bob["0"] / float(bob["1"])
error = abs(alice_ratio - bob_ratio) / alice_ratio
self.log.info("test_teleport: relative error = %s", error)
self.assertLess(error, 0.05)
def test_memory(self):
"""Test memory."""
# ┌───┐ ┌─┐
# qr_0: ┤ H ├──■─────┤M├───
# └───┘┌─┴─┐ └╥┘┌─┐
# qr_1: ─────┤ X ├────╫─┤M├
# └┬─┬┘ ║ └╥┘
# qr_2: ──────┤M├─────╫──╫─
# ┌───┐ └╥┘ ┌─┐ ║ ║
# qr_3: ┤ X ├──╫──┤M├─╫──╫─
# └───┘ ║ └╥┘ ║ ║
# cr0: 2/══════╬═══╬══╩══╩═
# ║ ║ 0 1
# ║ ║
# cr1: 2/══════╩═══╩═══════
# 0 1
qr = QuantumRegister(4, "qr")
cr0 = ClassicalRegister(2, "cr0")
cr1 = ClassicalRegister(2, "cr1")
circ = QuantumCircuit(qr, cr0, cr1)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.x(qr[3])
circ.measure(qr[0], cr0[0])
circ.measure(qr[1], cr0[1])
circ.measure(qr[2], cr1[0])
circ.measure(qr[3], cr1[1])
shots = 50
job = self.backend.run(
transpile(circ, self.backend), shots=shots, seed_simulator=self.seed, memory=True
)
result = job.result()
memory = result.get_memory()
self.assertEqual(len(memory), shots)
for mem in memory:
self.assertIn(mem, ["10 00", "10 11"])
def test_unitary(self):
"""Test unitary gate instruction"""
max_qubits = 4
x_mat = np.array([[0, 1], [1, 0]])
# Test 1 to max_qubits for random n-qubit unitary gate
for i in range(max_qubits):
num_qubits = i + 1
# Apply X gate to all qubits
multi_x = x_mat
for _ in range(i):
multi_x = np.kron(multi_x, x_mat)
# Target counts
shots = 1024
target_counts = {num_qubits * "1": shots}
# Test circuit
qr = QuantumRegister(num_qubits, "qr")
cr = ClassicalRegister(num_qubits, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.unitary(multi_x, qr)
circuit.measure(qr, cr)
job = self.backend.run(transpile(circuit, self.backend), shots=shots)
result = job.result()
counts = result.get_counts(0)
self.assertEqual(counts, target_counts)
if __name__ == "__main__":
unittest.main()
|
https://github.com/Ilan-Bondarevsky/qiskit_algorithm
|
Ilan-Bondarevsky
|
from qiskit import transpile
import qiskit.providers.fake_provider
from qiskit_ibm_provider import IBMProvider
from qiskit.transpiler.passes import RemoveBarriers
from qiskit_aer import AerSimulator, Aer
def run_backend(quantum_circuit, backend, *args, **kwargs):
'''Run current circuit on a given backend'''
if quantum_circuit is None:
return None
job = execute(quantum_circuit, backend=backend, *args, **kwargs)
return job
def get_unitary(quantum_circuit, decimals=3, *args, **kwargs):
'''Get unitary matrix of current circuit'''
backend = Aer.get_backend('unitary_simulator')
result = run_backend(quantum_circuit, backend, *args, **kwargs).result()
return result.get_unitary(quantum_circuit, decimals)
def get_state_vector(quantum_circuit, *args, **kwargs):
'''Get state vector of current circuit'''
backend = Aer.get_backend('statevector_simulator')
result = run_backend(quantum_circuit, backend, *args, **kwargs).result()
return result.get_statevector(quantum_circuit)
def run_simulator(quantum_circuit, simulator_backend = None, shots = 1024, *args, **kwargs):
'''Run circuit on a simulation backend.'''
if quantum_circuit is None:
return None
if simulator_backend is None:
simulator_backend = AerSimulator()
result = run_backend(quantum_circuit, simulator_backend, shots = shots, *args, **kwargs).result()
return result
def get_fake_backend_list(min_qubit=None, max_qubit = None):
'''Get a list of the excisting fake backends provided by qiskit.\n
Docs: https://docs.quantum.ibm.com/api/qiskit/providers_fake_provider'''
output = set()
backend_list = dir(qiskit.providers.fake_provider)
i = 0
for backend_name in backend_list:
try:
backend = getattr(qiskit.providers.fake_provider, backend_name)()
num_qubit = len({q for map in backend.coupling_map for q in map})
if min_qubit is None and max_qubit is None:
output.add((backend_name, num_qubit))
elif max_qubit is None:
output.add((backend_name, num_qubit)) if num_qubit >= min_qubit else None
elif min_qubit is None:
output.add((backend_name, num_qubit)) if num_qubit <= max_qubit else None
else:
output.add((backend_name, num_qubit)) if num_qubit >= min_qubit and num_qubit <= max_qubit else None
except:
pass
return list(output)
def get_fake_backend(name):
try:
backend = getattr(qiskit.providers.fake_provider, name)()
return backend
except:
pass
def get_ibm_provider(token, instance="ibm-q/open/main"):
return IBMProvider(instance=instance, token=token)
def get_ibm_backend_list(provider, **kwargs):
'''Get backends list of the IBM provider.\n
Docs: https://qiskit.org/ecosystem/ibm-provider/stubs/qiskit_ibm_provider.IBMProvider.backends.html#qiskit_ibm_provider.IBMProvider.backends'''
return provider.backends(**kwargs)
def get_ibm_backend(provider, backend_name='ibm_lagos'):
'''Choose IBM backend with given backend name'''
try:
backend = provider.get_backend(backend_name, hub=None)
except:
print('Backend name is not in the IBM library')
return backend
def transpile_quantum_circuit(qc, backend_name="Aer", optimization_level=0, initial_layout = None):
backend = get_fake_backend(backend_name)
if backend is None:
backend = AerSimulator()
if initial_layout == 'Full_Range':
initial_layout = list(range(len(qc.qubits)))
removed_barriar_qc = RemoveBarriers()(qc)
transpiled_qc = transpile(circuits=removed_barriar_qc, backend=backend,optimization_level=optimization_level, initial_layout=initial_layout)
return transpiled_qc
def get_transpiled_circuits_of_circuit(qc, backend_name_list:list = ['Aer'], initial_layout_list:list = [None], optimization_level_list:list = [0]):
output_list = []
for backend in backend_name_list:
for layout in initial_layout_list :
for level in optimization_level_list:
output_list.append(transpile_quantum_circuit(qc, backend_name=backend, initial_layout=layout,optimization_level=level))
output_list[-1].name = f"{backend} | {layout} | {level}"
return output_list
|
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/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test KAK over optimization"""
import unittest
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, transpile
from qiskit.circuit.library import CU1Gate
from qiskit.test import QiskitTestCase
class TestKAKOverOptim(QiskitTestCase):
"""Tests to verify that KAK decomposition
does not over optimize.
"""
def test_cz_optimization(self):
"""Test that KAK does not run on a cz gate"""
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.cz(qr[0], qr[1])
cz_circ = transpile(
qc,
None,
coupling_map=[[0, 1], [1, 0]],
basis_gates=["u1", "u2", "u3", "id", "cx"],
optimization_level=3,
)
ops = cz_circ.count_ops()
self.assertEqual(ops["u2"], 2)
self.assertEqual(ops["cx"], 1)
self.assertFalse("u3" in ops.keys())
def test_cu1_optimization(self):
"""Test that KAK does run on a cu1 gate and
reduces the cx count from two to one.
"""
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.append(CU1Gate(np.pi), [qr[0], qr[1]])
cu1_circ = transpile(
qc,
None,
coupling_map=[[0, 1], [1, 0]],
basis_gates=["u1", "u2", "u3", "id", "cx"],
optimization_level=3,
)
ops = cu1_circ.count_ops()
self.assertEqual(ops["cx"], 1)
if __name__ == "__main__":
unittest.main()
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# -*- 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/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":
### replaced z gate ###
qc.x(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/jdellaverson19/qiskit2020
|
jdellaverson19
|
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>)
out of four possible values."""
#import numpy and plot library
import matplotlib.pyplot as plt
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.quantum_info import Statevector
# import basic plot tools
from qiskit.visualization import plot_histogram
# define variables, 1) initialize qubits to zero
n = 2
grover_circuit = QuantumCircuit(n)
#define initialization function
def initialize_s(qc, qubits):
'''Apply a H-gate to 'qubits' in qc'''
for q in qubits:
qc.h(q)
return qc
### begin grovers circuit ###
#2) Put qubits in equal state of superposition
grover_circuit = initialize_s(grover_circuit, [0,1])
# 3) Apply oracle reflection to marked instance x_0 = 3, (|11>)
grover_circuit.cz(0,1)
statevec = job_sim.result().get_statevector()
from qiskit_textbook.tools import vector2latex
vector2latex(statevec, pretext="|\\psi\\rangle =")
# 4) apply additional reflection (diffusion operator)
grover_circuit.h([0,1])
grover_circuit.z([0,1])
grover_circuit.cz(0,1)
grover_circuit.h([0,1])
# 5) measure the qubits
grover_circuit.measure_all()
# Load IBM Q account and get the least busy backend device
provider = IBMQ.load_account()
device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and
not x.configuration().simulator and x.status().operational==True))
print("Running on current least busy device: ", device)
from qiskit.tools.monitor import job_monitor
job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3)
job_monitor(job, interval = 2)
results = job.result()
answer = results.get_counts(grover_circuit)
plot_histogram(answer)
#highest amplitude should correspond with marked value x_0 (|11>)
|
https://github.com/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.
"""
Example showing how to use Qiskit-Terra at level 0 (novice).
This example shows the most basic way to user Terra. It builds some circuits
and runs them on both the BasicAer (local Qiskit provider) or IBMQ (remote IBMQ provider).
To control the compile parameters we have provided a transpile function which can be used
as a level 1 user.
"""
# Import the Qiskit modules
from qiskit import QuantumCircuit
from qiskit import execute, BasicAer
# making first circuit: bell state
qc1 = QuantumCircuit(2, 2)
qc1.h(0)
qc1.cx(0, 1)
qc1.measure([0, 1], [0, 1])
# making another circuit: superpositions
qc2 = QuantumCircuit(2, 2)
qc2.h([0, 1])
qc2.measure([0, 1], [0, 1])
# setting up the backend
print("(BasicAER Backends)")
print(BasicAer.backends())
# running the job
job_sim = execute([qc1, qc2], BasicAer.get_backend("qasm_simulator"))
sim_result = job_sim.result()
# Show the results
print(sim_result.get_counts(qc1))
print(sim_result.get_counts(qc2))
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""A test for visualizing device coupling maps"""
import unittest
from io import BytesIO
from ddt import ddt, data
from qiskit.providers.fake_provider import (
FakeProvider,
FakeKolkata,
FakeWashington,
FakeKolkataV2,
FakeWashingtonV2,
)
from qiskit.visualization import (
plot_gate_map,
plot_coupling_map,
plot_circuit_layout,
plot_error_map,
)
from qiskit.utils import optionals
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler.layout import Layout, TranspileLayout
from .visualization import path_to_diagram_reference, QiskitVisualizationTestCase
if optionals.HAS_MATPLOTLIB:
import matplotlib.pyplot as plt
if optionals.HAS_PIL:
from PIL import Image
@ddt
@unittest.skipUnless(optionals.HAS_MATPLOTLIB, "matplotlib not available.")
@unittest.skipUnless(optionals.HAS_PIL, "PIL not available")
@unittest.skipUnless(optionals.HAS_SEABORN, "seaborn not available")
class TestGateMap(QiskitVisualizationTestCase):
"""visual tests for plot_gate_map"""
backends = list(
filter(
lambda x: not x.configuration().simulator
and x.configuration().num_qubits in range(5, 21),
FakeProvider().backends(),
)
)
@data(*backends)
def test_plot_gate_map(self, backend):
"""tests plotting of gate map of a device (20 qubit, 16 qubit, 14 qubit and 5 qubit)"""
n = backend.configuration().n_qubits
img_ref = path_to_diagram_reference(str(n) + "bit_quantum_computer.png")
fig = plot_gate_map(backend)
with BytesIO() as img_buffer:
fig.savefig(img_buffer, format="png")
img_buffer.seek(0)
self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2)
plt.close(fig)
@data(*backends)
def test_plot_circuit_layout(self, backend):
"""tests plot_circuit_layout for each device"""
layout_length = int(backend._configuration.n_qubits / 2)
qr = QuantumRegister(layout_length, "qr")
circuit = QuantumCircuit(qr)
circuit._layout = TranspileLayout(
Layout({qr[i]: i * 2 for i in range(layout_length)}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
circuit._layout.initial_layout.add_register(qr)
n = backend.configuration().n_qubits
img_ref = path_to_diagram_reference(str(n) + "_plot_circuit_layout.png")
fig = plot_circuit_layout(circuit, backend)
with BytesIO() as img_buffer:
fig.savefig(img_buffer, format="png")
img_buffer.seek(0)
self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.1)
plt.close(fig)
def test_plot_gate_map_no_backend(self):
"""tests plotting of gate map without a device"""
n_qubits = 8
coupling_map = [[0, 1], [1, 2], [2, 3], [3, 5], [4, 5], [5, 6], [2, 4], [6, 7]]
qubit_coordinates = [[0, 1], [1, 1], [1, 0], [1, 2], [2, 0], [2, 2], [2, 1], [3, 1]]
img_ref = path_to_diagram_reference(str(n_qubits) + "qubits.png")
fig = plot_coupling_map(
num_qubits=n_qubits, qubit_coordinates=qubit_coordinates, coupling_map=coupling_map
)
with BytesIO() as img_buffer:
fig.savefig(img_buffer, format="png")
img_buffer.seek(0)
self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2)
plt.close(fig)
def test_plot_error_map_backend_v1(self):
"""Test plotting error map with fake backend v1."""
backend = FakeKolkata()
img_ref = path_to_diagram_reference("kolkata_error.png")
fig = plot_error_map(backend)
with BytesIO() as img_buffer:
fig.savefig(img_buffer, format="png")
img_buffer.seek(0)
self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2)
plt.close(fig)
def test_plot_error_map_backend_v2(self):
"""Test plotting error map with fake backend v2."""
backend = FakeKolkataV2()
img_ref = path_to_diagram_reference("kolkata_v2_error.png")
fig = plot_error_map(backend)
with BytesIO() as img_buffer:
fig.savefig(img_buffer, format="png")
img_buffer.seek(0)
self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2)
plt.close(fig)
def test_plot_error_map_over_100_qubit(self):
"""Test plotting error map with large fake backend."""
backend = FakeWashington()
img_ref = path_to_diagram_reference("washington_error.png")
fig = plot_error_map(backend)
with BytesIO() as img_buffer:
fig.savefig(img_buffer, format="png")
img_buffer.seek(0)
self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2)
plt.close(fig)
def test_plot_error_map_over_100_qubit_backend_v2(self):
"""Test plotting error map with large fake backendv2."""
backend = FakeWashingtonV2()
img_ref = path_to_diagram_reference("washington_v2_error.png")
fig = plot_error_map(backend)
with BytesIO() as img_buffer:
fig.savefig(img_buffer, format="png")
img_buffer.seek(0)
self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2)
plt.close(fig)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
|
jonasmaziero
|
pip install -U qiskit==0.36.2
pip install pylatexenc
import qiskit
qiskit.__qiskit_version__
# Copie se API Token no IBMQ e cole aqui
qiskit.IBMQ.save_account('ade2e1cd8926fee57b535ff0761ddac06ce27b6ea7ea0ecb60121d873ccf19578850d46431bbb002e5a64db18657e028fd17ae71b73ce25c57002e2ff579eeb6', overwrite = True)
# Execute esse comando uma vez só
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider.backends()
from qiskit import *
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr,cr)
qc.h(qr[0])
qc.cx(qr[0],qr[1])
qc.measure(qr[0],cr[0])
qc.measure(qr[1],cr[1])
qc.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
nshots = 8192 # número de "prepara-e-mede"
job = execute(qc, backend = simulator, shots = nshots)
from qiskit.tools.visualization import plot_histogram
plot_histogram(job.result().get_counts(qc))
counts = job.result().get_counts(qc)
counts
counts['00']
# probabilidade
p00 = 0; p01 = 0; p10 = 0; p11 = 0
for j in (0,2):
for k in (0,2):
if '00' in counts:
p00 = counts['00']/nshots
if '01' in counts:
p01 = counts['01']/nshots
if '10' in counts:
p10 = counts['10']/nshots
if '11' in counts:
p11 = counts['11']/nshots
p00, p01, p10, p11
device = provider.get_backend('ibm_nairobi')
from qiskit.tools.monitor import job_monitor
job = execute(qc, backend = device, shots = nshots)
job_monitor(job)
plot_histogram(job.result().get_counts(qc))
counts = job.result().get_counts(qc)
counts
counts['00']
# probabilidade
p00 = 0; p01 = 0; p10 = 0; p11 = 0
for j in (0,2):
for k in (0,2):
if '00' in counts:
p00 = counts['00']/nshots
if '01' in counts:
p01 = counts['01']/nshots
if '10' in counts:
p10 = counts['10']/nshots
if '11' in counts:
p11 = counts['11']/nshots
p00, p01, p10, p11
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the NoiseAdaptiveLayout pass"""
from datetime import datetime
import unittest
from qiskit.transpiler.passes import NoiseAdaptiveLayout
from qiskit.converters import circuit_to_dag
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit.providers.models import BackendProperties
from qiskit.providers.models.backendproperties import Nduv, Gate
def make_qubit_with_error(readout_error):
"""Create a qubit for BackendProperties"""
calib_time = datetime(year=2019, month=2, day=1, hour=0, minute=0, second=0)
return [
Nduv(name="T1", date=calib_time, unit="µs", value=100.0),
Nduv(name="T2", date=calib_time, unit="µs", value=100.0),
Nduv(name="frequency", date=calib_time, unit="GHz", value=5.0),
Nduv(name="readout_error", date=calib_time, unit="", value=readout_error),
]
class TestNoiseAdaptiveLayout(QiskitTestCase):
"""Tests the NoiseAdaptiveLayout pass."""
def test_on_linear_topology(self):
"""
Test that the mapper identifies the correct gate in a linear topology
"""
calib_time = datetime(year=2019, month=2, day=1, hour=0, minute=0, second=0)
qr = QuantumRegister(2, name="q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
qubit_list = []
ro_errors = [0.01, 0.01, 0.01]
for ro_error in ro_errors:
qubit_list.append(make_qubit_with_error(ro_error))
p01 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.9)]
g01 = Gate(name="CX0_1", gate="cx", parameters=p01, qubits=[0, 1])
p12 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.1)]
g12 = Gate(name="CX1_2", gate="cx", parameters=p12, qubits=[1, 2])
gate_list = [g01, g12]
bprop = BackendProperties(
last_update_date=calib_time,
backend_name="test_backend",
qubits=qubit_list,
backend_version="1.0.0",
gates=gate_list,
general=[],
)
nalayout = NoiseAdaptiveLayout(bprop)
nalayout.run(dag)
initial_layout = nalayout.property_set["layout"]
self.assertNotEqual(initial_layout[qr[0]], 0)
self.assertNotEqual(initial_layout[qr[1]], 0)
def test_bad_readout(self):
"""Test that the mapper avoids bad readout unit"""
calib_time = datetime(year=2019, month=2, day=1, hour=0, minute=0, second=0)
qr = QuantumRegister(2, name="q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
qubit_list = []
ro_errors = [0.01, 0.01, 0.8]
for ro_error in ro_errors:
qubit_list.append(make_qubit_with_error(ro_error))
p01 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.1)]
g01 = Gate(name="CX0_1", gate="cx", parameters=p01, qubits=[0, 1])
p12 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.1)]
g12 = Gate(name="CX1_2", gate="cx", parameters=p12, qubits=[1, 2])
gate_list = [g01, g12]
bprop = BackendProperties(
last_update_date=calib_time,
backend_name="test_backend",
qubits=qubit_list,
backend_version="1.0.0",
gates=gate_list,
general=[],
)
nalayout = NoiseAdaptiveLayout(bprop)
nalayout.run(dag)
initial_layout = nalayout.property_set["layout"]
self.assertNotEqual(initial_layout[qr[0]], 2)
self.assertNotEqual(initial_layout[qr[1]], 2)
def test_grid_layout(self):
"""
Test that the mapper identifies best location for a star-like program graph
Machine row1: (0, 1, 2)
Machine row2: (3, 4, 5)
"""
calib_time = datetime(year=2019, month=2, day=1, hour=0, minute=0, second=0)
qr = QuantumRegister(4, name="q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[3])
circuit.cx(qr[1], qr[3])
circuit.cx(qr[2], qr[3])
dag = circuit_to_dag(circuit)
qubit_list = []
ro_errors = [0.01] * 6
for ro_error in ro_errors:
qubit_list.append(make_qubit_with_error(ro_error))
p01 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.3)]
p03 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.3)]
p12 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.3)]
p14 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.1)]
p34 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.1)]
p45 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.1)]
p25 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.3)]
g01 = Gate(name="CX0_1", gate="cx", parameters=p01, qubits=[0, 1])
g03 = Gate(name="CX0_3", gate="cx", parameters=p03, qubits=[0, 3])
g12 = Gate(name="CX1_2", gate="cx", parameters=p12, qubits=[1, 2])
g14 = Gate(name="CX1_4", gate="cx", parameters=p14, qubits=[1, 4])
g34 = Gate(name="CX3_4", gate="cx", parameters=p34, qubits=[3, 4])
g45 = Gate(name="CX4_5", gate="cx", parameters=p45, qubits=[4, 5])
g25 = Gate(name="CX2_5", gate="cx", parameters=p25, qubits=[2, 5])
gate_list = [g01, g03, g12, g14, g34, g45, g25]
bprop = BackendProperties(
last_update_date=calib_time,
backend_name="test_backend",
qubits=qubit_list,
backend_version="1.0.0",
gates=gate_list,
general=[],
)
nalayout = NoiseAdaptiveLayout(bprop)
nalayout.run(dag)
initial_layout = nalayout.property_set["layout"]
for qid in range(4):
for qloc in [0, 2]:
self.assertNotEqual(initial_layout[qr[qid]], qloc)
if __name__ == "__main__":
unittest.main()
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
import numpy as np
from linear_solver_float import LinearSolverFloat
# set floating point accuracy
R = 5
M = np.array([[-4,6,1],
[8,-11,-2],
[-3,4,1]]) # Test 2(f)
Y = np.array([0.75,-1.25,0.25])
M_inv = np.linalg.inv(M)
M_inv.dot(Y)
num_reads = 1000
min_occurrence = 2
lsf = LinearSolverFloat(M,Y,R=R,num_reads=num_reads, min_occurrence = min_occurrence)
sampleset = lsf.sample()
sampleset.to_pandas_dataframe()
solutions = lsf.getSolutions(10)
list(solutions)
M = np.array([[6.1795,11.8207,2.0583],
[15.673,-7.56717,-3.852],
[-5.6457,7.96872,15.9418]]) #Test 2(g)
Y = np.array([1.4114,0.9972,9.9643])
M_inv = np.linalg.inv(M)
M_inv.dot(Y)
M.dot(np.array([0,0.25,-0.75]))
lsf = LinearSolverFloat(M,Y,R=R,num_reads=num_reads, min_occurrence = min_occurrence)
sampleset = lsf.sample()
sampleset.to_pandas_dataframe()
list(lsf.getSolutions(10))
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# define a quantum register with one qubit
qreg3 = QuantumRegister(1)
# define a classical register with one bit
# it stores the measurement result of the quantum part
creg3 = ClassicalRegister(1)
# define our quantum circuit
mycircuit3 = QuantumCircuit(qreg3,creg3)
# apply x-gate to the first qubit
mycircuit3.x(qreg3[0])
# apply h-gate (Hadamard: quantum coin-flipping) to the first qubit
mycircuit3.h(qreg3[0])
# measure the first qubit, and store the result in the first classical bit
mycircuit3.measure(qreg3,creg3)
print("Everything looks fine, let's continue ...")
# draw the circuit by using matplotlib
mycircuit3.draw(output='mpl',reverse_bits=True)
# reexecute me if you DO NOT see the circuit diagram
# execute the circuit and read the results
job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=10000)
counts3 = job.result().get_counts(mycircuit3)
print(counts3)
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# define a quantum register with one qubit
qreg4 = QuantumRegister(1)
# define a classical register with one bit
# it stores the measurement result of the quantum part
creg4 = ClassicalRegister(1)
# define our quantum circuit
mycircuit4 = QuantumCircuit(qreg4,creg4)
# apply x-gate to the first qubit
mycircuit4.x(qreg4[0])
# apply h-gate (Hadamard: quantum coin-flipping) to the first qubit twice
mycircuit4.h(qreg4[0])
mycircuit4.h(qreg4[0])
# measure the first qubit, and store the result in the first classical bit
mycircuit4.measure(qreg4,creg4)
print("Everything looks fine, let's continue ...")
# draw the circuit by using matplotlib
mycircuit4.draw(output='mpl',reverse_bits=True)
# reexecute me if you DO NOT see the circuit diagram
# execute the circuit and read the results
job = execute(mycircuit4,Aer.get_backend('qasm_simulator'),shots=10000)
counts4 = job.result().get_counts(mycircuit4)
print(counts4)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import logging
import time
from qiskit import __version__ as terra_version
from qiskit.assembler.run_config import RunConfig
from qiskit.transpiler import Layout
from .utils import (run_qobjs, compile_circuits, CircuitCache,
get_measured_qubits_from_qobj,
build_measurement_error_mitigation_fitter,
mitigate_measurement_error)
from .utils.backend_utils import (is_aer_provider,
is_ibmq_provider,
is_statevector_backend,
is_simulator_backend,
is_local_backend)
logger = logging.getLogger(__name__)
class QuantumInstance:
"""Quantum Backend including execution setting."""
BACKEND_CONFIG = ['basis_gates', 'coupling_map']
COMPILE_CONFIG = ['pass_manager', 'initial_layout', 'seed_transpiler']
RUN_CONFIG = ['shots', 'max_credits', 'memory', 'seed']
QJOB_CONFIG = ['timeout', 'wait']
NOISE_CONFIG = ['noise_model']
# https://github.com/Qiskit/qiskit-aer/blob/master/qiskit/providers/aer/backends/qasm_simulator.py
BACKEND_OPTIONS_QASM_ONLY = ["statevector_sample_measure_opt", "max_parallel_shots"]
BACKEND_OPTIONS = ["initial_statevector", "chop_threshold", "max_parallel_threads",
"max_parallel_experiments", "statevector_parallel_threshold",
"statevector_hpc_gate_opt"] + BACKEND_OPTIONS_QASM_ONLY
def __init__(self, backend, shots=1024, seed=None, max_credits=10,
basis_gates=None, coupling_map=None,
initial_layout=None, pass_manager=None, seed_transpiler=None,
backend_options=None, noise_model=None, timeout=None, wait=5,
circuit_caching=True, cache_file=None, skip_qobj_deepcopy=True,
skip_qobj_validation=True, measurement_error_mitigation_cls=None,
cals_matrix_refresh_period=30):
"""Constructor.
Args:
backend (BaseBackend): instance of selected backend
shots (int, optional): number of repetitions of each circuit, for sampling
seed (int, optional): random seed for simulators
max_credits (int, optional): maximum credits to use
basis_gates (list[str], optional): list of basis gate names supported by the
target. Default: ['u1','u2','u3','cx','id']
coupling_map (list[list]): coupling map (perhaps custom) to target in mapping
initial_layout (dict, optional): initial layout of qubits in mapping
pass_manager (PassManager, optional): pass manager to handle how to compile the circuits
seed_transpiler (int, optional): the random seed for circuit mapper
backend_options (dict, optional): all running options for backend, please refer to the provider.
noise_model (qiskit.provider.aer.noise.noise_model.NoiseModel, optional): noise model for simulator
timeout (float, optional): seconds to wait for job. If None, wait indefinitely.
wait (float, optional): seconds between queries to result
circuit_caching (bool, optional): USe CircuitCache when calling compile_and_run_circuits
cache_file(str, optional): filename into which to store the cache as a pickle file
skip_qobj_deepcopy (bool, optional): Reuses the same qobj object over and over to avoid deepcopying
skip_qobj_validation (bool, optional): Bypass Qobj validation to decrease submission time
measurement_error_mitigation_cls (callable, optional): the approach to mitigate measurement error,
CompleteMeasFitter or TensoredMeasFitter
cals_matrix_refresh_period (int): how long to refresh the calibration matrix in measurement mitigation,
unit in minutes
"""
self._backend = backend
# setup run config
run_config = RunConfig(shots=shots, max_credits=max_credits)
if seed:
run_config.seed = seed
if getattr(run_config, 'shots', None) is not None:
if self.is_statevector and run_config.shots != 1:
logger.info("statevector backend only works with shot=1, change "
"shots from {} to 1.".format(run_config.shots))
run_config.shots = 1
self._run_config = run_config
# setup backend config
basis_gates = basis_gates or backend.configuration().basis_gates
coupling_map = coupling_map or getattr(backend.configuration(),
'coupling_map', None)
self._backend_config = {
'basis_gates': basis_gates,
'coupling_map': coupling_map
}
# setup noise config
noise_config = None
if noise_model is not None:
if is_aer_provider(self._backend):
if not self.is_statevector:
noise_config = noise_model
else:
logger.info("The noise model can be only used with Aer qasm simulator. "
"Change it to None.")
else:
logger.info("The noise model can be only used with Qiskit Aer. "
"Please install it.")
self._noise_config = {} if noise_config is None else {'noise_model': noise_config}
# setup compile config
if initial_layout is not None and not isinstance(initial_layout, Layout):
initial_layout = Layout(initial_layout)
self._compile_config = {
'pass_manager': pass_manager,
'initial_layout': initial_layout,
'seed_transpiler': seed_transpiler
}
# setup job config
self._qjob_config = {'timeout': timeout} if self.is_local \
else {'timeout': timeout, 'wait': wait}
# setup backend options for run
self._backend_options = {}
if is_ibmq_provider(self._backend):
logger.info("backend_options can not used with the backends in IBMQ provider.")
else:
self._backend_options = {} if backend_options is None \
else {'backend_options': backend_options}
self._shared_circuits = False
self._circuit_summary = False
self._circuit_cache = CircuitCache(skip_qobj_deepcopy=skip_qobj_deepcopy,
cache_file=cache_file) if circuit_caching else None
self._skip_qobj_validation = skip_qobj_validation
self._measurement_error_mitigation_cls = None
if self.is_statevector:
if measurement_error_mitigation_cls is not None:
logger.info("Measurement error mitigation does not work with statevector simulation, disable it.")
else:
self._measurement_error_mitigation_cls = measurement_error_mitigation_cls
self._measurement_error_mitigation_fitter = None
self._measurement_error_mitigation_method = 'least_squares'
self._cals_matrix_refresh_period = cals_matrix_refresh_period
self._prev_timestamp = 0
if self._measurement_error_mitigation_cls is not None:
logger.info("The measurement error mitigation is enable. "
"It will automatically submit an additional job to help calibrate the result of other jobs. "
"The current approach will submit a job with 2^N circuits to build the calibration matrix, "
"where N is the number of measured qubits. "
"Furthermore, Aqua will re-use the calibration matrix for {} minutes "
"and re-build it after that.".format(self._cals_matrix_refresh_period))
logger.info(self)
def __str__(self):
"""Overload string.
Returns:
str: the info of the object.
"""
info = "\nQiskit Terra version: {}\n".format(terra_version)
info += "Backend: '{} ({})', with following setting:\n{}\n{}\n{}\n{}\n{}\n{}".format(
self.backend_name, self._backend.provider(), self._backend_config, self._compile_config,
self._run_config, self._qjob_config, self._backend_options, self._noise_config)
info += "\nMeasurement mitigation: {}".format(self._measurement_error_mitigation_cls)
return info
def execute(self, circuits, **kwargs):
"""
A wrapper to interface with quantum backend.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute
Returns:
Result: Result object
"""
qobjs = compile_circuits(circuits, self._backend, self._backend_config, self._compile_config, self._run_config,
show_circuit_summary=self._circuit_summary, circuit_cache=self._circuit_cache,
**kwargs)
if self._measurement_error_mitigation_cls is not None:
if self.maybe_refresh_cals_matrix():
logger.info("Building calibration matrix for measurement error mitigation.")
qubit_list = get_measured_qubits_from_qobj(qobjs)
self._measurement_error_mitigation_fitter = build_measurement_error_mitigation_fitter(qubit_list,
self._measurement_error_mitigation_cls,
self._backend,
self._backend_config,
self._compile_config,
self._run_config,
self._qjob_config,
self._backend_options,
self._noise_config)
result = run_qobjs(qobjs, self._backend, self._qjob_config, self._backend_options, self._noise_config,
self._skip_qobj_validation)
if self._measurement_error_mitigation_fitter is not None:
result = mitigate_measurement_error(result, self._measurement_error_mitigation_fitter,
self._measurement_error_mitigation_method)
if self._circuit_summary:
self._circuit_summary = False
return result
def set_config(self, **kwargs):
"""Set configurations for the quantum instance."""
for k, v in kwargs.items():
if k in QuantumInstance.RUN_CONFIG:
setattr(self._run_config, k, v)
elif k in QuantumInstance.QJOB_CONFIG:
self._qjob_config[k] = v
elif k in QuantumInstance.COMPILE_CONFIG:
self._compile_config[k] = v
elif k in QuantumInstance.BACKEND_CONFIG:
self._backend_config[k] = v
elif k in QuantumInstance.BACKEND_OPTIONS:
if is_ibmq_provider(self._backend):
logger.info("backend_options can not used with the backends in IBMQ provider.")
else:
if k in QuantumInstance.BACKEND_OPTIONS_QASM_ONLY and self.is_statevector:
logger.info("'{}' is only applicable for qasm simulator but "
"statevector simulator is used. Skip the setting.")
else:
if 'backend_options' not in self._backend_options:
self._backend_options['backend_options'] = {}
self._backend_options['backend_options'][k] = v
elif k in QuantumInstance.NOISE_CONFIG:
self._noise_config[k] = v
else:
raise ValueError("unknown setting for the key ({}).".format(k))
@property
def qjob_config(self):
"""Getter of qjob_config."""
return self._qjob_config
@property
def backend_config(self):
"""Getter of backend_config."""
return self._backend_config
@property
def compile_config(self):
"""Getter of compile_config."""
return self._compile_config
@property
def run_config(self):
"""Getter of run_config."""
return self._run_config
@property
def noise_config(self):
"""Getter of noise_config."""
return self._noise_config
@property
def backend_options(self):
"""Getter of backend_options."""
return self._backend_options
@property
def shared_circuits(self):
"""Getter of shared_circuits."""
return self._shared_circuits
@shared_circuits.setter
def shared_circuits(self, new_value):
self._shared_circuits = new_value
@property
def circuit_summary(self):
"""Getter of circuit summary."""
return self._circuit_summary
@circuit_summary.setter
def circuit_summary(self, new_value):
self._circuit_summary = new_value
@property
def backend(self):
"""Return BaseBackend backend object."""
return self._backend
@property
def backend_name(self):
"""Return backend name."""
return self._backend.name()
@property
def is_statevector(self):
"""Return True if backend is a statevector-type simulator."""
return is_statevector_backend(self._backend)
@property
def is_simulator(self):
"""Return True if backend is a simulator."""
return is_simulator_backend(self._backend)
@property
def is_local(self):
"""Return True if backend is a local backend."""
return is_local_backend(self._backend)
@property
def circuit_cache(self):
return self._circuit_cache
@property
def has_circuit_caching(self):
return self._circuit_cache is not None
@property
def skip_qobj_validation(self):
return self._skip_qobj_validation
@skip_qobj_validation.setter
def skip_qobj_validation(self, new_value):
self._skip_qobj_validation = new_value
def maybe_refresh_cals_matrix(self):
"""
Calculate the time difference from the query of last time.
Returns:
bool: whether or not refresh the cals_matrix
"""
ret = False
curr_timestamp = time.time()
difference = int(curr_timestamp - self._prev_timestamp) / 60.0
if difference > self._cals_matrix_refresh_period:
self._prev_timestamp = curr_timestamp
ret = True
return ret
@property
def cals_matrix(self):
cals_matrix = None
if self._measurement_error_mitigation_fitter is not None:
cals_matrix = self._measurement_error_mitigation_fitter.cal_matrix
return cals_matrix
|
https://github.com/GabrielPontolillo/QiskitPBT
|
GabrielPontolillo
|
# class that inherits from property based test
import numpy as np
from qiskit import QuantumCircuit
from QiskitPBT.property import Property
from QiskitPBT.input_generators import RandomFourierTransformState
from QiskitPBT.case_studies.quantum_fourier_transform.quantum_fourier_transform import qft_general
class PhaseShiftToLinearShift(Property):
# specify the inputs that are to be generated
def get_input_generators(self):
state = RandomFourierTransformState(1, 5)
return [state]
# specify the preconditions for the test
def preconditions(self, state):
return True
# specify the operations to be performed on the input
def operations(self, state):
n = state.num_qubits
qft_1 = QuantumCircuit(n, n)
qft_1.initialize(state, range(n))
qft_1 = qft_1.compose(qft_general(n, swap=True).inverse(), reversed(range(n)))
qft_1 = linear_shift(qft_1)
qft_2 = QuantumCircuit(n, n)
qft_2.initialize(state, range(n))
qft_2 = phase_shift(qft_2)
qft_2 = qft_2.compose(qft_general(n, swap=True).inverse(), reversed(range(n)))
self.statistical_analysis.assert_equal(self, list(range(n)), qft_1, list(range(n)), qft_2)
def phase_shift(qc):
# we instead apply a positive phase shift to the qubits as the linear shift adds 1 (down shift instead of up)
for i in range(qc.num_qubits):
qc.p(np.pi / 2 ** (qc.num_qubits - 1 - i), i)
return qc
# Apply a series of controlled gates to perform the addition of 1
def linear_shift(qc):
# this
n = qc.num_qubits
for i in reversed(range(1, n)):
qubit_list = [j for j in range(i)]
qc.mcx(qubit_list, i)
qc.x(0)
return qc
|
https://github.com/petr-ivashkov/qiskit-cert-workbook
|
petr-ivashkov
|
#initialization
import matplotlib.pyplot as plt
import numpy as np
#ignore deprecation warnings because they are annoying (not recommened generally)
from warnings import simplefilter
simplefilter(action='ignore', category=DeprecationWarning)
# Importing standard Qiskit libraries
from qiskit import *
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.quantum_info import *
from qiskit.circuit.library import *
from ibm_quantum_widgets import *
NUM_QUBITS = 2
# let's construct a multi-qubit quantum register
qr = QuantumRegister(NUM_QUBITS, 'q')
qc = QuantumCircuit(qr, name='my-circuit')
# let's create a Bell's state
qc.h(0)
qc.cx(0,1)
qc.measure_all()
qc.draw()
# let's construct a multi-bit classical register
cr = ClassicalRegister(NUM_QUBITS, 'c')
qc = QuantumCircuit(qr, cr, name='my-circuit')
# explicitly measure qubits [0,1] into classical bits [0,1]
qc.measure(qr, cr)
# alternatively: qc.measure([0,1], [0,1])
qc.draw()
# Bell state 0
bell_0 = QuantumCircuit(2)
bell_0.h(0)
bell_0.cx(0,1)
sv = Statevector.from_label('00')
#evolve the initial state through the circuit
sv_bell1 = sv.evolve(bell_0)
sv_bell1.draw('latex')
# Bell state 1
bell_1 = QuantumCircuit(2)
bell_1.x(0)
bell_1.h(0)
bell_1.cx(0,1)
sv = Statevector.from_label('00')
#evolve the initial state through the circuit
sv_bell2 = sv.evolve(bell_1)
sv_bell2.draw('latex')
# Bell state 2
bell_2 = QuantumCircuit(2)
bell_2.x(0)
bell_2.h(1)
bell_2.cx(1,0)
sv = Statevector.from_label('00')
#evolve the initial state through the circuit
sv_bell3 = sv.evolve(bell_2)
sv_bell3.draw('latex')
# create the last remaining Bell state on your own
bell_3 = QuantumCircuit(2)
### ADD CODE BELOW
### DON'T ADD CODE BELOW
sv = Statevector.from_label('00')
#evolve the initial state through the circuit
sv_bell3 = sv.evolve(bell_3)
sv_bell3.draw('latex')
# state of equal superposition of basis states
max_sp = QuantumCircuit(2)
max_sp.h(0)
max_sp.h(1)
sv = Statevector.from_label('00')
# evolve the initial state through the circuit
### ADD CODE BELOW
### DON'T ADD CODE BELOW
qc = QuantumCircuit(1)
qc.h(0)
qc.h(0)
qc.draw('mpl')
backend = BasicAer.get_backend('qasm_simulator')
qc = QuantumCircuit(1)
qc.h(0)
qc.h(0)
transpile(qc, backend=backend).draw('mpl')
backend = BasicAer.get_backend('qasm_simulator')
qc = QuantumCircuit(1)
qc.h(0)
qc.barrier()
qc.h(0)
transpile(qc, backend=backend).draw('mpl')
# try it out yourself with different gates: instead of Hadamard, try Pauili gates
my_qc = QuantumCircuit(1)
### ADD CODE BELOW
### DON'T ADD CODE BELOW
transpile(my_qc, backend=backend).draw('mpl')
# did you get what you expected?
qc = QuantumCircuit(1)
qc.x(0)
qc.depth()
qc = QuantumCircuit(2)
qc.x([0,1])
qc.x(1)
qc.depth()
# draw the circuit yourself to see why the depth has increased now
### ADD CODE BELOW
### DON'T ADD CODE BELOW
qc = QuantumCircuit(2)
qc.x(0)
qc.barrier(0)
qc.h(0)
qc.cx(0,1)
qc.depth()
# draw the circuit yourself to see why the depth has increased now
# hint: the longest path is not always the lenth of the longest sequence along one channel
qc.draw('mpl')
# the second qubit only has a CX gate applied to it, but has to "wait" for the first qubit to provide the control
# also, barier doesn't count
# in the following we will use the implementation of Grover's algorithm in Qiskit
from qiskit.algorithms import Grover, AmplificationProblem
# let's construct an oracle with a single solution
sv = Statevector.from_label('010')
problem = AmplificationProblem(oracle=sv)
grover = Grover(iterations=2).construct_circuit(problem=problem)
# the original circuit contains unitaries
# transpile the circuit in terms of basis gates to see what it is "made of"
t_grover = transpile(grover, basis_gates=['cx', 'u3'])
t_grover.draw('mpl', fold=-1)
# draw the original cicuit yourself
grover.draw('mpl', fold=-1)
# lets's try to evolve the initial state through the circuit like we have done for Bell states
sv = Statevector.from_label('000')
sv_ev = sv.evolve(grover)
sv_ev.draw('latex')
# it is obvious from statevector evolutions, that the state 010
# has the best chances to be measured, as desired
# now let's obtain the same result from the QASM simulation
# for that we need to measure the qubits in the end of our circuit
grover.measure_all()
backend= BasicAer.get_backend('qasm_simulator')
job = execute(grover, backend, shots=1024)
result = job.result()
plot_histogram(result.get_counts())
# finally let's see how our circuit performs on actual hardware
# you will need your IBM Quantum account
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
# sometimes you might need to wait when running on real devices
# let's monitor the status of our job
from qiskit.tools import job_monitor
# to call a real backend let's pick the least busy one, which satisfies out requirments
from qiskit.providers.ibmq import least_busy
suitable_devices = provider.backends(filters = lambda b: b.configuration().n_qubits >= 3
and not b.configuration().simulator
and b.status().operational==True)
backend = least_busy(backends=suitable_devices)
print("We are runnig our circuit on ", backend)
job = execute(grover, backend=backend)
job_monitor(job)
# we see that results from a real device also match our expectations
# the algorithm successfully finds the marked string
result = job.result()
counts = result.get_counts()
# plot the histogramm yourself
### ADD CODE BELOW
### DON'T ADD CODE BELOW
# let's again use our transpiled Grover circuit to demonstarte the idea
# Notice: QASM doesn't look "nice". This is a low-level language which can be understood by quantum hardware.
# If you want to take a look at the QASM code make sure to specify 'formatted=True' which makes the code readable by a human being.
t_grover.qasm(formatted=True)
# store the circuit to a file in the follwing way
qasm_code = t_grover.qasm(filename='grover.qasm')
# to get the circuit back from QASM file execute the following
my_qc = QuantumCircuit.from_qasm_file('grover.qasm')
my_qc.draw('mpl', fold=-1)
# let's create an arbitrary Operator from a matrix
A = np.array([[0,1,0], [1,0,0], [0,1,1]])
op = Operator(A)
# Operator contains information about its matrix representation and input and output dimensions
op
# create an Operator from a circuit yourself
qc = QuantumCircuit(2)
qc.h([0,1])
qc.cx(0,1)
op = Operator(qc)
op
A = Operator(Pauli(label='X'))
B = Operator(Pauli(label='Z'))
A.expand(B) # B x A
A = Operator(Pauli(label='X'))
B = Operator(Pauli(label='Z'))
A.tensor(B) # result A x B
III = Operator(np.eye(2 ** 3))
XX = Operator(Pauli(label='XX'))
XIX = III.compose(XX, qargs=[0,2])
XIX # the resulting operator is X x I x X
# compose an XIXZ Operator from IIII and XX and Z Operators
### ADD CODE BELOW
### DON'T ADD CODE BELOW
# with Qiskit you can find the state fidelity between two quantum states
# let's investigate Bell states
state_fidelity(sv_bell3, sv_bell1)
basis_state_00 = Statevector.from_label('00')
state_fidelity(basis_state_00, sv_bell1)
basis_state_00 = Statevector.from_label('00')
state_fidelity(basis_state_00, sv_bell3)
# let's find process fidelity of X and H Operators
op_1 = Operator([[0,1],[0,1]])
op_2 = Operator([[1,1],[1,-1]])/np.sqrt(2)
F = process_fidelity(op_1, op_2)
F
# what about fidelity of X Operator with itself multiplied with a complex phase
op_1 = Operator([[0,1],[0,1]])
op_2 = op_1*np.exp(0.5j)
# calculate the process fidelity yourself
### ADD CODE BELOW
### DON'T ADD CODE BELOW
# as you expected, the fidelity is independent of global phase
# encountered a compatibility error? Check which version of Qiskit you are using
import qiskit
qiskit.__qiskit_version__
# display the entire version table
%qiskit_version_table
# Let's have an overview information on all the IBMQ backends that are available
%qiskit_backend_overview
# now let's pick one device and investigate it
from qiskit.visualization import plot_gate_map
backend = provider.get_backend('ibmq_bogota')
plot_gate_map(backend, plot_directed=True)
plot_error_map(backend)
# let's plot the layout of our Bell state circuit transpiled for our target backend
transpiled_bell = transpile(bell_0, backend=backend)
plot_circuit_layout(transpiled_bell, backend=backend)
# display the layout of transpiled Grover's circuit on our target backend
transpiled_grover = transpile(grover, backend=backend)
plot_circuit_layout(transpiled_grover, backend=backend)
# what if we want to specify a custom mapping of our circuit qubits to device qubits?
# let's create an initial layout
initial_layout = [2,3,4] # virtual to physical: virtual qubits are ordered
transpiled_qc = transpile(grover, backend=backend, initial_layout=initial_layout)
plot_circuit_layout(transpiled_qc, backend=backend)
# for example, let's draw our Bell's state circuit in text mode
bell_0.draw('text')
# qubits in reversed order
bell_0.draw('mpl', reverse_bits=True)
# More customization
style = {'linecolor': 'red', 'backgroundcolor': 'grey'}
bell_0.draw('mpl',scale = 1.2, style=style, fold=-1)
plot_bloch_vector([0,1,0])
plot_state_city(bell_0)
# to understand why the 'city' looks like this consider the density matrix of this state
plot_state_hinton(bell_0)
plot_state_qsphere(bell_0)
plot_state_paulivec(bell_0)
plot_bloch_multivector(bell_0)
# here, the bloch spheres represent maximally entangled qubits as zero-length vectors. Hence, no arrows.
# a more informative example
psi = Statevector.from_label('+1')
plot_bloch_multivector(psi)
# the first qubit is in state |1>
# the second qubit is in the superposition of |0> and |1>
rho = DensityMatrix.from_instruction(bell_0)
rho.draw('latex', prefix='\\rho_{Bell_0} = ')
plot_state_city(rho.data, title='Density Matrix')
# prepare a density matrix for the state of the equal superposition of 2 basis states
my_qc = QuantumCircuit(2)
my_qc.h([0,1])
my_rho = DensityMatrix.from_instruction(my_qc)
my_rho.draw('latex', prefix='\\rho_{equal} = ')
# prepare a density matrix for a mixed one-qubit state in an equal mixture of |0> and |1>
### ADD CODE BELOW
### DON'T ADD CODE BELOW
qr = QuantumRegister(3, name='q')
qc = QuantumCircuit(qr)
qc.ccx(control_qubit1=qr[1], control_qubit2=qr[2], target_qubit=qr[0])
qc.draw('mpl')
# Toffoli gate has the following matrix representation for the above configuration
matrix = Operator(qc).data
array_to_latex(matrix, prefix="CCX = ")
qr = QuantumRegister(2, name='q')
qc = QuantumCircuit(qr)
qc.swap(qubit1=qr[0], qubit2=[1])
qc.draw('mpl')
# SWAP gate has the following matrix representation for the above configuration
matrix = Operator(qc).data
# display the matrix in latex
array_to_latex(matrix, prefix="SWAP = ")
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Tests for Operator matrix linear operator class."""
import unittest
import logging
import copy
from test import combine
import numpy as np
from ddt import ddt
from numpy.testing import assert_allclose
import scipy.linalg as la
from qiskit import QiskitError
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit.library import HGate, CHGate, CXGate, QFT
from qiskit.test import QiskitTestCase
from qiskit.transpiler.layout import Layout, TranspileLayout
from qiskit.quantum_info.operators import Operator, ScalarOp
from qiskit.quantum_info.operators.predicates import matrix_equal
from qiskit.compiler.transpiler import transpile
from qiskit.circuit import Qubit
from qiskit.circuit.library import Permutation, PermutationGate
logger = logging.getLogger(__name__)
class OperatorTestCase(QiskitTestCase):
"""Test utils for Operator"""
# Pauli-matrix unitaries
UI = np.eye(2)
UX = np.array([[0, 1], [1, 0]])
UY = np.array([[0, -1j], [1j, 0]])
UZ = np.diag([1, -1])
UH = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
@classmethod
def rand_rho(cls, n):
"""Return random density matrix"""
seed = np.random.randint(0, np.iinfo(np.int32).max)
logger.debug("rand_rho default_rng seeded with seed=%s", seed)
rng = np.random.default_rng(seed)
psi = rng.random(n) + 1j * rng.random(n)
rho = np.outer(psi, psi.conj())
rho /= np.trace(rho)
return rho
@classmethod
def rand_matrix(cls, rows, cols=None, real=False):
"""Return a random matrix."""
seed = np.random.randint(0, np.iinfo(np.int32).max)
logger.debug("rand_matrix default_rng seeded with seed=%s", seed)
rng = np.random.default_rng(seed)
if cols is None:
cols = rows
if real:
return rng.random(size=(rows, cols))
return rng.random(size=(rows, cols)) + 1j * rng.random(size=(rows, cols))
def simple_circuit_no_measure(self):
"""Return a unitary circuit and the corresponding unitary array."""
qr = QuantumRegister(3)
circ = QuantumCircuit(qr)
circ.h(qr[0])
circ.x(qr[1])
circ.ry(np.pi / 2, qr[2])
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = Operator(np.kron(y90, np.kron(self.UX, self.UH)))
return circ, target
def simple_circuit_with_measure(self):
"""Return a unitary circuit with measurement."""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circ = QuantumCircuit(qr, cr)
circ.h(qr[0])
circ.x(qr[1])
circ.measure(qr, cr)
return circ
@ddt
class TestOperator(OperatorTestCase):
"""Tests for Operator linear operator class."""
def test_init_array_qubit(self):
"""Test subsystem initialization from N-qubit array."""
# Test automatic inference of qubit subsystems
mat = self.rand_matrix(8, 8)
op = Operator(mat)
assert_allclose(op.data, mat)
self.assertEqual(op.dim, (8, 8))
self.assertEqual(op.input_dims(), (2, 2, 2))
self.assertEqual(op.output_dims(), (2, 2, 2))
self.assertEqual(op.num_qubits, 3)
op = Operator(mat, input_dims=8, output_dims=8)
assert_allclose(op.data, mat)
self.assertEqual(op.dim, (8, 8))
self.assertEqual(op.input_dims(), (2, 2, 2))
self.assertEqual(op.output_dims(), (2, 2, 2))
self.assertEqual(op.num_qubits, 3)
def test_init_array(self):
"""Test initialization from array."""
mat = np.eye(3)
op = Operator(mat)
assert_allclose(op.data, mat)
self.assertEqual(op.dim, (3, 3))
self.assertEqual(op.input_dims(), (3,))
self.assertEqual(op.output_dims(), (3,))
self.assertIsNone(op.num_qubits)
mat = self.rand_matrix(2 * 3 * 4, 4 * 5)
op = Operator(mat, input_dims=[4, 5], output_dims=[2, 3, 4])
assert_allclose(op.data, mat)
self.assertEqual(op.dim, (4 * 5, 2 * 3 * 4))
self.assertEqual(op.input_dims(), (4, 5))
self.assertEqual(op.output_dims(), (2, 3, 4))
self.assertIsNone(op.num_qubits)
def test_init_array_except(self):
"""Test initialization exception from array."""
mat = self.rand_matrix(4, 4)
self.assertRaises(QiskitError, Operator, mat, input_dims=[4, 2])
self.assertRaises(QiskitError, Operator, mat, input_dims=[2, 4])
self.assertRaises(QiskitError, Operator, mat, input_dims=5)
def test_init_operator(self):
"""Test initialization from Operator."""
op1 = Operator(self.rand_matrix(4, 4))
op2 = Operator(op1)
self.assertEqual(op1, op2)
def test_circuit_init(self):
"""Test initialization from a circuit."""
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.x(1)
circuit.ry(np.pi / 2, 2)
op = Operator(circuit)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.cp(lam, 0, 1)
op = Operator(circuit)
target = np.diag([1, 1, 1, np.exp(1j * lam)])
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circuit.ch(0, 1)
op = Operator(circuit)
target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1]))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_instruction_init(self):
"""Test initialization from a circuit."""
gate = CXGate()
op = Operator(gate).data
target = gate.to_matrix()
global_phase_equivalent = matrix_equal(op, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
gate = CHGate()
op = Operator(gate).data
had = HGate().to_matrix()
target = np.kron(had, np.diag([0, 1])) + np.kron(np.eye(2), np.diag([1, 0]))
global_phase_equivalent = matrix_equal(op, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_circuit_init_except(self):
"""Test initialization from circuit with measure raises exception."""
circuit = self.simple_circuit_with_measure()
self.assertRaises(QiskitError, Operator, circuit)
def test_equal(self):
"""Test __eq__ method"""
mat = self.rand_matrix(2, 2, real=True)
self.assertEqual(Operator(np.array(mat, dtype=complex)), Operator(mat))
mat = self.rand_matrix(4, 4)
self.assertEqual(Operator(mat.tolist()), Operator(mat))
def test_data(self):
"""Test Operator representation string property."""
mat = self.rand_matrix(2, 2)
op = Operator(mat)
assert_allclose(mat, op.data)
def test_to_matrix(self):
"""Test Operator to_matrix method."""
mat = self.rand_matrix(2, 2)
op = Operator(mat)
assert_allclose(mat, op.to_matrix())
def test_dim(self):
"""Test Operator dim property."""
mat = self.rand_matrix(4, 4)
self.assertEqual(Operator(mat).dim, (4, 4))
self.assertEqual(Operator(mat, input_dims=[4], output_dims=[4]).dim, (4, 4))
self.assertEqual(Operator(mat, input_dims=[2, 2], output_dims=[2, 2]).dim, (4, 4))
def test_input_dims(self):
"""Test Operator input_dims method."""
op = Operator(self.rand_matrix(2 * 3 * 4, 4 * 5), input_dims=[4, 5], output_dims=[2, 3, 4])
self.assertEqual(op.input_dims(), (4, 5))
self.assertEqual(op.input_dims(qargs=[0, 1]), (4, 5))
self.assertEqual(op.input_dims(qargs=[1, 0]), (5, 4))
self.assertEqual(op.input_dims(qargs=[0]), (4,))
self.assertEqual(op.input_dims(qargs=[1]), (5,))
def test_output_dims(self):
"""Test Operator output_dims method."""
op = Operator(self.rand_matrix(2 * 3 * 4, 4 * 5), input_dims=[4, 5], output_dims=[2, 3, 4])
self.assertEqual(op.output_dims(), (2, 3, 4))
self.assertEqual(op.output_dims(qargs=[0, 1, 2]), (2, 3, 4))
self.assertEqual(op.output_dims(qargs=[2, 1, 0]), (4, 3, 2))
self.assertEqual(op.output_dims(qargs=[2, 0, 1]), (4, 2, 3))
self.assertEqual(op.output_dims(qargs=[0]), (2,))
self.assertEqual(op.output_dims(qargs=[1]), (3,))
self.assertEqual(op.output_dims(qargs=[2]), (4,))
self.assertEqual(op.output_dims(qargs=[0, 2]), (2, 4))
self.assertEqual(op.output_dims(qargs=[2, 0]), (4, 2))
def test_reshape(self):
"""Test Operator reshape method."""
op = Operator(self.rand_matrix(8, 8))
reshaped1 = op.reshape(input_dims=[8], output_dims=[8])
reshaped2 = op.reshape(input_dims=[4, 2], output_dims=[2, 4])
self.assertEqual(op.output_dims(), (2, 2, 2))
self.assertEqual(op.input_dims(), (2, 2, 2))
self.assertEqual(reshaped1.output_dims(), (8,))
self.assertEqual(reshaped1.input_dims(), (8,))
self.assertEqual(reshaped2.output_dims(), (2, 4))
self.assertEqual(reshaped2.input_dims(), (4, 2))
def test_reshape_num_qubits(self):
"""Test Operator reshape method with num_qubits."""
op = Operator(self.rand_matrix(8, 8), input_dims=(4, 2), output_dims=(2, 4))
reshaped = op.reshape(num_qubits=3)
self.assertEqual(reshaped.num_qubits, 3)
self.assertEqual(reshaped.output_dims(), (2, 2, 2))
self.assertEqual(reshaped.input_dims(), (2, 2, 2))
def test_reshape_raise(self):
"""Test Operator reshape method with invalid args."""
op = Operator(self.rand_matrix(3, 3))
self.assertRaises(QiskitError, op.reshape, num_qubits=2)
def test_copy(self):
"""Test Operator copy method"""
mat = np.eye(2)
with self.subTest("Deep copy"):
orig = Operator(mat)
cpy = orig.copy()
cpy._data[0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = Operator(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_is_unitary(self):
"""Test is_unitary method."""
# X-90 rotation
X90 = la.expm(-1j * 0.5 * np.pi * np.array([[0, 1], [1, 0]]) / 2)
self.assertTrue(Operator(X90).is_unitary())
# Non-unitary should return false
self.assertFalse(Operator([[1, 0], [0, 0]]).is_unitary())
def test_to_operator(self):
"""Test to_operator method."""
op1 = Operator(self.rand_matrix(4, 4))
op2 = op1.to_operator()
self.assertEqual(op1, op2)
def test_conjugate(self):
"""Test conjugate method."""
matr = self.rand_matrix(2, 4, real=True)
mati = self.rand_matrix(2, 4, real=True)
op = Operator(matr + 1j * mati)
uni_conj = op.conjugate()
self.assertEqual(uni_conj, Operator(matr - 1j * mati))
def test_transpose(self):
"""Test transpose method."""
matr = self.rand_matrix(2, 4, real=True)
mati = self.rand_matrix(2, 4, real=True)
op = Operator(matr + 1j * mati)
uni_t = op.transpose()
self.assertEqual(uni_t, Operator(matr.T + 1j * mati.T))
def test_adjoint(self):
"""Test adjoint method."""
matr = self.rand_matrix(2, 4, real=True)
mati = self.rand_matrix(2, 4, real=True)
op = Operator(matr + 1j * mati)
uni_adj = op.adjoint()
self.assertEqual(uni_adj, Operator(matr.T - 1j * mati.T))
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, Operator(np.eye(2)).compose, Operator(np.eye(3)))
self.assertRaises(QiskitError, Operator(np.eye(2)).compose, 2)
def test_compose(self):
"""Test compose method."""
op1 = Operator(self.UX)
op2 = Operator(self.UY)
targ = Operator(np.dot(self.UY, self.UX))
self.assertEqual(op1.compose(op2), targ)
self.assertEqual(op1 & op2, targ)
targ = Operator(np.dot(self.UX, self.UY))
self.assertEqual(op2.compose(op1), targ)
self.assertEqual(op2 & op1, targ)
def test_dot(self):
"""Test dot method."""
op1 = Operator(self.UY)
op2 = Operator(self.UX)
targ = Operator(np.dot(self.UY, self.UX))
self.assertEqual(op1.dot(op2), targ)
self.assertEqual(op1 @ op2, targ)
targ = Operator(np.dot(self.UX, self.UY))
self.assertEqual(op2.dot(op1), targ)
self.assertEqual(op2 @ op1, targ)
def test_compose_front(self):
"""Test front compose method."""
opYX = Operator(self.UY).compose(Operator(self.UX), front=True)
matYX = np.dot(self.UY, self.UX)
self.assertEqual(opYX, Operator(matYX))
opXY = Operator(self.UX).compose(Operator(self.UY), front=True)
matXY = np.dot(self.UX, self.UY)
self.assertEqual(opXY, Operator(matXY))
def test_compose_subsystem(self):
"""Test subsystem compose method."""
# 3-qubit operator
mat = self.rand_matrix(8, 8)
mat_a = self.rand_matrix(2, 2)
mat_b = self.rand_matrix(2, 2)
mat_c = self.rand_matrix(2, 2)
op = Operator(mat)
op1 = Operator(mat_a)
op2 = Operator(np.kron(mat_b, mat_a))
op3 = Operator(np.kron(mat_c, np.kron(mat_b, mat_a)))
# op3 qargs=[0, 1, 2]
targ = np.dot(np.kron(mat_c, np.kron(mat_b, mat_a)), mat)
self.assertEqual(op.compose(op3, qargs=[0, 1, 2]), Operator(targ))
self.assertEqual(op.compose(op3([0, 1, 2])), Operator(targ))
self.assertEqual(op & op3([0, 1, 2]), Operator(targ))
# op3 qargs=[2, 1, 0]
targ = np.dot(np.kron(mat_a, np.kron(mat_b, mat_c)), mat)
self.assertEqual(op.compose(op3, qargs=[2, 1, 0]), Operator(targ))
self.assertEqual(op & op3([2, 1, 0]), Operator(targ))
# op2 qargs=[0, 1]
targ = np.dot(np.kron(np.eye(2), np.kron(mat_b, mat_a)), mat)
self.assertEqual(op.compose(op2, qargs=[0, 1]), Operator(targ))
self.assertEqual(op & op2([0, 1]), Operator(targ))
# op2 qargs=[2, 0]
targ = np.dot(np.kron(mat_a, np.kron(np.eye(2), mat_b)), mat)
self.assertEqual(op.compose(op2, qargs=[2, 0]), Operator(targ))
self.assertEqual(op & op2([2, 0]), Operator(targ))
# op1 qargs=[0]
targ = np.dot(np.kron(np.eye(4), mat_a), mat)
self.assertEqual(op.compose(op1, qargs=[0]), Operator(targ))
self.assertEqual(op & op1([0]), Operator(targ))
# op1 qargs=[1]
targ = np.dot(np.kron(np.eye(2), np.kron(mat_a, np.eye(2))), mat)
self.assertEqual(op.compose(op1, qargs=[1]), Operator(targ))
self.assertEqual(op & op1([1]), Operator(targ))
# op1 qargs=[2]
targ = np.dot(np.kron(mat_a, np.eye(4)), mat)
self.assertEqual(op.compose(op1, qargs=[2]), Operator(targ))
self.assertEqual(op & op1([2]), Operator(targ))
def test_dot_subsystem(self):
"""Test subsystem dot method."""
# 3-qubit operator
mat = self.rand_matrix(8, 8)
mat_a = self.rand_matrix(2, 2)
mat_b = self.rand_matrix(2, 2)
mat_c = self.rand_matrix(2, 2)
op = Operator(mat)
op1 = Operator(mat_a)
op2 = Operator(np.kron(mat_b, mat_a))
op3 = Operator(np.kron(mat_c, np.kron(mat_b, mat_a)))
# op3 qargs=[0, 1, 2]
targ = np.dot(mat, np.kron(mat_c, np.kron(mat_b, mat_a)))
self.assertEqual(op.dot(op3, qargs=[0, 1, 2]), Operator(targ))
self.assertEqual(op.dot(op3([0, 1, 2])), Operator(targ))
# op3 qargs=[2, 1, 0]
targ = np.dot(mat, np.kron(mat_a, np.kron(mat_b, mat_c)))
self.assertEqual(op.dot(op3, qargs=[2, 1, 0]), Operator(targ))
self.assertEqual(op.dot(op3([2, 1, 0])), Operator(targ))
# op2 qargs=[0, 1]
targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_b, mat_a)))
self.assertEqual(op.dot(op2, qargs=[0, 1]), Operator(targ))
self.assertEqual(op.dot(op2([0, 1])), Operator(targ))
# op2 qargs=[2, 0]
targ = np.dot(mat, np.kron(mat_a, np.kron(np.eye(2), mat_b)))
self.assertEqual(op.dot(op2, qargs=[2, 0]), Operator(targ))
self.assertEqual(op.dot(op2([2, 0])), Operator(targ))
# op1 qargs=[0]
targ = np.dot(mat, np.kron(np.eye(4), mat_a))
self.assertEqual(op.dot(op1, qargs=[0]), Operator(targ))
self.assertEqual(op.dot(op1([0])), Operator(targ))
# op1 qargs=[1]
targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_a, np.eye(2))))
self.assertEqual(op.dot(op1, qargs=[1]), Operator(targ))
self.assertEqual(op.dot(op1([1])), Operator(targ))
# op1 qargs=[2]
targ = np.dot(mat, np.kron(mat_a, np.eye(4)))
self.assertEqual(op.dot(op1, qargs=[2]), Operator(targ))
self.assertEqual(op.dot(op1([2])), Operator(targ))
def test_compose_front_subsystem(self):
"""Test subsystem front compose method."""
# 3-qubit operator
mat = self.rand_matrix(8, 8)
mat_a = self.rand_matrix(2, 2)
mat_b = self.rand_matrix(2, 2)
mat_c = self.rand_matrix(2, 2)
op = Operator(mat)
op1 = Operator(mat_a)
op2 = Operator(np.kron(mat_b, mat_a))
op3 = Operator(np.kron(mat_c, np.kron(mat_b, mat_a)))
# op3 qargs=[0, 1, 2]
targ = np.dot(mat, np.kron(mat_c, np.kron(mat_b, mat_a)))
self.assertEqual(op.compose(op3, qargs=[0, 1, 2], front=True), Operator(targ))
# op3 qargs=[2, 1, 0]
targ = np.dot(mat, np.kron(mat_a, np.kron(mat_b, mat_c)))
self.assertEqual(op.compose(op3, qargs=[2, 1, 0], front=True), Operator(targ))
# op2 qargs=[0, 1]
targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_b, mat_a)))
self.assertEqual(op.compose(op2, qargs=[0, 1], front=True), Operator(targ))
# op2 qargs=[2, 0]
targ = np.dot(mat, np.kron(mat_a, np.kron(np.eye(2), mat_b)))
self.assertEqual(op.compose(op2, qargs=[2, 0], front=True), Operator(targ))
# op1 qargs=[0]
targ = np.dot(mat, np.kron(np.eye(4), mat_a))
self.assertEqual(op.compose(op1, qargs=[0], front=True), Operator(targ))
# op1 qargs=[1]
targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_a, np.eye(2))))
self.assertEqual(op.compose(op1, qargs=[1], front=True), Operator(targ))
# op1 qargs=[2]
targ = np.dot(mat, np.kron(mat_a, np.eye(4)))
self.assertEqual(op.compose(op1, qargs=[2], front=True), Operator(targ))
def test_power(self):
"""Test power method."""
X90 = la.expm(-1j * 0.5 * np.pi * np.array([[0, 1], [1, 0]]) / 2)
op = Operator(X90)
self.assertEqual(op.power(2), Operator([[0, -1j], [-1j, 0]]))
self.assertEqual(op.power(4), Operator(-1 * np.eye(2)))
self.assertEqual(op.power(8), Operator(np.eye(2)))
def test_expand(self):
"""Test expand method."""
mat1 = self.UX
mat2 = np.eye(3, dtype=complex)
mat21 = np.kron(mat2, mat1)
op21 = Operator(mat1).expand(Operator(mat2))
self.assertEqual(op21.dim, (6, 6))
assert_allclose(op21.data, Operator(mat21).data)
mat12 = np.kron(mat1, mat2)
op12 = Operator(mat2).expand(Operator(mat1))
self.assertEqual(op12.dim, (6, 6))
assert_allclose(op12.data, Operator(mat12).data)
def test_tensor(self):
"""Test tensor method."""
mat1 = self.UX
mat2 = np.eye(3, dtype=complex)
mat21 = np.kron(mat2, mat1)
op21 = Operator(mat2).tensor(Operator(mat1))
self.assertEqual(op21.dim, (6, 6))
assert_allclose(op21.data, Operator(mat21).data)
mat12 = np.kron(mat1, mat2)
op12 = Operator(mat1).tensor(Operator(mat2))
self.assertEqual(op12.dim, (6, 6))
assert_allclose(op12.data, Operator(mat12).data)
def test_power_except(self):
"""Test power method raises exceptions if not square."""
op = Operator(self.rand_matrix(2, 3))
# Non-integer power raises error
self.assertRaises(QiskitError, op.power, 0.5)
def test_add(self):
"""Test add method."""
mat1 = self.rand_matrix(4, 4)
mat2 = self.rand_matrix(4, 4)
op1 = Operator(mat1)
op2 = Operator(mat2)
self.assertEqual(op1._add(op2), Operator(mat1 + mat2))
self.assertEqual(op1 + op2, Operator(mat1 + mat2))
self.assertEqual(op1 - op2, Operator(mat1 - mat2))
def test_add_except(self):
"""Test add method raises exceptions."""
op1 = Operator(self.rand_matrix(2, 2))
op2 = Operator(self.rand_matrix(3, 3))
self.assertRaises(QiskitError, op1._add, op2)
def test_add_qargs(self):
"""Test add method with qargs."""
mat = self.rand_matrix(8, 8)
mat0 = self.rand_matrix(2, 2)
mat1 = self.rand_matrix(2, 2)
op = Operator(mat)
op0 = Operator(mat0)
op01 = Operator(np.kron(mat1, mat0))
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + Operator(np.kron(np.eye(4), mat0))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + Operator(np.kron(np.kron(np.eye(2), mat0), np.eye(2)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + Operator(np.kron(mat0, np.eye(4)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op + op01([0, 1])
target = op + Operator(np.kron(np.eye(2), np.kron(mat1, mat0)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op + op01([1, 0])
target = op + Operator(np.kron(np.eye(2), np.kron(mat0, mat1)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op + op01([0, 2])
target = op + Operator(np.kron(mat1, np.kron(np.eye(2), mat0)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op + op01([2, 0])
target = op + Operator(np.kron(mat0, np.kron(np.eye(2), mat1)))
self.assertEqual(value, target)
def test_sub_qargs(self):
"""Test subtract method with qargs."""
mat = self.rand_matrix(8, 8)
mat0 = self.rand_matrix(2, 2)
mat1 = self.rand_matrix(2, 2)
op = Operator(mat)
op0 = Operator(mat0)
op01 = Operator(np.kron(mat1, mat0))
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - Operator(np.kron(np.eye(4), mat0))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - Operator(np.kron(np.kron(np.eye(2), mat0), np.eye(2)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - Operator(np.kron(mat0, np.eye(4)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op - op01([0, 1])
target = op - Operator(np.kron(np.eye(2), np.kron(mat1, mat0)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op - op01([1, 0])
target = op - Operator(np.kron(np.eye(2), np.kron(mat0, mat1)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op - op01([0, 2])
target = op - Operator(np.kron(mat1, np.kron(np.eye(2), mat0)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op - op01([2, 0])
target = op - Operator(np.kron(mat0, np.kron(np.eye(2), mat1)))
self.assertEqual(value, target)
def test_multiply(self):
"""Test multiply method."""
mat = self.rand_matrix(4, 4)
val = np.exp(5j)
op = Operator(mat)
self.assertEqual(op._multiply(val), Operator(val * mat))
self.assertEqual(val * op, Operator(val * mat))
self.assertEqual(op * val, Operator(mat * val))
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
op = Operator(self.rand_matrix(2, 2))
self.assertRaises(QiskitError, op._multiply, "s")
self.assertRaises(QiskitError, op.__rmul__, "s")
self.assertRaises(QiskitError, op._multiply, op)
self.assertRaises(QiskitError, op.__rmul__, op)
def test_negate(self):
"""Test negate method"""
mat = self.rand_matrix(4, 4)
op = Operator(mat)
self.assertEqual(-op, Operator(-1 * mat))
def test_equiv(self):
"""Test negate method"""
mat = np.diag([1, np.exp(1j * np.pi / 2)])
phase = np.exp(-1j * np.pi / 4)
op = Operator(mat)
self.assertTrue(op.equiv(phase * mat))
self.assertTrue(op.equiv(Operator(phase * mat)))
self.assertFalse(op.equiv(2 * mat))
def test_reverse_qargs(self):
"""Test reverse_qargs method"""
circ1 = QFT(5)
circ2 = circ1.reverse_bits()
state1 = Operator(circ1)
state2 = Operator(circ2)
self.assertEqual(state1.reverse_qargs(), state2)
def test_drawings(self):
"""Test draw method"""
qc1 = QFT(5)
op = Operator.from_circuit(qc1)
with self.subTest(msg="str(operator)"):
str(op)
for drawtype in ["repr", "text", "latex_source"]:
with self.subTest(msg=f"draw('{drawtype}')"):
op.draw(drawtype)
with self.subTest(msg=" draw('latex')"):
op.draw("latex")
def test_from_circuit_constructor_no_layout(self):
"""Test initialization from a circuit using the from_circuit constructor."""
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.x(1)
circuit.ry(np.pi / 2, 2)
op = Operator.from_circuit(circuit)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.cp(lam, 0, 1)
op = Operator.from_circuit(circuit)
target = np.diag([1, 1, 1, np.exp(1j * lam)])
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circuit.ch(0, 1)
op = Operator.from_circuit(circuit)
target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1]))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_reverse_embedded_layout(self):
"""Test initialization from a circuit with an embedded reverse layout."""
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(2)
circuit.x(1)
circuit.ry(np.pi / 2, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
op = Operator.from_circuit(circuit)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.cp(lam, 1, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
op = Operator.from_circuit(circuit)
target = np.diag([1, 1, 1, np.exp(1j * lam)])
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circuit.ch(1, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
op = Operator.from_circuit(circuit)
target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1]))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_reverse_embedded_layout_from_transpile(self):
"""Test initialization from a circuit with an embedded final layout."""
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.x(1)
circuit.ry(np.pi / 2, 2)
output = transpile(circuit, initial_layout=[2, 1, 0])
op = Operator.from_circuit(output)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_reverse_embedded_layout_from_transpile_with_registers(self):
"""Test initialization from a circuit with an embedded final layout."""
# Test tensor product of 1-qubit gates
qr = QuantumRegister(3, name="test_reg")
circuit = QuantumCircuit(qr)
circuit.h(0)
circuit.x(1)
circuit.ry(np.pi / 2, 2)
output = transpile(circuit, initial_layout=[2, 1, 0])
op = Operator.from_circuit(output)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_reverse_embedded_layout_and_final_layout(self):
"""Test initialization from a circuit with an embedded final layout."""
# Test tensor product of 1-qubit gates
qr = QuantumRegister(3, name="test_reg")
circuit = QuantumCircuit(qr)
circuit.h(2)
circuit.x(1)
circuit.ry(np.pi / 2, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
Layout({circuit.qubits[0]: 1, circuit.qubits[1]: 2, circuit.qubits[2]: 0}),
)
circuit.swap(0, 1)
circuit.swap(1, 2)
op = Operator.from_circuit(circuit)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_reverse_embedded_layout_and_manual_final_layout(self):
"""Test initialization from a circuit with an embedded final layout."""
# Test tensor product of 1-qubit gates
qr = QuantumRegister(3, name="test_reg")
circuit = QuantumCircuit(qr)
circuit.h(2)
circuit.x(1)
circuit.ry(np.pi / 2, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
final_layout = Layout({circuit.qubits[0]: 1, circuit.qubits[1]: 2, circuit.qubits[2]: 0})
circuit.swap(0, 1)
circuit.swap(1, 2)
op = Operator.from_circuit(circuit, final_layout=final_layout)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_reverse_embedded_layout_ignore_set_layout(self):
"""Test initialization from a circuit with an ignored embedded reverse layout."""
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(2)
circuit.x(1)
circuit.ry(np.pi / 2, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
op = Operator.from_circuit(circuit, ignore_set_layout=True).reverse_qargs()
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.cp(lam, 1, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
op = Operator.from_circuit(circuit, ignore_set_layout=True).reverse_qargs()
target = np.diag([1, 1, 1, np.exp(1j * lam)])
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circuit.ch(1, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
op = Operator.from_circuit(circuit, ignore_set_layout=True).reverse_qargs()
target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1]))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_reverse_user_specified_layout(self):
"""Test initialization from a circuit with a user specified reverse layout."""
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(2)
circuit.x(1)
circuit.ry(np.pi / 2, 0)
layout = Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2})
op = Operator.from_circuit(circuit, layout=layout)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.cp(lam, 1, 0)
layout = Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1})
op = Operator.from_circuit(circuit, layout=layout)
target = np.diag([1, 1, 1, np.exp(1j * lam)])
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circuit.ch(1, 0)
layout = Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1})
op = Operator.from_circuit(circuit, layout=layout)
target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1]))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_ghz_out_of_order_layout(self):
"""Test an out of order ghz state with a layout set."""
circuit = QuantumCircuit(5)
circuit.h(3)
circuit.cx(3, 4)
circuit.cx(3, 2)
circuit.cx(3, 0)
circuit.cx(3, 1)
circuit._layout = TranspileLayout(
Layout(
{
circuit.qubits[3]: 0,
circuit.qubits[4]: 1,
circuit.qubits[2]: 2,
circuit.qubits[0]: 3,
circuit.qubits[1]: 4,
}
),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
result = Operator.from_circuit(circuit)
expected = QuantumCircuit(5)
expected.h(0)
expected.cx(0, 1)
expected.cx(0, 2)
expected.cx(0, 3)
expected.cx(0, 4)
expected_op = Operator(expected)
self.assertTrue(expected_op.equiv(result))
def test_from_circuit_empty_circuit_empty_layout(self):
"""Test an out of order ghz state with a layout set."""
circuit = QuantumCircuit()
circuit._layout = TranspileLayout(Layout(), {})
op = Operator.from_circuit(circuit)
self.assertEqual(Operator([1]), op)
def test_from_circuit_constructor_empty_layout(self):
"""Test an out of order ghz state with a layout set."""
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
layout = Layout()
with self.assertRaises(IndexError):
Operator.from_circuit(circuit, layout=layout)
def test_compose_scalar(self):
"""Test that composition works with a scalar-valued operator over no qubits."""
base = Operator(np.eye(2, dtype=np.complex128))
scalar = Operator(np.array([[-1.0 + 0.0j]]))
composed = base.compose(scalar, qargs=[])
self.assertEqual(composed, Operator(-np.eye(2, dtype=np.complex128)))
def test_compose_scalar_op(self):
"""Test that composition works with an explicit scalar operator over no qubits."""
base = Operator(np.eye(2, dtype=np.complex128))
scalar = ScalarOp(coeff=-1.0 + 0.0j)
composed = base.compose(scalar, qargs=[])
self.assertEqual(composed, Operator(-np.eye(2, dtype=np.complex128)))
def test_from_circuit_single_flat_default_register_transpiled(self):
"""Test a transpiled circuit with layout set from default register."""
circuit = QuantumCircuit(5)
circuit.h(3)
circuit.cx(3, 4)
circuit.cx(3, 2)
circuit.cx(3, 0)
circuit.cx(3, 1)
init_layout = Layout(
{
circuit.qubits[0]: 3,
circuit.qubits[1]: 4,
circuit.qubits[2]: 1,
circuit.qubits[3]: 2,
circuit.qubits[4]: 0,
}
)
tqc = transpile(circuit, initial_layout=init_layout)
result = Operator.from_circuit(tqc)
self.assertTrue(Operator.from_circuit(circuit).equiv(result))
def test_from_circuit_loose_bits_transpiled(self):
"""Test a transpiled circuit with layout set from loose bits."""
bits = [Qubit() for _ in range(5)]
circuit = QuantumCircuit()
circuit.add_bits(bits)
circuit.h(3)
circuit.cx(3, 4)
circuit.cx(3, 2)
circuit.cx(3, 0)
circuit.cx(3, 1)
init_layout = Layout(
{
circuit.qubits[0]: 3,
circuit.qubits[1]: 4,
circuit.qubits[2]: 1,
circuit.qubits[3]: 2,
circuit.qubits[4]: 0,
}
)
tqc = transpile(circuit, initial_layout=init_layout)
result = Operator.from_circuit(tqc)
self.assertTrue(Operator(circuit).equiv(result))
def test_from_circuit_multiple_registers_bits_transpiled(self):
"""Test a transpiled circuit with layout set from loose bits."""
regs = [QuantumRegister(1, name=f"custom_reg-{i}") for i in range(5)]
circuit = QuantumCircuit()
for reg in regs:
circuit.add_register(reg)
circuit.h(3)
circuit.cx(3, 4)
circuit.cx(3, 2)
circuit.cx(3, 0)
circuit.cx(3, 1)
tqc = transpile(circuit, initial_layout=[3, 4, 1, 2, 0])
result = Operator.from_circuit(tqc)
self.assertTrue(Operator(circuit).equiv(result))
def test_from_circuit_single_flat_custom_register_transpiled(self):
"""Test a transpiled circuit with layout set from loose bits."""
circuit = QuantumCircuit(QuantumRegister(5, name="custom_reg"))
circuit.h(3)
circuit.cx(3, 4)
circuit.cx(3, 2)
circuit.cx(3, 0)
circuit.cx(3, 1)
tqc = transpile(circuit, initial_layout=[3, 4, 1, 2, 0])
result = Operator.from_circuit(tqc)
self.assertTrue(Operator(circuit).equiv(result))
def test_from_circuit_mixed_reg_loose_bits_transpiled(self):
"""Test a transpiled circuit with layout set from loose bits."""
bits = [Qubit(), Qubit()]
circuit = QuantumCircuit()
circuit.add_bits(bits)
circuit.add_register(QuantumRegister(3, name="a_reg"))
circuit.h(3)
circuit.cx(3, 4)
circuit.cx(3, 2)
circuit.cx(3, 0)
circuit.cx(3, 1)
init_layout = Layout(
{
circuit.qubits[0]: 3,
circuit.qubits[1]: 4,
circuit.qubits[2]: 1,
circuit.qubits[3]: 2,
circuit.qubits[4]: 0,
}
)
tqc = transpile(circuit, initial_layout=init_layout)
result = Operator.from_circuit(tqc)
self.assertTrue(Operator(circuit).equiv(result))
def test_apply_permutation_back(self):
"""Test applying permutation to the operator,
where the operator is applied first and the permutation second."""
op = Operator(self.rand_matrix(64, 64))
pattern = [1, 2, 0, 3, 5, 4]
# Consider several methods of computing this operator and show
# they all lead to the same result.
# Compose the operator with the operator constructed from the
# permutation circuit.
op2 = op.copy()
perm_op = Operator(Permutation(6, pattern))
op2 &= perm_op
# Compose the operator with the operator constructed from the
# permutation gate.
op3 = op.copy()
perm_op = Operator(PermutationGate(pattern))
op3 &= perm_op
# Modify the operator using apply_permutation method.
op4 = op.copy()
op4 = op4.apply_permutation(pattern, front=False)
self.assertEqual(op2, op3)
self.assertEqual(op2, op4)
def test_apply_permutation_front(self):
"""Test applying permutation to the operator,
where the permutation is applied first and the operator second"""
op = Operator(self.rand_matrix(64, 64))
pattern = [1, 2, 0, 3, 5, 4]
# Consider several methods of computing this operator and show
# they all lead to the same result.
# Compose the operator with the operator constructed from the
# permutation circuit.
op2 = op.copy()
perm_op = Operator(Permutation(6, pattern))
op2 = perm_op & op2
# Compose the operator with the operator constructed from the
# permutation gate.
op3 = op.copy()
perm_op = Operator(PermutationGate(pattern))
op3 = perm_op & op3
# Modify the operator using apply_permutation method.
op4 = op.copy()
op4 = op4.apply_permutation(pattern, front=True)
self.assertEqual(op2, op3)
self.assertEqual(op2, op4)
def test_apply_permutation_qudits_back(self):
"""Test applying permutation to the operator with heterogeneous qudit spaces,
where the operator O is applied first and the permutation P second.
The matrix of the resulting operator is the product [P][O] and
corresponds to suitably permuting the rows of O's matrix.
"""
mat = np.array(range(6 * 6)).reshape((6, 6))
op = Operator(mat, input_dims=(2, 3), output_dims=(2, 3))
perm = [1, 0]
actual = op.apply_permutation(perm, front=False)
# Rows of mat are ordered to 00, 01, 02, 10, 11, 12;
# perm maps these to 00, 10, 20, 01, 11, 21,
# while the default ordering is 00, 01, 10, 11, 20, 21.
permuted_mat = mat.copy()[[0, 2, 4, 1, 3, 5]]
expected = Operator(permuted_mat, input_dims=(2, 3), output_dims=(3, 2))
self.assertEqual(actual, expected)
def test_apply_permutation_qudits_front(self):
"""Test applying permutation to the operator with heterogeneous qudit spaces,
where the permutation P is applied first and the operator O is applied second.
The matrix of the resulting operator is the product [O][P] and
corresponds to suitably permuting the columns of O's matrix.
"""
mat = np.array(range(6 * 6)).reshape((6, 6))
op = Operator(mat, input_dims=(2, 3), output_dims=(2, 3))
perm = [1, 0]
actual = op.apply_permutation(perm, front=True)
# Columns of mat are ordered to 00, 01, 02, 10, 11, 12;
# perm maps these to 00, 10, 20, 01, 11, 21,
# while the default ordering is 00, 01, 10, 11, 20, 21.
permuted_mat = mat.copy()[:, [0, 2, 4, 1, 3, 5]]
expected = Operator(permuted_mat, input_dims=(3, 2), output_dims=(2, 3))
self.assertEqual(actual, expected)
@combine(
dims=((2, 3, 4, 5), (5, 2, 4, 3), (3, 5, 2, 4), (5, 3, 4, 2), (4, 5, 2, 3), (4, 3, 2, 5))
)
def test_reverse_qargs_as_apply_permutation(self, dims):
"""Test reversing qargs by pre- and post-composing with reversal
permutation.
"""
perm = [3, 2, 1, 0]
op = Operator(
np.array(range(120 * 120)).reshape((120, 120)), input_dims=dims, output_dims=dims
)
op2 = op.reverse_qargs()
op3 = op.apply_permutation(perm, front=True).apply_permutation(perm, front=False)
self.assertEqual(op2, op3)
def test_apply_permutation_exceptions(self):
"""Checks that applying permutation raises an error when dimensions do not match."""
op = Operator(
np.array(range(24 * 30)).reshape((24, 30)), input_dims=(6, 5), output_dims=(2, 3, 4)
)
with self.assertRaises(QiskitError):
op.apply_permutation([1, 0], front=False)
with self.assertRaises(QiskitError):
op.apply_permutation([2, 1, 0], front=True)
def test_apply_permutation_dimensions(self):
"""Checks the dimensions of the operator after applying permutation."""
op = Operator(
np.array(range(24 * 30)).reshape((24, 30)), input_dims=(6, 5), output_dims=(2, 3, 4)
)
op2 = op.apply_permutation([1, 2, 0], front=False)
self.assertEqual(op2.output_dims(), (4, 2, 3))
op = Operator(
np.array(range(24 * 30)).reshape((30, 24)), input_dims=(2, 3, 4), output_dims=(6, 5)
)
op2 = op.apply_permutation([2, 0, 1], front=True)
self.assertEqual(op2.input_dims(), (4, 2, 3))
if __name__ == "__main__":
unittest.main()
|
https://github.com/achilles-d/qiskitsummerjam
|
achilles-d
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
from PIL import Image
from numpy import*
import matplotlib.cm as cm
import numpy as np
import matplotlib.pyplot as plt
temp=Image.open('download.png')
temp=temp.convert('1') # Convert to black&white
A = array(temp) # Creates an array, white pixels==True and black pixels==False
new_A=empty((A.shape[0],A.shape[1]),None) #New array with same size as A
for i in range(len(A)):
for j in range(len(A[i])):
if A[i][j]==True:
new_A[i][j]=0
else:
new_A[i][j]=1
shape = new_A.shape
#new_A = new_A[0:50,0:50]
# make a 1-dimensional view of arr
flat_arr = new_A.ravel()
print(sum(flat_arr), len(flat_arr))
"""
COPIED CODE
"""
import sys
sys.path.append("../../qiskit-sdk-py/")
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
import math
from qiskit import(
QuantumCircuit,
execute,
Aer)
from qiskit.tools.visualization import plot_histogram
from qiskit import IBMQ
# set up registers and program
qr = QuantumRegister(len(flat_arr), 'qr')
cr = ClassicalRegister(len(flat_arr),'cr')
qc = QuantumCircuit(qr, cr)
# rightmost eight (qu)bits have ')' = 00101001
count = 0;
#for num, k in enumerate(flat_arr):
#if (k == 1):
index = [index for index, value in enumerate(flat_arr) if value == 1]
for k in index:
qc.x(qr[k])
qc.measure(qr[k], cr[k])
print("hello")
simulator = Aer.get_backend('qasm_simulator')
print("hello")
job = execute(qc, simulator, shots=1024)
print("hello")
results = job.result()
print("hello")
stats = results.get_counts(qc)
print("hello")
vector = np.matrix(flat_arr)
#print(count)
# if (count%100 == 0):
# print(count)
# count = count +1
from PIL import Image
from numpy import*
import matplotlib.cm as cm
import numpy as np
import matplotlib.pyplot as plt
from scipy import misc
from sklearn.decomposition import PCA
def pixelate(first_file, second_file, pixel_size):
im1 = Image.open(first_file)
im2 = Image.open(second_file)
#resizing
im1 = im1.resize((size, size), Image.BILINEAR)
im2 = im2.resize((size, size), Image.BILINEAR)
A1 = (im1)
A2 = (im2)
return A1, A2
def black_and_white(temp):
temp=temp.convert('1')
A = array(temp) # Creates an array, white pixels==True and black pixels==False
new_A=empty((A.shape[0],A.shape[1]),None) #New array with same size as A
for i in range(len(A)):
for j in range(len(A[i])):
if A[i][j]==True:
new_A[i][j]=0
else:
new_A[i][j]=1
return A
file_1 = "download.png"
size = 10
A1, A2 = pixelate(file_1, file_1, size)
plt.imsave('filename2.jpeg',A2, cmap=cm.gray)
new_A=empty((A1.shape[0],A1.shape[1]),None) #New array with same size as A
for i in range(len(A1)):
for j in range(len(A1[i])):
if A1[i][j]==True:
new_A[i][j]=0
else:
new_A[i][j]=1
shape = new_A.shape
#new_A = new_A[0:50,0:50]
img = np.asarray(A1)
new_img = img.reshape((img.shape[0]*img.shape[1]), img.shape[2])
new_img = new_img.transpose()
new_img.shape
from PIL import Image
from numpy import*
import matplotlib.cm as cm
import numpy as np
import matplotlib.pyplot as plt
#flat_arr = new_A.ravel()
#print(sum(flat_arr), len(flat_arr))
"""
COPIED CODE
"""
import sys
sys.path.append("../../qiskit-sdk-py/")
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
import math
from qiskit import(
QuantumCircuit,
execute,
Aer)
from qiskit.tools.visualization import plot_histogram
from qiskit import IBMQ
# set up registers and program
qr = QuantumRegister(15, 'qr')
cr = ClassicalRegister(15,'cr')
qc = QuantumCircuit(qr, cr)
# rightmost eight (qu)bits have ')' = 00101001
count = 0;
#for num, k in enumerate(flat_arr):
#if (k == 1):
#index = [index for index, value in enumerate(flat_arr) if value == 1]
double = np.zeros((3,100))
count = 1
for p in range(3):
for k in range(100):
num_1 = bin(new_img[p][k])
num_2 = bin(new_img[p][k])
#print("num1 index: ", len(str(num_1)))
for i in range(len(str(num_1))):
if num_1[i] == str(1):
qc.x(qr[i])
qc.h(qr[7]) # create superposition on 9
qc.cx(qr[7],qr[8]) # spread it to 8 with a cnot
for i in range(len(str(num_2))):
if num_2[i] == str(1):
qc.x(qr[i+5])
for j in range(15):
qc.measure(qr[j], cr[j])
simulator = Aer.get_backend('qasm_simulator')
job = execute(qc, simulator, shots=1)
results = job.result()
stats = results.get_counts(qc)
register_value = stats.keys()
for x in register_value:
split = x[0:7]
split2 = x[7:15]
#print(split2)
total = abs(int(split,2)-int(split2,2))
double[p][k] = total
#print(total)
print("Quantum1 :", (abs(int(split,2)+int(split2,2)))/2, " num1 :", int(num_1, 2))
print ("count: ", count)
count = count +1
double
for i in range(len(str(num_1))):
if num_1[i] == str(1):
qc.x(qr[i])
x = []
for elem in '1000110010111010100101111010110000100010010101011100001010001100000101101100011110000100011100000000':
x.append(elem)
x
arr2 = np.asarray(x).reshape(shape)
for j in range(len(flat_arr)):
qc.measure(qr[j], cr[j])
print("hello")
simulator = Aer.get_backend('qasm_simulator')
print("hello")
job = execute(qc, simulator, shots=5)
print("hello")
results = job.result()
print("hello")
stats = results.get_counts(qc)
print("hello")
vector = np.matrix(flat_arr)
arr2 = np.asarray(vector).reshape(shape)
arr2
plt.imsave('filename1.jpeg',arr2, cmap=cm.gray)
A1
arr2
x = []
for bitString in stats: # loop over all results
for k in range(len(bitString)-1):
x.append(int(bitString[k:k+1]))
x.append(1)
x = np.array(x)
x = x[0:2500]
vector = np.matrix(x)
shape = new_A.shape
arr2 = np.asarray(vector).reshape(shape)
img = plt.imshow(double)
plt.show()
img = plt.imshow(new_img)
plt.show()
|
https://github.com/Qiskit/feedback
|
Qiskit
|
!pip install pyRiemann-qiskit
!pip install moabb
from pyriemann_qiskit.pipelines import (
QuantumMDMWithRiemannianPipeline,
)
from moabb.datasets import BI2012
from moabb.paradigms import P300
from sklearn.model_selection import train_test_split
from sklearn.metrics import balanced_accuracy_score
from sklearn.preprocessing import LabelEncoder
from time import time
# Instantiate dataset
# This has to be adapted for the data you used
dataset = BI2012() #selected dataset
# Instantiate paradigm:
# It defines the pre-processing steps for data extraction
# This is specific to the MOABB library
paradigm = P300()
# Get first subject's data
X, y, _ = paradigm.get_data(dataset, subjects=[1])
# Encode class label into numeric value
label_encoder = LabelEncoder()
y = label_encoder.fit_transform(y)
# Let's keep it simple without cross-validation
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=100, stratify=y)
# Instantiate our pipeline (inherits from sklearn mixins)
clf = QuantumMDMWithRiemannianPipeline(
convex_metric="distance", quantum=True
)
display(clf._pipe)
start_time = time()
clf.fit(X_train, y_train)
fit_time = time() - start_time
# Perform classification (prediction)
# This use QAOA and a Aer/statevector simulator.
# An account token can also be provided to the estimator
# to run on real quantum backend
start_time = time()
y_pred = clf.predict(X_test)
pred_time = time() - start_time
# Compute dataset balance
n_class_0 = y[y == 1].shape[0]
n_class_1 = y[y == 0].shape[0]
# Our dataset is not balanced
balance = n_class_0 / n_class_1
print(f'balance = {balance}')
# Then we will use the balanced-accuracy
# which is a better metric than accuracy in this case:
score = balanced_accuracy_score(y_test, y_pred)
# Do not pay to much attention to the score.
# There is no cross-validation here.
# It likely just depends on the random_state.
print(f'score = {score}')
# Print execution time
# The fitting is classical, the prediction (here on simulator) is quantum.
# Other versions of the algorithm exist (with fitting quantum and prediction classical)
print("Fit time: {:.3f}s".format(fit_time))
print("Prediction time: {:.3f}s".format(pred_time))
# Time required for the classfication of a single trial:
n_train = y_train.shape[0]
n_test = y_test.shape[0]
print("Fit time (1 example): {:.3f}s".format(fit_time / n_train))
print("Prediction time (1 example): {:.3f}s".format(pred_time / n_test))
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# Copyright 2022-2023 Ohad Lev.
# 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,
# or in the root directory of this package("LICENSE.txt").
# 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.
"""
`SATInterface` class.
"""
import os
import json
from typing import List, Tuple, Union, Optional, Dict, Any
from sys import stdout
from datetime import datetime
from hashlib import sha256
from qiskit import transpile, QuantumCircuit, qpy
from qiskit.result.counts import Counts
from qiskit.visualization.circuit.text import TextDrawing
from qiskit.providers.backend import Backend
from qiskit.transpiler.passes import RemoveBarriers
from IPython import display
from matplotlib.figure import Figure
from sat_circuits_engine.util import timer_dec, timestamp, flatten_circuit
from sat_circuits_engine.util.settings import DATA_PATH, TRANSPILE_KWARGS
from sat_circuits_engine.circuit import GroverConstraintsOperator, SATCircuit
from sat_circuits_engine.constraints_parse import ParsedConstraints
from sat_circuits_engine.interface.circuit_decomposition import decompose_operator
from sat_circuits_engine.interface.counts_visualization import plot_histogram
from sat_circuits_engine.interface.translator import ConstraintsTranslator
from sat_circuits_engine.classical_processing import (
find_iterations_unknown,
calc_iterations,
ClassicalVerifier,
)
from sat_circuits_engine.interface.interactive_inputs import (
interactive_operator_inputs,
interactive_solutions_num_input,
interactive_run_input,
interactive_backend_input,
interactive_shots_input,
)
# Local globlas for visualization of charts and diagrams
IFRAME_WIDTH = "100%"
IFRAME_HEIGHT = "700"
class SATInterface:
"""
An interface for building, running and mining data from n-SAT problems quantum circuits.
There are 2 options to use this class:
(1) Using an interactive interface (intuitive but somewhat limited) - for this
just initiate a bare instance of this class: `SATInterface()`.
(2) Using the API defined by this class, that includes the following methods:
* The following descriptions are partial, for full annotations see the methods' docstrings.
- `__init__`: an instance of `SATInterface must be initiated with exactly 1 combination:
(a) (high_level_constraints_string + high_level_vars) - for constraints
in a high-level format.
(b) (num_input_qubits + constraints_string) - for constraints
in a low-level foramt.
* For formats annotations see `constriants_format.ipynb` in the main directory.
- `obtain_grover_operator`: obtains the suitable grover operator for the constraints.
- `save_display_grover_operator`: saves and displays data generated
by the `obtain_grover_operator` method.
- `obtain_overall_circuit`: obtains the suitable overall SAT circuit.
- `save_display_overall_circuit: saves and displays data generated
by the `obtain_overall_circuit` method.
- `run_overall_circuit`: executes the overall SAT circuit.
- `save_display_results`: saves and displays data generated
by the `run_overall_circuit` method.
It is very recommended to go through `demos.ipynb` that demonstrates the various optional uses
of this class, in addition to reading `constraints_format.ipynb`, which is a must for using
this package properly. Both notebooks are in ther main directory.
"""
def __init__(
self,
num_input_qubits: Optional[int] = None,
constraints_string: Optional[str] = None,
high_level_constraints_string: Optional[str] = None,
high_level_vars: Optional[Dict[str, int]] = None,
name: Optional[str] = None,
save_data: Optional[bool] = True,
) -> None:
"""
Accepts the combination of paramters:
(high_level_constraints_string + high_level_vars) or (num_input_qubits + constraints_string).
Exactly one combination is accepted.
In other cases either an iteractive user interface will be called to take user's inputs,
or an exception will be raised due to misuse of the API.
Args:
num_input_qubits (Optional[int] = None): number of input qubits.
constraints_string (Optional[str] = None): a string of constraints in a low-level format.
high_level_constraints_string (Optional[str] = None): a string of constraints in a
high-level format.
high_level_vars (Optional[Dict[str, int]] = None): a dictionary that configures
the high-level variables - keys are names and values are bits-lengths.
name (Optional[str] = None): a name for this object, if None than the
generic name "SAT" is given automatically.
save_data (Optional[bool] = True): if True, saves all data and metadata generated by this
class to a unique data folder (by using the `save_XXX` methods of this class).
Raises:
SyntaxError - if a forbidden combination of arguments has been provided.
"""
if name is None:
name = "SAT"
self.name = name
# Creating a directory for data to be saved
if save_data:
self.time_created = timestamp(datetime.now())
self.dir_path = f"{DATA_PATH}{self.time_created}_{self.name}/"
os.mkdir(self.dir_path)
print(f"Data will be saved into '{self.dir_path}'.")
# Initial metadata, more to be added by this class' `save_XXX` methods
self.metadata = {
"name": self.name,
"datetime": self.time_created,
"num_input_qubits": num_input_qubits,
"constraints_string": constraints_string,
"high_level_constraints_string": high_level_constraints_string,
"high_level_vars": high_level_vars,
}
self.update_metadata()
# Identifying user's platform, for visualization purposes
self.identify_platform()
# In the case of low-level constraints format, that is the default value
self.high_to_low_map = None
# Case A - interactive interface
if (num_input_qubits is None or constraints_string is None) and (
high_level_constraints_string is None or high_level_vars is None
):
self.interactive_interface()
# Case B - API
else:
self.high_level_constraints_string = high_level_constraints_string
self.high_level_vars = high_level_vars
# Case B.1 - high-level format constraints inputs
if num_input_qubits is None or constraints_string is None:
self.num_input_qubits = sum(self.high_level_vars.values())
self.high_to_low_map, self.constraints_string = ConstraintsTranslator(
self.high_level_constraints_string, self.high_level_vars
).translate()
# Case B.2 - low-level format constraints inputs
elif num_input_qubits is not None and constraints_string is not None:
self.num_input_qubits = num_input_qubits
self.constraints_string = constraints_string
# Misuse
else:
raise SyntaxError(
"SATInterface accepts the combination of paramters:"
"(high_level_constraints_string + high_level_vars) or "
"(num_input_qubits + constraints_string). "
"Exactly one combination is accepted, not both."
)
self.parsed_constraints = ParsedConstraints(
self.constraints_string, self.high_level_constraints_string
)
def update_metadata(self, update_metadata: Optional[Dict[str, Any]] = None) -> None:
"""
Updates the metadata file (in the unique data folder of a given `SATInterface` instance).
Args:
update_metadata (Optional[Dict[str, Any]] = None):
- If None - just dumps `self.metadata` into the metadata JSON file.
- If defined - updates the `self.metadata` attribute and then dumps it.
"""
if update_metadata is not None:
self.metadata.update(update_metadata)
with open(f"{self.dir_path}metadata.json", "w") as metadata_file:
json.dump(self.metadata, metadata_file, indent=4)
def identify_platform(self) -> None:
"""
Identifies user's platform.
Writes True to `self.jupyter` for Jupyter notebook, False for terminal.
"""
# If True then the platform is a terminal/command line/shell
if stdout.isatty():
self.jupyter = False
# If False, we assume the platform is a Jupyter notebook
else:
self.jupyter = True
def output_to_platform(
self,
*,
title: str,
output_terminal: Union[TextDrawing, str],
output_jupyter: Union[Figure, str],
display_both_on_jupyter: Optional[bool] = False,
) -> None:
"""
Displays output to user's platform.
Args:
title (str): a title for the output.
output_terminal (Union[TextDrawing, str]): text to print for a terminal platform.
output_jupyter: (Union[Figure, str]): objects to display for a Jupyter notebook platform.
can handle `Figure` matplotlib objects or strings of paths to IFrame displayable file,
e.g PDF files.
display_both_on_jupyter (Optional[bool] = False): if True, displays both
`output_terminal` and `output_jupyter` in a Jupyter notebook platform.
Raises:
TypeError - in the case of misusing the `output_jupyter` argument.
"""
print()
print(title)
if self.jupyter:
if isinstance(output_jupyter, str):
display.display(display.IFrame(output_jupyter, width=IFRAME_WIDTH, height=IFRAME_HEIGHT))
elif isinstance(output_jupyter, Figure):
display.display(output_jupyter)
else:
raise TypeError("output_jupyter must be an str (path to image file) or a Figure object.")
if display_both_on_jupyter:
print(output_terminal)
else:
print(output_terminal)
def interactive_interface(self) -> None:
"""
An interactive CLI that allows exploiting most (but not all) of the package's features.
Uses functions of the form `interactive_XXX_inputs` from the `interactive_inputs.py` module.
Divided into 3 main stages:
1. Obtaining Grover's operator for the SAT problem.
2. Obtaining the overall SAT cirucit.
3. Executing the circuit and parsing the results.
The interface is built in a modular manner such that a user can halt at any stage.
The defualt settings for the interactive user intreface are:
1. `name = "SAT"`.
2. `save_data = True`.
3. `display = True`.
4. `transpile_kwargs = {'basis_gates': ['u', 'cx'], 'optimization_level': 3}`.
5. Backends are limited to those defined in the global-constant-like function `BACKENDS`:
- Those are the local `aer_simulator` and the remote `ibmq_qasm_simulator` for now.
Due to these default settings the interactive CLI is somewhat restrictive,
for full flexibility a user should use the API and not the CLI.
"""
# Handling operator part
operator_inputs = interactive_operator_inputs()
self.num_input_qubits = operator_inputs["num_input_qubits"]
self.high_to_low_map = operator_inputs["high_to_low_map"]
self.constraints_string = operator_inputs["constraints_string"]
self.high_level_constraints_string = operator_inputs["high_level_constraints_string"]
self.high_level_vars = operator_inputs["high_level_vars"]
self.parsed_constraints = ParsedConstraints(
self.constraints_string, self.high_level_constraints_string
)
self.update_metadata(
{
"num_input_qubits": self.num_input_qubits,
"constraints_string": self.constraints_string,
"high_level_constraints_string": self.high_level_constraints_string,
"high_level_vars": self.high_level_vars,
}
)
obtain_grover_operator_output = self.obtain_grover_operator()
self.save_display_grover_operator(obtain_grover_operator_output)
# Handling overall circuit part
solutions_num = interactive_solutions_num_input()
if solutions_num is not None:
backend = None
if solutions_num == -1:
backend = interactive_backend_input()
overall_circuit_data = self.obtain_overall_sat_circuit(
obtain_grover_operator_output["operator"], solutions_num, backend
)
self.save_display_overall_circuit(overall_circuit_data)
# Handling circuit execution part
if interactive_run_input():
if backend is None:
backend = interactive_backend_input()
shots = interactive_shots_input()
counts_parsed = self.run_overall_sat_circuit(
overall_circuit_data["circuit"], backend, shots
)
self.save_display_results(counts_parsed)
print()
print(f"Done saving data into '{self.dir_path}'.")
def obtain_grover_operator(
self, transpile_kwargs: Optional[Dict[str, Any]] = None
) -> Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]:
"""
Obtains the suitable `GroverConstraintsOperator` object for the constraints,
decomposes it using the `circuit_decomposition.py` module and transpiles it
according to `transpile_kwargs`.
Args:
transpile_kwargs (Optional[Dict[str, Any]]): kwargs for Qiskit's transpile function.
The defualt is set to the global constant `TRANSPILE_KWARGS`.
Returns:
(Dict[str, Union[GroverConstraintsOperator, QuantumCircuit, Dict[str, List[int]]]]):
- 'operator' (GroverConstraintsOperator):the high-level blocks operator.
- 'decomposed_operator' (QuantumCircuit): decomposed to building-blocks operator.
* For annotations regarding the decomposition method see the
`circuit_decomposition` module.
- 'transpiled_operator' (QuantumCircuit): the transpiled operator.
*** The high-level operator and the decomposed operator are generated with barriers
between constraints as default for visualizations purposes. The barriers are stripped
off before transpiling so the the transpiled operator object contains no barriers. ***
- 'high_level_to_bit_indexes_map' (Optional[Dict[str, List[int]]] = None):
A map of high-level variables with their allocated bit-indexes in the input register.
"""
print()
print(
"The system synthesizes and transpiles a Grover's "
"operator for the given constraints. Please wait.."
)
if transpile_kwargs is None:
transpile_kwargs = TRANSPILE_KWARGS
self.transpile_kwargs = transpile_kwargs
operator = GroverConstraintsOperator(
self.parsed_constraints, self.num_input_qubits, insert_barriers=True
)
decomposed_operator = decompose_operator(operator)
no_baerriers_operator = RemoveBarriers()(operator)
transpiled_operator = transpile(no_baerriers_operator, **transpile_kwargs)
print("Done.")
return {
"operator": operator,
"decomposed_operator": decomposed_operator,
"transpiled_operator": transpiled_operator,
"high_level_to_bit_indexes_map": self.high_to_low_map,
}
def save_display_grover_operator(
self,
obtain_grover_operator_output: Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]],
display: Optional[bool] = True,
) -> None:
"""
Handles saving and displaying data generated by the `self.obtain_grover_operator` method.
Args:
obtain_grover_operator_output(Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]):
the dictionary returned upon calling the `self.obtain_grover_operator` method.
display (Optional[bool] = True) - If true, displays objects to user's platform.
"""
# Creating a directory to save operator's data
operator_dir_path = f"{self.dir_path}grover_operator/"
os.mkdir(operator_dir_path)
# Titles for displaying objects, by order of `obtain_grover_operator_output`
titles = [
"The operator diagram - high level blocks:",
"The operator diagram - decomposed:",
f"The transpiled operator diagram saved into '{operator_dir_path}'.\n"
f"It's not presented here due to its complexity.\n"
f"Please note that barriers appear in the high-level diagrams above only for convenient\n"
f"visual separation between constraints.\n"
f"Before transpilation all barriers are removed to avoid redundant inefficiencies.",
]
for index, (op_name, op_obj) in enumerate(obtain_grover_operator_output.items()):
# Generic path and name for files to be saved
files_path = f"{operator_dir_path}{op_name}"
# Generating a circuit diagrams figure
figure_path = f"{files_path}.pdf"
op_obj.draw("mpl", filename=figure_path, fold=-1)
# Generating a QPY serialization file for the circuit object
qpy_file_path = f"{files_path}.qpy"
with open(qpy_file_path, "wb") as qpy_file:
qpy.dump(op_obj, qpy_file)
# Original high-level operator and decomposed operator
if index < 2 and display:
# Displaying to user
self.output_to_platform(
title=titles[index], output_terminal=op_obj.draw("text"), output_jupyter=figure_path
)
# Transpiled operator
elif index == 2:
# Output to user, not including the circuit diagram
print()
print(titles[index])
print()
print(f"The transpilation kwargs are: {self.transpile_kwargs}.")
transpiled_operator_depth = op_obj.depth()
transpiled_operator_gates_count = op_obj.count_ops()
print(f"Transpiled operator depth: {transpiled_operator_depth}.")
print(f"Transpiled operator gates count: {transpiled_operator_gates_count}.")
print(f"Total number of qubits: {op_obj.num_qubits}.")
# Generating QASM 2.0 file only for the (flattened = no registers) tranpsiled operator
qasm_file_path = f"{files_path}.qasm"
flatten_circuit(op_obj).qasm(filename=qasm_file_path)
# Index 3 is 'high_level_to_bit_indexes_map' so it's time to break from the loop
break
# Mapping from high-level variables to bit-indexes will be displayed as well
mapping = obtain_grover_operator_output["high_level_to_bit_indexes_map"]
if mapping:
print()
print(f"The high-level variables mapping to bit-indexes:\n{mapping}")
print()
print(
f"Saved into '{operator_dir_path}':\n",
" Circuit diagrams for all levels.\n",
" QPY serialization exports for all levels.\n",
" QASM 2.0 export only for the transpiled level.",
)
with open(f"{operator_dir_path}operator.qpy", "rb") as qpy_file:
operator_qpy_sha256 = sha256(qpy_file.read()).hexdigest()
self.update_metadata(
{
"high_level_to_bit_indexes_map": self.high_to_low_map,
"transpile_kwargs": self.transpile_kwargs,
"transpiled_operator_depth": transpiled_operator_depth,
"transpiled_operator_gates_count": transpiled_operator_gates_count,
"operator_qpy_sha256": operator_qpy_sha256,
}
)
def obtain_overall_sat_circuit(
self,
grover_operator: GroverConstraintsOperator,
solutions_num: int,
backend: Optional[Backend] = None,
) -> Dict[str, SATCircuit]:
"""
Obtains the suitable `SATCircuit` object (= the overall SAT circuit) for the SAT problem.
Args:
grover_operator (GroverConstraintsOperator): Grover's operator for the SAT problem.
solutions_num (int): number of solutions for the SAT problem. In the case the number
of solutions is unknown, specific negative values are accepted:
* '-1' - for launching a classical iterative stochastic process that finds an adequate
number of iterations - by calling the `find_iterations_unknown` function (see its
docstrings for more information).
* '-2' - for generating a dynamic circuit that iterates over Grover's iterator until
a solution is obtained, using weak measurements. TODO - this feature isn't ready yet.
backend (Optional[Backend] = None): in the case of a '-1' value given to `solutions_num`,
a backend object to execute the depicted iterative prcess upon should be provided.
Returns:
(Dict[str, SATCircuit]):
- 'circuit' key for the overall SAT circuit.
- 'concise_circuit' key for the overall SAT circuit, with only 1 iteration over Grover's
iterator (operator + diffuser). Useful for visualization purposes.
*** The concise circuit is generated with barriers between segments as default
for visualizations purposes. In the actual circuit there no barriers. ***
"""
# -1 = Unknown number of solutions - iterative stochastic process
print()
if solutions_num == -1:
assert backend is not None, "Need to specify a backend if `solutions_num == -1`."
print("Please wait while the system checks various solutions..")
circuit, iterations = find_iterations_unknown(
self.num_input_qubits,
grover_operator,
self.parsed_constraints,
precision=10,
backend=backend,
)
print()
print(f"An adequate number of iterations found = {iterations}.")
# -2 = Unknown number of solutions - implement a dynamic circuit
# TODO this feature isn't fully implemented yet
elif solutions_num == -2:
print("The system builds a dynamic circuit..")
circuit = SATCircuit(self.num_input_qubits, grover_operator, iterations=None)
circuit.add_input_reg_measurement()
iterations = None
# Known number of solutions
else:
print("The system builds the overall circuit..")
iterations = calc_iterations(self.num_input_qubits, solutions_num)
print(f"\nFor {solutions_num} solutions, {iterations} iterations needed.")
circuit = SATCircuit(
self.num_input_qubits, grover_operator, iterations, insert_barriers=False
)
circuit.add_input_reg_measurement()
self.iterations = iterations
# Obtaining a SATCircuit object with one iteration for concise representation
concise_circuit = SATCircuit(
self.num_input_qubits, grover_operator, iterations=1, insert_barriers=True
)
concise_circuit.add_input_reg_measurement()
return {"circuit": circuit, "concise_circuit": concise_circuit}
def save_display_overall_circuit(
self, obtain_overall_sat_circuit_output: Dict[str, SATCircuit], display: Optional[bool] = True
) -> None:
"""
Handles saving and displaying data generated by the `self.obtain_overall_sat_circuit` method.
Args:
obtain_overall_sat_circuit_output(Dict[str, SATCircuit]):
the dictionary returned upon calling the `self.obtain_overall_sat_circuit` method.
display (Optional[bool] = True) - If true, displays objects to user's platform.
"""
circuit = obtain_overall_sat_circuit_output["circuit"]
concise_circuit = obtain_overall_sat_circuit_output["concise_circuit"]
# Creating a directory to save overall circuit's data
overall_circuit_dir_path = f"{self.dir_path}overall_circuit/"
os.mkdir(overall_circuit_dir_path)
# Generating a figure of the overall SAT circuit with just 1 iteration (i.e "concise")
concise_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_1_iteration.pdf"
concise_circuit.draw("mpl", filename=concise_circuit_fig_path, fold=-1)
# Displaying the concise circuit to user
if display:
if self.iterations:
self.output_to_platform(
title=(
f"The high level circuit contains {self.iterations}"
f" iterations of the following form:"
),
output_terminal=concise_circuit.draw("text"),
output_jupyter=concise_circuit_fig_path,
)
# Dynamic circuit case - TODO NOT FULLY IMPLEMENTED YET
else:
dynamic_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_dynamic.pdf"
circuit.draw("mpl", filename=dynamic_circuit_fig_path, fold=-1)
self.output_to_platform(
title="The dynamic circuit diagram:",
output_terminal=circuit.draw("text"),
output_jupyter=dynamic_circuit_fig_path,
)
if self.iterations:
transpiled_overall_circuit = transpile(flatten_circuit(circuit), **self.transpile_kwargs)
print()
print(f"The transpilation kwargs are: {self.transpile_kwargs}.")
transpiled_overall_circuit_depth = transpiled_overall_circuit.depth()
transpiled_overall_circuit_gates_count = transpiled_overall_circuit.count_ops()
print(f"Transpiled overall-circuit depth: {transpiled_overall_circuit_depth}.")
print(f"Transpiled overall-circuit gates count: {transpiled_overall_circuit_gates_count}.")
print(f"Total number of qubits: {transpiled_overall_circuit.num_qubits}.")
print()
print("Exporting the full overall SAT circuit object..")
export_files_path = f"{overall_circuit_dir_path}overall_circuit"
with open(f"{export_files_path}.qpy", "wb") as qpy_file:
qpy.dump(circuit, qpy_file)
if self.iterations:
transpiled_overall_circuit.qasm(filename=f"{export_files_path}.qasm")
print()
print(
f"Saved into '{overall_circuit_dir_path}':\n",
" A concised (1 iteration) circuit diagram of the high-level overall SAT circuit.\n",
" QPY serialization export for the full overall SAT circuit object.",
)
if self.iterations:
print(" QASM 2.0 export for the transpiled full overall SAT circuit object.")
metadata_update = {
"num_total_qubits": circuit.num_qubits,
"num_iterations": circuit.iterations,
}
if self.iterations:
metadata_update["transpiled_overall_circuit_depth"] = (transpiled_overall_circuit_depth,)
metadata_update[
"transpiled_overall_circuit_gates_count"
] = transpiled_overall_circuit_gates_count
self.update_metadata(metadata_update)
@timer_dec("Circuit simulation execution time = ")
def run_overall_sat_circuit(
self, circuit: QuantumCircuit, backend: Backend, shots: int
) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]:
"""
Executes a `circuit` on `backend` transpiled w.r.t backend, `shots` times.
Args:
circuit (QuantumCircuit): `QuantumCircuit` object or child-object (a.k.a `SATCircuit`)
to execute.
backend (Backend): backend to execute `circuit` upon.
shots (int): number of execution shots.
Returns:
(Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]):
dict object returned by `self.parse_counts` - see this method's docstrings for annotations.
"""
# Defines also instance attributes to use in other methods
self.backend = backend
self.shots = shots
print()
print(f"The system is running the circuit {shots} times on {backend}, please wait..")
print("This process might take a while.")
job = backend.run(transpile(circuit, backend), shots=shots)
counts = job.result().get_counts()
print("Done.")
parsed_counts = self.parse_counts(counts)
return parsed_counts
def parse_counts(
self, counts: Counts
) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]:
"""
Parses a `Counts` object into several desired datas (see 'Returns' section).
Args:
counts (Counts): the `Counts` object to parse.
Returns:
(Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]):
'counts' (Counts) - the original `Counts` object.
'counts_sorted' (List[Tuple[Union[str, int]]]) - results sorted in a descending order.
'distilled_solutions' (List[str]): list of solutions (bitstrings).
'high_level_vars_values' (List[Dict[str, int]]): list of solutions (each solution is a
dictionary with variable-names as keys and their integer values as values).
"""
# Sorting results in an a descending order
counts_sorted = sorted(counts.items(), key=lambda x: x[1], reverse=True)
# Generating a set of distilled verified-only solutions
verifier = ClassicalVerifier(self.parsed_constraints)
distilled_solutions = set()
for count_item in counts_sorted:
if not verifier.verify(count_item[0]):
break
distilled_solutions.add(count_item[0])
# In the case of high-level format in use, translating `distilled_solutions` into integer values
high_level_vars_values = None
if self.high_level_constraints_string and self.high_level_vars:
# Container for dictionaries with variables integer values
high_level_vars_values = []
for solution in distilled_solutions:
# Keys are variable-names and values are their integer values
solution_vars = {}
for var, bits_bundle in self.high_to_low_map.items():
reversed_solution = solution[::-1]
var_bitstring = ""
for bit_index in bits_bundle:
var_bitstring += reversed_solution[bit_index]
# Translating to integer value
solution_vars[var] = int(var_bitstring, 2)
high_level_vars_values.append(solution_vars)
return {
"counts": counts,
"counts_sorted": counts_sorted,
"distilled_solutions": distilled_solutions,
"high_level_vars_values": high_level_vars_values,
}
def save_display_results(
self,
run_overall_sat_circuit_output: Dict[
str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]
],
display: Optional[bool] = True,
) -> None:
"""
Handles saving and displaying data generated by the `self.run_overall_sat_circuit` method.
Args:
run_overall_sat_circuit_output (Dict[str, Union[Counts, List[Tuple[Union[str, int]]],
List[str], List[Dict[str, int]]]]): the dictionary returned upon calling
the `self.run_overall_sat_circuit` method.
display (Optional[bool] = True) - If true, displays objects to user's platform.
"""
counts = run_overall_sat_circuit_output["counts"]
counts_sorted = run_overall_sat_circuit_output["counts_sorted"]
distilled_solutions = run_overall_sat_circuit_output["distilled_solutions"]
high_level_vars_values = run_overall_sat_circuit_output["high_level_vars_values"]
# Creating a directory to save results data
results_dir_path = f"{self.dir_path}results/"
os.mkdir(results_dir_path)
# Defining custom dimensions for the custom `plot_histogram` of this package
histogram_fig_width = max((len(counts) * self.num_input_qubits * (10 / 72)), 7)
histogram_fig_height = 5
histogram_figsize = (histogram_fig_width, histogram_fig_height)
histogram_path = f"{results_dir_path}histogram.pdf"
plot_histogram(counts, figsize=histogram_figsize, sort="value_desc", filename=histogram_path)
if display:
# Basic output text
output_text = (
f"All counts:\n{counts_sorted}\n"
f"\nDistilled solutions ({len(distilled_solutions)} total):\n"
f"{distilled_solutions}"
)
# Additional outputs for a high-level constraints format
if high_level_vars_values:
# Mapping from high-level variables to bit-indexes will be displayed as well
output_text += (
f"\n\nThe high-level variables mapping to bit-indexes:" f"\n{self.high_to_low_map}"
)
# Actual integer solutions will be displayed as well
additional_text = ""
for solution_index, solution in enumerate(high_level_vars_values):
additional_text += f"Solution {solution_index + 1}: "
for var_index, (var, value) in enumerate(solution.items()):
additional_text += f"{var} = {value}"
if var_index != len(solution) - 1:
additional_text += ", "
else:
additional_text += "\n"
output_text += f"\n\nHigh-level format solutions: \n{additional_text}"
self.output_to_platform(
title=f"The results for {self.shots} shots are:",
output_terminal=output_text,
output_jupyter=histogram_path,
display_both_on_jupyter=True,
)
results_dict = {
"high_level_to_bit_indexes_map": self.high_to_low_map,
"solutions": list(distilled_solutions),
"high_level_solutions": high_level_vars_values,
"counts": counts_sorted,
}
with open(f"{results_dir_path}results.json", "w") as results_file:
json.dump(results_dict, results_file, indent=4)
self.update_metadata(
{
"num_solutions": len(distilled_solutions),
"backend": str(self.backend),
"shots": self.shots,
}
)
|
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)
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)
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))
# 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/menegolli/Quantum_synth
|
menegolli
|
from qiskit import *
import numpy as np
import random
import sys
from backends_select import ChooseBackEnd
def GenerateCircuitSingleNote(circuit, note_id):
if (note_id >= 12):
sys.exit("Note must be an integer smaller than 11 and larger (or equal) to 0.")
bitstring = str(bin(note_id)[2:])
bitstring = "0"*(4-len(bitstring))+bitstring
for i in range(len(bitstring)):
if bitstring[len(bitstring)-1-i] == "1":
circuit.x(i)
qc = QuantumCircuit(4,4)
GenerateCircuitSingleNote(qc, 7)
ChooseBackEnd(qc, 'statevector_simulator')
def BellStateGenerationTwoQubits(quantumCircuit, firstQubit=0, secondQubit=1, specificEntangledState="Phi"):
if specificEntangledState == "Phi":
quantumCircuit.h(firstQubit)
quantumCircuit.cx(firstQubit, secondQubit)
elif specificEntangledState == "Psi":
quantumCircuit.h(firstQubit)
quantumCircuit.x(secondQubit)
quantumCircuit.cx(firstQubit, secondQubit)
qc = QuantumCircuit(4,4)
BellStateGenerationTwoQubits(qc, 0, 1)
ChooseBackEnd(qc, 'qasm_simulator')
def ChooseEqualSuperposition(quantumCircuit, states):
desiredVector = np.zeros(2**quantumCircuit.n_qubits)
flag = 1
for k in states:
if 0 <= k <= 11:
desiredVector[k] = 1/np.sqrt(len(states))
flag = flag*1
else:
flag = flag*0
if flag == 1:
quantumCircuit.initialize(desiredVector, range(4))
def ChooseEqualSuperpositionRandom(quantumCircuit):
randomNumberOfNotes = np.random.randint(2,13)
listModes = list(range(12))
listToSuperimpose = []
for i in range(randomNumberOfNotes):
tmp = random.choice(listModes)
listToSuperimpose.append(tmp)
listModes.remove(tmp)
ChooseEqualSuperposition(quantumCircuit, listToSuperimpose)
qc = QuantumCircuit(4,4)
ChooseEqualSuperposition(qc, [1, 4, 7])
ChooseBackEnd(qc, 'qasm_simulator')
def Hadamard(quantumCircuit, listOfQubits):
for k in listOfQubits:
if 0 <= k <= quantumCircuit.n_qubits:
quantumCircuit.h(k)
qc = QuantumCircuit(4,4)
Hadamard(qc, [0, 2])
ChooseBackEnd(qc, 'statevector_simulator')
def RandomRotation(quantumCircuit):
for k in range(quantumCircuit.n_qubits):
quantumCircuit.u3(q=k, theta = np.random.random()*2*np.pi, phi = np.random.random()*np.pi, lam = np.random.random()*np.pi)
qc = QuantumCircuit(4,4)
RandomRotation(qc)
ChooseBackEnd(qc, 'qasm_simulator')
def __multiplecz(quantumCircuit, target, initialLength):
quantumCircuit.ccx(0,1, initialLength)
for k in range(2, initialLength-1):
quantumCircuit.ccx(k, initialLength+k-2, initialLength+k-1)
quantumCircuit.cz(quantumCircuit.n_qubits-1, initialLength-1)
for k in reversed(range(2, initialLength-1)):
quantumCircuit.ccx(k, initialLength+k-2, initialLength+k-1)
quantumCircuit.ccx(0,1, initialLength)
def Grover(quantumCircuit, target, initialLength):
for k in range(initialLength):
quantumCircuit.h(k)
ancillaQubit = QuantumRegister(2)
quantumCircuit.add_register(ancillaQubit)
for n in range(int(np.round(np.pi/4*np.sqrt(2**initialLength)))):
for singleBit in range(initialLength):
if target[initialLength-singleBit-1] == '0':
quantumCircuit.x(singleBit)
__multiplecz(quantumCircuit, target, initialLength)
for singleBit in range(initialLength):
if target[initialLength-singleBit-1] == '0':
quantumCircuit.x(singleBit)
for qubit in range(initialLength):
quantumCircuit.h(qubit)
quantumCircuit.x(qubit)
__multiplecz(quantumCircuit, target, initialLength)
for qubit in range(initialLength):
quantumCircuit.x(qubit)
quantumCircuit.h(qubit)
qc = QuantumCircuit(4,4)
targ = format(10, '#06b')[2:]
Grover(qc,targ,4)
ChooseBackEnd(quantumCircuit=qc, backendType="statevector_simulator", qubitsToBeMeasured=range(4))
def AmplitudeAmplification(quantumCircuit, target, initialLength, numIterations):
for k in range(initialLength):
quantumCircuit.h(k)
ancillaQubit = QuantumRegister(2)
quantumCircuit.add_register(ancillaQubit)
for n in range(numIterations):
for singleBit in range(initialLength):
if target[initialLength - singleBit - 1] == '0':
quantumCircuit.x(singleBit)
__multiplecz(quantumCircuit, target, initialLength)
for singleBit in range(initialLength):
if target[initialLength - singleBit - 1] == '0':
quantumCircuit.x(singleBit)
for qubit in range(initialLength):
quantumCircuit.h(qubit)
quantumCircuit.x(qubit)
__multiplecz(quantumCircuit, target, initialLength)
for qubit in range(initialLength):
quantumCircuit.x(qubit)
quantumCircuit.h(qubit)
def GroverSequence(target, initialLength,backendType,RealDeviceName,noisePresent):
iterations = []
for k in range(4):
temporaryQuantumCircuit = QuantumCircuit(initialLength, initialLength)
AmplitudeAmplification(temporaryQuantumCircuit, target, initialLength, k)
# listForMusic = ChooseBackEnd(music, backendType=mystr[0], qubitsToBeMeasured=range(4),
# numberShots=int(mystr[3]), noisePresent=True, RealDeviceName=mystr[1])
iterations.append(ChooseBackEnd(quantumCircuit=temporaryQuantumCircuit, noisePresent=noisePresent,backendType=backendType,qubitsToBeMeasured=range(4),RealDeviceName=RealDeviceName))
# ChooseBackEnd(quantumCircuit=temporaryQuantumCircuit, noisePresent=True,backendType=backendType,qubitsToBeMeasured=range(4),RealDeviceName=RealDeviceName)
del (temporaryQuantumCircuit)
return iterations
targ = format(10, '#06b')[2:]
GroverSequence(targ,4,'statevector_simulator','ibmq_ourense',False)
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import math
from qiskit.visualization import plot_state_qsphere
from qiskit import *
from qiskit.tools.visualization import plot_histogram
from IPython.display import display, Math, Latex
def reflect(U, n):
for i in range(int(n/2)):
U.swap(i, n-i-1)
def myQFT(n):
U = QuantumCircuit(n)
for x_k in range(n):
U.h(x_k)
for x_j in range(x_k+1, n):
angle = math.pi/2**(x_j-x_k)
U.cu1(angle, x_j, x_k)
reflect(U, n)
U = U.to_gate()
U.name = 'Quantum Fourier Tranform'
#ctl_U = U.control() make it a controlled gate
return U
n = 5
mc = QuantumCircuit(n, n)
#state |x> = |10101>
mc.x(0)
mc.x(2)
mc.x(4)
#Computational basis state qsphere
backend = BasicAer.get_backend('statevector_simulator')
job0 = execute(mc, backend).result()
U = myQFT(n)
mc.append(U, range(n))
#Fourier basis state qsphere
job1 = execute(mc, backend).result()
mc.measure(range(n), range(n))
backend = BasicAer.get_backend('qasm_simulator')
atp = 1024
res = execute(mc, backend=backend, shots=atp).result()
ans = res.get_counts()
mc.draw('mpl')
plot_histogram(ans)
plot_state_qsphere(job0.get_statevector(mc))
plot_state_qsphere(job1.get_statevector(mc))
|
https://github.com/qismib/TraNQI
|
qismib
|
#!/usr/bin/env python
# coding: utf-8
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 *
# importing packages
import matplotlib.pyplot as plt
import torch
from torch.autograd import Function
from torchvision import datasets, transforms
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import qiskit
from qiskit import transpile, assemble
from qiskit.visualization import *
import time
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
# GLOBAL VARIABLE DEFINITION
n_qubits = 3
simulator = qiskit.Aer.get_backend('qasm_simulator')
n_shots = 1000
shift = np.pi / 2
#chosing the real quantum computer or the simulator
from qiskit.providers.ibmq import least_busy
# We execute on the least busy device (among the actual quantum computers)
#simulator = least_busy(provider.backends(operational = True, simulator=False, status_msg='active',
# filters=lambda x: x.configuration().n_qubits > 1))
simulator = provider.get_backend('ibmq_athens')
print("We are executing on...",simulator)
print("It has",simulator.status().pending_jobs,"pending jobs")
import itertools
# creating a list of all possible outputs of a quantum circuit, used for the expectation value
def create_QC_OUTPUTS(n_qubits):
measurements = list(itertools.product([1, 0], repeat=n_qubits))
return [''.join([str(bit) for bit in measurement]) for measurement in measurements]
# Hadamard gate (superposition) + Rotation_Y (trainable parameter) + Measure_Z. Returning the frequency of results (00, 01, 10, 11 for 2 qubits)
class QuantumCircuit:
"""
This class provides an interface to interact with our Quantum Circuit
"""
def __init__(self, n_qubits, backend, shots):
# -----Circuit definition
self._circuit = qiskit.QuantumCircuit(n_qubits)
self.n_qubits = n_qubits
self.parameters = qiskit.circuit.ParameterVector('parameters', n_qubits)
all_qubits = [i for i in range(n_qubits)] # qubits vector
self._circuit.h(all_qubits) # over all the qubits
self._circuit.barrier()
for k in range(n_qubits):
self._circuit.ry(self.parameters[k], k)
self._circuit.measure_all()
# -----
self.backend = backend
self.shots = shots
self.QC_OUTPUTS = create_QC_OUTPUTS(n_qubits)
def expectation_Z_parameters(self, counts, shots, n_qubits):
expects = np.zeros(n_qubits)
i = 0
for key in counts.keys():
percentage = counts[key] / shots
if (i < 3):
expects[i] += percentage
i += 1
else:
i = 0
return expects
def expectation_Z_counts(self, counts, shots, n_qubits):
expects = np.zeros(len(self.QC_OUTPUTS))
for k in range(len(self.QC_OUTPUTS)):
key = self.QC_OUTPUTS[k]
perc = counts.get(key, 0) / shots
expects[k] = perc
return expects
def run(self, thetas):
# acting on a simulator
thetas = thetas.squeeze()
# print(thetas)
p_circuit = self._circuit.bind_parameters({self.parameters[k]: thetas[k].item() for k in range(self.n_qubits)})
job_sim = qiskit.execute(p_circuit,
self.backend,
shots=self.shots)
result = job_sim.result()
counts = result.get_counts(p_circuit)
# print('C: ', counts)
# expectation_parameters = self.expectation_Z_parameters(counts, self.shots, self.n_qubits)
expectation_counts = self.expectation_Z_counts(counts, self.shots, self.n_qubits)
return expectation_counts
circuit = QuantumCircuit(n_qubits, simulator, n_shots)
print(circuit._circuit)
circuit._circuit.draw(output = 'mpl', filename = 'N_qubits.png')#to print as a pyplot figure (new library needed)
rotation = torch.Tensor([np.pi / 4] * n_qubits)
exp = circuit.run(rotation)
print('Expected value for rotation pi/4: {}'.format(exp))
class HybridFunction(Function):
"""Hybrid quantum-classical function definition"""
@staticmethod
def forward(ctx, input, quantum_circuit, shift):
"""Forward pass computation"""
ctx.shift = shift
ctx.quantum_circuit = quantum_circuit
# context variable (it may take multiple values and return them related to the context). Used to keep track for backpropagation
expectation_z = ctx.quantum_circuit.run(input) # evaluating model with trainable parameter
result = torch.tensor([expectation_z])
ctx.save_for_backward(input,
result) # saves a given tensor for a future call to backward (trainable parameter and the result obtained)
# input = parametri che passo(3), result = risultati del calcolo(2**n_qubit)
return result
@staticmethod
def backward(ctx, grad_output): # grad_output os previous gradient
"""Backward computation"""
input, expectation = ctx.saved_tensors # evaluated in forward
input = torch.reshape(input, (-1,))
gradients = torch.Tensor()
# iterating to evaluate gradient
for k in range(len(input)):
# shifting parameters
shift_right, shift_left = input.detach().clone(), input.detach().clone()
shift_right[k] += ctx.shift
shift_left[k] -= ctx.shift
# evaluating model after shift
expectation_right = ctx.quantum_circuit.run(shift_right)
expectation_left = ctx.quantum_circuit.run(shift_left)
# evaluating gradient with finite difference formula
gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left])
gradients = torch.cat((gradients, gradient.float()))
result = gradients.float() * grad_output.float()
return (result).T, None, None
class Hybrid(nn.Module):
"""Hybrid quantum-cassical layer definition"""
def __init__(self, n_qubits, backend, shots, shift):
super(Hybrid, self).__init__()
self.quantum_circuit = QuantumCircuit(n_qubits, backend, shots)
self.shift = shift # parameter shift
def forward(self, input):
return HybridFunction.apply(input, self.quantum_circuit, self.shift) # calling forward and backward
class AddGaussianNoise(object):
def __init__(self, mean=0., std=5):
self.std = std
self.mean = mean
def __call__(self, tensor):
return tensor + torch.randn(tensor.size()) * self.std + self.mean
def __repr__(self):
return self.__class__.__name__ + '(mean={0}, std={1})'.format(self.mean, self.std)
#you can chose whether to use noisy training data or not
# DATA LOADING
# training data
n_samples = 100
mean, std_dv = 0, 0.2
X_train = datasets.MNIST(root='./data', train=True, download=True,
transform=transforms.Compose([transforms.ToTensor()]))
# keeping only labels 0 and 1
idx = np.append(np.where(X_train.targets == 0)[0][:n_samples], np.where(X_train.targets == 1)[0][:n_samples])
X_train.data = X_train.data[idx] # tensor values
X_train.targets = X_train.targets[idx] # tensor labels
# making batches (dim = 1). Ir returns an iterable(pytorch tensor)
train_loader = torch.utils.data.DataLoader(X_train, batch_size=1, shuffle=True)
data_iter = iter(
train_loader) # making the iterable an iterator, an object with the next method that can be used in a for cycle
# showing samples
n_samples_show = 6
fig, axes = plt.subplots(nrows=1, ncols=int(n_samples_show), figsize=(10, 3))
# subolot returns the figure and axis that are indipendent as default
while n_samples_show > 0:
images, targets = data_iter.__next__()
axes[int(n_samples_show) - 1].imshow(images[0].numpy().squeeze(),
cmap='gray') # squeeze removes unuseful dim(1). Converting into a numpy vector
axes[int(n_samples_show) - 1].set_xticks([])
axes[int(n_samples_show) - 1].set_yticks([])
axes[int(n_samples_show) - 1].set_title("Labeled: {}".format(targets.item()))
n_samples_show -= 1
n_samples = 2000
X_test = datasets.MNIST(root='./data', train=False, download=True,
transform=transforms.Compose([transforms.ToTensor()]))
idx = np.append(np.where(X_test.targets == 0)[0][:n_samples],
np.where(X_test.targets == 1)[0][:n_samples])
X_test.data = X_test.data[idx]
X_test.targets = X_test.targets[idx]
test_loader = torch.utils.data.DataLoader(X_test, batch_size=1, shuffle=True)
# CREATING THE NN
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 6, kernel_size=5) # input = gray scale
self.conv2 = nn.Conv2d(6, 16, kernel_size=5)
self.dropout = nn.Dropout2d() # deactivating randomly some neurons to avoid overfitting
self.fc1 = nn.Linear(256, 64) # input dimension: CH(16) x Matrix_dim (4x4)
self.fc2 = nn.Linear(64, n_qubits)
self.hybrid = Hybrid(n_qubits, simulator, n_shots, shift)
self.fc3 = nn.Linear(2 ** n_qubits, 2)
def forward(self, x):
x = F.max_pool2d(F.relu(self.conv1(x)), 2)
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
x = self.dropout(x)
x = x.view(1, -1) # reshaping tensor
x = F.relu(self.fc1(x))
x = self.fc2(x)
# print('Params to QC: ', x)
x = self.hybrid(x) # calling the forward method for the quantum layer
# print('output of QC', x)
x = torch.Tensor(x.float())
x = self.fc3(x)
x = torch.softmax(x, dim=1) # evaluating probabilities (loss function is a cross entropy)
return x
def training_loop (n_epochs, optimizer, model, loss_fn, train_loader):
loss_values = []
for epoch in range(0, n_epochs, +1):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()#getting rid of previous gradients
output = model(data)#forward pass
loss = loss_fn(output, target)
loss.backward()
optimizer.step()#updating parameters
total_loss.append(loss.item())#item transforms into a number
loss_values.append(sum(total_loss)/len(total_loss))#obtainign the average loss
print('Training [{:.0f}%] Loss: {:.4f}'.format(100*(epoch+1)/n_epochs, loss_values[-1]))
return loss_values
#######################
# TRAINING AND TESTING
# Training the NN
# we can use any optimizer, learning rate and cost/loss function to train over multiple epochs
model = Net()
params = list(model.parameters())
learning_rate = 0.01
optimizer = optim.Adam(params, learning_rate)
loss_func = nn.CrossEntropyLoss()
loss_list = []
model.train() # training the module in training mode(specifying the intention to the layers). Used for dropout or batchnorm
epochs = 15
begin = time.time()
loss_list = (training_loop(epochs, optimizer, model, loss_func, train_loader))
end = time.time()
# plotting the training graph
plt.figure(num=2)
plt.plot(loss_list)
plt.title('Hybrid NN Training convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Cross Entropy Loss')
plt.savefig('TC_NQ.pdf')
#defining a function to test our net
def validate(model, test_loader, loss_function, n_test, axes):
correct = 0
total_loss = []
count = 0
with torch.no_grad(): # disabling the gradient as we don't want to update parameters
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data) #evaluating the model on test data
# evaluating the accuracy of our model
pred = output.argmax(dim=1,
keepdim=True) # we are interested in the max value of probability
correct += pred.eq(target.view_as(pred)).sum().item() # checking if it matches with label
#evaluating loss function
loss = loss_function(output, target)
total_loss.append(loss.item())
#printing the resut as images
if count >= n_test:
continue
else:
axes[count].imshow(data[0].numpy().squeeze(), cmap='gray')
axes[count].set_xticks([])
axes[count].set_yticks([])
axes[count].set_title('P: {}'.format(pred.item()))
count += 1
print('Performance on test data: \n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'
.format(sum(total_loss)/len(total_loss),(correct / len(test_loader))*100))
# TESTING THE NN
n_test_show = 6
fig, axes = plt.subplots(nrows=1, ncols=n_test_show, figsize=(10, 3))
model.eval()
validate(model, test_loader, loss_func, n_test_show, axes)
print('The training has taken : ', end - begin, 's to complete')
#testing the NN over set of noisy validation data, with different values of standard deviation
class AddGaussianNoise(object):
def __init__(self, mean=0., std=5):
self.std = std
self.mean = mean
def __call__(self, tensor):
return tensor + torch.randn(tensor.size()) * self.std + self.mean
def __repr__(self):
return self.__class__.__name__ + '(mean={0}, std={1})'.format(self.mean, self.std)
stop,mean, std_dv= 10, 0, 0.1
for i in range (1, stop):
print('Gaussian noise with std deviation: ', std_dv)
X_test_n = datasets.MNIST(root='./data', train=False, download=True,
transform=transforms.Compose([transforms.ToTensor(), AddGaussianNoise(mean, std_dv)]))
idx = np.append(np.where(X_test_n.targets == 0)[0][:n_samples],
np.where(X_test_n.targets == 1)[0][:n_samples])
X_test_n.data = X_test_n.data[idx] # tensor values
X_test_n.targets = X_test_n.targets[idx] # tensor labels
test_loader_n = torch.utils.data.DataLoader(X_test_n, batch_size=1, shuffle=True)
test_iter_n = iter(test_loader_n)
fig_1, axes_1 = plt.subplots(nrows=1, ncols=n_test_show, figsize=(10, 3))
model.eval()
validate(model, test_loader_n, loss_func, n_test_show, axes_1)
std_dv = std_dv + 0.1
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
#
# your code is here or you may find the values by hand (in mind)
#
#
# your solution is here
#
|
https://github.com/lynnlangit/learning-quantum
|
lynnlangit
|
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
!pip install tensorflow==2.4.1
!pip install tensorflow-quantum
# Update package resources to account for version changes.
import importlib, pkg_resources
importlib.reload(pkg_resources)
import tensorflow as tf
import tensorflow_quantum as tfq
import cirq
import sympy
import numpy as np
# visualization tools
%matplotlib inline
import matplotlib.pyplot as plt
from cirq.contrib.svg import SVGCircuit
a, b = sympy.symbols('a b')
# Create two qubits
q0, q1 = cirq.GridQubit.rect(1, 2)
# Create a circuit on these qubits using the parameters you created above.
circuit = cirq.Circuit(
cirq.rx(a).on(q0),
cirq.ry(b).on(q1), cirq.CNOT(control=q0, target=q1))
SVGCircuit(circuit)
# Calculate a state vector with a=0.5 and b=-0.5.
resolver = cirq.ParamResolver({a: 0.5, b: -0.5})
output_state_vector = cirq.Simulator().simulate(circuit, resolver).final_state_vector
output_state_vector
z0 = cirq.Z(q0)
qubit_map={q0: 0, q1: 1}
z0.expectation_from_state_vector(output_state_vector, qubit_map).real
z0x1 = 0.5 * z0 + cirq.X(q1)
z0x1.expectation_from_state_vector(output_state_vector, qubit_map).real
# Rank 1 tensor containing 1 circuit.
circuit_tensor = tfq.convert_to_tensor([circuit])
print(circuit_tensor.shape)
print(circuit_tensor.dtype)
# Rank 1 tensor containing 2 Pauli operators.
pauli_tensor = tfq.convert_to_tensor([z0, z0x1])
pauli_tensor.shape
batch_vals = np.array(np.random.uniform(0, 2 * np.pi, (5, 2)), dtype=np.float32)
cirq_results = []
cirq_simulator = cirq.Simulator()
for vals in batch_vals:
resolver = cirq.ParamResolver({a: vals[0], b: vals[1]})
final_state_vector = cirq_simulator.simulate(circuit, resolver).final_state_vector
cirq_results.append(
[z0.expectation_from_state_vector(final_state_vector, {
q0: 0,
q1: 1
}).real])
print('cirq batch results: \n {}'.format(np.array(cirq_results)))
tfq.layers.Expectation()(circuit,
symbol_names=[a, b],
symbol_values=batch_vals,
operators=z0)
# Parameters that the classical NN will feed values into.
control_params = sympy.symbols('theta_1 theta_2 theta_3')
# Create the parameterized circuit.
qubit = cirq.GridQubit(0, 0)
model_circuit = cirq.Circuit(
cirq.rz(control_params[0])(qubit),
cirq.ry(control_params[1])(qubit),
cirq.rx(control_params[2])(qubit))
SVGCircuit(model_circuit)
# The classical neural network layers.
controller = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation='elu'),
tf.keras.layers.Dense(3)
])
controller(tf.constant([[0.0],[1.0]])).numpy()
# This input is the simulated miscalibration that the model will learn to correct.
circuits_input = tf.keras.Input(shape=(),
# The circuit-tensor has dtype `tf.string`
dtype=tf.string,
name='circuits_input')
# Commands will be either `0` or `1`, specifying the state to set the qubit to.
commands_input = tf.keras.Input(shape=(1,),
dtype=tf.dtypes.float32,
name='commands_input')
dense_2 = controller(commands_input)
# TFQ layer for classically controlled circuits.
expectation_layer = tfq.layers.ControlledPQC(model_circuit,
# Observe Z
operators = cirq.Z(qubit))
expectation = expectation_layer([circuits_input, dense_2])
# The full Keras model is built from our layers.
model = tf.keras.Model(inputs=[circuits_input, commands_input],
outputs=expectation)
tf.keras.utils.plot_model(model, show_shapes=True, dpi=70)
# The command input values to the classical NN.
commands = np.array([[0], [1]], dtype=np.float32)
# The desired Z expectation value at output of quantum circuit.
expected_outputs = np.array([[1], [-1]], dtype=np.float32)
random_rotations = np.random.uniform(0, 2 * np.pi, 3)
noisy_preparation = cirq.Circuit(
cirq.rx(random_rotations[0])(qubit),
cirq.ry(random_rotations[1])(qubit),
cirq.rz(random_rotations[2])(qubit)
)
datapoint_circuits = tfq.convert_to_tensor([
noisy_preparation
] * 2) # Make two copied of this circuit
datapoint_circuits.shape
model([datapoint_circuits, commands]).numpy()
optimizer = tf.keras.optimizers.Adam(learning_rate=0.05)
loss = tf.keras.losses.MeanSquaredError()
model.compile(optimizer=optimizer, loss=loss)
history = model.fit(x=[datapoint_circuits, commands],
y=expected_outputs,
epochs=30,
verbose=0)
plt.plot(history.history['loss'])
plt.title("Learning to Control a Qubit")
plt.xlabel("Iterations")
plt.ylabel("Error in Control")
plt.show()
def check_error(command_values, desired_values):
"""Based on the value in `command_value` see how well you could prepare
the full circuit to have `desired_value` when taking expectation w.r.t. Z."""
params_to_prepare_output = controller(command_values).numpy()
full_circuit = noisy_preparation + model_circuit
# Test how well you can prepare a state to get expectation the expectation
# value in `desired_values`
for index in [0, 1]:
state = cirq_simulator.simulate(
full_circuit,
{s:v for (s,v) in zip(control_params, params_to_prepare_output[index])}
).final_state_vector
expt = cirq.Z(qubit).expectation_from_state_vector(state, {qubit: 0}).real
print(f'For a desired output (expectation) of {desired_values[index]} with'
f' noisy preparation, the controller\nnetwork found the following '
f'values for theta: {params_to_prepare_output[index]}\nWhich gives an'
f' actual expectation of: {expt}\n')
check_error(commands, expected_outputs)
model([datapoint_circuits, commands])
# Define inputs.
commands_input = tf.keras.layers.Input(shape=(1),
dtype=tf.dtypes.float32,
name='commands_input')
circuits_input = tf.keras.Input(shape=(),
# The circuit-tensor has dtype `tf.string`
dtype=tf.dtypes.string,
name='circuits_input')
operators_input = tf.keras.Input(shape=(1,),
dtype=tf.dtypes.string,
name='operators_input')
# Define classical NN.
controller = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation='elu'),
tf.keras.layers.Dense(3)
])
dense_2 = controller(commands_input)
# Since you aren't using a PQC or ControlledPQC you must append
# your model circuit onto the datapoint circuit tensor manually.
full_circuit = tfq.layers.AddCircuit()(circuits_input, append=model_circuit)
expectation_output = tfq.layers.Expectation()(full_circuit,
symbol_names=control_params,
symbol_values=dense_2,
operators=operators_input)
# Contruct your Keras model.
two_axis_control_model = tf.keras.Model(
inputs=[circuits_input, commands_input, operators_input],
outputs=[expectation_output])
# The operators to measure, for each command.
operator_data = tfq.convert_to_tensor([[cirq.X(qubit)], [cirq.Z(qubit)]])
# The command input values to the classical NN.
commands = np.array([[0], [1]], dtype=np.float32)
# The desired expectation value at output of quantum circuit.
expected_outputs = np.array([[1], [-1]], dtype=np.float32)
optimizer = tf.keras.optimizers.Adam(learning_rate=0.05)
loss = tf.keras.losses.MeanSquaredError()
two_axis_control_model.compile(optimizer=optimizer, loss=loss)
history = two_axis_control_model.fit(
x=[datapoint_circuits, commands, operator_data],
y=expected_outputs,
epochs=30,
verbose=1)
plt.plot(history.history['loss'])
plt.title("Learning to Control a Qubit")
plt.xlabel("Iterations")
plt.ylabel("Error in Control")
plt.show()
controller.predict(np.array([0,1]))
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the Unroll3qOrMore pass"""
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Qubit, Clbit
from qiskit.circuit.library import CCXGate, RCCXGate
from qiskit.transpiler.passes import Unroll3qOrMore
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.quantum_info.operators import Operator
from qiskit.quantum_info.random import random_unitary
from qiskit.test import QiskitTestCase
from qiskit.extensions import UnitaryGate
from qiskit.transpiler import Target
class TestUnroll3qOrMore(QiskitTestCase):
"""Tests the Unroll3qOrMore pass, for unrolling all
gates until reaching only 1q or 2q gates."""
def test_ccx(self):
"""Test decompose CCX."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(1, "qr2")
circuit = QuantumCircuit(qr1, qr2)
circuit.ccx(qr1[0], qr1[1], qr2[0])
dag = circuit_to_dag(circuit)
pass_ = Unroll3qOrMore()
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 15)
for node in op_nodes:
self.assertIn(node.name, ["h", "t", "tdg", "cx"])
def test_cswap(self):
"""Test decompose CSwap (recursively)."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(1, "qr2")
circuit = QuantumCircuit(qr1, qr2)
circuit.cswap(qr1[0], qr1[1], qr2[0])
dag = circuit_to_dag(circuit)
pass_ = Unroll3qOrMore()
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 17)
for node in op_nodes:
self.assertIn(node.name, ["h", "t", "tdg", "cx"])
def test_decompose_conditional(self):
"""Test decompose a 3-qubit gate with a conditional."""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 0)
dag = circuit_to_dag(circuit)
pass_ = Unroll3qOrMore()
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 15)
for node in op_nodes:
self.assertIn(node.name, ["h", "t", "tdg", "cx"])
self.assertEqual(node.op.condition, (cr, 0))
def test_decompose_unitary(self):
"""Test unrolling of unitary gate over 4qubits."""
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
unitary = random_unitary(16, seed=42)
circuit.unitary(unitary, [0, 1, 2, 3])
dag = circuit_to_dag(circuit)
pass_ = Unroll3qOrMore()
after_dag = pass_.run(dag)
after_circ = dag_to_circuit(after_dag)
self.assertTrue(Operator(circuit).equiv(Operator(after_circ)))
def test_identity(self):
"""Test unrolling of identity gate over 3qubits."""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
gate = UnitaryGate(np.eye(2**3))
circuit.append(gate, range(3))
dag = circuit_to_dag(circuit)
pass_ = Unroll3qOrMore()
after_dag = pass_.run(dag)
after_circ = dag_to_circuit(after_dag)
self.assertTrue(Operator(circuit).equiv(Operator(after_circ)))
def test_target(self):
"""Test target is respected by the unroll 3q or more pass."""
target = Target(num_qubits=3)
target.add_instruction(CCXGate())
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
qc.append(RCCXGate(), [0, 1, 2])
unroll_pass = Unroll3qOrMore(target=target)
res = unroll_pass(qc)
self.assertIn("ccx", res.count_ops())
self.assertNotIn("rccx", res.count_ops())
def test_basis_gates(self):
"""Test basis_gates are respected by the unroll 3q or more pass."""
basis_gates = ["rccx"]
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
qc.append(RCCXGate(), [0, 1, 2])
unroll_pass = Unroll3qOrMore(basis_gates=basis_gates)
res = unroll_pass(qc)
self.assertNotIn("ccx", res.count_ops())
self.assertIn("rccx", res.count_ops())
def test_target_over_basis_gates(self):
"""Test target is respected over basis_gates by the unroll 3q or more pass."""
target = Target(num_qubits=3)
basis_gates = ["rccx"]
target.add_instruction(CCXGate())
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
qc.append(RCCXGate(), [0, 1, 2])
unroll_pass = Unroll3qOrMore(target=target, basis_gates=basis_gates)
res = unroll_pass(qc)
self.assertIn("ccx", res.count_ops())
self.assertNotIn("rccx", res.count_ops())
def test_if_else(self):
"""Test that a simple if-else over 3+ qubits unrolls correctly."""
pass_ = Unroll3qOrMore(basis_gates=["u", "cx"])
true_body = QuantumCircuit(3, 1)
true_body.h(0)
true_body.ccx(0, 1, 2)
false_body = QuantumCircuit(3, 1)
false_body.rccx(2, 1, 0)
test = QuantumCircuit(3, 1)
test.h(0)
test.measure(0, 0)
test.if_else((0, True), true_body, false_body, [0, 1, 2], [0])
expected = QuantumCircuit(3, 1)
expected.h(0)
expected.measure(0, 0)
expected.if_else((0, True), pass_(true_body), pass_(false_body), [0, 1, 2], [0])
self.assertEqual(pass_(test), expected)
def test_nested_control_flow(self):
"""Test that the unroller recurses into nested control flow."""
pass_ = Unroll3qOrMore(basis_gates=["u", "cx"])
qubits = [Qubit() for _ in [None] * 3]
clbit = Clbit()
for_body = QuantumCircuit(qubits, [clbit])
for_body.ccx(0, 1, 2)
while_body = QuantumCircuit(qubits, [clbit])
while_body.rccx(0, 1, 2)
true_body = QuantumCircuit(qubits, [clbit])
true_body.while_loop((clbit, True), while_body, [0, 1, 2], [0])
test = QuantumCircuit(qubits, [clbit])
test.for_loop(range(2), None, for_body, [0, 1, 2], [0])
test.if_else((clbit, True), true_body, None, [0, 1, 2], [0])
expected_if_body = QuantumCircuit(qubits, [clbit])
expected_if_body.while_loop((clbit, True), pass_(while_body), [0, 1, 2], [0])
expected = QuantumCircuit(qubits, [clbit])
expected.for_loop(range(2), None, pass_(for_body), [0, 1, 2], [0])
expected.if_else(range(2), pass_(expected_if_body), None, [0, 1, 2], [0])
self.assertEqual(pass_(test), expected)
def test_if_else_in_basis(self):
"""Test that a simple if-else over 3+ qubits unrolls correctly."""
pass_ = Unroll3qOrMore(basis_gates=["u", "cx", "if_else", "for_loop", "while_loop"])
true_body = QuantumCircuit(3, 1)
true_body.h(0)
true_body.ccx(0, 1, 2)
false_body = QuantumCircuit(3, 1)
false_body.rccx(2, 1, 0)
test = QuantumCircuit(3, 1)
test.h(0)
test.measure(0, 0)
test.if_else((0, True), true_body, false_body, [0, 1, 2], [0])
expected = QuantumCircuit(3, 1)
expected.h(0)
expected.measure(0, 0)
expected.if_else((0, True), pass_(true_body), pass_(false_body), [0, 1, 2], [0])
self.assertEqual(pass_(test), expected)
def test_nested_control_flow_in_basis(self):
"""Test that the unroller recurses into nested control flow."""
pass_ = Unroll3qOrMore(basis_gates=["u", "cx", "if_else", "for_loop", "while_loop"])
qubits = [Qubit() for _ in [None] * 3]
clbit = Clbit()
for_body = QuantumCircuit(qubits, [clbit])
for_body.ccx(0, 1, 2)
while_body = QuantumCircuit(qubits, [clbit])
while_body.rccx(0, 1, 2)
true_body = QuantumCircuit(qubits, [clbit])
true_body.while_loop((clbit, True), while_body, [0, 1, 2], [0])
test = QuantumCircuit(qubits, [clbit])
test.for_loop(range(2), None, for_body, [0, 1, 2], [0])
test.if_else((clbit, True), true_body, None, [0, 1, 2], [0])
expected_if_body = QuantumCircuit(qubits, [clbit])
expected_if_body.while_loop((clbit, True), pass_(while_body), [0, 1, 2], [0])
expected = QuantumCircuit(qubits, [clbit])
expected.for_loop(range(2), None, pass_(for_body), [0, 1, 2], [0])
expected.if_else(range(2), pass_(expected_if_body), None, [0, 1, 2], [0])
self.assertEqual(pass_(test), expected)
def test_custom_block_over_3q(self):
"""Test a custom instruction is unrolled in a control flow block."""
pass_ = Unroll3qOrMore(basis_gates=["u", "cx", "if_else", "for_loop", "while_loop"])
ghz = QuantumCircuit(5, 5)
ghz.h(0)
ghz.cx(0, 1)
ghz.cx(0, 2)
ghz.cx(0, 3)
ghz.cx(0, 4)
ghz.measure(0, 0)
ghz.measure(1, 1)
ghz.measure(2, 2)
ghz.measure(3, 3)
ghz.measure(4, 4)
ghz.reset(0)
ghz.reset(1)
ghz.reset(2)
ghz.reset(3)
ghz.reset(4)
for_block = QuantumCircuit(5, 5, name="ghz")
for_block.append(ghz, list(range(5)), list(range(5)))
qc = QuantumCircuit(5, 5)
qc.for_loop((1,), None, for_block, [2, 4, 1, 3, 0], [0, 1, 2, 3, 4])
result = pass_(qc)
expected = QuantumCircuit(5, 5)
expected.for_loop((1,), None, ghz, [2, 4, 1, 3, 0], [0, 1, 2, 3, 4])
self.assertEqual(result, expected)
|
https://github.com/usamisaori/qLipschitz
|
usamisaori
|
from sklearn import datasets
import pennylane as qml
import numpy as np
from pennylane.optimize import AdamOptimizer
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
X_train, Y_train = datasets.make_circles(n_samples=400, noise=0.06, factor=0.7)
X_test, Y_test = datasets.make_circles(n_samples=100, noise=0.06, factor=0.7)
print('Training Data:')
print(X_train[:10])
print('\nTraining Label:')
print(Y_train[:10])
plt.scatter(X_train[:, 0], X_train[:, 1], c=Y_train)
plt.show()
print(f'Total datas: {len(X_train)}')
print(f'labels: {list(set(Y_train))}')
print(f'label 0 datas: {len(list(filter(lambda x: x==0, Y_train)))}')
print(f'label 1 datas: {len(list(filter(lambda x: x==1, Y_train)))}')
Z_train = (X_train[:, 0] ** 2 + X_train[:, 1] ** 2) ** 0.5
temp = np.zeros((X_train.shape[0], len(X_train[0]) + 1))
temp[:, :-1] = X_train
temp[:, -1] = Z_train
X_train2 = temp
Z_test = (X_test[:, 0] ** 2 + X_test[:, 1] ** 2) ** 0.5
temp = np.zeros((X_test.shape[0], len(X_test[0]) + 1))
temp[:, :-1] = X_test
temp[:, -1] = Z_test
X_test2 = temp
print('Solved Training Data:')
print(X_train2[:10])
def plot3D(X, Y):
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(
X[:, 0], X[:, 1], X[:, 2],
zdir='z', s=30, c=Y, depthshade=True
)
plt.show()
plot3D(X_train2, Y_train)
print(f'Total datas: {len(X_train2)}')
print(f'labels: {list(set(Y_train))}')
print(f'label 0 datas: {len(list(filter(lambda x: x==0, Y_train)))}')
print(f'label 1 datas: {len(list(filter(lambda x: x==1, Y_train)))}')
qubits_num = 3
layers_num = 2
dev = qml.device("default.qubit", wires=qubits_num)
@qml.qnode(dev)
def circuit(params, data):
angles = [ i * np.pi for i in data ]
for i in range(qubits_num):
qml.RX(angles[i], wires=i)
qml.Rot( *(params[0, i]), wires=i )
qml.CZ(wires=[1, 0])
qml.CZ(wires=[1, 2])
qml.CZ(wires=[0, 2])
for i in range(qubits_num):
qml.Rot( *(params[1, i]), wires=i )
# PauliZ measure => 1 -> |0> while -1 -> |1>
return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliZ(2))
@qml.qnode(dev)
def circuit2(params_fixed, params_training, data):
angles = [ i * np.pi for i in data ]
for i in range(qubits_num):
qml.RX(angles[i], wires=i)
qml.Rot( *(params_fixed[i]), wires=i )
qml.CZ(wires=[1, 0])
qml.CZ(wires=[1, 2])
qml.CZ(wires=[0, 2])
for i in range(qubits_num):
qml.Rot( *(params_training[i]), wires=i )
# PauliZ measure => 1 -> |0> while -1 -> |1>
return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliZ(2))
import qiskit
from qiskit import QuantumCircuit
from qiskit import Aer, execute
unitary_backend = Aer.get_backend('unitary_simulator')
qasm_backend = Aer.get_backend('qasm_simulator')
def predict(params, data):
qcircuit = QuantumCircuit(3, 3)
qubits = qcircuit.qubits
for i, d in enumerate(data):
qcircuit.rx(d * np.pi, qubits[i])
for i in range(qubits_num):
qcircuit.u3(*(params[0][i]), qubits[i])
qcircuit.cz(qubits[0], qubits[1])
qcircuit.cz(qubits[1], qubits[2])
qcircuit.cz(qubits[0], qubits[2])
for i in range(qubits_num):
qcircuit.u3(*(params[1][i]), qubits[i])
# the measurement
qcircuit.measure([0, 1, 2], [0, 1, 2])
# job execution
shots = 1000
job_sim = execute(qcircuit, qasm_backend, shots=shots)
result_sim = job_sim.result()
counts = result_sim.get_counts(qcircuit)
p1 = (counts.get('100', 0) + counts.get('111', 0) + counts.get('101', 0) + counts.get('110',0)) / shots
if p1 > 0.5:
return 1
else:
return 0
def cost(weights, datas, labels):
loss = 0
for i, data in enumerate(datas):
# like [-1, 1, 1]
measured = circuit(weights, data)
p = measured[0]
if labels[i] == 0:
loss += (1 - p) ** 2
else:
loss += (-1 - p) ** 2
return loss / len(datas)
def cost2(params_fixed, params_training, datas, labels):
loss = 0
for i, data in enumerate(datas):
# like [-1, 1, 1]
measured = circuit2(params_fixed, params_training, data)
p = measured[0]
if labels[i] == 0:
loss += (1 - p) ** 2
else:
loss += (-1 - p) ** 2
return loss / len(datas)
def accuracy(weights, datas, labels):
predictions = [ predict(weights, data) for data in datas ]
acc = 0
for i, p in enumerate(predictions):
if p == labels[i]:
acc += 1
return acc / len(predictions)
class VQC:
def __init__(self):
# 3 => U3(theta, phi, lambda)
# self.params = 0.01 * np.random.random(size=(layers_num, qubits_num, 3))
self.params = (0.01 * np.random.randn(layers_num, qubits_num, 3))
self.bestparams = self.params
self.bestcost = 10
self.bestaccuracy = 0
self.weights = []
self.costs = []
self.accuracies = []
def fit(self, X_train, Y_train, *, epoch=300, stepsize=0.125, batch_size=20, fixed=False):
self.opt = AdamOptimizer(stepsize)
for turn in range(epoch):
# Update the weights by one optimizer step
if batch_size != -1:
batch_index = np.random.randint(0, len(X_train), (batch_size,))
X_train_batch = X_train[batch_index]
Y_train_batch = Y_train[batch_index]
if fixed:
params_fixed = self.params[0]
params_training = self.params[1]
self.params[1] = self.opt.step(lambda v: cost2(params_fixed, v, X_train_batch, Y_train_batch), params_training)
else:
self.params = self.opt.step(lambda v: cost(v, X_train_batch, Y_train_batch), self.params)
else:
if fixed:
params_fixed = self.params[0]
params_training = self.params[1]
self.params[1] = self.opt.step(lambda v: cost2(params_fixed, v, X_train, Y_train), params_training)
else:
self.params = self.opt.step(lambda v: cost(v, X_train, Y_train), self.params)
cost_now = cost(self.params, X_train, Y_train)
acc_now = accuracy(self.params, X_train, Y_train)
if cost_now < self.bestcost:
self.bestcost = cost_now
self.bestparams = self.params
self.weights.append(self.params)
self.costs.append(cost_now)
self.accuracies.append(acc_now)
print(
"Turn: {:5d} | Cost: {:0.7f} | Accuracy: {:0.2f}% ".format(
turn + 1, cost_now, acc_now * 100
))
def score(self, X_test, Y_test):
predictions = [ predict(self.bestparams, data) for data in X_test ]
acc = accuracy(self.bestparams, X_test, Y_test)
print("FINAL ACCURACY: {:0.2f}%".format(acc * 100))
from qiskit.quantum_info import DensityMatrix
def getDensityMatrix(circuit):
return DensityMatrix(circuit).data
from scipy.linalg import sqrtm
def D(rou, sigma):
A = rou - sigma
A_ = sqrtm( np.dot( A.conj().T, A ) )
return 0.5 * np.linalg.norm( np.trace(A_) )
def params_loss_distance(params, data1, data2, label1, label2):
u3Circuits = []
for i in range(qubits_num):
circuit = QuantumCircuit(1, 1)
circuit.u3(*( params[i] ), 0)
u3Circuits.append(circuit)
circuit1 = QuantumCircuit(qubits_num, qubits_num)
for qubit in range(qubits_num):
circuit1.rx(data1[qubit] * np.pi, qubit)
circuit2 = QuantumCircuit(qubits_num, qubits_num)
for qubit in range(qubits_num):
circuit2.rx(data2[qubit] * np.pi, qubit)
matrix1 = getDensityMatrix(circuit1)
matrix2 = getDensityMatrix(circuit2)
d = D(matrix1, matrix2)
if label1 == label2:
loss = d ** 2
else:
loss = (1 - d) ** 2
return loss
def params_loss_gradient(params, datas, labels, *, loss_function, epsilon=0.001):
length = len(datas)
derivates = np.zeros(len(params))
loss_origin = 0
# calculate origin loss
for i in range(length // 2):
j = i + length // 2
loss_origin += loss_function(params, datas[i], datas[j], labels[i], labels[j])
loss_origin /= length // 2
for i in range(len(params)):
params[i] += epsilon
loss = 0
for j in range(length // 2):
k = j + length // 2
loss += loss_function(params, datas[j], datas[k], labels[j], labels[k])
loss /= length // 2
derivates[i] = (loss - loss_origin) / epsilon
params[i] -= epsilon
return loss_origin, derivates
import random
def sub_train_params(datas, labels, *, epoch, alpha, batch_size, loss_function):
# params = 0.01 * np.random.random(size=(1, qubits_num, 3))[0]
params = (0.01 * np.random.randn(1, qubits_num, 3))[0]
# params = params.reshape(qubits_num, 3)
print(f'Training at alpha: {alpha} ')
momentum, s = 0, 0
belta1 = 0.9; belta2 = 0.999
e = 1e-3 # 1e-8
lastloss = 100
for turn in range(epoch):
if turn % 10 == 9:
print(f' -- training: ({turn + 1}/{epoch})')
batch_index = random.sample(range(0, len(datas)), batch_size)
# batch_index = range(0, 300)
loss, grad = params_loss_gradient(params, datas[batch_index], labels[batch_index],
loss_function=loss_function)
if abs(loss - lastloss) < 1e-4:
break
lastloss = loss
# Adam Optimizer
momentum = belta1 * momentum + (1 - belta1) * grad
s = belta2 * s + (1 - belta2) * (grad ** 2)
m_ = momentum / (1 - belta1 ** (turn + 1))
s_ = s / (1 - belta2 ** (turn + 1))
# update parameters
params = params - alpha * (m_ / ( s_ ** 0.5 + e ))
return loss, params
def train_params(datas, labels, *, epoch=30, loss_function=params_loss_distance):
# alpha_grid = [0.05, 0.1, 0.125, 0.25, 0.35, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3]
# alpha_grid = [0.05, 0.15, 0.25, 0.5]
alpha_grid = [0.05, 0.075, 0.1, 0.125, 0.25, 0.5, 0.75, 1]
alpha_best = None; params_best = None; loss_best = 1000
batch_size = 30
for alpha in alpha_grid:
loss, params = sub_train_params(datas, labels,
alpha=alpha, batch_size=batch_size, epoch=epoch, loss_function=loss_function)
print(f' - finished. (loss {loss})\n')
if loss < loss_best:
loss_best = loss
alpha_best = alpha
params_best = params
return {
'alpha': alpha_best,
'params': params_best,
'loss': loss_best
}
result = train_params(X_train2, Y_train, epoch=300)
print(f'best alpha: {result["alpha"]}')
print(f'best loss: {result["loss"]}')
print(f'best params: {result["params"]}')
vqc = VQC()
stepsize = 0.001
vqc.fit(X_train2, Y_train, epoch=200, stepsize=stepsize)
params_origin = vqc.bestparams
params_origin
print(cost(params_origin, X_train2, Y_train))
print(cost(params_origin, X_test2, Y_test))
vqc.score(X_test2, Y_test)
vqc = VQC()
vqc.params[0] = result['params']
stepsize = result['alpha']
# stepsize = 0.125
vqc.fit(X_train2, Y_train, epoch=10, stepsize=stepsize, fixed=False)
params_init = vqc.bestparams
params_init
print(cost(params_init, X_train2, Y_train))
print(cost(params_init, X_test2, Y_test))
vqc.score(X_test2, Y_test)
params_test = vqc.bestparams
params_test
vqc = VQC()
print(f'training with alpha: {result["alpha"]}')
vqc.params[0] = result['params']
# vqc.params[1] = result['params']
stepsize = result['alpha'] / 100
# stepsize =
vqc.fit(X_train2, Y_train, epoch=15, stepsize=stepsize)
print(cost(params_test, X_train2, Y_train))
print(cost(params_test, X_test2, Y_test))
vqc.score(X_test2, Y_test)
params_u3 = vqc.bestparams
print(params_u3)
def createInputCircuit(data):
qubits_num = len(data)
qcircuit = QuantumCircuit(qubits_num, qubits_num)
qubits = qcircuit.qubits
for i, d in enumerate(data):
qcircuit.rx(d * np.pi, qubits[i])
return qcircuit
def createModelCircuit(params):
qubits_num = len(params[0])
qcircuit = QuantumCircuit(qubits_num, qubits_num)
qubits = qcircuit.qubits
for i in range(qubits_num):
qcircuit.u3(*params[0][i], qubits[i])
for i in range(qubits_num - 1):
qcircuit.cz(qubits[i], qubits[i + 1])
qcircuit.cz(qubits[0], qubits[qubits_num - 1])
for i in range(qubits_num):
qcircuit.u3(*params[1][i], qubits[i])
return qcircuit
def createCircuit(params, data):
input_circuit = createInputCircuit(data)
model_circuit = createModelCircuit(params)
full_circuit = input_circuit.compose(model_circuit)
return full_circuit
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.utils import insert_noise
from qiskit.providers.aer.noise import pauli_error, depolarizing_error, mixed_unitary_error
from qiskit.circuit.library import XGate, IGate, ZGate
from qiskit.quantum_info import DensityMatrix
def createNoiseModel(p, errorType):
# QuantumError objects
if errorType == 'bit_flip':
error = pauli_error([('X', p), ('I', 1 - p)])
elif errorType == 'phase_flip':
error = pauli_error([('Z', p), ('I', 1 - p)])
elif errorType == 'depolarizing':
error = depolarizing_error(p, num_qubits=1)
elif errorType == 'mixed':
error = mixed_unitary_error([(XGate(), p/2), (ZGate(), p/2), (IGate(), 1 - p)])
## two-qubits quantumError objects
if errorType == 'depolarizing':
error_2qubits = depolarizing_error(p, num_qubits=2)
else:
error_2qubits = error.tensor(error)
# Add errors to noise model
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error, ['u3'])
noise_model.add_all_qubit_quantum_error(error_2qubits, ['cz'])
return noise_model
def createNoisyModelCircuit(params, p, errorType, *, model_circuit=None):
noise_model = createNoiseModel(p, errorType)
if model_circuit == None:
model_circuit = createModelCircuit(params)
return insert_noise(model_circuit, noise_model)
from functools import reduce
Dag = lambda matrix: matrix.conj().T
Kron = lambda *matrices: reduce(np.kron, matrices)
psi_0 = np.array([1.0, 0.0])
psi_1 = np.array([0.0, 1.0])
I = np.eye(2)
M_0 = psi_0.reshape([2, 1]) @ psi_0.reshape([1, 2]).conj()
M_1 = psi_1.reshape([2, 1]) @ psi_1.reshape([1, 2]).conj()
def getMeasurements(qubits_num):
measurement_0 = [M_0]
measurement_1 = [M_1]
for i in range(qubits_num - 1):
measurement_0.append(I)
measurement_1.append(I)
return [
Kron(*measurement_0),
Kron(*measurement_1)
]
def powerSets(items):
N = len(items)
combs = []
for i in range(2 ** N):
comb = []
for j in range(N):
if (i >> j) % 2:
comb.append(items[j])
combs.append(comb)
return combs
class Algorithm:
def __init__(self, model_circuit, measurements, outputs):
# DensityMatrix of model
self.E = getDensityMatrix(model_circuit)
# Measurements
self.M = dict()
for index, output in enumerate(outputs):
self.M[output] = measurements[index]
# Outputs
self.O = outputs
self.O_ = powerSets(outputs)
def d(A, rou, sigma):
distance = 0
for output in A.O:
trace = np.trace(
Dag(A.M[output]) @ A.M[output] @
(A.E @ (rou - sigma) @ Dag(A.E))
)
distance += np.linalg.norm(trace)
return distance / 2
def Lipschitz(A):
E, M, O, O_ = A.E, A.M, A.O, A.O_
# Step 1: Calculate W_i
W = dict()
for i in O:
W[i] = Dag(E) @ Dag(M[i]) @ M[i] @ E
# Step 2: Calculate K_star
K_star = 0; vectors = [None, None]
M_star = np.zeros(E.shape)
for S in O_:
if len(S) == 0:
continue
# calculate M_S = Σ Wi
M_S = np.zeros(E.shape).astype('complex64')
for i in S:
M_S += W[i]
# calculate eigenvalues and eigenvectors of M_S
eigenvalues, eigenvectors = np.linalg.eigh(M_S)
min_index = np.where(eigenvalues == eigenvalues.min())
max_index = np.where(eigenvalues == eigenvalues.max())
# calculate K_S
K_S = np.linalg.norm(eigenvalues[max_index][0] - eigenvalues[min_index][0])
if K_S > K_star:
K_star = K_S
vectors[0] = eigenvectors.T[max_index][0]
vectors[1] = eigenvectors.T[min_index][0]
return K_star, np.array(vectors)
def FairVeriQ(A, epsilon, delta):
# epsilon <= 1 and delta > 0
K_star, kernel = Lipschitz(A)
if delta >= K_star * epsilon:
return True, None
else:
return False, kernel
def generateBiasPair(sigma, kernel, epsilon):
psi, phi = kernel
size = len(psi)
psi = psi.reshape(size, 1) @ Dag(psi.reshape(size, 1))
phi = phi.reshape(size, 1) @ Dag(phi.reshape(size, 1))
rou_psi = epsilon * psi + (1 - epsilon) * sigma
rou_phi = epsilon * phi + (1 - epsilon) * sigma
return np.array([
rou_psi, rou_phi
])
X_train2[0]
# params trained by noiesless environment
vqc.bestparams
# calculate lipschitz constant in noisy model
probabilities = [0.0001, 0.001, 0.05, 0.1]
models_type = [
'noiseless', 'bit_flip', 'phase_flip', 'depolarizing'
]
print('Classifier for centric circle: ')
params = vqc.bestparams
for p in probabilities:
circuits = [
createModelCircuit(params),
createNoisyModelCircuit(params, p, 'bit_flip'),
createNoisyModelCircuit(params, p, 'phase_flip'),
createNoisyModelCircuit(params, p, 'depolarizing')
]
print(f'p: {p}')
for i, model_type in enumerate(models_type):
noisy_A = Algorithm(circuits[i], getMeasurements(qubits_num=3), [0, 1])
print(f'{model_type} model: {Lipschitz(noisy_A)[0]}')
print()
def createParamTrainingCircuit(params):
qubits_num = len(params) // 3
qcircuit = QuantumCircuit(qubits_num, qubits_num)
qubits = qcircuit.qubits
for i in range(qubits_num):
qcircuit.u3(*params[i*3: (i+1)*3], qubits[i])
return qcircuit
def params_loss_noisemodel_distance_factory(p, noiseType):
def params_loss_noisemodel_distance(params, data1, data2, label1, label2):
u3Circuit = QuantumCircuit(qubits_num, qubits_num)
qubits = u3Circuit.qubits
for i in range(qubits_num):
u3Circuit.u3(*params[i*3: (i+1)*3], qubits[i])
inputCircuit1 = QuantumCircuit(qubits_num, qubits_num)
qubits = inputCircuit1.qubits
for i, d in enumerate(data1):
inputCircuit1.rx(d * np.pi, qubits[i])
inputCircuit2 = QuantumCircuit(qubits_num, qubits_num)
qubits = inputCircuit2.qubits
for i, d in enumerate(data1):
inputCircuit2.rx(d * np.pi, qubits[i])
# calculate distance
matrix_1 = getDensityMatrix(circuit1)
matrix_2 = getDensityMatrix(circuit2)
d = D(matrix_1, matrix_2)
if label1 == label2:
return d ** 2
else:
return (1 - d) ** 2
return params_loss_noisemodel_distance
params_loss_noisemodel_distance = params_loss_noisemodel_distance_factory(0.001, 'bit_flip')
result_noise = train_params(X_train2, Y_train, epoch=200, loss_function=params_loss_noisemodel_distance)
print(f'best alpha: {result_noise["alpha"]}')
print(f'best loss: {result_noise["loss"]}')
print(f'best params: {result_noise["params"]}')
vqc = VQC()
vqc.params[0] = result_noise['params']
stepsize = result_noise['alpha'] / 10
vqc.fit(X_train2, Y_train, epoch=5, stepsize=stepsize)
print(cost(vqc.bestparams, X_train2, Y_train))
print(cost(vqc.bestparams, X_test2, Y_test))
vqc.score(X_test2, Y_test)
# calculate lipschitz constant in noisy model
probabilities = [0.0001, 0.001, 0.05, 0.1]
models_type = [
'noiseless', 'bit_flip', 'phase_flip', 'depolarizing'
]
print('Classifier for centric circle: ')
params = vqc.bestparams
for p in probabilities:
circuits = [
createModelCircuit(params),
createNoisyModelCircuit(params, p, 'bit_flip'),
createNoisyModelCircuit(params, p, 'phase_flip'),
createNoisyModelCircuit(params, p, 'depolarizing')
]
print(f'p: {p}')
for i, model_type in enumerate(models_type):
noisy_A = Algorithm(circuits[i], getMeasurements(qubits_num=3), [0, 1])
print(f'{model_type} model: {Lipschitz(noisy_A)[0]}')
print()
circuit_ = createNoisyModelCircuit(params, 0.01, 'mixed')
circuit_.draw(output='mpl')
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
from qiskit import *
# set up circuit (no measurements required)
qc = QuantumCircuit(2)
qc.h(0)
qc.h(1)
qc.rz(3.14/4,1)
# set up simulator that returns statevectors
backend = Aer.get_backend('statevector_simulator')
# run the circuit to get the state vector
state = execute(qc,backend).result().get_statevector()
# now we use some fanciness to display it in latex
from IPython.display import display, Markdown, Latex
def state2latex(state):
state_latex = '\\begin{pmatrix}'
for amplitude in state:
state_latex += str(amplitude) + '\\\\'
state_latex = state_latex[0:-4]
state_latex += '\end{pmatrix}'
display(Markdown(state_latex))
state2latex(state)
|
https://github.com/Keerthiraj-Nagaraj/IBM-quantum-challenge-2020
|
Keerthiraj-Nagaraj
|
from IPython.display import Image, display
Image("ryoko.png", width="70")
from IPython.display import Image, display
Image('unstructured_search.png', width="700")
Image("oracle.png", width="700")
Image("step0.png", width="700")
Image("step1.png", width="700")
Image("step2.png", width="700")
Image("grover_algorithm.png", width="700")
#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
def phase_oracle(circuit, register):
circuit.cz(register[0], register[1])
qr = QuantumRegister(2)
oracleCircuit = QuantumCircuit(qr)
phase_oracle(oracleCircuit, qr)
oracleCircuit.draw(output="mpl")
def inversion_about_average(circuit, register):
"""Apply inversion about the average step of Grover's algorithm."""
circuit.h(register)
circuit.x(register)
circuit.h(register[1])
circuit.cx(register[0], register[1])
circuit.h(register[1])
circuit.x(register)
circuit.h(register)
qAverage = QuantumCircuit(qr)
inversion_about_average(qAverage, qr)
qAverage.draw(output='mpl')
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
groverCircuit = QuantumCircuit(qr,cr)
groverCircuit.h(qr)
phase_oracle(groverCircuit, qr)
inversion_about_average(groverCircuit, qr)
groverCircuit.measure(qr,cr)
groverCircuit.draw(output="mpl")
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(groverCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend_lb = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and
not b.configuration().simulator and b.status().operational==True))
print("Least busy backend: ", backend_lb)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
backend = backend_lb
shots = 1024
job_exp = execute(groverCircuit, backend=backend, shots=shots)
job_monitor(job_exp, interval = 2)
# get the results from the computation
results = job_exp.result()
answer = results.get_counts(groverCircuit)
plot_histogram(answer)
# 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
def phase_oracle(circuit, register,oracle_register):
circuit.h(oracle_register)
circuit.ccx(register[0], register[1],oracle_register)
circuit.h(oracle_register)
qr = QuantumRegister(3)
oracleCircuit = QuantumCircuit(qr)
oracleCircuit.x(qr[2])
phase_oracle(oracleCircuit, qr,qr[2])
oracleCircuit.draw(output="mpl")
def inversion_about_average(circuit, register):
"""Apply inversion about the average step of Grover's algorithm."""
circuit.h(register)
circuit.x(register)
circuit.h(register[1])
circuit.cx(register[0], register[1])
circuit.h(register[1])
circuit.x(register)
circuit.h(register)
qAverage = QuantumCircuit(qr)
inversion_about_average(qAverage, qr[0:2])
qAverage.draw(output='mpl')
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
groverCircuit = QuantumCircuit(qr,cr)
groverCircuit.h(qr[0:2])
groverCircuit.x(qr[2])
phase_oracle(groverCircuit, qr,qr[2])
inversion_about_average(groverCircuit, qr[0:2])
groverCircuit.measure(qr,cr)
groverCircuit.draw(output="mpl")
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(groverCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
database = QuantumRegister(4,'d')
oracle = QuantumRegister(1, 'o')
auxiliary = QuantumRegister(2, 'q')
cr = ClassicalRegister(4, 'c')
qc = QuantumCircuit(database, oracle, auxiliary, cr)
qc.h(database[:])
qc.x(oracle[0])
qc.h(oracle[0])
qc.x(database[0])
qc.mct(database[:], oracle[0], auxiliary[:], mode='basic')
qc.x(database[0])
qc.h(database[:])
qc.x(database[:])
qc.h(database[3])
qc.mct(database[0:3], database[3], auxiliary[:], mode='basic')
qc.h(database[3])
qc.x(database[:])
qc.h(database[:])
qc.h(oracle[0])
qc.x(oracle[0])
qc.measure(database,cr)
# Change the endian
qc = qc.reverse_bits()
qc.draw(output="mpl")
backend = BasicAer.get_backend('qasm_simulator')
prob_of_ans = []
count_list = []
for x in range(12):
database = QuantumRegister(4)
oracle = QuantumRegister(1)
auxiliary = QuantumRegister(2)
cr = ClassicalRegister(4)
qc = QuantumCircuit(database, oracle, auxiliary, cr)
qc.h(database[:])
qc.x(oracle[0])
qc.h(oracle[0])
for j in range(x):
# oracle_4q
# search 7: 0111
qc.x(database[0])
qc.mct(database[:], oracle[0], auxiliary[:], mode='basic')
qc.x(database[0])
# diffusion_4q
qc.h(database[:])
qc.x(database[:])
qc.h(database[3])
qc.mct(database[0:3], database[3], auxiliary[:], mode='basic')
qc.h(database[3])
qc.x(database[:])
qc.h(database[:])
qc.h(oracle[0])
qc.x(oracle[0])
qc.measure(database,cr)
# Change the endian
qc = qc.reverse_bits()
job = execute(qc, backend=backend, shots=1000, seed_simulator=12345, backend_options={"fusion_enable":True})
result = job.result()
count = result.get_counts()
count_list.append(count)
answer = count['0111']
prob_of_ans.append(answer)
#count_list[0]
for i in range(12):
print(len(count_list[i]))
count_list[9]
import numpy as np
import matplotlib.pyplot as plt
iteration = [i for i in range(12)]
correct = prob_of_ans
plt.bar(iteration, correct)
plt.xlabel('# of iteration')
plt.ylabel('# of times the solution was obtained')
num_database = 7
database = QuantumRegister(num_database, 'd')
oracle = QuantumRegister(1, 'o')
auxiliary = QuantumRegister(5, 'a')
cr = ClassicalRegister(num_database, 'c')
qc = QuantumCircuit(database, oracle, auxiliary, cr)
qc.h(database[:])
qc.x(oracle[0])
qc.h(oracle[0])
qc.x(database[0])
qc.mct(database[:], oracle[0], auxiliary[:], mode='basic')
qc.x(database[0])
qc.h(database[:])
qc.x(database[:])
qc.h(database[num_database-1])
qc.mct(database[0:num_database-1], database[num_database-1], auxiliary[:], mode='basic')
qc.h(database[num_database-1])
qc.x(database[:])
qc.h(database[:])
qc.h(oracle[0])
qc.x(oracle[0])
qc.measure(database,cr)
qc = qc.reverse_bits()
qc.draw(output="mpl")
#My solution
backend = BasicAer.get_backend('qasm_simulator')
prob_of_ans = []
count_list = []
total_iter = 16
num_database = 7
for x in range(total_iter):
database = QuantumRegister(num_database, 'd')
oracle = QuantumRegister(1, 'o')
auxiliary = QuantumRegister(5, 'a')
cr = ClassicalRegister(num_database, 'c')
qc = QuantumCircuit(database, oracle, auxiliary, cr)
qc.h(database[:])
qc.x(oracle[0])
qc.h(oracle[0])
for j in range(x):
# oracle_4q
# search 7: 0111
qc.x(database[0])
qc.mct(database[:], oracle[0], auxiliary[:], mode='basic')
qc.x(database[0])
# diffusion_4q
qc.h(database[:])
qc.x(database[:])
qc.h(database[num_database-1])
qc.mct(database[0:num_database-1], database[num_database-1], auxiliary[:], mode='basic')
qc.h(database[num_database-1])
qc.x(database[:])
qc.h(database[:])
qc.h(oracle[0])
qc.x(oracle[0])
qc.measure(database,cr)
# Change the endian
qc = qc.reverse_bits()
job = execute(qc, backend=backend, shots=1000, seed_simulator=12345, backend_options={"fusion_enable":True})
result = job.result()
count = result.get_counts()
count_list.append(count)
answer = count['0111111']
prob_of_ans.append(answer)
#count_list[0]
for i in range(total_iter):
print(len(count_list[i]))
count_list[8]
import numpy as np
import matplotlib.pyplot as plt
iteration = [i for i in range(total_iter)]
correct = prob_of_ans
plt.bar(iteration, correct)
plt.xlabel('# of iteration')
plt.ylabel('# of times the solution was obtained')
ans = 8
# Change ans of following code and check your answer.
# ans must be an interger.
from qc_grader import grade_ex1b
grade_ex1b(ans)
# Change ans of following code and submit it.
# ans must be interger.
from qc_grader import submit_ex1b
submit_ex1b(ans)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Necessary imports
import numpy as np
import matplotlib.pyplot as plt
from torch import Tensor
from torch.nn import Linear, CrossEntropyLoss, MSELoss
from torch.optim import LBFGS
from qiskit import QuantumCircuit
from qiskit.utils import algorithm_globals
from qiskit.circuit import Parameter
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN
from qiskit_machine_learning.connectors import TorchConnector
# Set seed for random generators
algorithm_globals.random_seed = 42
# Generate random dataset
# Select dataset dimension (num_inputs) and size (num_samples)
num_inputs = 2
num_samples = 20
# Generate random input coordinates (X) and binary labels (y)
X = 2 * algorithm_globals.random.random([num_samples, num_inputs]) - 1
y01 = 1 * (np.sum(X, axis=1) >= 0) # in { 0, 1}, y01 will be used for SamplerQNN example
y = 2 * y01 - 1 # in {-1, +1}, y will be used for EstimatorQNN example
# Convert to torch Tensors
X_ = Tensor(X)
y01_ = Tensor(y01).reshape(len(y)).long()
y_ = Tensor(y).reshape(len(y), 1)
# Plot dataset
for x, y_target in zip(X, y):
if y_target == 1:
plt.plot(x[0], x[1], "bo")
else:
plt.plot(x[0], x[1], "go")
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
# Set up a circuit
feature_map = ZZFeatureMap(num_inputs)
ansatz = RealAmplitudes(num_inputs)
qc = QuantumCircuit(num_inputs)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
qc.draw("mpl")
# Setup QNN
qnn1 = EstimatorQNN(
circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters
)
# Set up PyTorch module
# Note: If we don't explicitly declare the initial weights
# they are chosen uniformly at random from [-1, 1].
initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn1.num_weights) - 1)
model1 = TorchConnector(qnn1, initial_weights=initial_weights)
print("Initial weights: ", initial_weights)
# Test with a single input
model1(X_[0, :])
# Define optimizer and loss
optimizer = LBFGS(model1.parameters())
f_loss = MSELoss(reduction="sum")
# Start training
model1.train() # set model to training mode
# Note from (https://pytorch.org/docs/stable/optim.html):
# Some optimization algorithms such as LBFGS need to
# reevaluate the function multiple times, so you have to
# pass in a closure that allows them to recompute your model.
# The closure should clear the gradients, compute the loss,
# and return it.
def closure():
optimizer.zero_grad() # Initialize/clear gradients
loss = f_loss(model1(X_), y_) # Evaluate loss function
loss.backward() # Backward pass
print(loss.item()) # Print loss
return loss
# Run optimizer step4
optimizer.step(closure)
# Evaluate model and compute accuracy
y_predict = []
for x, y_target in zip(X, y):
output = model1(Tensor(x))
y_predict += [np.sign(output.detach().numpy())[0]]
print("Accuracy:", sum(y_predict == y) / len(y))
# Plot results
# red == wrongly classified
for x, y_target, y_p in zip(X, y, y_predict):
if y_target == 1:
plt.plot(x[0], x[1], "bo")
else:
plt.plot(x[0], x[1], "go")
if y_target != y_p:
plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2)
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
# Define feature map and ansatz
feature_map = ZZFeatureMap(num_inputs)
ansatz = RealAmplitudes(num_inputs, entanglement="linear", reps=1)
# Define quantum circuit of num_qubits = input dim
# Append feature map and ansatz
qc = QuantumCircuit(num_inputs)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
# Define SamplerQNN and initial setup
parity = lambda x: "{:b}".format(x).count("1") % 2 # optional interpret function
output_shape = 2 # parity = 0, 1
qnn2 = SamplerQNN(
circuit=qc,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
interpret=parity,
output_shape=output_shape,
)
# Set up PyTorch module
# Reminder: If we don't explicitly declare the initial weights
# they are chosen uniformly at random from [-1, 1].
initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn2.num_weights) - 1)
print("Initial weights: ", initial_weights)
model2 = TorchConnector(qnn2, initial_weights)
# Define model, optimizer, and loss
optimizer = LBFGS(model2.parameters())
f_loss = CrossEntropyLoss() # Our output will be in the [0,1] range
# Start training
model2.train()
# Define LBFGS closure method (explained in previous section)
def closure():
optimizer.zero_grad(set_to_none=True) # Initialize gradient
loss = f_loss(model2(X_), y01_) # Calculate loss
loss.backward() # Backward pass
print(loss.item()) # Print loss
return loss
# Run optimizer (LBFGS requires closure)
optimizer.step(closure);
# Evaluate model and compute accuracy
y_predict = []
for x in X:
output = model2(Tensor(x))
y_predict += [np.argmax(output.detach().numpy())]
print("Accuracy:", sum(y_predict == y01) / len(y01))
# plot results
# red == wrongly classified
for x, y_target, y_ in zip(X, y01, y_predict):
if y_target == 1:
plt.plot(x[0], x[1], "bo")
else:
plt.plot(x[0], x[1], "go")
if y_target != y_:
plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2)
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
# Generate random dataset
num_samples = 20
eps = 0.2
lb, ub = -np.pi, np.pi
f = lambda x: np.sin(x)
X = (ub - lb) * algorithm_globals.random.random([num_samples, 1]) + lb
y = f(X) + eps * (2 * algorithm_globals.random.random([num_samples, 1]) - 1)
plt.plot(np.linspace(lb, ub), f(np.linspace(lb, ub)), "r--")
plt.plot(X, y, "bo")
plt.show()
# Construct simple feature map
param_x = Parameter("x")
feature_map = QuantumCircuit(1, name="fm")
feature_map.ry(param_x, 0)
# Construct simple feature map
param_y = Parameter("y")
ansatz = QuantumCircuit(1, name="vf")
ansatz.ry(param_y, 0)
qc = QuantumCircuit(1)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
# Construct QNN
qnn3 = EstimatorQNN(circuit=qc, input_params=[param_x], weight_params=[param_y])
# Set up PyTorch module
# Reminder: If we don't explicitly declare the initial weights
# they are chosen uniformly at random from [-1, 1].
initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn3.num_weights) - 1)
model3 = TorchConnector(qnn3, initial_weights)
# Define optimizer and loss function
optimizer = LBFGS(model3.parameters())
f_loss = MSELoss(reduction="sum")
# Start training
model3.train() # set model to training mode
# Define objective function
def closure():
optimizer.zero_grad(set_to_none=True) # Initialize gradient
loss = f_loss(model3(Tensor(X)), Tensor(y)) # Compute batch loss
loss.backward() # Backward pass
print(loss.item()) # Print loss
return loss
# Run optimizer
optimizer.step(closure)
# Plot target function
plt.plot(np.linspace(lb, ub), f(np.linspace(lb, ub)), "r--")
# Plot data
plt.plot(X, y, "bo")
# Plot fitted line
y_ = []
for x in np.linspace(lb, ub):
output = model3(Tensor([x]))
y_ += [output.detach().numpy()[0]]
plt.plot(np.linspace(lb, ub), y_, "g-")
plt.show()
# Additional torch-related imports
import torch
from torch import cat, no_grad, manual_seed
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import torch.optim as optim
from torch.nn import (
Module,
Conv2d,
Linear,
Dropout2d,
NLLLoss,
MaxPool2d,
Flatten,
Sequential,
ReLU,
)
import torch.nn.functional as F
# Train Dataset
# -------------
# Set train shuffle seed (for reproducibility)
manual_seed(42)
batch_size = 1
n_samples = 100 # We will concentrate on the first 100 samples
# Use pre-defined torchvision function to load MNIST train data
X_train = datasets.MNIST(
root="./data", train=True, download=True, transform=transforms.Compose([transforms.ToTensor()])
)
# Filter out labels (originally 0-9), leaving only labels 0 and 1
idx = np.append(
np.where(X_train.targets == 0)[0][:n_samples], np.where(X_train.targets == 1)[0][:n_samples]
)
X_train.data = X_train.data[idx]
X_train.targets = X_train.targets[idx]
# Define torch dataloader with filtered data
train_loader = DataLoader(X_train, batch_size=batch_size, shuffle=True)
n_samples_show = 6
data_iter = iter(train_loader)
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
while n_samples_show > 0:
images, targets = data_iter.__next__()
axes[n_samples_show - 1].imshow(images[0, 0].numpy().squeeze(), cmap="gray")
axes[n_samples_show - 1].set_xticks([])
axes[n_samples_show - 1].set_yticks([])
axes[n_samples_show - 1].set_title("Labeled: {}".format(targets[0].item()))
n_samples_show -= 1
# Test Dataset
# -------------
# Set test shuffle seed (for reproducibility)
# manual_seed(5)
n_samples = 50
# Use pre-defined torchvision function to load MNIST test data
X_test = datasets.MNIST(
root="./data", train=False, download=True, transform=transforms.Compose([transforms.ToTensor()])
)
# Filter out labels (originally 0-9), leaving only labels 0 and 1
idx = np.append(
np.where(X_test.targets == 0)[0][:n_samples], np.where(X_test.targets == 1)[0][:n_samples]
)
X_test.data = X_test.data[idx]
X_test.targets = X_test.targets[idx]
# Define torch dataloader with filtered data
test_loader = DataLoader(X_test, batch_size=batch_size, shuffle=True)
# Define and create QNN
def create_qnn():
feature_map = ZZFeatureMap(2)
ansatz = RealAmplitudes(2, reps=1)
qc = QuantumCircuit(2)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
# REMEMBER TO SET input_gradients=True FOR ENABLING HYBRID GRADIENT BACKPROP
qnn = EstimatorQNN(
circuit=qc,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
input_gradients=True,
)
return qnn
qnn4 = create_qnn()
# Define torch NN module
class Net(Module):
def __init__(self, qnn):
super().__init__()
self.conv1 = Conv2d(1, 2, kernel_size=5)
self.conv2 = Conv2d(2, 16, kernel_size=5)
self.dropout = Dropout2d()
self.fc1 = Linear(256, 64)
self.fc2 = Linear(64, 2) # 2-dimensional input to QNN
self.qnn = TorchConnector(qnn) # Apply torch connector, weights chosen
# uniformly at random from interval [-1,1].
self.fc3 = Linear(1, 1) # 1-dimensional output from QNN
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(x.shape[0], -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.qnn(x) # apply QNN
x = self.fc3(x)
return cat((x, 1 - x), -1)
model4 = Net(qnn4)
# Define model, optimizer, and loss function
optimizer = optim.Adam(model4.parameters(), lr=0.001)
loss_func = NLLLoss()
# Start training
epochs = 10 # Set number of epochs
loss_list = [] # Store loss history
model4.train() # Set model to training mode
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad(set_to_none=True) # Initialize gradient
output = model4(data) # Forward pass
loss = loss_func(output, target) # Calculate loss
loss.backward() # Backward pass
optimizer.step() # Optimize weights
total_loss.append(loss.item()) # Store loss
loss_list.append(sum(total_loss) / len(total_loss))
print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1]))
# Plot loss convergence
plt.plot(loss_list)
plt.title("Hybrid NN Training Convergence")
plt.xlabel("Training Iterations")
plt.ylabel("Neg. Log Likelihood Loss")
plt.show()
torch.save(model4.state_dict(), "model4.pt")
qnn5 = create_qnn()
model5 = Net(qnn5)
model5.load_state_dict(torch.load("model4.pt"))
model5.eval() # set model to evaluation mode
with no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model5(data)
if len(output.shape) == 1:
output = output.reshape(1, *output.shape)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print(
"Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%".format(
sum(total_loss) / len(total_loss), correct / len(test_loader) / batch_size * 100
)
)
# Plot predicted labels
n_samples_show = 6
count = 0
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
model5.eval()
with no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
if count == n_samples_show:
break
output = model5(data[0:1])
if len(output.shape) == 1:
output = output.reshape(1, *output.shape)
pred = output.argmax(dim=1, keepdim=True)
axes[count].imshow(data[0].numpy().squeeze(), cmap="gray")
axes[count].set_xticks([])
axes[count].set_yticks([])
axes[count].set_title("Predicted {}".format(pred.item()))
count += 1
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/TheGupta2012/QPE-Algorithms
|
TheGupta2012
|
from qiskit import QuantumCircuit, execute, transpile, Aer
from qiskit.extensions import UnitaryGate,Initialize
from qiskit.tools.visualization import plot_histogram
from qiskit.compiler import assemble
import numpy as np
from time import sleep
from qiskit.tools.monitor import job_monitor
from qiskit.extensions import UnitaryGate
from qiskit.quantum_info import Statevector
import sys
from scipy.stats import unitary_group
import matplotlib.pyplot as plt
class SPEA():
'''
This is a class which implements the Statistical Phase Estimation algorithm
paper1 - https://arxiv.org/pdf/2104.10285.pdf
paper2 - https://arxiv.org/pdf/1906.11401.pdf(discussion)
Attributes :
resolution(int) : the number of intervals the angle range has to be divided into
dims(int) : dimensions of the passed unitary matrix
c_unitary_gate(Unitary Gate) : the controlled unitary gate in our algorithm
error(int) : the number of places after decimal, upto which the cost of the algorithm
would be estimated
itrations(int) : the maximum iterations after which the algorithm ends the computation
basis(list of np.ndarray) : the basis generated at the start of the algorithm
unitary_circuit(QuantumCircuit): a pre-transpiled QuantumCircuit which is applied during
the algorithm
Methods :
__get_basis_vectors(randomize) : Get the d dimensional basis for the initializtion of the algorithm
__get_unitary_circuit(backend) : Get the pre-transpiled circuit for the unitary matrix
__get_alternate_cost(angle,state,backend,shots) : Get the cost through the alternate method specified in the algorithm
__get_standard_cost(angle,state,backend,shots) : Get the cost through the standard method specified in the algorithm
__get_circuit(state,angle,backend,shots) : Get the completed circuit used inside the algorithm to estimate the phase
get_eigen_pair(backend, algo='alternate', theta_left,theta_right,progress, randomize, target_cost, basis, basis_ind,shots) : Get the eigenstate and eigenphase phase for the unitary matrix
'''
def __init__(self, unitary, resolution=50, error=3, max_iters=20):
# handle resolution
if not isinstance(resolution, int):
raise TypeError(
"Please enter the number of intervals as an integer value")
if resolution < 10 or resolution > 1e6:
raise ValueError(
"Resolution needs to be atleast 0.1 and greater than 0.000001")
self.resolution = resolution
# handle unitary
if not isinstance(unitary, np.ndarray) and not isinstance(unitary, QuantumCircuit)\
and not isinstance(unitary, UnitaryGate):
raise TypeError(
"A numpy array or Quantum Circuit or UnitaryGate needs to be passed as the unitary matrix")
# convert circuit to numpy array for uniformity
if isinstance(unitary, UnitaryGate):
U = unitary.to_matrix()
else: # both QC and ndarray type
U = unitary
# note - the unitary here is not just a single qubit unitary
if isinstance(U, np.ndarray):
self.dims = U.shape[0]
else:
self.dims = 2**(U.num_qubits)
if isinstance(U, np.ndarray):
self.c_unitary_gate = UnitaryGate(data=U).control(
num_ctrl_qubits=1, label='CU', ctrl_state='1')
else:
self.c_unitary_gate = U.control(
num_ctrl_qubits=1, label='CU', ctrl_state='1')
# handle error
if not isinstance(error, int):
raise TypeError(
"The allowable error should be provided as an int. Interpreted as 10**(-error)")
if error <= 0:
raise ValueError(
"The error threshold must be finite and greater than 0.")
self.error = error
# handle max_iters
if not isinstance(max_iters, int):
raise TypeError("Max iterations must be of integer type")
if max_iters <= 0 and max_iters > 1e5:
raise ValueError(
"Max iterations should be atleast 1 and less than 1e5")
self.iterations = max_iters
self.basis = []
def __get_basis_vectors(self, randomize=True):
''' Get the d dimensional basis for the unitary provided
Args : randomize (bool) : whether to pick a random basis or
not
Returns:
a list of np.ndarrays which are used as the basis
vectors '''
if randomize == True:
UR = unitary_group.rvs(self.dims)
else:
UR = np.identity(self.dims)
basis = []
for k in UR:
basis.append(np.array(k, dtype=complex))
return basis
def __get_unitary_circuit(self, backend):
'''Return the pretranspiled circuit
Args:
backend : the IBMQBackend on which we want to transpile.
If None, Default : 'qasm_simulator'
Returns: QuantumCircuit containing the transpiled circuit
for the controlled unitary
'''
if backend is None:
backend = Aer.get_backend('qasm_simulator')
qc = QuantumCircuit(1 + int(np.log2(self.dims)))
# make the circuit
qc.h(0)
qc = qc.compose(self.c_unitary_gate, qubits=range(
1+int(np.log2(self.dims))))
qc.barrier()
# RANDOMNESS 1
qc = transpile(qc,backend=backend,optimization_level = 3)
return qc
def __get_circuit(self, state, backend, shots,angle=None):
'''Given an initial state ,
return the assembled and transpiled
circuit that is generated with
inverse rotation
Args:
state(np.ndarray) : The eigenvector guess state for the initialization
backend(IBMQBackend) : the backend on which this circuit is going to be
executed
shots(int) : the number of shots in our experiments
angle(float) : whether the returned circuit contains an inverse rotation
gate or not. If angle is None, no rotation gate attached
Else, cp(angle) is attached on control qubit 0
Returns:
QuantumCircuit which is pre-transpiled according to the backend provided
'''
# all theta values are iterated over for the same state
phi = Initialize(state)
qc1 = QuantumCircuit(1 + int(np.log2(self.dims)), 1)
# initialize the circuit
qc1 = qc1.compose(phi, qubits=list(
range(1, int(np.log2(self.dims))+1)))
qc1.barrier()
# RANDOMNESS 2
qc1 = transpile(qc1, backend=backend,optimization_level=1)
# get the circuit2
qc2 = self.unitary_circuit
qc3 = QuantumCircuit(1 + int(np.log2(self.dims)), 1)
if angle is not None:
# add inverse rotation on the first qubit
qc3.p(-2*np.pi*angle, 0)
# add hadamard
qc3.h(0)
qc3 = transpile(qc3, backend=backend,optimization_level=1)
# make final circuit
qc = qc1 + qc2 + qc3
# measure
qc.measure([0], [0])
return qc
def __get_standard_cost(self, angles, state, backend,shots):
'''Given an initial state and a set of angles,
return the best cost and the associated angle.
Implements the standard method as specified in the paper.
Args :
angles(np.ndarray) : the set of angles on which we execute
the circuits
state(np.ndarray) : the initialization state provided
backend(IBMQBackend): the backend on which this circuit
needs to be executed
shots(int) : the number of shots used to execute this circuit
Returns :
result(dict) : {result : (float), theta : (float)}
result - the best cost given this set of angles
theta - the best theta value amongst this set
of angles'''
result = {'cost': -1, 'theta': -1}
# all theta values are iterated over for the same state
circuits = []
for theta in angles:
qc = self.__get_circuit(state,backend,shots,theta)
circuits.append(qc)
# RANDOMNESS 3
# execute only once...
counts = backend.run(circuits, shots=shots).result().get_counts()
# get the cost for this theta
for k, theta in zip(counts, angles):
# for all experiments you ran
try:
C_val = (k['0'])/shots
except:
C_val = 0
if C_val > result['cost']:
# means this is a better theta value
result['theta'] = theta
result['cost'] = C_val
return result
def __get_alternate_cost(self, angles, state, backend,shots):
'''Given an initial state and a set of angles,
return the best cost and the associated angle.
Implements the alternate method as specified in the paper1
and discussion of paper2.
Args :
angles(np.ndarray) : the set of angles on which we execute
the circuits
state(np.ndarray) : the initialization state provided
backend(IBMQBackend): the backend on which this circuit
needs to be executed
shots(int) : the number of shots used to execute this circuit
Returns :
result(dict) : {result : (float), theta : (float)}
result - the best cost given this set of angles
theta - the best theta value amongst this set
of angles'''
result = {'cost': -1, 'theta': -1}
# all theta values are iterated over for the same state
qc = self.__get_circuit(state,backend,shots)
# execute only once...
counts = backend.run(qc, shots=shots).result().get_counts()
# generate experimental probabilities
try:
p0 = counts['0']/shots
except:
p0 = 0
try:
p1 = counts['1']/shots
except:
p1 = 0
# now, find the best theta as specified by the
# alternate method classically
min_s = 1e5
for theta in angles:
# generate theoretical probabilities
c0 = (np.cos(np.pi*theta))**2
c1 = 1 - c0
# generate s value
s = (p0-c0)**2 + (p1-c1)**2
if s < min_s:
result['theta'] = theta
min_s = s
# now , we have the best theta stored in phi
# run circuit once again to get the value of C*
# RANDOMNESS 4
qc = self.__get_circuit(state, backend, shots, result['theta'])
counts = backend.run(qc, shots=shots).result().get_counts()
try:
result['cost'] = counts['0']/shots
except:
result['cost'] = 0
# no 0 counts present
# return the result
return result
def get_eigen_pair(self, backend, algo='alternate', theta_left = 0,theta_right = 1,progress=False, randomize=True, target_cost=None, basis = None, basis_ind = None,shots=512):
'''Finding the eigenstate pair for the unitary
Args :
backend(IBMQBackend) : the backend on which the circuit needs to be executed
algo(str) : ['alternate','standard'] the algorithm to use as specified in the
paper1 section 3.
theta_left(float): the left bound for the search of eigenvalue. Default : 0
theta_right(float): the right bound for the search of eigenvalue. Default : 1
progress(bool) : Whether to show the progress as the algorithm runs
randomize(bool): Whether to choose random initialization of basis states or not
If False, computational basis is chosen.
target_cost(float) : the min cost required to be achieved by the algorithm
basis(list of np.ndarray) : The basis to be used in the algorithm.
Note, if basis is specified, randomize value is ignored
basis_ind(int) : the index of the basis vector to be used as the initial state
vector
Returns :
result(dict) : {cost :(float), theta :(float), state : (np.ndarray)
cost - the cost with which the algorithm terminates
theta - the eigenvalue estimated by SPEA
state - the eigenvector estimated by SPEA
'''
# handle algorithm...
self.unitary_circuit = self.__get_unitary_circuit(backend)
if(theta_left > theta_right):
raise ValueError("Left bound for theta should be smaller than the right bound")
elif (theta_left<0) or (theta_right>1):
raise ValueError("Bounds of theta are [0,1].")
if not isinstance(algo, str):
raise TypeError(
"Algorithm must be mentioned as a string from the values {alternate,standard}")
elif algo not in ['alternate', 'standard']:
raise ValueError(
"Algorithm must be specified as 'alternate' or 'standard' ")
if not isinstance(progress, bool):
raise TypeError("Progress must be a boolean variable")
if not isinstance(randomize, bool):
raise Exception("Randomize must be a boolean variable")
if target_cost is not None:
if not isinstance(target_cost, float):
raise TypeError("Target cost must be a float")
if (target_cost <= 0 or target_cost >= 1):
raise ValueError(
"Target cost must be a float value between 0 and 1")
results = dict()
# first initialize the state phi
if basis is None:
self.basis = self.__get_basis_vectors(randomize)
else:
# is basis is specified, given as array of vectors...
self.basis = basis
# choose a random index
if basis_ind is None:
ind = np.random.choice(self.dims)
else:
# choose the index given in that basis
ind = basis_ind
phi = self.basis[ind]
# doing the method 1 of our algorithm
# define resolution of angles and precision
if target_cost == None:
precision = 1/10**self.error
else:
precision = 1 - target_cost
samples = self.resolution
# initialization of range
left, right = theta_left, theta_right
# generate the angles
angles = np.linspace(left, right, samples)
# iterate once
if algo == 'alternate':
result = self.__get_alternate_cost(angles, phi, backend,shots)
else:
result = self.__get_standard_cost(angles, phi, backend,shots)
# get initial estimates
cost = min(1,result['cost'])
theta_max = result['theta']
best_phi = phi
# the range upto which theta extends iin each iteration
angle_range = (right - left)/2
# a parameter
a = 1
# start algorithm
iters = 0
found = True
while 1 - cost >= precision:
# get angles, note if theta didn't change, then we need to
# again generate the same range again
right = min(theta_right, theta_max + angle_range/2)
left = max(theta_left, theta_max - angle_range/2)
if progress:
print("Right :", right)
print("Left :", left)
# generate the angles only if the theta has been updated
if found == True:
angles = np.linspace(left, right, samples)
found = False # for this iteration
if progress:
print("ITERATION NUMBER", iters+1, "...")
for i in range((2*self.dims)):
# everyone is supplied with the same range of theta in one iteration
# define z
if i < self.dims:
z = 1
else:
z = 1j
# alter and normalise phi
curr_phi = best_phi + z*a*(1 - cost)*self.basis[i % self.dims]
curr_phi = curr_phi / np.linalg.norm(curr_phi)
# iterate (angles would be same until theta is changed)
if algo == 'alternate':
res = self.__get_alternate_cost(angles, curr_phi, backend,shots)
else:
res = self.__get_standard_cost(angles, curr_phi, backend,shots)
curr_cost = res['cost']
curr_theta = res['theta']
# at this point I have the best Cost for the state PHI and the
if curr_cost > cost:
theta_max = float(curr_theta)
cost = min(1.0,float(curr_cost))
best_phi = curr_phi
found = True
if progress:
sys.stdout.write('\r')
sys.stdout.write("%f %%completed" %
(100*(i+1)/(2*self.dims)))
sys.stdout.flush()
# iteration completes
if found == False:
# phi was not updated , change a
a = a/2
if progress:
print("\nNo change, updating a...")
else:
angle_range /= 2 # updated phi and thus theta too -> refine theta range
iters += 1
if progress:
print("\nCOST :", cost)
print("THETA :", theta_max)
if iters >= self.iterations:
print(
"Maximum iterations reached for the estimation.\nTerminating algorithm...")
break
# add the warning that iters maxed out
# add cost, eigenvector and theta to the dict
results['cost'] = cost
results['theta'] = theta_max
results['state'] = best_phi
return results
|
https://github.com/abbarreto/qiskit4
|
abbarreto
| |
https://github.com/Harshithan07/Quantum-Computing-using-Qiskit-SDK
|
Harshithan07
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram
%matplotlib inline
secretnumber = '11100011'
circuit = QuantumCircuit(len(secretnumber)+1,len(secretnumber))
circuit.h(range(len(secretnumber)))
circuit.x(len(secretnumber))
circuit.h(len(secretnumber))
circuit.barrier()
for ii, yesno in enumerate(reversed(secretnumber)):
if yesno == '1':
circuit.cx(ii,len(secretnumber))
circuit.barrier()
circuit.h(range(len(secretnumber)))
circuit.barrier()
circuit.measure(range(len(secretnumber)),range(len(secretnumber)))
circuit.draw(output = 'mpl')
|
https://github.com/arnavdas88/QuGlassyIsing
|
arnavdas88
|
!pip install qiskit
!git clone https://github.com/arnavdas88/QuGlassyIsing
!mv QuGlassyIsing/research/pickle-files/ ./pickle
from qiskit.providers.aer import QasmSimulator
from qiskit.providers.aer import AerSimulator
from qiskit import Aer, transpile
from qiskit.circuit.library import TwoLocal
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import EfficientSU2
# opflow is Qiskit's module for creating operators like yours
from qiskit import *
from qiskit.opflow import OperatorBase
from qiskit.opflow import Z, X, I # Pauli Z, X matrices and identity
import pylab
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
import os
import pickle
file_list = []
for dirlist in os.walk('./pickle'):
base, dir, files = dirlist
if 'j=1' in base:
for f in files:
file_list += [os.path.join(base, f)]
print(file_list)
print("Loading Optimization History")
counts_values = {}
for f in file_list:
with open(f, 'rb') as handle:
counts_values[f] = pickle.load(handle)
list(counts_values.values())[0]
tempdata = [ v for v in counts_values.values() ]
def flatten(x): return sum(x, [])
def build_graph_data(x):
sqrt = len(x)**(float(1)/2)
sqrt = int(sqrt)
if not sqrt**2 == len(x):
raise Exception("not able to form a square")
result = []
xa = np.asarray([float(i) for i in x])
return xa.reshape((sqrt, sqrt)), x
import numpy as np
import seaborn as sns
import matplotlib.pylab as plt
def draw_graph(x, t):
plt.figure(figsize=(7, 7))
plt.title(t, pad=6.2, fontsize=18, wrap=True)
plt.imshow(x, cmap='copper', interpolation='nearest', aspect='auto')
# plt.xticks(X, X/10, label="Bx", rotation=90, fontsize=16)
# plt.xlabel('Bx →', fontsize=24)
# plt.yticks(Y, label="Bz", fontsize=16)
# plt.ylabel('Bz →', fontsize=24)
# plt.colorbar()
# plt.savefig("Heatmap representing the change of `Minimum Ground State Energy` in Bx vs Bz.png", bbox_inches='tight', dpi=1080)
plt.show()
def build_graph_data_from_list(x):
for i in x:
p, t = build_graph_data(i)
draw_graph(p, t)
import numpy as np
import seaborn as sns
import matplotlib.pylab as plt
from qiskit.visualization import plot_histogram
def show_counts_data_1st(tempdata_i, max_val = 0):
arr = tempdata_i['vqe_result']
arr = arr['eigenstate']
data = np.asarray(arr)
# print(list(arr.keys()))
arr = {a: arr[a] for a in arr if arr[a] == max(list(arr.values()))}
# return plot_histogram(arr)
return arr
# return len(list(arr.keys()))
# return data
de = { k: show_counts_data_2nd(v) for k, v in counts_values.items() if not "AF1" in k }
for k, e in de.items():
print(k)
build_graph_data_from_list(list(e.keys()))
import numpy as np
import seaborn as sns
import matplotlib.pylab as plt
from qiskit.visualization import plot_histogram
def max_2nd(x):
x.remove(max(x))
return max(x)
def show_counts_data_2nd(tempdata_i, max_val = 0):
arr = tempdata_i['vqe_result']
arr = arr['eigenstate']
data = np.asarray(arr)
# print(list(arr.keys()))
arr = {a: arr[a] for a in arr if arr[a] == max_2nd(list(arr.values()))}
# return plot_histogram(arr)
return arr
# return len(list(arr.keys()))
# return data
de = { k: show_counts_data_2nd(v) for k, v in counts_values.items() if not "AF1" in k }
for k, e in de.items():
print(k)
build_graph_data_from_list(list(e.keys()))
def max_3rd(x):
x.remove(max(x))
x.remove(max(x))
return max(x)
def show_counts_data_3rd(tempdata_i, max_val = 0):
arr = tempdata_i['vqe_result']
arr = arr['eigenstate']
data = np.asarray(arr)
# print(list(arr.keys()))
arr = {a: arr[a] for a in arr if arr[a] == max_3rd(list(arr.values()))}
# return plot_histogram(arr)
return arr
de = { k: show_counts_data_3rd(v) for k, v in counts_values.items() if not "AF1" in k }
for k, e in de.items():
print(k)
build_graph_data_from_list(list(e.keys()))
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import pi
# the angle of rotation
theta = pi/16
# we read streams of length 8, 16, 24, 32, 40, 48, 56, 64
for i in [8, 16, 24, 32, 40, 48, 56, 64]:
# quantum circuit with one qubit and one bit
qreg = QuantumRegister(1)
creg = ClassicalRegister(1)
mycircuit = QuantumCircuit(qreg,creg)
# the stream of length i
for j in range(i):
mycircuit.ry(2*theta,qreg[0]) # apply one rotation for each symbol
# we measure after reading the whole stream
mycircuit.measure(qreg[0],creg[0])
# execute the circuit 100 times
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(mycircuit)
d = i /8
if d % 2 == 0: print(i,"is even multiple of 8")
else: print(i,"is odd multiple of 8")
print("stream of lenght",i,"->",counts)
print()
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import pi
from random import randrange
# the angle of rotation
r = randrange(1,11)
print("the picked angle is",r,"times of 2pi/11")
print()
theta = r*2*pi/11
# we read streams of length from 1 to 11
for i in range(1,12):
# quantum circuit with one qubit and one bit
qreg = QuantumRegister(1)
creg = ClassicalRegister(1)
mycircuit = QuantumCircuit(qreg,creg)
# the stream of length i
for j in range(i):
mycircuit.ry(2*theta,qreg[0]) # apply one rotation for each symbol
# we measure after reading the whole stream
mycircuit.measure(qreg[0],creg[0])
# execute the circuit 1000 times
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1000)
counts = job.result().get_counts(mycircuit)
print("stream of lenght",i,"->",counts)
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import pi
from random import randrange
# for each stream of length from 1 to 10
for i in range(1,11):
# we try each angle of the form k*2*pi/11 for k=1,...,10
# we try to find the best k for which we observe 1 the most
number_of_one_state = 0
best_k = 1
all_outcomes_for_i = "length "+str(i)+"-> "
for k in range(1,11):
theta = k*2*pi/11
# quantum circuit with one qubit and one bit
qreg = QuantumRegister(1)
creg = ClassicalRegister(1)
mycircuit = QuantumCircuit(qreg,creg)
# the stream of length i
for j in range(i):
mycircuit.ry(2*theta,qreg[0]) # apply one rotation for each symbol
# we measure after reading the whole stream
mycircuit.measure(qreg[0],creg[0])
# execute the circuit 10000 times
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=10000)
counts = job.result().get_counts(mycircuit)
all_outcomes_for_i = all_outcomes_for_i + str(k)+ ":" + str(counts['1']) + " "
if int(counts['1']) > number_of_one_state:
number_of_one_state = counts['1']
best_k = k
print(all_outcomes_for_i)
print("for length",i,", the best k is",best_k)
print()
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import pi
from random import randrange
# the angles of rotations
theta1 = 3*2*pi/31
theta2 = 7*2*pi/31
theta3 = 11*2*pi/31
# we read streams of length from 1 to 30
for i in range(1,31):
# quantum circuit with three qubits and three bits
qreg = QuantumRegister(3)
creg = ClassicalRegister(3)
mycircuit = QuantumCircuit(qreg,creg)
# the stream of length i
for j in range(i):
# apply rotations for each symbol
mycircuit.ry(2*theta1,qreg[0])
mycircuit.ry(2*theta2,qreg[1])
mycircuit.ry(2*theta3,qreg[2])
# we measure after reading the whole stream
mycircuit.measure(qreg,creg)
# execute the circuit N times
N = 1000
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=N)
counts = job.result().get_counts(mycircuit)
print(counts)
if '000' in counts.keys():
c = counts['000']
else:
c = 0
print('000 is observed',c,'times out of',N)
percentange = round(c/N*100,1)
print("the ratio of 000 is ",percentange,"%")
print()
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import pi
from random import randrange
# randomly picked angles of rotations
k1 = randrange(1,31)
theta1 = k1*2*pi/31
k2 = randrange(1,31)
theta2 = k2*2*pi/31
k3 = randrange(1,31)
theta3 = k3*2*pi/31
print("k1 =",k1,"k2 =",k2,"k3 =",k3)
print()
max_percentange = 0
# we read streams of length from 1 to 30
for i in range(1,31):
k1 = randrange(1,31)
theta1 = k1*2*pi/31
k2 = randrange(1,31)
theta2 = k2*2*pi/31
k3 = randrange(1,31)
theta3 = k3*2*pi/31
# quantum circuit with three qubits and three bits
qreg = QuantumRegister(3)
creg = ClassicalRegister(3)
mycircuit = QuantumCircuit(qreg,creg)
# the stream of length i
for j in range(i):
# apply rotations for each symbol
mycircuit.ry(2*theta1,qreg[0])
mycircuit.ry(2*theta2,qreg[1])
mycircuit.ry(2*theta3,qreg[2])
# we measure after reading the whole stream
mycircuit.measure(qreg,creg)
# execute the circuit N times
N = 1000
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=N)
counts = job.result().get_counts(mycircuit)
# print(counts)
if '000' in counts.keys():
c = counts['000']
else:
c = 0
# print('000 is observed',c,'times out of',N)
percentange = round(c/N*100,1)
if max_percentange < percentange: max_percentange = percentange
# print("the ration of 000 is ",percentange,"%")
# print()
print("max percentage is",max_percentange)
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import pi
from random import randrange
number_of_qubits = 4
#number_of_qubits = 5
# randomly picked angles of rotations
theta = []
for i in range(number_of_qubits):
k = randrange(1,31)
print("k",str(i),"=",k)
theta += [k*2*pi/31]
# print(theta)
# we count the number of zeros
zeros = ''
for i in range(number_of_qubits):
zeros = zeros + '0'
print("zeros = ",zeros)
print()
max_percentange = 0
# we read streams of length from 1 to 30
for i in range(1,31):
# quantum circuit with qubits and bits
qreg = QuantumRegister(number_of_qubits)
creg = ClassicalRegister(number_of_qubits)
mycircuit = QuantumCircuit(qreg,creg)
# the stream of length i
for j in range(i):
# apply rotations for each symbol
for k in range(number_of_qubits):
mycircuit.ry(2*theta[k],qreg[k])
# we measure after reading the whole stream
mycircuit.measure(qreg,creg)
# execute the circuit N times
N = 1000
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=N)
counts = job.result().get_counts(mycircuit)
# print(counts)
if zeros in counts.keys():
c = counts[zeros]
else:
c = 0
# print('000 is observed',c,'times out of',N)
percentange = round(c/N*100,1)
if max_percentange < percentange: max_percentange = percentange
# print("the ration of 000 is ",percentange,"%")
# print()
print("max percentage is",max_percentange)
|
https://github.com/qBraid/qBraid
|
qBraid
|
from qiskit import *
from oracle_generation import generate_oracle
get_bin = lambda x, n: format(x, 'b').zfill(n)
def gen_circuits(min,max,size):
circuits = []
secrets = []
ORACLE_SIZE = size
for i in range(min,max+1):
cur_str = get_bin(i,ORACLE_SIZE-1)
(circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str)
circuits.append(circuit)
secrets.append(secret)
return (circuits, secrets)
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("./")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="lq")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors)
print("created zne_qcs (length:", len(zne_qcs), ")")
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
# print("provider:", provider)
# backend = provider.get_backend("ibmq_jakarta")
shots = 1 << 13
reps = 1 # unused
# Number of trotter steps
print("trotter step: ", num_steps)
# execute: reps = 1
job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた?
print('Job ID', job.job_id())
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results)
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fidelity = state_fidelity(rho, target_state)
print(fidelity)
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
number = 5 # integer
real = -3.4 # float
name = 'Asja' # string
surname = "Sarkana" # string
boolean1 = True # Boolean
boolean2 = False # Boolean
a = 13
b = 5
print("a =",a)
print("b =",b)
print()
# basics operators
print("a + b =",a+b)
print("a - b =",a-b)
print("a * b =",a*b)
print("a / b =",a/b)
a = 13
b = 5
print("a =",a)
print("b =",b)
print()
print("integer division:")
print("a//b =",a//b)
print("modulus operator:")
print("a mod b =",a % b)
b = 5
print("b =",b)
print()
print("b*b =",b**2)
print("b*b*b =",b**3)
print("sqrt(b)=",b**0.5)
# list
mylist = [10,8,6,4,2]
print(mylist)
# tuple
mytuple=(1,4,5,'Asja')
print(mytuple)
# dictionary
mydictionary = {
'name' : "Asja",
'surname':'Sarkane',
'age': 23
}
print(mydictionary)
print(mydictionary['surname'])
# list of the other objects or variables
list_of_other_objects =[
mylist,
mytuple,
3,
"Asja",
mydictionary
]
print(list_of_other_objects)
# length of a string
print(len("Asja Sarkane"))
# size of a list
print(len([1,2,3,4]))
# size of a dictionary
mydictionary = { 'name' : "Asja", 'surname':'Sarkane', 'age': 23}
print(len(mydictionary))
i = 10
while i>0: # while condition(s):
print(i)
i = i - 1
for i in range(10): # i is in [0,1,...,9]
print(i)
for i in range(-5,6): # i is in [-5,-4,...,0,...,4,5]
print(i)
for i in range(0,23,4): # i is in [0,4,8,12,16,20]
print(i)
for i in [3,8,-5,11]:
print(i)
for i in "Sarkane":
print(i)
# dictionary
mydictionary = {
'name' : "Asja",
'surname':'Sarkane',
'age': 23,
}
for key in mydictionary:
print("key is",key,"and its value is",mydictionary[key])
for a in range(4,7):
# if condition(s)
if a<5:
print(a,"is less than 5")
# elif conditions(s)
elif a==5:
print(a,"is equal to 5")
# else
else:
print(a,"is greater than 5")
# Logical operator "and"
i = -3
j = 4
if i<0 and j > 0:
print(i,"is negative AND",j,"is positive")
# Logical operator "or"
i = -2
j = 2
if i==2 or j == 2:
print("i OR j is 2: (",i,",",j,")")
# Logical operator "not"
i = 3
if not (i==2):
print(i,"is NOT equal to 2")
# Operator "equal to"
i = -1
if i == -1:
print(i,"is EQUAL TO -1")
# Operator "not equal to"
i = 4
if i != 3:
print(i,"is NOT EQUAL TO 3")
# Operator "not equal to"
i = 2
if i <= 5:
print(i,"is LESS THAN OR EQUAL TO 5")
# Operator "not equal to"
i = 5
if i >= 1:
print(i,"is GREATER THAN OR EQUAL TO 3")
A =[
[1,2,3],
[-2,-4,-6],
[3,6,9]
]
# print all
print(A)
print()
# print each list in a new line
for list in A:
print(list)
list1 = [1,2,3]
list2 = [4,5,6]
#concatenation of two lists
list3 = list1 + list2
print(list3)
list4 = list2 + list1
print(list4)
list = [0,1,2]
list.append(3)
print(list)
list = list + [4]
print(list)
def summation_of_integers(n):
summation = 0
for integer in range(n+1):
summation = summation + integer
return summation
print(summation_of_integers(10))
print(summation_of_integers(20))
from random import randrange
print(randrange(10),"is picked randomly between 0 and 9")
print(randrange(-9,10),"is picked randomly between -9 and 9")
print(randrange(0,20,3),"is picked randomly from the list [0,3,6,9,12,15,18]")
|
https://github.com/ritamsarmah/cs239
|
ritamsarmah
|
"""Qiskit code for running Simon's algorithm on quantum hardware for 2 qubits and b = '11' """
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, execute
# import basic plot tools
from qiskit.visualization import plot_histogram
from qiskit_textbook.tools import simon_oracle
#set b equal to '11'
b = '11'
#1) initialize qubits
n = 2
simon_circuit_2 = QuantumCircuit(n*2, n)
#2) Apply Hadamard gates before querying the oracle
simon_circuit_2.h(range(n))
#3) Query oracle
simon_circuit_2 += simon_oracle(b)
#5) Apply Hadamard gates to the input register
simon_circuit_2.h(range(n))
#3) and 6) Measure qubits
simon_circuit_2.measure(range(n), range(n))
# Load saved IBMQ accounts and get the least busy backend device
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= n and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Execute and monitor the job
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(simon_circuit_2, backend=backend, shots=shots, optimization_level=3)
job_monitor(job, interval = 2)
# Get results and plot counts
device_counts = job.result().get_counts()
plot_histogram(device_counts)
#additionally, function for calculating dot product of results
def bdotz(b, z):
accum = 0
for i in range(len(b)):
accum += int(b[i]) * int(z[i])
return (accum % 2)
print('b = ' + b)
for z in device_counts:
print( '{}.{} = {} (mod 2) ({:.1f}%)'.format(b, z, bdotz(b,z), device_counts[z]*100/shots))
#the most significant results are those for which b dot z=0(mod 2).
'''b = 11
11.00 = 0 (mod 2) (45.0%)
11.01 = 1 (mod 2) (6.2%)
11.10 = 1 (mod 2) (6.4%)
11.11 = 0 (mod 2) (42.4%)'''
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
# Build a quantum circuit
n = 3 # number of qubits
q = QuantumRegister(n)
c = ClassicalRegister(n)
circuit = QuantumCircuit(q, c)
circuit.x(q[1])
circuit.h(q)
circuit.cx(q[0], q[1])
circuit.measure(q, c);
print(circuit)
circuit.draw()
# Matplotlib Drawing
circuit.draw(output='mpl')
# Latex Drawing
circuit.draw(output='latex')
# Draw a new circuit with barriers and more registers
q_a = QuantumRegister(3, name='qa')
q_b = QuantumRegister(5, name='qb')
c_a = ClassicalRegister(3)
c_b = ClassicalRegister(5)
circuit = QuantumCircuit(q_a, q_b, c_a, c_b)
circuit.x(q_a[1])
circuit.x(q_b[1])
circuit.x(q_b[2])
circuit.x(q_b[4])
circuit.barrier()
circuit.h(q_a)
circuit.barrier(q_a)
circuit.h(q_b)
circuit.cswap(q_b[0], q_b[1], q_b[2])
circuit.cswap(q_b[2], q_b[3], q_b[4])
circuit.cswap(q_b[3], q_b[4], q_b[0])
circuit.barrier(q_b)
circuit.measure(q_a, c_a)
circuit.measure(q_b, c_b);
# Draw the circuit
circuit.draw(output='latex')
# Draw the circuit with reversed bit order
circuit.draw(output='latex', reverse_bits=True)
# Draw the circuit without barriers
circuit.draw(output='latex', plot_barriers=False)
# Draw the circuit without barriers and reverse bit order
circuit.draw(output='latex', plot_barriers=False, reverse_bits=True)
# Set line length to 80 for above circuit
circuit.draw(output='text', line_length=80)
# Change the background color in mpl
style = {'backgroundcolor': 'lightgreen'}
circuit.draw(output='mpl', style=style)
# Scale the mpl output to 1/2 the normal size
circuit.draw(output='mpl', scale=0.5)
# Scale the latex output to 1/2 the normal size
circuit.draw(output='latex', scale=0.5)
# Print the latex source for the visualization
print(circuit.draw(output='latex_source'))
# Save the latex source to a file
circuit.draw(output='latex_source', filename='/tmp/circuit.tex');
from qiskit.tools.visualization import circuit_drawer
circuit_drawer(circuit, output='mpl', plot_barriers=False)
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
import pickle
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
def trotter_gate(dt, to_instruction = True):
qc = QuantumCircuit(2)
qc.rx(2*dt,0)
qc.rz(2*dt,1)
qc.h(1)
qc.cx(1,0)
qc.rz(-2*dt, 0)
qc.rx(-2*dt, 1)
qc.rz(2*dt, 1)
qc.cx(1,0)
qc.h(1)
qc.rz(2*dt, 0)
return qc.to_instruction() if to_instruction else qc
trotter_gate(np.pi / 6, to_instruction=False).draw("mpl")
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
Trot_gate = trotter_gate(dt)
# Number of trotter steps
trotter_steps = 15 ### CAN BE >= 4
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(7)
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
qc.x([5]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Simulate time evolution under H_heis3 Hamiltonian
for _ in range(trotter_steps):
qc.append(Trot_gate, [qr[3], qr[5]])
qc.cx(qr[3], qr[1])
qc.cx(qr[5], qr[3])
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time/trotter_steps})
t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_qc = transpile(t3_qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(t3_qc, [qr[1], qr[3], qr[5]])
# Display circuit for confirmation
# st_qcs[-1].decompose().draw() # view decomposition of trotter gates
st_qcs[-1].draw("mpl") # only view trotter gates
# from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
shots = 8192
reps = 8
jobs = []
for _ in range(reps):
# execute
job = execute(st_qcs, backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=[5,3,1])
print('Job ID', cal_job.job_id())
dt_now = datetime.datetime.now()
print(dt_now)
with open("jobs_jakarta_15step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open("job_ids_jakarta_15step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
filename = "job_ids_jakarta_15step_20220412_031437_.pkl" # change here
with open(filename, "rb") as f:
job_ids_dict = pickle.load(f)
job_ids = job_ids_dict["job_ids"]
cal_job_id = job_ids_dict["cal_job_id"]
retrieved_jobs = []
for job_id in job_ids:
retrieved_jobs.append(backend.retrieve_job(job_id))
retrieved_cal_job = backend.retrieve_job(cal_job_id)
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
# set the target state
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
# mit_results = meas_fitter.filter.apply(job.result()) # apply QREM
rho = StateTomographyFitter(job.result(), st_qcs).fit(method='lstsq')
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import HGate
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.h(1)
custom = qc1.to_gate().control(2)
qc2 = QuantumCircuit(4)
qc2.append(custom, [0, 3, 1, 2])
qc2.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
# You can reverse the order of the qubits.
from qiskit.quantum_info import DensityMatrix
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.t(1)
qc.s(0)
qc.cx(0,1)
matrix = DensityMatrix(qc)
plot_bloch_multivector(matrix, title='My Bloch Spheres', reverse_bits=True)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(range(2))
qc.measure(range(2), range(2))
# apply x gate if the classical register has the value 2 (10 in binary)
qc.x(0).c_if(cr, 2)
# apply y gate if bit 0 is set to 1
qc.y(1).c_if(0, 1)
qc.draw('mpl')
|
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
"""
Bernstein-Vazirani 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 = "Bernstein-Vazirani"
np.random.seed(0)
verbose = False
# Variable for number of resets to perform after mid circuit measurements
num_resets = 1
# saved circuits for display
QC_ = None
Uf_ = None
############### Circuit Definition
def create_oracle(num_qubits, input_size, secret_int):
# Initialize first n qubits and single ancilla qubit
qr = QuantumRegister(num_qubits)
qc = QuantumCircuit(qr, name=f"Uf")
# perform CX for each qubit that matches a bit in secret string
s = ('{0:0' + str(input_size) + 'b}').format(secret_int)
for i_qubit in range(input_size):
if s[input_size - 1 - i_qubit] == '1':
qc.cx(qr[i_qubit], qr[input_size])
return qc
def BersteinVazirani (num_qubits, secret_int, method = 1):
# size of input is one less than available qubits
input_size = num_qubits - 1
if method == 1:
# allocate qubits
qr = QuantumRegister(num_qubits); cr = ClassicalRegister(input_size);
qc = QuantumCircuit(qr, cr, name=f"bv({method})-{num_qubits}-{secret_int}")
# put ancilla in |1> state
qc.x(qr[input_size])
# start with Hadamard on all qubits, including ancilla
for i_qubit in range(num_qubits):
qc.h(qr[i_qubit])
qc.barrier()
#generate Uf oracle
Uf = create_oracle(num_qubits, input_size, secret_int)
qc.append(Uf,qr)
qc.barrier()
# start with Hadamard on all qubits, including ancilla
for i_qubit in range(num_qubits):
qc.h(qr[i_qubit])
# uncompute ancilla qubit, not necessary for algorithm
qc.x(qr[input_size])
qc.barrier()
# measure all data qubits
for i in range(input_size):
qc.measure(i, i)
global Uf_
if Uf_ == None or num_qubits <= 6:
if num_qubits < 9: Uf_ = Uf
elif method == 2:
# allocate qubits
qr = QuantumRegister(2); cr = ClassicalRegister(input_size); qc = QuantumCircuit(qr, cr, name="main")
# put ancilla in |-> state
qc.x(qr[1])
qc.h(qr[1])
qc.barrier()
# perform CX for each qubit that matches a bit in secret string
s = ('{0:0' + str(input_size) + 'b}').format(secret_int)
for i in range(input_size):
if s[input_size - 1 - i] == '1':
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.h(qr[0])
qc.measure(qr[0], cr[i])
# Perform num_resets reset operations
qc.reset([0]*num_resets)
# save smaller circuit example for display
global QC_
if QC_ == None or num_qubits <= 6:
if num_qubits < 9: QC_ = qc
# return a handle on the circuit
return qc
############### Result Data 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, secret_int, num_shots):
# size of input is one less than available qubits
input_size = num_qubits - 1
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
if verbose: print(f"For secret int {secret_int} measured: {probs}")
# create the key that is expected to have all the measurements (for this circuit)
key = format(secret_int, f"0{input_size}b")
# correct distribution is measuring the key 100% of the time
correct_dist = {key: 1.0}
# use our polarization fidelity rescaling
fidelity = metrics.polarization_fidelity(probs, correct_dist)
return probs, fidelity
################ Benchmark Loop
# Execute program with default parameters
def run (min_qubits=3, max_qubits=8, skip_qubits=1, max_circuits=3, num_shots=100,
backend_id='dm_simulator', method = 1, provider_backend=None,
# hub="ibm-q", group="open", project="main",
exec_options=None, context=None):
print(f"{benchmark_name} ({method}) Benchmark Program - QSim")
# validate parameters (smallest circuit is 3 qubits)
max_qubits = max(3, max_qubits)
min_qubits = min(max(3, 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} ({method}) Benchmark"
##########
# Variable for new qubit group ordering if using mid_circuit measurements
mid_circuit_qubit_group = []
# If using mid_circuit measurements, set transform qubit group to true
transform_qubit_group = True if method ==2 else False
# 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)
counts, 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)
# for noiseless simulation, set noise model to be None
# ex.set_noise_model(None)
##########
# 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):
input_size = num_qubits - 1
# determine number of circuits to execute for this group
num_circuits = min(2**(input_size), max_circuits)
print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}")
# determine range of secret strings to loop over
if 2**(input_size) <= max_circuits:
s_range = list(range(num_circuits))
else:
s_range = np.random.choice(2**(input_size), num_circuits, False)
# loop over limited # of secret strings for this
for s_int in s_range:
# If mid circuit, then add 2 to new qubit group since the circuit only uses 2 qubits
if method == 2:
mid_circuit_qubit_group.append(2)
# create the circuit for given qubit size and secret string, store time metric
ts = time.time()
qc = BersteinVazirani(num_qubits, s_int, method).reverse_bits() # reverse_bits() is to change the endianness
print(qc)
metrics.store_metric(num_qubits, s_int, 'create_time', time.time()-ts)
# collapse the sub-circuit levels 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, shots=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
print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!")
if method == 1: print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!")
# Plot metrics for all circuit sizes
metrics.plot_metrics(f"Benchmark Results - {benchmark_name} ({method}) - QSim",
transform_qubit_group = transform_qubit_group, new_qubit_group = mid_circuit_qubit_group)
# if main, execute method
if __name__ == '__main__': run()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Depth pass testing"""
import unittest
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.passes import CountOpsLongestPath
from qiskit.test import QiskitTestCase
class TestCountOpsLongestPathPass(QiskitTestCase):
"""Tests for CountOpsLongestPath analysis methods."""
def test_empty_dag(self):
"""Empty DAG has empty counts."""
circuit = QuantumCircuit()
dag = circuit_to_dag(circuit)
pass_ = CountOpsLongestPath()
_ = pass_.run(dag)
self.assertDictEqual(pass_.property_set["count_ops_longest_path"], {})
def test_just_qubits(self):
"""A dag with 9 operations (3 CXs, 2Xs, 2Ys and 2 Hs) on the longest
path
"""
# ┌───┐┌───┐┌───┐
# q0_0: ──■──┤ X ├┤ Y ├┤ H ├──■───────────────────■──
# ┌─┴─┐└───┘└───┘└───┘┌─┴─┐┌───┐┌───┐┌───┐┌─┴─┐
# q0_1: ┤ X ├───────────────┤ X ├┤ X ├┤ Y ├┤ H ├┤ X ├
# └───┘ └───┘└───┘└───┘└───┘└───┘
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.x(qr[0])
circuit.y(qr[0])
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.x(qr[1])
circuit.y(qr[1])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
pass_ = CountOpsLongestPath()
_ = pass_.run(dag)
count_ops = pass_.property_set["count_ops_longest_path"]
self.assertDictEqual(count_ops, {"cx": 3, "x": 2, "y": 2, "h": 2})
if __name__ == "__main__":
unittest.main()
|
https://github.com/bayesian-randomized-benchmarking/qiskit-advocates-bayes-RB
|
bayesian-randomized-benchmarking
|
#Import general libraries (needed for functions)
import numpy as np
import matplotlib.pyplot as plt
from IPython import display
#Import Qiskit classes
import qiskit
from qiskit.tools.monitor import job_monitor
from qiskit import Aer
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors.standard_errors import depolarizing_error, thermal_relaxation_error
from qiskit import QuantumRegister, QuantumCircuit
#Import the RB Functions
import qiskit.ignis.verification.randomized_benchmarking as rb
import copy
import time
# import the bayesian packages
import pymc3 as pm
import arviz as az
from scipy.optimize import curve_fit
def obtain_priors_and_data_from_fitter(rbfit, nCliffs, shots, printout = True):
m_gates = copy.deepcopy(nCliffs)
# We choose the count matrix corresponding to 2 Qubit RB
Y = (np.array(rbfit._raw_data[0])*shots).astype(int)
# alpha prior and bounds
alpha_ref = rbfit._fit[0]['params'][1]
#alpha_lower = alpha_ref - 6*rbfit._fit[0]['params_err'][1]
#alpha_upper = alpha_ref + 6*rbfit._fit[0]['params_err'][1]
alpha_lower = .95*alpha_ref
alpha_upper = min(1.05*alpha_ref,1.0)
# priors for A anbd B
mu_AB = np.delete(rbfit._fit[0]['params'],1)
cov_AB=np.delete(rbfit._fit[0]['params_err'],1)**2
# prior for sigma theta:
sigma_theta = 0.004 # WIP
if printout:
print("priors:\nalpha_ref",alpha_ref)
print("alpha_lower", alpha_lower, "alpha_upper", alpha_upper)
print("A,B", mu_AB, "\ncov A,B", cov_AB)
print("sigma_theta", sigma_theta)
return m_gates, Y, alpha_ref, alpha_lower, alpha_upper, mu_AB, cov_AB, sigma_theta
# modified for accelerated BM with EPCest as extra parameter
def get_bayesian_model(model_type,Y,shots,m_gates,mu_AB,cov_AB, alpha_ref,
alpha_lower=0.5,alpha_upper=0.999,alpha_testval=0.9,
p_lower=0.9,p_upper=0.999,p_testval=0.95,
RvsI=None,IvsR=None,sigma_theta=0.001,
sigma_theta_l=0.0005,sigma_theta_u=0.0015):
# Bayesian model
# from https://iopscience.iop.org/arti=RvsI, cle/1sigma_theta=0.004,0.1088/1367-2630/17/1/013042/pdf
# see https://docs.pymc.io/api/model.html
RB_model = pm.Model()
with RB_model:
# note: shots can be used in place of total_shots (broadcast)
# to be checked however for all models
total_shots = np.full(Y.shape, shots)
#Priors for unknown model parameters
alpha = pm.Uniform("alpha",lower=alpha_lower,
upper=alpha_upper, testval = alpha_ref)
BoundedMvNormal = pm.Bound(pm.MvNormal, lower=0.0)
AB = BoundedMvNormal("AB", mu=mu_AB,testval = mu_AB,
cov= np.diag(cov_AB),
shape = (2))
if model_type == "hierarchical":
GSP = AB[0]*alpha**m_gates + AB[1]
theta = pm.Beta("GSP",
mu=GSP,
sigma = sigma_theta,
shape = Y.shape[1])
# Likelihood (sampling distribution) of observations
p = pm.Binomial("Counts_h", p=theta, observed=Y,
n = total_shots)
elif model_type == "h_sigma":
sigma_t = pm.Uniform("sigma_t", testval = sigma_theta,
upper = sigma_theta_u, lower = sigma_theta_l)
GSP = AB[0]*alpha**m_gates + AB[1]
theta = pm.Beta("GSP",
mu=GSP,
sigma = sigma_t,
shape = Y.shape[1])
# Likelihood (sampling distribution) of observations
p = pm.Binomial("Counts_h", p=theta, observed=Y,
n = total_shots)
elif model_type == "tilde":
p_tilde = pm.Uniform("p_tilde",lower=p_lower,
upper=p_upper, testval = p_testval)
GSP = AB[0]*(RvsI*alpha**m_gates + IvsR*(alpha*p_tilde)**m_gates) + AB[1]
# Likelihood (sampling distribution) of observations
p = pm.Binomial("Counts_t", p=GSP, observed=Y,
n = total_shots)
elif model_type == "h_tilde":
p_tilde = pm.Uniform("p_tilde",lower=p_lower,
upper=p_upper, testval = p_testval)
sigma_t = pm.Uniform("sigma_t", testval = sigma_theta,
upper = sigma_theta_u, lower = sigma_theta_l)
GSP = AB[0]*(RvsI*alpha**np.tile(m_gates,2) +\
IvsR*(alpha*p_tilde)**np.tile(m_gates,2)) \
+ AB[1]
theta = pm.Beta("GSP",
mu=GSP,
sigma = sigma_t,
shape = ((2*len(m_gates,))) )
# Likelihood (sampling distribution) of observations
p = pm.Binomial("Counts_t", p= theta, observed = Y, n = shots)
else: # default model "pooled"
GSP = AB[0]*alpha**m_gates + AB[1]
# Likelihood (sampling distribution) of observations
p = pm.Binomial("Counts_p", p=GSP, observed=Y,
n = total_shots)
return RB_model
#.reshape( ((Y.shape[1],Y.shape[0])) )
# .reshape( ((len(m_gates),2)) )
# HERE WE USE FOUR UNIFORMS
def build_bayesian_model(model_type,Y,shots,m_gates,mu_AB=None,cov_AB=None, alpha_ref=None,
alpha_lower=0.5,alpha_upper=0.999,alpha_testval=0.9,
p_lower=0.9,p_upper=0.999,p_testval=0.95,
popt = None, pcov = None,
RvsI=None,IvsR=None,sigma_theta=0.001,
sigma_theta_l=0.0005,sigma_theta_u=0.0015):
# Bayesian model
# from https://iopscience.iop.org/arti=RvsI, cle/1sigma_theta=0.004,0.1088/1367-2630/17/1/013042/pdf
# see https://docs.pymc.io/api/model.html
RB_model = pm.Model()
with RB_model:
#Priors for unknown model parameters
BoundedUniform = pm.Bound(pm.Uniform,
lower=np.fmax(popt-0.1, np.full(popt.shape,1.e-9)),
upper=np.fmin(popt+0.1, np.full(popt.shape,1.-1e-9)))
if model_type == "hierarchical":
# legacy: sigma_theta is a scalar
pi = BoundedUniform("A_α_B", testval = popt, shape = popt.shape)
GSP = pi[0]*pi[1]**m_gates + pi[2]
theta = pm.Beta('θ',
mu=GSP,
sigma = sigma_theta,
shape = Y.shape[1])
# Likelihood (sampling distribution) of observations
p = pm.Binomial("Counts_h", p=theta, observed=Y,
n = shots)
elif model_type == "h_sigma":
pi = BoundedUniform("A_α_B", testval = popt, shape = popt.shape)
sigma_t = pm.Uniform("σ Beta", testval = sigma_theta,
upper = sigma_theta_u, lower = sigma_theta_l)
GSP = pi[0]*pi[1]**m_gates + pi[2]
theta = pm.Beta('θ',
mu=GSP,
sigma = sigma_t,
shape = Y.shape[1])
# Likelihood (sampling distribution) of observations
p = pm.Binomial("Counts", p=theta, observed=Y,
n = shots)
elif model_type == "tilde":
pi = BoundedUniform("A_α_ƥ_B", testval = popt, shape = popt.shape)
GSP = pi[0]*(RvsI*pi[1]**m_gates + IvsR*(pi[1]*pi[2])**m_gates) + pi[3]
# Likelihood (sampling distribution) of observations
p = pm.Binomial("Counts_t", p=GSP, observed=Y,
n = shots)
elif model_type == "h_tilde":
pi = BoundedUniform("A_α_ƥ_B",testval = popt, shape = popt.shape)
sigma_t = pm.Uniform("σ Beta", testval = sigma_theta,
upper = sigma_theta_u, lower = sigma_theta_l)
GSP = pi[0]*(RvsI*pi[1]**np.tile(m_gates,2) +\
IvsR*(pi[1]*pi[2])**np.tile(m_gates,2)) \
+ pi[3]
theta = pm.Beta('θ',
mu=GSP,
sigma = sigma_t,
shape = ((2*len(m_gates,))) )
# Likelihood (sampling distribution) of observations
p = pm.Binomial("Counts", p= theta, observed = Y, n = shots)
else: # default model "pooled"
pi = BoundedUniform("A_α_B", testval = popt, shape = popt.shape)
GSP = pi[0]*pi[1]**m_gates + pi[2]
# Likelihood (sampling distribution) of observations
p = pm.Binomial("Counts", p=GSP, observed=Y,
n = shots)
return RB_model
#.reshape( ((Y.shape[1],Y.shape[0])) )
# .reshape( ((len(m_gates),2)) )
def get_bayesian_model_hierarchical(model_type,Y): # modified for accelerated BM with EPCest as extra parameter
# maintained for backward compatibility, deprecated
# Bayesian model
# from https://iopscience.iop.org/article/10.1088/1367-2630/17/1/013042/pdf
# see https://docs.pymc.io/api/model.html
RBH_model = pm.Model()
with RBH_model:
#Priors for unknown model parameters
alpha = pm.Uniform("alpha",lower=alpha_lower,
upper=alpha_upper, testval = alpha_ref)
BoundedMvNormal = pm.Bound(pm.MvNormal, lower=0.0)
AB = BoundedMvNormal("AB", mu=mu_AB,testval = mu_AB,
cov= np.diag(cov_AB),
shape = (2))
# Expected value of outcome
GSP = AB[0]*alpha**m_gates + AB[1]
total_shots = np.full(Y.shape, shots)
theta = pm.Beta("GSP",
mu=GSP,
sigma = sigma_theta,
shape = Y.shape[1])
# Likelihood (sampling distribution) of observations
p = pm.Binomial("Counts", p=theta, observed=Y,
n = total_shots)
return RBH_model
def get_trace(RB_model, draws = 2000, tune= 10000, target_accept=0.95, return_inferencedata=True):
# Gradient-based sampling methods
# see also: https://docs.pymc.io/notebooks/sampler-stats.html
# and https://docs.pymc.io/notebooks/api_quickstart.html
with RB_model:
trace= pm.sample(draws = draws, tune= tune, target_accept=target_accept,
return_inferencedata=return_inferencedata)
with RB_model:
az.plot_trace(trace);
return trace
def get_summary(RB_model, trace, round_to=6, hdi_prob=.94, kind='stats'):
with RB_model:
# (hdi_prob=.94 is default)
az_summary = az.summary(trace, round_to=round_to, hdi_prob=hdi_prob, kind=kind )
return az_summary
# obtain EPC from alpha (used by plot_posterior) # deprecated, should use scale
#def alpha_to_EPC(alpha):
#return 3*(1-alpha)/4
def get_EPC_and_legends(rbfit,azs):
EPC_Bayes = alpha_to_EPC(azs['mean']['alpha'])
EPC_Bayes_err = EPC_Bayes - alpha_to_EPC(azs['mean']['alpha']+azs['sd']['alpha'])
Bayes_legend ="EPC Bayes {0:.5f} ({1:.5f})".format(EPC_Bayes, EPC_Bayes_err)
Fitter_legend ="EPC Fitter {0:.5f} ({1:.5f})".format(rbfit.fit[0]['epc']\
,rbfit._fit[0]['epc_err'])
if pred_epc > 0.0:
pred_epc_legend = "EPC predicted {0:.5f}".format(pred_epc)
else:
pred_epc_legend = ''
return EPC_Bayes, EPC_Bayes_err, Bayes_legend,Fitter_legend, pred_epc_legend
def EPC_compare_fitter_to_bayes(RB_model, azs, trace,m_name,rbfit):
EPC_Bayes, EPC_Bayes_err, Bayes_legend,Fitter_legend, pred_epc_legend = get_EPC_and_legends(rbfit,azs)
with RB_model:
az.plot_posterior(trace, var_names=['alpha'], round_to=4,
transform = alpha_to_EPC, point_estimate=None)
plt.title("Error per Clifford "+RB_process+" device: "+hardware
+' backend: '+backend.name()+' model:'+m_name,
fontsize=12)
plt.axvline(x=alpha_to_EPC(alpha_ref),color='red')
if pred_epc > 0.0:
plt.axvline(x=pred_epc,color='green')
plt.legend((Bayes_legend, "Higher density interval",Fitter_legend, pred_epc_legend), fontsize=10)
else:
plt.legend((Bayes_legend, "Higher density interval",Fitter_legend), fontsize=10 )
plt.show()
def GSP_compare_fitter_to_bayes(RB_model, azs,m_name,rbfit):
EPC_Bayes, EPC_Bayes_err, Bayes_legend,Fitter_legend,_ = get_EPC_and_legends(rbfit,azs)
# plot ground state population ~ Clifford length
fig, axes = plt.subplots(1, 1, sharex=True, figsize=(10, 6))
axes.set_ylabel("Ground State Population")
axes.set_xlabel("Clifford Length")
axes.plot(m_gates, np.mean(Y/shots,axis=0), 'r.')
axes.plot(m_gates,azs['mean']['AB[0]']*azs['mean']['alpha']**m_gates+azs['mean']['AB[1]'],'--')
#axes.plot(m_gates,azs['mean']['GSP'],'--') # WIP
#axes.errorbar(m_gates, azs['mean']['GSP'], azs['sd']['GSP'], linestyle='None', marker='^') # WIP
axes.plot(m_gates,mu_AB[0]*np.power(alpha_ref,m_gates)+mu_AB[1],':')
for i_seed in range(nseeds):
plt.scatter(m_gates-0.25, Y[i_seed,:]/shots, label = "data", marker="x")
axes.legend(["Mean Observed Frequencies",
"Bayesian Model\n"+Bayes_legend,
"Fitter Model\n"+Fitter_legend],fontsize=12)
axes.set_title(RB_process+" device: "+hardware+' backend: '+backend.name()+' model:'+m_name,
fontsize=14) # WIP
def get_predicted_EPC(error_source):
#Count the number of single and 2Q gates in the 2Q Cliffords
gates_per_cliff = rb.rb_utils.gates_per_clifford(transpile_list,xdata[0],basis_gates,rb_opts['rb_pattern'][0])
for basis_gate in basis_gates:
print("Number of %s gates per Clifford: %f "%(basis_gate ,
np.mean([gates_per_cliff[rb_pattern[0][0]][basis_gate],
gates_per_cliff[rb_pattern[0][1]][basis_gate]])))
# Calculate the predicted epc
# from the known depolarizing errors on the simulation
if error_source == "depolarization":
# Error per gate from noise model
epgs_1q = {'u1': 0, 'u2': p1Q/2, 'u3': 2*p1Q/2}
epg_2q = p2Q*3/4
pred_epc = rb.rb_utils.calculate_2q_epc(
gate_per_cliff=gates_per_cliff,
epg_2q=epg_2q,
qubit_pair=[0, 2],
list_epgs_1q=[epgs_1q, epgs_1q])
# using the predicted primitive gate errors from the coherence limit
if error_source == "from_T1_T2":
# Predicted primitive gate errors from the coherence limit
u2_error = rb.rb_utils.coherence_limit(1,[t1],[t2],gate1Q)
u3_error = rb.rb_utils.coherence_limit(1,[t1],[t2],2*gate1Q)
epg_2q = rb.rb_utils.coherence_limit(2,[t1,t1],[t2,t2],gate2Q)
epgs_1q = {'u1': 0, 'u2': u2_error, 'u3': u3_error}
pred_epc = rb.rb_utils.calculate_2q_epc(
gate_per_cliff=gates_per_cliff,
epg_2q=epg_2q,
qubit_pair=[0, 1],
list_epgs_1q=[epgs_1q, epgs_1q])
return pred_epc
def get_and_run_seeds(rb_circs, shots, backend, coupling_map,
basis_gates, noise_model, retrieve_list=[]):
#basis_gates = ['u1','u2','u3','cx'] # use U,CX for now
result_list = []
transpile_list = []
for rb_seed,rb_circ_seed in enumerate(rb_circs):
print('Compiling seed %d'%rb_seed)
rb_circ_transpile = qiskit.transpile(rb_circ_seed,
optimization_level=0,
basis_gates=basis_gates)
print('Runing seed %d'%rb_seed)
if retrieve_list == []:
if noise_model == None: # this indicates harware run
job = qiskit.execute(rb_circ_transpile,
shots=shots,
backend=backend,
coupling_map=coupling_map,
basis_gates=basis_gates)
else:
job = qiskit.execute(rb_circ_transpile,
shots=shots,
backend=backend,
coupling_map=coupling_map,
noise_model=noise_model,
basis_gates=basis_gates)
job_monitor(job)
else:
job = backend.retrieve_job(retrieve_list[rb_seed])
result_list.append(job.result())
transpile_list.append(rb_circ_transpile)
print("Finished Jobs")
return result_list, transpile_list
def get_count_data(result_list, nCliffs):
### another way to obtain the observed counts
#corrected for accomodation pooled data from 1Q, 2Q and 3Q interleave processes
list_bitstring = ['0','00', '000', '100'] # all valid bistrings
Y_list = []
for rbseed, result in enumerate(result_list):
row_list = []
for c_index, c_value in enumerate(nCliffs) :
total_counts = 0
for key,val in result.get_counts()[c_index].items():
if key in list_bitstring:
total_counts += val
#print(key,val,total_counts)
row_list.append(total_counts)
Y_list.append(row_list)
return np.array(Y_list)
# This section for the LS fit in this model pooling
# data from 2Q and 3Q interleave processes
def func(x, a, b, c):
return a * b ** x + c
def epc_fitter_when_mixed_2Q_3Q_RB(X,Y1,Y2,shots,check_plot=False):
xdata = np.array(list(X)*Y1.shape[0]) # must be something simpler
ydata1 = np.ravel(Y1)/shots
popt, pcov = curve_fit(func, xdata, ydata1)
perr= np.sqrt(np.diag(pcov))
ydata2 = np.ravel(Y2)/shots
popt2, pcov2 = curve_fit(func, xdata, ydata2)
perr2= np.sqrt(np.diag(pcov2))
if check_plot:
import matplotlib.pyplot as plt
plt.plot(xdata, ydata1, 'bx', label='Reference')
plt.plot(xdata, ydata2, 'r+', label='Interleave')
plt.plot(X, np.mean(Y1,axis=0)/shots, 'b-', label=None)
plt.plot(X, np.mean(Y2,axis=0)/shots, 'r-', label=None)
plt.ylabel('Population of |00>')
plt.xlabel('Number of Cliffords')
plt.legend()
plt.show()
print(popt[1])
print(perr[1])
print(popt2[1])
print(perr2[1])
epc_est_fitter = 3*(1 - popt2[1]/popt[1])/4
epc_est_fitter_err = 3*(popt2[1]/popt[1])/4 * (np.sqrt(perr[1]**2 + perr2[1]**2))
return epc_est_fitter, epc_est_fitter_err
# This section for the demo with qiskit experiment
def retrieve_from_lsf(exp):
perr_fm = np.sqrt(np.diag(exp._analysis_results[0]['pcov']))
popt_fm = exp._analysis_results[0]['popt']
epc_est_fm = exp._analysis_results[0]['EPC']
epc_est_fm_err = exp._analysis_results[0]['EPC_err']
experiment_type = exp._data[0]['metadata']['experiment_type']
return perr_fm, popt_fm, epc_est_fm, epc_est_fm_err, experiment_type
def get_GSP_counts(data, x_length, data_range):
#obtain the observed counts used in the bayesian model
#corrected for accomodation pooled data from 1Q, 2Q and 3Q interleave processes
list_bitstring = ['0','00', '000', '100'] # all valid bistrings
Y_list = []
for i_samples in data_range:
row_list = []
for c_index in range(x_length) :
total_counts = 0
i_data = i_samples*x_length + c_index
for key,val in data[i_data]['counts'].items():
if key in list_bitstring:
total_counts += val
row_list.append(total_counts)
Y_list.append(row_list)
return np.array(Y_list)
def RB_bayesian_results(resmodel, trace, lengths,
epc_est_fm, epc_est_fm_err, experiment_type, scale, num_samples, Y, shots, physical_qubits,
interleaved_gate, backend,
EPG_dic = None, epc_calib = np.nan,
Y1 = None, Y2= None, show_plot = True,
routine = 'get_bayesian_model'):
# obtain EPC from alpha (used by az.plot_posterior)
def alpha_to_EPC(alpha):
return scale*(1-alpha)
azt_summary = get_summary(resmodel, trace, kind = 'stats')
print(azt_summary,'\n')
if experiment_type == "StandardRB":
if routine == 'get_bayesian_model':
v_name = 'alpha'
alpha = azt_summary['mean']['alpha']
sd_alpha = azt_summary['sd']['alpha']
A = azt_summary['mean']['AB[0]']
B = azt_summary['mean']['AB[1]']
elif routine == 'build_bayesian_model':
v_name = 'A_α_B'
alpha = azt_summary['mean']['A_α_B[1]']
sd_alpha = azt_summary['sd']['A_α_B[1]']
A = azt_summary['mean']['A_α_B[0]']
B = azt_summary['mean']['A_α_B[2]']
epc_est_a = scale*(1 - alpha)
epc_est_a_err = scale * sd_alpha
# compare LSF and SMC
print("Model: Frequentist Bayesian")
print("_______________________________________")
print("EPC {0:1.3e} {1:1.3e} "
.format(epc_est_fm,epc_est_a))
print("± sigma ± {0:1.3e} ± {1:1.3e} "
.format(epc_est_fm_err, epc_est_a_err))
for i, (gate,EPG) in enumerate(EPG_dic.items()):
print("{0:<12}{1:1.3e} {2:1.3e}"
.format("EPG "+gate,EPG,EPG*epc_est_a/epc_est_fm))
if show_plot == False:
return
import matplotlib.pyplot as plt # seems we need to reimport for replot WIP
fig, plt = plt.subplots(1, 1)
plt.set_ylabel("P(0)")
plt.set_xlabel("Cliffords Length")
plt.plot(lengths,A*alpha**lengths + B,'-',color="r")
for i_seed in range(num_samples):
plt.scatter(lengths, Y[i_seed,:]/shots, label = "data", marker="x",color="grey")
plt.set_title(experiment_type +', ' + "qubit: " + str(physical_qubits)\
+', backend: '+backend.name(),
fontsize=14);
elif experiment_type == "InterleavedRB":
if routine == 'get_bayesian_model':
v_name = 'p_tilde'
alpha = azt_summary['mean']['alpha']
p = azt_summary['mean']['p_tilde']
sd_p = p = azt_summary['sd']['p_tilde']
A = azt_summary['mean']['AB[0]']
B = azt_summary['mean']['AB[1]']
elif routine == 'build_bayesian_model':
v_name = 'A_α_ƥ_B'
alpha = azt_summary['mean']['A_α_ƥ_B[1]']
p = azt_summary['mean']['A_α_ƥ_B[2]']
sd_p = azt_summary['sd']['A_α_ƥ_B[2]']
A = azt_summary['mean']['A_α_ƥ_B[0]']
B= azt_summary['mean']['A_α_ƥ_B[3]']
epc_est_a = scale*(1 - p)
epc_est_a_err = scale * sd_p
# compare LSF and SMC
print("Model: Frequentist Bayesian Calibration")
print("__________________________________________________________")
print("EPC {0:1.3e} {1:1.3e} {2:1.3e}"
.format(epc_est_fm,epc_est_a,epc_calib ))
print("± sigma ± {0:1.3e} ± {1:1.3e} "
.format(epc_est_fm_err, epc_est_a_err))
if show_plot ==False:
return
import matplotlib.pyplot as plt # seems we need to reimport for replot WIP
fig, plt = plt.subplots(1, 1)
plt.set_ylabel("P(0)")
plt.set_xlabel("Cliffords Length")
for i_seed in range(num_samples):
plt.scatter(lengths, Y1[i_seed,:]/shots, label = "data", marker="x",color="r")
plt.scatter(lengths, Y2[i_seed,:]/shots, label = "data", marker="+",color="orange")
plt.plot(lengths,A*alpha**lengths + B,'--',color="r")
plt.plot(lengths,A*(alpha*p)**lengths + B,'--',color="orange")
plt.legend(("Standard, SMC model",
"Interleaved, SMC model"))
plt.set_title(experiment_type +', ' + interleaved_gate + str(physical_qubits)\
+', backend: '+backend.name(),
fontsize=14);
import matplotlib.pyplot as plt # if not yet imported
#plt.rcParams["figure.figsize"] = plt.rcParamsDefault["figure.figsize"]
# to reset to default
plt.rcParams["figure.figsize"] = (8,5)
if routine == 'build_bayesian_model': # WIP
return
with resmodel:
ax = az.plot_posterior(trace, var_names=[v_name],
round_to=4, point_estimate=None,
transform = alpha_to_EPC)
ax.set_xlim(epc_est_a - 6*epc_est_a_err, epc_est_a + 6*epc_est_a_err)
plt.axvline(x=epc_est_fm,color='cyan',ls="-")
if epc_calib != np.nan:
plt.axvline(x=epc_calib,color='r',ls=":")
plt.axvline(x=epc_est_a,color='blue',ls=":")
plt.title(experiment_type +', ' + interleaved_gate + " qubit(s):" + str(physical_qubits)\
+', backend: '+backend.name(),
fontsize=14)
Bayes_legend = "EPC SMC: {0:1.3e} ± {1:1.3e}".format(epc_est_a, epc_est_a_err)
LSF_legend = "EPC LSF: {0:1.3e} ± {1:1.3e}".format(epc_est_fm, epc_est_fm_err)
Cal_legend = "EPC Calibration: {0:1.3e}".format(epc_calib)
if epc_calib > 0.0:
plt.legend((Bayes_legend, "$Highest\; density\; interval$ HDI",
LSF_legend,
Cal_legend), fontsize=12 )
else:
plt.legend((Bayes_legend, "$Highest\; density\; interval$ HDI",
LSF_legend), fontsize=12 )
# obtain EPC from alpha and scale(used by az.plot_posterior)
def alpha_to_EPC_from_scale(alpha, scale):
return scale*(1-alpha)
# guess number of shots
def guess_shots(Y):
shot_exp = 1
test_shot = np.max(Y)
while test_shot > 2**shot_exp:
shot_exp += 1
return 2**shot_exp
def bayesian_standard_RB_model():
# construct model
RB_model = get_bayesian_model(model_type="pooled",Y=Y,shots=shots,m_gates=lengths,
mu_AB=[popt_fm[0],popt_fm[2]],cov_AB=[perr_fm[0],perr_fm[2]],
alpha_ref=popt_fm[1],
alpha_lower=popt_fm[1]-6*perr_fm[1],
alpha_upper=min(1.-1.E-6,popt_fm[1]+6*perr_fm[1]),
RvsI=None,IvsR=None)
return RB_model
def bayesian_interleaved_RB_model():
# construct model
RB_model = get_bayesian_model("tilde",Y=Y,shots=shots, m_gates=lengths,
alpha_ref=popt_fm[1], p_testval= popt_fm[2],
alpha_lower=popt_fm[1]-6*perr_fm[1],
alpha_upper=min(1.-1.E-6,popt_fm[1]+6*perr_fm[1]),
p_lower=popt_fm[2]-6*perr_fm[2],
p_upper=min(1.-1.E-6,popt_fm[2]+6*perr_fm[2]),
mu_AB=[popt_fm[0],popt_fm[3]],cov_AB=[perr_fm[0],perr_fm[3]],
RvsI=RvsI,IvsR=IvsR)
return RB_model
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.measure(0, 0)
qc.draw('mpl')
|
https://github.com/DEBARGHYA4469/quantum-compiler
|
DEBARGHYA4469
|
# Implement the control_U2 gate
# Written by Debarghya Kundu
# Email : debarghya4469@iitg.ernet.in
from zy_decomposition import *
from qiskit import ClassicalRegister,QuantumRegister,QuantumJob
from qiskit import available_backends,execute,register,get_backend
from qiskit.tools.visualization import plot_histogram
from qiskit import QuantumCircuit
def Rzz(ckt,theta,q,n): # Phase-Shift gate
ckt.u1(theta,q[n-1]) # Rzz for last qubit is required
ckt.x(q[n-1])
ckt.u1(theta,q[n-1])
ckt.x(q[n-1])
return ckt
def Rz(ckt,theta,q,n): #rotation along -z axis
ckt.u1(theta,q[n-1])
ckt = Rzz(ckt,-1.0*theta/2.0,q,n)
return ckt
def Ry(ckt,theta,q,n): #rotation along -y axis
ckt.u3(theta,0,0,q[n-1])
return ckt
def CU2(U,ckt,q,n):
alpha,beta,gama,delta = zy_decompose(U)
ckt = Rz(ckt,(delta-beta)/2.0,q,n) # Apply :: C
ckt.cx(q[2*n-3],q[n-1]) # ancilla as ctr,tgt
ckt = Rz(ckt,-1.0*(beta+delta)/2.0,q,n) # Apply :: B
ckt = Ry(ckt,-1.0*gama/2.0,q,n) # Apply :: B
ckt.cx(q[2*n-3],q[n-1]) # ancilla as ctr,tgt
ckt = Ry(ckt,gama/2.0,q,n) # Apply :: A
ckt = Rz(ckt,beta,q,n) # Apply :: A
ckt.u1(alpha,q[2*n-3]) # phase to ancilla -> ref: N&C
return ckt
def get_result(ckt):
shots = 10000
backend = 'local_qasm_simulator'
job = execute(ckt,backend=backend,shots=shots)
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
def test_main():
q = QuantumRegister(3+1)
c = ClassicalRegister(4)
a = math.cos(3.0)
b = math.sin(3.0)
U = np.array([[a,-1.0*b.conjugate()],[b,a.conjugate()]])
ckt = QuantumCircuit(q,c)
# ckt.x(q[3])
ckt = CU2(U,ckt,q,3)
for i in range(4):
ckt.measure(q[i],c[i])
get_result(ckt)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("./")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="lq")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
t3_st_qcs = transpile(t3_st_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_st_qcs), ")")
t3_st_qcs[-1].draw("mpl") # only view trotter gates
# from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
shots = 8192
reps = 8
jobs = []
for _ in range(reps):
# execute
job = execute(t3_st_qcs, backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=initial_layout)
print('Job ID', cal_job.job_id())
dt_now = datetime.datetime.now()
print(dt_now)
with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
filename = "job_ids_jakarta_100step_20220412_171248_.pkl" # change here
with open(filename, "rb") as f:
job_ids_dict = pickle.load(f)
job_ids = job_ids_dict["job_ids"]
cal_job_id = job_ids_dict["cal_job_id"]
retrieved_jobs = []
for job_id in job_ids:
retrieved_jobs.append(backend.retrieve_job(job_id))
retrieved_cal_job = backend.retrieve_job(cal_job_id)
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
# set the target state
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
# mit_results = meas_fitter.filter.apply(job.result()) # apply QREM
rho = StateTomographyFitter(job.result(), st_qcs).fit(method='lstsq')
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
from qiskit import QuantumCircuit,QuantumRegister,transpile
from qiskit.test.mock import FakeVigo,FakeLondon
qc=QuantumCircuit(1)
qc.h(0)
qc.barrier(0)
qc.x(0)
qc.barrier(0)
qc.h(0)
qc.draw(output="mpl")
device_backend = FakeVigo()
config_details = device_backend.configuration()
config_details.backend_name
config_details.n_qubits
config_details.basis_gates
qc_transpile=transpile(qc,device_backend)
qc_transpile.draw(output="mpl")
qc=QuantumCircuit(1)
qc.h(0)
qc.x(0)
qc.h(0)
qc.draw(output="mpl")
qc_transpile=transpile(qc,device_backend)
qc_transpile.draw(output="mpl")
device_backend = FakeLondon()
config_details = device_backend.configuration()
config_details.backend_name
config_details.n_qubits
config_details.basis_gates
qc=QuantumCircuit(1)
qc.h(0)
qc.x(0)
qc.h(0)
qc.draw(output="mpl")
qc_transpile=transpile(qc,device_backend)
qc_transpile.draw(output="mpl")
qc=QuantumCircuit(1)
qc.h(0)
qc.barrier(0)
qc.x(0)
qc.barrier(0)
qc.h(0)
qc.draw(output="mpl")
qc_transpile=transpile(qc,device_backend)
qc_transpile.draw(output="mpl")
|
https://github.com/abhik-99/Qiskit-Summer-School
|
abhik-99
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# If you introduce a list with less colors than bars, the color of the bars will
# alternate following the sequence from the list.
import numpy as np
from qiskit.quantum_info import DensityMatrix
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0, 1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
matrix = DensityMatrix(qc)
plot_state_paulivec(matrix, color=['crimson', 'midnightblue', 'seagreen'])
|
https://github.com/MiChaelinzo/Quantum-time-travel
|
MiChaelinzo
|
import qiskit
import math
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_histogram
from qiskit_aer import Aer
def time_travel_circuit(target_time, num_qubits=6):
"""
Creates a quantum circuit simulating time travel (fictional).
This circuit applies Hadamard gates to create a superposition, encodes
the target time using phase gates, and entangles qubits in a linear chain.
Args:
target_time (int): The target time to encode as a binary string.
num_qubits (int, optional): The number of qubits in the circuit. Defaults to 6.
Returns:
QuantumCircuit: The constructed quantum circuit.
"""
qc = QuantumCircuit(num_qubits, num_qubits)
# Apply Hadamard gates to create superposition
for qubit in range(num_qubits):
qc.h(qubit)
# Encode target time using phase gates
time_binary = bin(target_time)[2:].zfill(num_qubits)
for qubit, time_bit in enumerate(time_binary):
if time_bit == '1':
qc.p(math.pi, qubit) # Apply phase if the time bit is 1
# Entangle qubits in a linear chain
for qubit in range(num_qubits - 1):
qc.cx(qubit, qubit + 1)
# Measure all qubits
qc.measure(range(num_qubits), range(num_qubits))
return qc
# Example usage:
target_time = 25 # Example target time
num_qubits = 6 # Number of qubits
# Create and run the circuit
ttc = time_travel_circuit(target_time, num_qubits)
simulator = Aer.get_backend('qasm_simulator')
compiled_circuit = transpile(ttc, simulator)
job = simulator.run(compiled_circuit, shots=1024)
results = job.result()
counts = results.get_counts(ttc)
# Visualize the results
print(plot_histogram(counts))
# Visualize the results
plot_histogram (counts)
|
https://github.com/quantum-melbourne/qiskit-challenge-22
|
quantum-melbourne
|
from qiskit_nature.drivers import Molecule
from qiskit_nature.drivers.second_quantization import ElectronicStructureDriverType, ElectronicStructureMoleculeDriver
# PSPCz molecule
geometry = [['C', [ -0.2316640, 1.1348450, 0.6956120]],
['C', [ -0.8886300, 0.3253780, -0.2344140]],
['C', [ -0.1842470, -0.1935670, -1.3239330]],
['C', [ 1.1662930, 0.0801450, -1.4737160]],
['C', [ 1.8089230, 0.8832220, -0.5383540]],
['C', [ 1.1155860, 1.4218050, 0.5392780]],
['S', [ 3.5450920, 1.2449890, -0.7349240]],
['O', [ 3.8606900, 1.0881590, -2.1541690]],
['C', [ 4.3889120, -0.0620730, 0.1436780]],
['O', [ 3.8088290, 2.4916780, -0.0174650]],
['C', [ 4.6830900, 0.1064460, 1.4918230]],
['C', [ 5.3364470, -0.9144080, 2.1705280]],
['C', [ 5.6895490, -2.0818670, 1.5007820]],
['C', [ 5.4000540, -2.2323130, 0.1481350]],
['C', [ 4.7467230, -1.2180160, -0.5404770]],
['N', [ -2.2589180, 0.0399120, -0.0793330]],
['C', [ -2.8394600, -1.2343990, -0.1494160]],
['C', [ -4.2635450, -1.0769890, 0.0660760]],
['C', [ -4.5212550, 0.2638010, 0.2662190]],
['C', [ -3.2669630, 0.9823890, 0.1722720]],
['C', [ -2.2678900, -2.4598950, -0.3287380]],
['C', [ -3.1299420, -3.6058560, -0.3236210]],
['C', [ -4.5179520, -3.4797390, -0.1395160]],
['C', [ -5.1056310, -2.2512990, 0.0536940]],
['C', [ -5.7352450, 1.0074800, 0.5140960]],
['C', [ -5.6563790, 2.3761270, 0.6274610]],
['C', [ -4.4287740, 3.0501460, 0.5083650]],
['C', [ -3.2040560, 2.3409470, 0.2746950]],
['H', [ -0.7813570, 1.5286610, 1.5426490]],
['H', [ -0.7079140, -0.7911480, -2.0611600]],
['H', [ 1.7161320, -0.2933710, -2.3302930]],
['H', [ 1.6308220, 2.0660550, 1.2427990]],
['H', [ 4.4214900, 1.0345500, 1.9875450]],
['H', [ 5.5773000, -0.7951290, 3.2218590]],
['H', [ 6.2017810, -2.8762260, 2.0345740]],
['H', [ 5.6906680, -3.1381740, -0.3739110]],
['H', [ 4.5337010, -1.3031330, -1.6001680]],
['H', [ -1.1998460, -2.5827750, -0.4596910]],
['H', [ -2.6937370, -4.5881470, -0.4657540]],
['H', [ -5.1332290, -4.3740010, -0.1501080]],
['H', [ -6.1752900, -2.1516170, 0.1987120]],
['H', [ -6.6812260, 0.4853900, 0.6017680]],
['H', [ -6.5574610, 2.9529350, 0.8109620]],
['H', [ -4.3980410, 4.1305040, 0.5929440]],
['H', [ -2.2726630, 2.8838620, 0.1712760]]]
molecule = Molecule(geometry=geometry, charge=0, multiplicity=1)
driver = ElectronicStructureMoleculeDriver(molecule=molecule,
basis='631g*',
driver_type=ElectronicStructureDriverType.PYSCF)
num_ao = {
'C': 14,
'H': 2,
'N': 14,
'O': 14,
'S': 18,
}
##############################
# Provide your code here
num_C_atom =
num_H_atom =
num_N_atom =
num_O_atom =
num_S_atom =
num_atoms_total =
num_AO_total =
num_MO_total =
##############################
answer_ex2a ={
'C': num_C_atom,
'H': num_H_atom,
'N': num_N_atom,
'O': num_O_atom,
'S': num_S_atom,
'atoms': num_atoms_total,
'AOs': num_AO_total,
'MOs': num_MO_total
}
print(answer_ex2a)
# Check your answer and submit using the following code
from qc_grader.challenges.unimelb_2022 import grade_ex2a
grade_ex2a(answer_ex2a)
from qiskit_nature.drivers.second_quantization import HDF5Driver
driver_reduced = HDF5Driver("resources/PSPCz_reduced.hdf5")
properties = driver_reduced.run()
from qiskit_nature.properties.second_quantization.electronic import ElectronicEnergy
electronic_energy = properties.get_property(ElectronicEnergy)
print(electronic_energy)
from qiskit_nature.properties.second_quantization.electronic import ParticleNumber
##############################
# Provide your code here
particle_number =
num_electron =
num_MO =
num_SO =
num_qubits =
##############################
answer_ex2b = {
'electrons': num_electron,
'MOs': num_MO,
'SOs': num_SO,
'qubits': num_qubits
}
print(answer_ex2b)
# Check your answer and submit using the following code
from qc_grader.challenges.unimelb_2022 import grade_ex2b
grade_ex2b(answer_ex2b)
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
##############################
# Provide your code here
es_problem =
##############################
second_q_op = es_problem.second_q_ops()
print(second_q_op[0])
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper, ParityMapper, BravyiKitaevMapper
##############################
# Provide your code here
qubit_converter =
##############################
qubit_op = qubit_converter.convert(second_q_op[0])
print(qubit_op)
from qiskit_nature.circuit.library import HartreeFock
##############################
# Provide your code here
init_state =
##############################
init_state.draw()
from qiskit.circuit.library import EfficientSU2, TwoLocal, NLocal, PauliTwoDesign
from qiskit_nature.circuit.library import UCCSD, PUCCD, SUCCD
##############################
# Provide your code here
ansatz =
##############################
ansatz.decompose().draw()
from qiskit.algorithms import NumPyMinimumEigensolver
from qiskit_nature.algorithms import GroundStateEigensolver
##############################
# Provide your code here
numpy_solver =
numpy_ground_state_solver =
numpy_results =
##############################
exact_energy = numpy_results.computed_energies[0]
print(f"Exact electronic energy: {exact_energy:.6f} Hartree\n")
print(numpy_results)
# Check your answer and submit using the following code
from qc_grader.challenges.unimelb_2022 import grade_ex2c
grade_ex2c(numpy_results)
from qiskit.providers.aer import StatevectorSimulator, QasmSimulator
from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA, SLSQP
##############################
# Provide your code here
backend =
optimizer =
##############################
from qiskit.algorithms import VQE
from qiskit_nature.algorithms import VQEUCCFactory, GroundStateEigensolver
from jupyterplot import ProgressPlot
import numpy as np
error_threshold = 10 # mHartree
np.random.seed(5) # fix seed for reproducibility
initial_point = np.random.random(ansatz.num_parameters)
# for live plotting
pp = ProgressPlot(plot_names=['Energy'],
line_names=['Runtime VQE', f'Target + {error_threshold}mH', 'Target'])
intermediate_info = {
'nfev': [],
'parameters': [],
'energy': [],
'stddev': []
}
def callback(nfev, parameters, energy, stddev):
intermediate_info['nfev'].append(nfev)
intermediate_info['parameters'].append(parameters)
intermediate_info['energy'].append(energy)
intermediate_info['stddev'].append(stddev)
pp.update([[energy, exact_energy+error_threshold/1000, exact_energy]])
##############################
# Provide your code here
vqe =
vqe_ground_state_solver =
vqe_results =
##############################
print(vqe_results)
error = (vqe_results.computed_energies[0] - exact_energy) * 1000 # mHartree
print(f'Error is: {error:.3f} mHartree')
# Check your answer and submit using the following code
from qc_grader.challenges.unimelb_2022 import grade_ex2d
grade_ex2d(vqe_results)
from qiskit_nature.algorithms import QEOM
##############################
# Provide your code here
qeom_excited_state_solver =
qeom_results =
##############################
print(qeom_results)
# Check your answer and submit using the following code
from qc_grader.challenges.unimelb_2022 import grade_ex2e
grade_ex2e(qeom_results)
bandgap = qeom_results.computed_energies[1] - qeom_results.computed_energies[0]
bandgap # in Hartree
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-education', group='ibm-4', project='qiskit-hackathon')
backend = provider.get_backend('ibmq_qasm_simulator')
backend
from qiskit_nature.runtime import VQEProgram
error_threshold = 10 # mHartree
# for live plotting
pp = ProgressPlot(plot_names=['Energy'],
line_names=['Runtime VQE', f'Target + {error_threshold}mH', 'Target'])
intermediate_info = {
'nfev': [],
'parameters': [],
'energy': [],
'stddev': []
}
def callback(nfev, parameters, energy, stddev):
intermediate_info['nfev'].append(nfev)
intermediate_info['parameters'].append(parameters)
intermediate_info['energy'].append(energy)
intermediate_info['stddev'].append(stddev)
pp.update([[energy,exact_energy+error_threshold/1000, exact_energy]])
##############################
# Provide your code here
optimizer = {
'name': 'QN-SPSA', # leverage the Quantum Natural SPSA
# 'name': 'SPSA', # set to ordinary SPSA
'maxiter': 100,
}
runtime_vqe =
##############################
# Submit a runtime job using the following code
from qc_grader.challenges.unimelb_2022 import prepare_ex2f
runtime_job = prepare_ex2f(runtime_vqe, qubit_converter, es_problem)
# Check your answer and submit using the following code
from qc_grader.challenges.unimelb_2022 import grade_ex2f
grade_ex2f(runtime_job)
print(runtime_job.result().get("eigenvalue"))
# Please change backend before running the following code
runtime_job_real_device = prepare_ex2f(runtime_vqe, qubit_converter, es_problem, real_device=True)
print(runtime_job_real_device.result().get("eigenvalue"))
|
https://github.com/urwin419/QiskitChecker
|
urwin419
|
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)
### added y gate ###
qc.y(0)
qc.h(1)
return qc
|
https://github.com/Qiskit/feedback
|
Qiskit
|
from qiskit_nature.second_q.operators import BosonicOp, FermionicOp
# Create a creation operator
bosonic_op = BosonicOp({'+_0': 1}, num_modes=1)
# Create an annihilation operator
bosonic_op = BosonicOp({'-_0': 1}, num_modes=1)
bosonic_op1 = BosonicOp({'+_0 -_0 -_1 +_1': 2}, num_modes=2)
bosonic_op2 = BosonicOp({'+_2 -_2': 1.5, '+_0': 3}, num_modes=3)
# Sum
print("Sum")
print(bosonic_op1 + bosonic_op2)
# Multiplication
print("\nMultiplication")
print(0.5 * bosonic_op1 @ bosonic_op2)
bosonic_op = BosonicOp({'+_0 -_0 -_1 +_0': 1}, num_modes=2)
# Normal order (reorder all operators such that all creation op are in front). Due to the commutation relations, when inverting -_0 +_0 we get 1 + +_0 -_0, which explains the two terms
print("Normal Ordering")
print(bosonic_op.normal_order())
# Index order (reorder all operators such that the lowest indices come first)
print("\nIndex Ordering")
print(bosonic_op.index_order())
# Simplify
print("Simplify")
# Simplify can be used to reduce numerical noise:
print(BosonicOp({'+_0 -_0': 1}) + BosonicOp({'+_0 -_0': 1e-10}).simplify(atol=1e-9))
print("\nSimplify with two creation operators")
print("\nBosons:")
print(BosonicOp({'+_0 -_0 -_1 +_0 +_0': 1}, num_modes=2).simplify())
print("\nFermions:")
print(FermionicOp({'+_0 -_0 -_1 +_0 +_0': 1}, num_spin_orbitals=2).simplify())
FermionicOp({'+_0 -_0 -_1 +_0': 1}, num_spin_orbitals=2).simplify()
from qiskit_nature.second_q.mappers import BosonicLinearMapper
from qiskit_nature import settings
settings.use_pauli_sum_op = False
mapper_occ1 = BosonicLinearMapper(max_occupation=1)
boson1 = mapper_occ1.map(BosonicOp({'+_0 -_0': 1}))
print(boson1)
print("Max occupation = 1")
boson_p1 = mapper_occ1.map(BosonicOp({'+_0': 1}))
boson_m1 = mapper_occ1.map(BosonicOp({'-_0': 1}))
print(boson_p1)
print("\nMax occupation = 2")
mapper_occ2 = BosonicLinearMapper(max_occupation=2)
boson_p2 = mapper_occ2.map(BosonicOp({'+_0': 1}))
boson_m2 = mapper_occ2.map(BosonicOp({'-_0': 1}))
print(boson_p2)
print("\nMax occupation = 3")
mapper_occ3 = BosonicLinearMapper(max_occupation=3)
boson_p3 = mapper_occ3.map(BosonicOp({'+_0': 1}))
boson_m3 = mapper_occ3.map(BosonicOp({'-_0': 1}))
print(boson_p3)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeAuckland
backend = FakeAuckland()
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
depths = []
gate_counts = []
non_local_gate_counts = []
levels = [str(x) for x in range(4)]
for level in range(4):
circ = transpile(ghz, backend, optimization_level=level)
depths.append(circ.depth())
gate_counts.append(sum(circ.count_ops().values()))
non_local_gate_counts.append(circ.num_nonlocal_gates())
fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.bar(levels, depths, label='Depth')
ax1.set_xlabel("Optimization Level")
ax1.set_ylabel("Depth")
ax1.set_title("Output Circuit Depth")
ax2.bar(levels, gate_counts, label='Number of Circuit Operations')
ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates')
ax2.set_xlabel("Optimization Level")
ax2.set_ylabel("Number of gates")
ax2.legend()
ax2.set_title("Number of output circuit gates")
fig.tight_layout()
plt.show()
|
https://github.com/QForestCommunity/launchpad
|
QForestCommunity
|
import qiskit
qiskit.__qiskit_version__
from qiskit import QuantumCircuit, BasicAer, execute
from qiskit.visualization import plot_histogram
qcSwap = QuantumCircuit(2, 2) #create a quantum circuit with 2 quantum bits and 2 classical bits.
qcSwap.x(0) #apply a pauli X gate to the first qubit to better demonstrate the swap.
qcSwap.swap(0, 1) #apply a swap gate on the first and second qubits.
qcSwap.measure([0, 1], [0, 1]) #measure the qubits to see what their states end up being
qcSwap.draw(output = "mpl") #draw the circuit.
backend = BasicAer.get_backend("statevector_simulator")
state = execute(qcSwap, backend, shots=1024).result().get_counts()
#the initial state should've been '01' before the swap,
#go ahead and comment the swap gate out and run the code!
#the state is '01' before the swap because of qiskit's little endian encoding.
print(state)
n = 4 #number of data qubits.
ancilla = n #number of ancillary qubits is the same as number of qubits in this example.
#number of classical registers is equal to the number of data qubits, since we want the values of only those.
qcShift = QuantumCircuit(n + ancilla, n)
seed = "1011" #this is the initial value of our data qubits.
seed = list(map(int, list(seed)))[::-1] #reverse the list to follow qiskit's encoding scheme.
#to encode the seed, when we encounter a 1, we apply a pauli x gate.
for bit in range(len(seed)):
if seed[bit] == 1:
qcShift.x(bit)
qcShift.barrier(range(n + ancilla)) #add a barrier to mark the end of the encoding phase.
#to apply the swap gates
for qubit in range(1, n + ancilla)[::-1]:
qcShift.swap(qubit, qubit - 1)
qcShift.barrier(range(n + ancilla)) #add a barrier to mark the end of the swapping phase.
#measure the values of the data qubits.
qcShift.measure(range(n), range(n))
qcShift.barrier(range(n + ancilla)) #add a barrier to mark the end of the measuring phase.
qcShift.draw(output = "mpl")
def create_shift_gate(n:int, circular:bool = False):
"""Creates a gate out of a shift circuit.
Args:
n : number of data qubits.
seed : initial state of the data qubits.
circular : flag indicating whether the shift register is circular in nature or not.
"""
if circular:
name = "Circular Left Shift"
else:
name = "Left Shift"
ancilla = n
#n data qubits and the same number of ancillary qubits and one extra qubit to act as the control
#bit for deciding if the operation should be a left shift or a circular left shift.
shiftGate = QuantumCircuit(n + ancilla + 1, name=name)
for qubit in range(1, n + ancilla)[::-1]:
shiftGate.swap(qubit, qubit - 1)
#implement the controlled swap.
shiftGate.cx(0, n)
shiftGate.toffoli(n + ancilla, n, 0)
shiftGate.cx(0, n)
return shiftGate.to_gate()
n = 4
seed = '1011'
ancilla = n
#n data qubits and the same number of ancillary qubits and one extra qubit to act as the control
#bit for deciding if the operation should be a left shift or a circular left shift.
shiftCirc = QuantumCircuit(n + ancilla + 1, n)
seed = list(map(int, list(seed)))[::-1]
circular = True
#encode the circuit
for bit in range(len(seed)):
if seed[bit] == 1:
shiftCirc.x(bit)
if circular:
shiftCirc.x(n + ancilla) #encode the control qubit.
shiftCirc.barrier(range(n + ancilla + 1))
shiftGate = create_shift_gate(n, circular)
#perform 2 shift operations.
shiftCirc.append(shiftGate, range(n + ancilla + 1))
shiftCirc.append(shiftGate, range(n + ancilla + 1))
shiftCirc.barrier(range(n + ancilla + 1))
#get the state of the data qubits.
shiftCirc.measure(range(n), range(n))
shiftCirc.barrier(range(n + ancilla))
#draw the circuit.
shiftCirc.draw(output="mpl")
#get the state of the shift register
backend = BasicAer.get_backend("statevector_simulator")
register_state = execute(shiftCirc, backend, shots=1024).result().get_counts()
plot_histogram(register_state)
#as it can be seen, the state of the register is '1110' which is what
#you would get by performing two left shift operations circularly.
#to see what the shift gate is acutally made up of.
seeShiftGate = QuantumCircuit(n + ancilla + 1)
seeShiftGate.append(shiftGate, range(n + ancilla + 1))
seeShiftGate.decompose().draw(output = "mpl")
#q8 is the control qubit. q0-q3 are the data qubits and q4-q7 are the ancillary qubits.
|
https://github.com/Aman-Agrawal01/Quantum-Computing-Qiskit-Tutorial
|
Aman-Agrawal01
|
from qiskit import *
%matplotlib inline
import numpy as np
from qiskit.visualization import plot_histogram
n = 2 #Number of qubits
qr1 = QuantumRegister(size=n)
qr2 = QuantumRegister(size=1)
cr = ClassicalRegister(size=n)
def function(circuit,fn):
if fn == 'const-0':
circuit.x(qr2)
circuit.barrier()
circuit.h(qr1)
circuit.h(qr2)
circuit.barrier()
circuit.barrier()
circuit.h(qr1)
circuit.barrier()
circuit.measure(qr1,cr)
elif fn == 'const-1':
circuit.x(qr2)
circuit.barrier()
circuit.h(qr1)
circuit.h(qr2)
circuit.barrier()
circuit.x(qr1)
circuit.barrier()
circuit.h(qr1)
circuit.barrier()
circuit.measure(qr1,cr)
elif fn == 'balanced':
circuit.x(qr2)
circuit.barrier()
circuit.h(qr1)
circuit.h(qr2)
circuit.barrier()
circuit.cx(qr1[0],qr2)
circuit.barrier()
circuit.h(qr1)
circuit.barrier()
circuit.measure(qr1,cr)
return circuit
circuit_1 = QuantumCircuit(qr1,qr2,cr)
circuit_1 = function(circuit_1,'const-1')
circuit_1.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit_1,backend=simulator).result()
plot_histogram(result.get_counts())
circuit_0 = QuantumCircuit(qr1,qr2,cr)
circuit_0 = function(circuit_0,'const-0')
circuit_0.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit_0,backend=simulator).result()
plot_histogram(result.get_counts())
circuit_b = QuantumCircuit(qr1,qr2,cr)
circuit_b = function(circuit_b,'balanced')
circuit_b.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit_b,backend=simulator).result()
plot_histogram(result.get_counts())
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# 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.
"""
Initialize test.
"""
import math
import unittest
import numpy as np
from ddt import ddt, data
from qiskit import QuantumCircuit
from qiskit import QuantumRegister
from qiskit import ClassicalRegister
from qiskit import transpile
from qiskit import execute, assemble, BasicAer
from qiskit.quantum_info import state_fidelity, Statevector, Operator
from qiskit.exceptions import QiskitError
from qiskit.test import QiskitTestCase
from qiskit.extensions.quantum_initializer import Initialize
@ddt
class TestInitialize(QiskitTestCase):
"""Qiskit Initialize tests."""
_desired_fidelity = 0.99
def test_uniform_superposition(self):
"""Initialize a uniform superposition on 2 qubits."""
desired_vector = [0.5, 0.5, 0.5, 0.5]
qr = QuantumRegister(2, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_deterministic_state(self):
"""Initialize a computational-basis state |01> on 2 qubits."""
desired_vector = [0, 1, 0, 0]
qr = QuantumRegister(2, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_statevector(self):
"""Initialize gates from a statevector."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/5134 (footnote)
desired_vector = [0, 0, 0, 1]
qc = QuantumCircuit(2)
statevector = Statevector.from_label("11")
qc.initialize(statevector, [0, 1])
self.assertEqual(qc.data[0].operation.params, desired_vector)
def test_bell_state(self):
"""Initialize a Bell state on 2 qubits."""
desired_vector = [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]
qr = QuantumRegister(2, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_ghz_state(self):
"""Initialize a GHZ state on 3 qubits."""
desired_vector = [1 / math.sqrt(2), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(2)]
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1], qr[2]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_initialize_register(self):
"""Initialize one register out of two."""
desired_vector = [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]
qr = QuantumRegister(2, "qr")
qr2 = QuantumRegister(2, "qr2")
qc = QuantumCircuit(qr, qr2)
qc.initialize(desired_vector, qr)
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, np.kron([1, 0, 0, 0], desired_vector))
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_initialize_one_by_one(self):
"""Initializing qubits individually into product state same as initializing the pair."""
qubit_0_state = [1, 0]
qubit_1_state = [1 / math.sqrt(2), 1 / math.sqrt(2)]
qr = QuantumRegister(2, "qr")
qc_a = QuantumCircuit(qr)
qc_a.initialize(np.kron(qubit_1_state, qubit_0_state), qr)
qc_b = QuantumCircuit(qr)
qc_b.initialize(qubit_0_state, [qr[0]])
qc_b.initialize(qubit_1_state, [qr[1]])
job = execute([qc_a, qc_b], BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector_a = result.get_statevector(0)
statevector_b = result.get_statevector(1)
fidelity = state_fidelity(statevector_a, statevector_b)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_single_qubit(self):
"""Initialize a single qubit to a weighted superposition state."""
desired_vector = [1 / math.sqrt(3), math.sqrt(2) / math.sqrt(3)]
qr = QuantumRegister(1, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_random_3qubit(self):
"""Initialize to a non-trivial 3-qubit state."""
desired_vector = [
1 / math.sqrt(16) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(16) * complex(1, 1),
0,
0,
1 / math.sqrt(8) * complex(1, 2),
1 / math.sqrt(16) * complex(1, 0),
0,
]
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1], qr[2]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_random_4qubit(self):
"""Initialize to a non-trivial 4-qubit state."""
desired_vector = [
1 / math.sqrt(4) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
0,
0,
0,
0,
0,
0,
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(8) * complex(0, 1),
0,
0,
0,
0,
1 / math.sqrt(4) * complex(1, 0),
1 / math.sqrt(8) * complex(1, 0),
]
qr = QuantumRegister(4, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1], qr[2], qr[3]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_malformed_amplitudes(self):
"""Initializing to a vector with 3 amplitudes fails."""
desired_vector = [1 / math.sqrt(3), math.sqrt(2) / math.sqrt(3), 0]
qr = QuantumRegister(2, "qr")
qc = QuantumCircuit(qr)
self.assertRaises(QiskitError, qc.initialize, desired_vector, [qr[0], qr[1]])
def test_non_unit_probability(self):
"""Initializing to a vector with probabilities not summing to 1 fails."""
desired_vector = [1, 1]
qr = QuantumRegister(2, "qr")
qc = QuantumCircuit(qr)
self.assertRaises(QiskitError, qc.initialize, desired_vector, [qr[0], qr[1]])
def test_normalize(self):
"""Test initializing with a non-normalized vector is normalized, if specified."""
desired_vector = [1, 1]
normalized = np.asarray(desired_vector) / np.linalg.norm(desired_vector)
qc = QuantumCircuit(1)
qc.initialize(desired_vector, [0], normalize=True)
op = qc.data[0].operation
self.assertAlmostEqual(np.linalg.norm(op.params), 1)
self.assertEqual(Statevector(qc), Statevector(normalized))
def test_wrong_vector_size(self):
"""Initializing to a vector with a size different to the qubit parameter length.
See https://github.com/Qiskit/qiskit-terra/issues/2372"""
qr = QuantumRegister(2)
random_state = [
1 / math.sqrt(4) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
0,
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(8) * complex(0, 1),
0,
1 / math.sqrt(4) * complex(1, 0),
1 / math.sqrt(8) * complex(1, 0),
]
qc = QuantumCircuit(qr)
self.assertRaises(QiskitError, qc.initialize, random_state, qr[0:2])
def test_initialize_middle_circuit(self):
"""Reset + initialize gives the correct statevector."""
desired_vector = [0.5, 0.5, 0.5, 0.5]
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.reset(qr[0])
qc.reset(qr[1])
qc.initialize(desired_vector, [qr[0], qr[1]])
qc.measure(qr, cr)
# statevector simulator does not support reset
shots = 2000
threshold = 0.005 * shots
job = execute(qc, BasicAer.get_backend("qasm_simulator"), shots=shots, seed_simulator=42)
result = job.result()
counts = result.get_counts()
target = {"00": shots / 4, "01": shots / 4, "10": shots / 4, "11": shots / 4}
self.assertDictAlmostEqual(counts, target, threshold)
def test_math_amplitudes(self):
"""Initialize to amplitudes given by math expressions"""
desired_vector = [
0,
math.cos(math.pi / 3) * complex(0, 1) / math.sqrt(4),
math.sin(math.pi / 3) / math.sqrt(4),
0,
0,
0,
0,
0,
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(8) * complex(0, 1),
0,
0,
0,
0,
1 / math.sqrt(4),
1 / math.sqrt(4) * complex(0, 1),
]
qr = QuantumRegister(4, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1], qr[2], qr[3]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_combiner(self):
"""Combining two circuits containing initialize."""
desired_vector_1 = [1.0 / math.sqrt(2), 1.0 / math.sqrt(2)]
desired_vector_2 = [1.0 / math.sqrt(2), -1.0 / math.sqrt(2)]
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(1, "cr")
qc1 = QuantumCircuit(qr, cr)
qc1.initialize(desired_vector_1, [qr[0]])
qc2 = QuantumCircuit(qr, cr)
qc2.initialize(desired_vector_2, [qr[0]])
job = execute(qc1.compose(qc2), BasicAer.get_backend("statevector_simulator"))
result = job.result()
quantum_state = result.get_statevector()
fidelity = state_fidelity(quantum_state, desired_vector_2)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_equivalence(self):
"""Test two similar initialize instructions evaluate to equal."""
desired_vector = [0.5, 0.5, 0.5, 0.5]
qr = QuantumRegister(2, "qr")
qc1 = QuantumCircuit(qr, name="circuit")
qc1.initialize(desired_vector, [qr[0], qr[1]])
qc2 = QuantumCircuit(qr, name="circuit")
qc2.initialize(desired_vector, [qr[0], qr[1]])
self.assertEqual(qc1, qc2)
def test_max_number_cnots(self):
"""
Check if the number of cnots <= 2^(n+1) - 2n (arXiv:quant-ph/0406176)
"""
num_qubits = 4
_optimization_level = 0
vector = np.array(
[
0.1314346 + 0.0j,
0.32078572 - 0.01542775j,
0.13146466 + 0.0945312j,
0.21090852 + 0.07935982j,
0.1700122 - 0.07905648j,
0.15570757 - 0.12309154j,
0.18039667 + 0.04904504j,
0.22227187 - 0.05055569j,
0.23573255 - 0.09894111j,
0.27307292 - 0.10372994j,
0.24162792 + 0.1090791j,
0.3115577 + 0.1211683j,
0.1851788 + 0.08679141j,
0.36226463 - 0.09940202j,
0.13863395 + 0.10558225j,
0.30767986 + 0.02073838j,
]
)
vector = vector / np.linalg.norm(vector)
qr = QuantumRegister(num_qubits, "qr")
circuit = QuantumCircuit(qr)
circuit.initialize(vector, qr)
b = transpile(
circuit,
basis_gates=["u1", "u2", "u3", "cx"],
optimization_level=_optimization_level,
seed_transpiler=42,
)
number_cnots = b.count_ops()["cx"]
max_cnots = 2 ** (num_qubits + 1) - 2 * num_qubits
self.assertLessEqual(number_cnots, max_cnots)
def test_from_labels(self):
"""Initialize from labels."""
desired_sv = Statevector.from_label("01+-lr")
qc = QuantumCircuit(6)
qc.initialize("01+-lr", range(6))
actual_sv = Statevector.from_instruction(qc)
self.assertTrue(desired_sv == actual_sv)
def test_from_int(self):
"""Initialize from int."""
desired_sv = Statevector.from_label("110101")
qc = QuantumCircuit(6)
qc.initialize(53, range(6))
actual_sv = Statevector.from_instruction(qc)
self.assertTrue(desired_sv == actual_sv)
def _remove_resets(self, circ):
circ.data = [instr for instr in circ.data if instr.operation.name != "reset"]
def test_global_phase_random(self):
"""Test global phase preservation with random state vectors"""
from qiskit.quantum_info.random import random_statevector
repeats = 5
for n_qubits in [1, 2, 4]:
for irep in range(repeats):
with self.subTest(i=f"{n_qubits}_{irep}"):
dim = 2**n_qubits
qr = QuantumRegister(n_qubits)
initializer = QuantumCircuit(qr)
target = random_statevector(dim)
initializer.initialize(target, qr)
uninit = initializer.data[0].operation.definition
self._remove_resets(uninit)
evolve = Statevector(uninit)
self.assertEqual(target, evolve)
def test_global_phase_1q(self):
"""Test global phase preservation with some simple 1q statevectors"""
target_list = [
Statevector([1j, 0]),
Statevector([0, 1j]),
Statevector([1j / np.sqrt(2), 1j / np.sqrt(2)]),
]
n_qubits = 1
dim = 2**n_qubits
qr = QuantumRegister(n_qubits)
for target in target_list:
with self.subTest(i=target):
initializer = QuantumCircuit(qr)
initializer.initialize(target, qr)
# need to get rid of the resets in order to use the Operator class
disentangler = Operator(initializer.data[0].operation.definition.data[1].operation)
zero = Statevector.from_int(0, dim)
actual = zero & disentangler
self.assertEqual(target, actual)
@data(2, "11", [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
def test_decompose_contains_stateprep(self, state):
"""Test initialize decomposes to a StatePreparation and reset"""
qc = QuantumCircuit(2)
qc.initialize(state)
decom_circ = qc.decompose()
self.assertEqual(decom_circ.data[0].operation.name, "reset")
self.assertEqual(decom_circ.data[1].operation.name, "reset")
self.assertEqual(decom_circ.data[2].operation.name, "state_preparation")
def test_mutating_params(self):
"""Test mutating Initialize params correctly updates StatePreparation params"""
init = Initialize("11")
init.params = "00"
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.append(init, qr)
decom_circ = qc.decompose()
self.assertEqual(decom_circ.data[2].operation.name, "state_preparation")
self.assertEqual(decom_circ.data[2].operation.params, ["0", "0"])
class TestInstructionParam(QiskitTestCase):
"""Test conversion of numpy type parameters."""
def test_diag(self):
"""Verify diagonal gate converts numpy.complex to complex."""
# ref: https://github.com/Qiskit/qiskit-aer/issues/696
diag = np.array([1 + 0j, 1 + 0j])
qc = QuantumCircuit(1)
qc.diagonal(list(diag), [0])
params = qc.data[0].operation.params
self.assertTrue(
all(isinstance(p, complex) and not isinstance(p, np.number) for p in params)
)
qobj = assemble(qc)
params = qobj.experiments[0].instructions[0].params
self.assertTrue(
all(isinstance(p, complex) and not isinstance(p, np.number) for p in params)
)
def test_init(self):
"""Verify initialize gate converts numpy.complex to complex."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/4151
qc = QuantumCircuit(1)
vec = np.array([0, 0 + 1j])
qc.initialize(vec, 0)
params = qc.data[0].operation.params
self.assertTrue(
all(isinstance(p, complex) and not isinstance(p, np.number) for p in params)
)
qobj = assemble(qc)
params = qobj.experiments[0].instructions[0].params
self.assertTrue(
all(isinstance(p, complex) and not isinstance(p, np.number) for p in params)
)
if __name__ == "__main__":
unittest.main()
|
https://github.com/IceKhan13/purplecaffeine
|
IceKhan13
|
"""Tests for Trial."""
import os
import shutil
from pathlib import Path
from typing import Optional
from unittest import TestCase
import numpy as np
from qiskit import QuantumCircuit, __version__
from qiskit.circuit.library import XGate
from qiskit.quantum_info import Operator
from purplecaffeine import Trial, LocalStorage, BaseStorage as TrialStorage
def dummy_trial(
name: Optional[str] = "test_trial", storage: Optional[TrialStorage] = None
):
"""Returns dummy trial for tests.
Returns:
dummy trial
"""
trial = Trial(name=name, storage=storage)
trial.add_description("Short desc")
trial.add_metric("test_metric", 42)
trial.add_parameter("test_parameter", "parameter")
trial.add_circuit("test_circuit", QuantumCircuit(2))
trial.add_operator("test_operator", Operator(XGate()))
trial.add_text("test_text", "text")
trial.add_array("test_array", np.array([42]))
trial.add_tag("qiskit")
trial.add_tag("test")
trial.add_version("numpy", "1.2.3-4")
return trial
class TestTrial(TestCase):
"""TestTrial."""
def setUp(self) -> None:
"""SetUp Trial object."""
current_directory = os.path.dirname(os.path.abspath(__file__))
self.save_path = os.path.join(current_directory, "resources")
if not os.path.exists(self.save_path):
Path(self.save_path).mkdir(parents=True, exist_ok=True)
self.local_storage = LocalStorage(path=self.save_path)
def test_trial_context(self):
"""Test train context."""
uuid = "some_uuid"
with Trial(name="test_trial", storage=self.local_storage, uuid=uuid) as trial:
trial.add_metric("test_metric", 42)
trial.read(trial_id=uuid)
self.assertTrue(
os.path.isfile(os.path.join(self.save_path, f"trial_{uuid}/trial.json"))
)
self.assertEqual(trial.metrics, [["test_metric", 42]])
self.assertEqual(trial.versions, [["qiskit", __version__]])
def test_add_trial(self):
"""Test adding stuff into Trial."""
trial = dummy_trial()
self.assertEqual(trial.description, "Short desc")
self.assertEqual(trial.metrics, [["test_metric", 42]])
self.assertEqual(trial.parameters, [["test_parameter", "parameter"]])
self.assertEqual(trial.circuits, [["test_circuit", QuantumCircuit(2)]])
self.assertEqual(trial.operators, [["test_operator", Operator(XGate())]])
self.assertEqual(trial.texts, [["test_text", "text"]])
self.assertEqual(trial.arrays, [["test_array", np.array([42])]])
self.assertEqual(trial.tags, ["qiskit", "test"])
self.assertEqual(trial.versions, [["numpy", "1.2.3-4"]])
def test_save_read_local_trial(self):
"""Test save and read Trial locally."""
trial = dummy_trial(storage=self.local_storage)
trial.save()
self.assertTrue(
os.path.isfile(
os.path.join(self.save_path, f"trial_{trial.uuid}/trial.json")
)
)
recovered = trial.read(trial_id=trial.uuid)
self.assertEqual(recovered.description, "Short desc")
self.assertEqual(recovered.metrics, [["test_metric", 42]])
self.assertEqual(recovered.parameters, [["test_parameter", "parameter"]])
self.assertEqual(recovered.circuits, [["test_circuit", QuantumCircuit(2)]])
self.assertEqual(recovered.operators, [["test_operator", Operator(XGate())]])
self.assertEqual(recovered.texts, [["test_text", "text"]])
self.assertEqual(recovered.arrays, [["test_array", np.array([42])]])
self.assertEqual(recovered.tags, ["qiskit", "test"])
self.assertEqual(recovered.versions, [["numpy", "1.2.3-4"]])
def test_export_import(self):
"""Test export and import Trial from shared file."""
trial = dummy_trial()
# Export
trial.export_to_shared_file(path=self.save_path)
self.assertTrue(
os.path.isdir(os.path.join(self.save_path, f"trial_{trial.uuid}"))
)
# Import
new_trial = Trial("test_import").import_from_shared_file(
self.save_path, trial.uuid
)
self.assertEqual(new_trial.description, "Short desc")
self.assertEqual(new_trial.metrics, [["test_metric", 42]])
self.assertEqual(new_trial.parameters, [["test_parameter", "parameter"]])
self.assertEqual(new_trial.circuits, [["test_circuit", QuantumCircuit(2)]])
self.assertEqual(new_trial.operators, [["test_operator", Operator(XGate())]])
self.assertEqual(new_trial.texts, [["test_text", "text"]])
self.assertEqual(new_trial.arrays, [["test_array", np.array([42])]])
self.assertEqual(new_trial.tags, ["qiskit", "test"])
self.assertEqual(new_trial.versions, [["numpy", "1.2.3-4"]])
def tearDown(self) -> None:
"""TearDown Trial object."""
file_to_remove = os.path.join(self.save_path)
if os.path.exists(file_to_remove):
shutil.rmtree(file_to_remove)
|
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.
"""Example on how to load a file into a QuantumCircuit."""
from qiskit import QuantumCircuit
from qiskit import execute, BasicAer
circ = QuantumCircuit.from_qasm_file("examples/qasm/entangled_registers.qasm")
print(circ)
# See the backend
sim_backend = BasicAer.get_backend("qasm_simulator")
# Compile and run the Quantum circuit on a local simulator backend
job_sim = execute(circ, sim_backend)
sim_result = job_sim.result()
# Show the results
print("simulation: ", sim_result)
print(sim_result.get_counts(circ))
|
https://github.com/AnikenC/JaxifiedQiskit
|
AnikenC
|
import numpy as np
import qiskit
from qiskit import pulse
from qiskit_dynamics import Solver, DynamicsBackend
from qiskit_dynamics.pulse import InstructionToSignals
import jax.numpy as jnp
from jax import jit, vmap, block_until_ready
import chex
from typing import Optional, Union
from library.utils import PauliToQuditOperator
class JaxedDynamicsBackend:
def __init__(
self,
):
super().__init__()
class JaxedSolver:
def __init__(
self,
schedule_func,
solver,
dt,
carrier_freqs,
ham_chans,
ham_ops,
t_span,
rtol,
atol,
):
super().__init__()
self.schedule_func = schedule_func
self.solver = solver
self.dt = dt
self.carrier_freqs = carrier_freqs
self.ham_chans = ham_chans
self.ham_ops = ham_ops
self.t_span = t_span
self.rtol = rtol
self.atol = atol
self.fast_batched_sim = jit(vmap(self.run_sim))
def run_sim(self, y0, obs, params):
sched = self.schedule_func(params)
converter = InstructionToSignals(
self.dt, carriers=self.carrier_freqs, channels=self.ham_chans
)
signals = converter.get_signals(sched)
results = self.solver.solve(
t_span=self.t_span,
y0=y0 / jnp.linalg.norm(y0),
t_eval=self.t_span,
signals=signals,
rtol=self.rtol,
atol=self.atol,
convert_results=False,
method="jax_odeint",
)
state_vec = results.y.data[-1]
state_vec = state_vec / jnp.linalg.norm(state_vec)
new_vec = obs @ state_vec
probs_vec = jnp.abs(new_vec) ** 2
probs_vec = jnp.clip(probs_vec, a_min=0.0, a_max=1.0)
# Shots instead of probabilities
return probs_vec
def estimate2(self, batch_y0, batch_params, batch_obs_str):
batch_obs = jnp.zeros(
(batch_y0.shape[0], batch_y0.shape[1], batch_y0.shape[1]),
dtype=jnp.complex64,
)
num_qubits = len(batch_obs_str[0])
for i, b_str in enumerate(batch_obs_str):
batch_obs = batch_obs.at[i].set(
PauliToQuditOperator(b_str, int(batch_y0.shape[1] ** (1 / num_qubits)))
)
return self.fast_batched_sim(batch_y0, batch_obs, batch_params)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse3Q
# TODO: This example should use a real mock backend.
backend = FakeOpenPulse3Q()
d2 = pulse.DriveChannel(2)
with pulse.build(backend) as bell_prep:
pulse.u2(0, math.pi, 0)
pulse.cx(0, 1)
with pulse.build(backend) as decoupled_bell_prep_and_measure:
# We call our bell state preparation schedule constructed above.
with pulse.align_right():
pulse.call(bell_prep)
pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2)
pulse.barrier(0, 1, 2)
registers = pulse.measure_all()
decoupled_bell_prep_and_measure.draw()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, execute
from qiskit.providers.fake_provider import FakeVigoV2
from qiskit.visualization import plot_gate_map
backend = FakeVigoV2()
plot_gate_map(backend)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import *
from qiskit.visualization import plot_histogram
# quantum circuit to make a Bell state
bell = QuantumCircuit(2, 2)
bell.h(0)
bell.cx(0, 1)
meas = QuantumCircuit(2, 2)
meas.measure([0,1], [0,1])
# execute the quantum circuit
backend = BasicAer.get_backend('qasm_simulator') # the device to run on
circ = bell.compose(meas)
result = backend.run(transpile(circ, backend), shots=1000).result()
counts = result.get_counts(circ)
print(counts)
plot_histogram(counts)
# Execute 2-qubit Bell state again
second_result = backend.run(transpile(circ, backend), shots=1000).result()
second_counts = second_result.get_counts(circ)
# Plot results with legend
legend = ['First execution', 'Second execution']
plot_histogram([counts, second_counts], legend=legend)
plot_histogram([counts, second_counts], legend=legend, sort='desc', figsize=(15,12),
color=['orange', 'black'], bar_labels=False)
from qiskit.visualization import plot_state_city, plot_bloch_multivector
from qiskit.visualization import plot_state_paulivec, plot_state_hinton
from qiskit.visualization import plot_state_qsphere
# execute the quantum circuit
backend = BasicAer.get_backend('statevector_simulator') # the device to run on
result = backend.run(transpile(bell, backend)).result()
psi = result.get_statevector(bell)
plot_state_city(psi)
plot_state_hinton(psi)
plot_state_qsphere(psi)
plot_state_paulivec(psi)
plot_bloch_multivector(psi)
plot_state_city(psi, title="My City", color=['black', 'orange'])
plot_state_hinton(psi, title="My Hinton")
plot_state_paulivec(psi, title="My Paulivec", color=['purple', 'orange', 'green'])
plot_bloch_multivector(psi, title="My Bloch Spheres")
from qiskit.visualization import plot_bloch_vector
plot_bloch_vector([0,1,0])
plot_bloch_vector([0,1,0], title='My Bloch Sphere')
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Operator
from qiskit.transpiler.passes import UnitarySynthesis
circuit = QuantumCircuit(1)
circuit.rx(0.8, 0)
unitary = Operator(circuit).data
unitary_circ = QuantumCircuit(1)
unitary_circ.unitary(unitary, [0])
synth = UnitarySynthesis(basis_gates=["h", "s"], method="sk")
out = synth(unitary_circ)
out.draw('mpl')
|
https://github.com/AbeerVaishnav13/Using-Qiskit
|
AbeerVaishnav13
|
import numpy as np
from qiskit import *
from qiskit.visualization import plot_histogram, plot_gate_map
from qiskit.tools.monitor import job_monitor
from qiskit.test.mock import FakeProvider
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
backends = list(filter(lambda x:
not (x.configuration().simulator or
x.configuration().n_qubits <= 5),
FakeProvider().backends()))
ghz = QuantumCircuit(5, 5)
ghz.h(0)
for idx in range(1, 5):
ghz.cx(0, idx)
ghz.barrier()
ghz.measure(range(5), range(5))
ghz.draw(output='mpl')
ghz_basis = ghz.decompose()
ghz_basis.draw(output='mpl')
import inspect
inspect.signature(transpile)
qc = QuantumCircuit(3, 2)
# Preparation using superposition
qc.h(0)
qc.h(1)
qc.x(2)
qc.h(2)
qc.barrier()
# Function Uw
qc.x(0)
qc.ccx(0, 1, 2)
qc.x(0)
qc.barrier()
# Function Us
qc.h(0)
qc.h(1)
qc.x(0)
qc.x(1)
qc.ccx(0, 1, 2)
qc.x(0)
qc.x(1)
qc.h(0)
qc.h(1)
qc.barrier()
# Measure
qc.measure([0, 1], [0, 1])
qc.draw(output='mpl')
qc_basis = qc.decompose()
qc_basis.draw(output='mpl')
print(qc.depth(), ', ', qc_basis.depth())
# Without barrier
qc = QuantumCircuit(3, 2)
# Preparation using superposition
qc.h(0)
qc.h(1)
qc.x(2)
qc.h(2)
# Function Uw
qc.x(0)
qc.ccx(0, 1, 2)
qc.x(0)
# Function Us
qc.h(0)
qc.h(1)
qc.x(0)
qc.x(1)
qc.ccx(0, 1, 2)
qc.x(0)
qc.x(1)
qc.h(0)
qc.h(1)
# Measure
qc.measure([0, 1], [0, 1])
qc.draw(output='mpl')
qc_basis = qc.decompose()
qc_basis.draw(output='mpl')
print(qc.depth(), ', ', qc_basis.depth())
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../utils/")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling
print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
# from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
print(str(backend))
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
#! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# we have to feed initial_layout to calibration matrix
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
meas_calibs[0].draw("mpl")
dt_now = datetime.datetime.now()
print(dt_now)
filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl"
print(filename)
with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open(filename, "wb") as f:
pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
filename = "job_ids_ibmq_jakarta_100step_20220413_030821_.pkl" # change here
with open(filename, "rb") as f:
job_ids_dict = pickle.load(f)
job_ids = job_ids_dict["job_ids"]
cal_job_id = job_ids_dict["cal_job_id"]
retrieved_jobs = []
for job_id in job_ids:
retrieved_jobs.append(backend.retrieve_job(job_id))
retrieved_cal_job = backend.retrieve_job(cal_job_id)
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# we import all necessary methods and objects
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
from random import randrange
# we will use 10 quantum bits and 10 classical bits
qreg3 = QuantumRegister(10)
creg3 = ClassicalRegister(10)
mycircuit3 = QuantumCircuit(qreg3,creg3)
# we will store the index of each qubit to which x-gate is applied
picked_qubits=[]
for i in range(10):
if randrange(2) == 0: # Assume that 0 is Head and 1 is Tail
mycircuit3.x(qreg3[i]) # apply x-gate
print("x-gate is applied to the qubit with index",i)
picked_qubits.append(i) # i is picked
# measurement
mycircuit3.measure(qreg3,creg3)
print("Everything looks fine, let's continue ...")
# draw the circuit
drawer(mycircuit3)
# reexecute me if you DO NOT see the circuit diagram
def print_outcomes(counts): # takes a dictionary variable
for outcome in counts: # for each key-value in dictionary
reverse_outcome = ''
for i in outcome: # each string can be considered as a list of characters
reverse_outcome = i + reverse_outcome # each new symbol comes before the old symbol(s)
print(reverse_outcome,"is observed",counts[outcome],"times")
# execute the circuit and read the results
job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=128)
counts = job.result().get_counts(mycircuit3)
print_outcomes(counts)
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# I am a comment in python
print("Hello From Quantum World :-)")
# please run this cell
# import the objects from qiskit
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from random import randrange
# Create my circuit and register objects
qreg = QuantumRegister(2) # my quantum register
creg = ClassicalRegister(2) # my classical register
circuit = QuantumCircuit(qreg,creg) # my quantum circuit
# let's apply a Hadamard gate to the first qubit
circuit.h(qreg[0])
# let's set the second qubit to |1>
circuit.x(qreg[1])
# let's apply CNOT(first_qubit,second_qubit)
circuit.cx(qreg[0],qreg[1])
# let's measure the both qubits
circuit.measure(qreg,creg)
print("The execution of the cell was completed, and the circuit was created :)")
## execute the circuit 100 times
job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=1024)
# get the result
counts = job.result().get_counts(circuit)
print(counts)
# draw circuit
circuit.draw(output='mpl',reverse_bits=True)
# the output will be a "matplotlib.Figure" object
from qiskit import IBMQ
IBMQ.save_account('write YOUR IBM API TOKEN here')
# Then, execute this cell
IBMQ.stored_accounts()
IBMQ.load_accounts()
IBMQ.active_accounts()
IBMQ.backends()
IBMQ.backends(operational=True, simulator=False)
from qiskit.providers.ibmq import least_busy
least_busy(IBMQ.backends(simulator=False))
backend = least_busy(IBMQ.backends(simulator=True))
backend.name()
from qiskit import compile
qobj = compile(circuit, backend=backend, shots=1024)
job = backend.run(qobj)
result = job.result()
counts = result.get_counts()
print(counts)
backend_real = least_busy(IBMQ.backends(simulator=False))
backend_real.name()
backend_real.status()
qobj_real = compile(circuit, backend=backend_real, shots=1024)
job_real = backend_real.run(qobj_real)
job_real.queue_position()
result_real = job_real.result()
counts_real = result_real.get_counts()
print(counts_real)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import IntegerComparator
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
# set problem parameters
n_z = 2
z_max = 2
z_values = np.linspace(-z_max, z_max, 2**n_z)
p_zeros = [0.15, 0.25]
rhos = [0.1, 0.05]
lgd = [1, 2]
K = len(p_zeros)
alpha = 0.05
from qiskit_finance.circuit.library import GaussianConditionalIndependenceModel as GCI
u = GCI(n_z, z_max, p_zeros, rhos)
u.draw()
u_measure = u.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(u_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# analyze uncertainty circuit and determine exact solutions
p_z = np.zeros(2**n_z)
p_default = np.zeros(K)
values = []
probabilities = []
num_qubits = u.num_qubits
for i, prob in binary_probabilities.items():
# extract value of Z and corresponding probability
i_normal = int(i[-n_z:], 2)
p_z[i_normal] += prob
# determine overall default probability for k
loss = 0
for k in range(K):
if i[K - k - 1] == "1":
p_default[k] += prob
loss += lgd[k]
values += [loss]
probabilities += [prob]
values = np.array(values)
probabilities = np.array(probabilities)
expected_loss = np.dot(values, probabilities)
losses = np.sort(np.unique(values))
pdf = np.zeros(len(losses))
for i, v in enumerate(losses):
pdf[i] += sum(probabilities[values == v])
cdf = np.cumsum(pdf)
i_var = np.argmax(cdf >= 1 - alpha)
exact_var = losses[i_var]
exact_cvar = np.dot(pdf[(i_var + 1) :], losses[(i_var + 1) :]) / sum(pdf[(i_var + 1) :])
print("Expected Loss E[L]: %.4f" % expected_loss)
print("Value at Risk VaR[L]: %.4f" % exact_var)
print("P[L <= VaR[L]]: %.4f" % cdf[exact_var])
print("Conditional Value at Risk CVaR[L]: %.4f" % exact_cvar)
# plot loss PDF, expected loss, var, and cvar
plt.bar(losses, pdf)
plt.axvline(expected_loss, color="green", linestyle="--", label="E[L]")
plt.axvline(exact_var, color="orange", linestyle="--", label="VaR(L)")
plt.axvline(exact_cvar, color="red", linestyle="--", label="CVaR(L)")
plt.legend(fontsize=15)
plt.xlabel("Loss L ($)", size=15)
plt.ylabel("probability (%)", size=15)
plt.title("Loss Distribution", size=20)
plt.xticks(size=15)
plt.yticks(size=15)
plt.show()
# plot results for Z
plt.plot(z_values, p_z, "o-", linewidth=3, markersize=8)
plt.grid()
plt.xlabel("Z value", size=15)
plt.ylabel("probability (%)", size=15)
plt.title("Z Distribution", size=20)
plt.xticks(size=15)
plt.yticks(size=15)
plt.show()
# plot results for default probabilities
plt.bar(range(K), p_default)
plt.xlabel("Asset", size=15)
plt.ylabel("probability (%)", size=15)
plt.title("Individual Default Probabilities", size=20)
plt.xticks(range(K), size=15)
plt.yticks(size=15)
plt.grid()
plt.show()
# add Z qubits with weight/loss 0
from qiskit.circuit.library import WeightedAdder
agg = WeightedAdder(n_z + K, [0] * n_z + lgd)
from qiskit.circuit.library import LinearAmplitudeFunction
# define linear objective function
breakpoints = [0]
slopes = [1]
offsets = [0]
f_min = 0
f_max = sum(lgd)
c_approx = 0.25
objective = LinearAmplitudeFunction(
agg.num_sum_qubits,
slope=slopes,
offset=offsets,
# max value that can be reached by the qubit register (will not always be reached)
domain=(0, 2**agg.num_sum_qubits - 1),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
# define the registers for convenience and readability
qr_state = QuantumRegister(u.num_qubits, "state")
qr_sum = QuantumRegister(agg.num_sum_qubits, "sum")
qr_carry = QuantumRegister(agg.num_carry_qubits, "carry")
qr_obj = QuantumRegister(1, "objective")
# define the circuit
state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A")
# load the random variable
state_preparation.append(u.to_gate(), qr_state)
# aggregate
state_preparation.append(agg.to_gate(), qr_state[:] + qr_sum[:] + qr_carry[:])
# linear objective function
state_preparation.append(objective.to_gate(), qr_sum[:] + qr_obj[:])
# uncompute aggregation
state_preparation.append(agg.to_gate().inverse(), qr_state[:] + qr_sum[:] + qr_carry[:])
# draw the circuit
state_preparation.draw()
state_preparation_measure = state_preparation.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(state_preparation_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# evaluate the result
value = 0
for i, prob in binary_probabilities.items():
if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1":
value += prob
print("Exact Expected Loss: %.4f" % expected_loss)
print("Exact Operator Value: %.4f" % value)
print("Mapped Operator value: %.4f" % objective.post_processing(value))
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=state_preparation,
objective_qubits=[len(qr_state)],
post_processing=objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
# print results
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % expected_loss)
print("Estimated value:\t%.4f" % result.estimation_processed)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
# set x value to estimate the CDF
x_eval = 2
comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False)
comparator.draw()
def get_cdf_circuit(x_eval):
# define the registers for convenience and readability
qr_state = QuantumRegister(u.num_qubits, "state")
qr_sum = QuantumRegister(agg.num_sum_qubits, "sum")
qr_carry = QuantumRegister(agg.num_carry_qubits, "carry")
qr_obj = QuantumRegister(1, "objective")
qr_compare = QuantumRegister(1, "compare")
# define the circuit
state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A")
# load the random variable
state_preparation.append(u, qr_state)
# aggregate
state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:])
# comparator objective function
comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False)
state_preparation.append(comparator, qr_sum[:] + qr_obj[:] + qr_carry[:])
# uncompute aggregation
state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:])
return state_preparation
state_preparation = get_cdf_circuit(x_eval)
state_preparation.draw()
state_preparation_measure = state_preparation.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(state_preparation_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# evaluate the result
var_prob = 0
for i, prob in binary_probabilities.items():
if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1":
var_prob += prob
print("Operator CDF(%s)" % x_eval + " = %.4f" % var_prob)
print("Exact CDF(%s)" % x_eval + " = %.4f" % cdf[x_eval])
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_state)])
# construct amplitude estimation
ae_cdf = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_cdf = ae_cdf.estimate(problem)
# print results
conf_int = np.array(result_cdf.confidence_interval)
print("Exact value: \t%.4f" % cdf[x_eval])
print("Estimated value:\t%.4f" % result_cdf.estimation)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
def run_ae_for_cdf(x_eval, epsilon=0.01, alpha=0.05, simulator="aer_simulator"):
# construct amplitude estimation
state_preparation = get_cdf_circuit(x_eval)
problem = EstimationProblem(
state_preparation=state_preparation, objective_qubits=[len(qr_state)]
)
ae_var = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_var = ae_var.estimate(problem)
return result_var.estimation
def bisection_search(
objective, target_value, low_level, high_level, low_value=None, high_value=None
):
"""
Determines the smallest level such that the objective value is still larger than the target
:param objective: objective function
:param target: target value
:param low_level: lowest level to be considered
:param high_level: highest level to be considered
:param low_value: value of lowest level (will be evaluated if set to None)
:param high_value: value of highest level (will be evaluated if set to None)
:return: dictionary with level, value, num_eval
"""
# check whether low and high values are given and evaluated them otherwise
print("--------------------------------------------------------------------")
print("start bisection search for target value %.3f" % target_value)
print("--------------------------------------------------------------------")
num_eval = 0
if low_value is None:
low_value = objective(low_level)
num_eval += 1
if high_value is None:
high_value = objective(high_level)
num_eval += 1
# check if low_value already satisfies the condition
if low_value > target_value:
return {
"level": low_level,
"value": low_value,
"num_eval": num_eval,
"comment": "returned low value",
}
elif low_value == target_value:
return {"level": low_level, "value": low_value, "num_eval": num_eval, "comment": "success"}
# check if high_value is above target
if high_value < target_value:
return {
"level": high_level,
"value": high_value,
"num_eval": num_eval,
"comment": "returned low value",
}
elif high_value == target_value:
return {
"level": high_level,
"value": high_value,
"num_eval": num_eval,
"comment": "success",
}
# perform bisection search until
print("low_level low_value level value high_level high_value")
print("--------------------------------------------------------------------")
while high_level - low_level > 1:
level = int(np.round((high_level + low_level) / 2.0))
num_eval += 1
value = objective(level)
print(
"%2d %.3f %2d %.3f %2d %.3f"
% (low_level, low_value, level, value, high_level, high_value)
)
if value >= target_value:
high_level = level
high_value = value
else:
low_level = level
low_value = value
# return high value after bisection search
print("--------------------------------------------------------------------")
print("finished bisection search")
print("--------------------------------------------------------------------")
return {"level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success"}
# run bisection search to determine VaR
objective = lambda x: run_ae_for_cdf(x)
bisection_result = bisection_search(
objective, 1 - alpha, min(losses) - 1, max(losses), low_value=0, high_value=1
)
var = bisection_result["level"]
print("Estimated Value at Risk: %2d" % var)
print("Exact Value at Risk: %2d" % exact_var)
print("Estimated Probability: %.3f" % bisection_result["value"])
print("Exact Probability: %.3f" % cdf[exact_var])
# define linear objective
breakpoints = [0, var]
slopes = [0, 1]
offsets = [0, 0] # subtract VaR and add it later to the estimate
f_min = 0
f_max = 3 - var
c_approx = 0.25
cvar_objective = LinearAmplitudeFunction(
agg.num_sum_qubits,
slopes,
offsets,
domain=(0, 2**agg.num_sum_qubits - 1),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
cvar_objective.draw()
# define the registers for convenience and readability
qr_state = QuantumRegister(u.num_qubits, "state")
qr_sum = QuantumRegister(agg.num_sum_qubits, "sum")
qr_carry = QuantumRegister(agg.num_carry_qubits, "carry")
qr_obj = QuantumRegister(1, "objective")
qr_work = QuantumRegister(cvar_objective.num_ancillas - len(qr_carry), "work")
# define the circuit
state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, qr_work, name="A")
# load the random variable
state_preparation.append(u, qr_state)
# aggregate
state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:])
# linear objective function
state_preparation.append(cvar_objective, qr_sum[:] + qr_obj[:] + qr_carry[:] + qr_work[:])
# uncompute aggregation
state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:])
state_preparation_measure = state_preparation.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(state_preparation_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# evaluate the result
value = 0
for i, prob in binary_probabilities.items():
if prob > 1e-6 and i[-(len(qr_state) + 1)] == "1":
value += prob
# normalize and add VaR to estimate
value = cvar_objective.post_processing(value)
d = 1.0 - bisection_result["value"]
v = value / d if d != 0 else 0
normalized_value = v + var
print("Estimated CVaR: %.4f" % normalized_value)
print("Exact CVaR: %.4f" % exact_cvar)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=state_preparation,
objective_qubits=[len(qr_state)],
post_processing=cvar_objective.post_processing,
)
# construct amplitude estimation
ae_cvar = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_cvar = ae_cvar.estimate(problem)
# print results
d = 1.0 - bisection_result["value"]
v = result_cvar.estimation_processed / d if d != 0 else 0
print("Exact CVaR: \t%.4f" % exact_cvar)
print("Estimated CVaR:\t%.4f" % (v + var))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
import pickle
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
def trotter_gate(dt, to_instruction = True):
qc = QuantumCircuit(2)
qc.rx(2*dt,0)
qc.rz(2*dt,1)
qc.h(1)
qc.cx(1,0)
qc.rz(-2*dt, 0)
qc.rx(-2*dt, 1)
qc.rz(2*dt, 1)
qc.cx(1,0)
qc.h(1)
qc.rz(2*dt, 0)
return qc.to_instruction() if to_instruction else qc
trotter_gate(np.pi / 6, to_instruction=False).draw("mpl")
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
Trot_gate = trotter_gate(dt)
# Number of trotter steps
trotter_steps = 50 ### CAN BE >= 4
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(7)
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
qc.x([5]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Simulate time evolution under H_heis3 Hamiltonian
for _ in range(trotter_steps):
qc.append(Trot_gate, [qr[3], qr[5]])
qc.cx(qr[3], qr[1])
qc.cx(qr[5], qr[3])
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time/trotter_steps})
t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_qc = transpile(t3_qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(t3_qc, [qr[1], qr[3], qr[5]])
# Display circuit for confirmation
# st_qcs[-1].decompose().draw() # view decomposition of trotter gates
st_qcs[-1].draw("mpl") # only view trotter gates
# from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
shots = 8192
reps = 8
jobs = []
for _ in range(reps):
# execute
job = execute(st_qcs, backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=[5,3,1])
print('Job ID', cal_job.job_id())
dt_now = datetime.datetime.now()
print(dt_now)
with open("jobs_jakarta_50step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open("job_ids_jakarta_50step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
with open("jakarta_50step.pkl", "rb") as f:
job_list = pickle.load(f)
jobs = job_list["jobs"]
cal_job = job_list["cal_job"]
cal_results = cal_job.result()
print("retrieved cal_results")
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
mit_results = []
for i, job in enumerate(jobs):
mit_results.append( meas_fitter.filter.apply(job.result()) )
print("retrieved", i, "th results")
# Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits
def state_tomo(result, st_qcs):
# The expected final state; necessary to determine state tomography fidelity
target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Fit state tomography results
tomo_fitter = StateTomographyFitter(result, st_qcs)
rho_fit = tomo_fitter.fit(method='lstsq')
# Compute fidelity
fid = state_fidelity(rho_fit, target_state)
return fid
# Compute tomography fidelities for each repetition
fids = []
for result in mit_results:
fid = state_tomo(result, st_qcs)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/pranavdurai10/quantum-gates
|
pranavdurai10
|
'''
///////////////////////////////////////////////////////////////////////////
Code written by Pranav Durai for Quantum Computer on 28.05.2023 @ 20:22:15
Component: Pauli-Y-Gate (bit-flip-gate)
Framework: Qiskit 0.43.0
///////////////////////////////////////////////////////////////////////////
'''
# Import necessary libraries
from qiskit import QuantumCircuit, Aer, execute
# Create a quantum circuit with one qubit
circuit = QuantumCircuit(1)
# Apply Pauli-Y gate to the qubit
circuit.y(0)
# Measure the qubit
circuit.measure_all()
# Simulate the circuit using the local Aer simulator
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, simulator, shots=1)
# Get the result
result = job.result()
counts = result.get_counts(circuit)
# Print the measurement outcome
print("Measurement outcome:", list(counts.keys())[0])
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
%matplotlib inline
import qiskit.pulse as pulse
import qiskit.pulse.pulse_lib as pulse_lib
from qiskit.compiler import assemble
import qiskit
qiskit.__qiskit_version__
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='your-hub-name') # change to your hub name
backend = provider.get_backend('ibmq_poughkeepsie')
backend_config = backend.configuration()
from qiskit.tools.jupyter import backend_overview, backend_monitor
%qiskit_backend_monitor backend
backend_defaults = backend.defaults()
backend_devicespec = pulse.DeviceSpecification.create_from(backend)
dt = backend_config.dt
# choose device to work on
from qiskit import IBMQ
IBMQ.load_account()
qubit = 1
center_frequency_GHz = backend_defaults.qubit_freq_est[qubit]
# define frequencies to do VNA sweep
import numpy as np
frequency_span_kHz = 20000
frequency_step_kHz = 1000
frequency_min = center_frequency_GHz - frequency_span_kHz/2.e6
frequency_max = center_frequency_GHz + frequency_span_kHz/2.e6
frequencies_GHz = np.arange(frequency_min, frequency_max, frequency_step_kHz/1e6)
print(frequencies_GHz)
# drive pulse parameters
drive_power = 0.01
drive_samples = 128
drive_sigma = 16
# creating drive pulse
drive_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_power,
sigma=drive_sigma, name='mydrivepulse')
drive_pulse_qubit = drive_pulse(backend_devicespec.q[qubit].drive)
# measurement pulse parameters
meas_amp = 0.05
meas_samples = 1200
meas_sigma = 4
meas_risefall = 25
# creating measurement pulse
meas_pulse = pulse_lib.gaussian_square(duration=meas_samples, amp=meas_amp,
sigma=meas_sigma, risefall=meas_risefall,
name='mymeasurepulse')
meas_pulse_qubit = meas_pulse(backend_devicespec.q[qubit].measure)
# create acquire pulse
acq_cmd=pulse.Acquire(duration=meas_samples)
acq_cmd_qubit = acq_cmd(backend_devicespec.q, backend_devicespec.mem)
# combined measure and acquire pulse
measure_and_acquire_qubit = meas_pulse_qubit | acq_cmd_qubit
# scalefactor for received data
scale_factor = 1e-10
# schedules
schedules = []
schedule_LOs = []
num_shots_per_frequency = 256
for jj, drive_frequency in enumerate(frequencies_GHz):
# start an empty schedule with a label
this_schedule = pulse.Schedule(name="Frequency = {}".format(drive_frequency))
this_schedule += drive_pulse_qubit
this_schedule += measure_and_acquire_qubit << this_schedule.duration
schedules.append(this_schedule)
thisLO = pulse.LoConfig({backend_devicespec.q[qubit].drive: drive_frequency})
schedule_LOs.append(thisLO)
VNASweep_experiment_qobj = assemble(schedules, backend = backend,
meas_level=1, meas_return='single',
shots=num_shots_per_frequency,
schedule_los = schedule_LOs
)
schedules[-1].draw(channels_to_plot=[backend_devicespec.q[qubit].measure,
backend_devicespec.q[qubit].drive,
#backend_devicespec.q[qubit].acquire,
],
scaling=10.0)
job = backend.run(VNASweep_experiment_qobj)
from qiskit.tools.monitor import job_monitor
print(job.job_id())
job_monitor(job, monitor_async='True')
job = backend.retrieve_job('5d2e228e15ce0100196d8c22')
VNASweep_results = job.result(timeout=3600)
plot_X = frequencies_GHz
plot_Y = []
for kk, drive_frequency in enumerate(frequencies_GHz):
thisfrequency_results = VNASweep_results.get_memory(kk)*scale_factor
plot_Y.append( np.mean(thisfrequency_results[:, qubit]) )
import matplotlib.pyplot as plotter
plotter.plot(plot_X, plot_Y)
rough_frequency_qubit = frequencies_GHz [
np.where( plot_Y == np.max(plot_Y))[0]
].tolist()[0]
rough_frequency_qubit = round(rough_frequency_qubit, 5)
print(rough_frequency_qubit)
# Rabi experiment parameters
num_Rabi_points = 64
num_shots_per_point = 256
# drive parameters
drive_power_min = 0
drive_power_max = 0.1
drive_powers = np.linspace(drive_power_min, drive_power_max, num_Rabi_points)
drive_samples = 128
drive_sigma = 16
# create schedules for Rabi experiment
Rabi_schedules = []
Rabi_schedule_LOs = []
for ii, drive_power in enumerate(drive_powers):
rabi_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_power,
sigma=drive_sigma, name='rabi_pulse_{}'.format(ii))
rabi_pulse_qubit = rabi_pulse(backend_devicespec.q[qubit].drive)
# start an empty schedule with a label
this_schedule = pulse.Schedule(name="Rabi drive = {}".format(drive_power))
this_schedule += rabi_pulse_qubit
this_schedule += measure_and_acquire_qubit << this_schedule.duration
Rabi_schedules.append(this_schedule)
thisLO = pulse.LoConfig({backend_devicespec.q[qubit].drive: rough_frequency_qubit})
Rabi_schedule_LOs.append(thisLO)
Rabi_schedules[-1].draw(channels_to_plot=[backend_devicespec.q[qubit].measure,
backend_devicespec.q[qubit].drive,
#backend_devicespec.q[qubit].acquire,
],
scaling=10.0)
rabi_experiment_qobj = assemble (Rabi_schedules, backend = backend,
meas_level=1, meas_return='avg',
shots=num_shots_per_point,
schedule_los = Rabi_schedule_LOs
)
job = backend.run(rabi_experiment_qobj)
print(job.job_id())
job_monitor(job, monitor_async=True)
job = backend.retrieve_job('5d2e2a0099a509001888ab02')
Rabi_results = job.result(timeout=3600)
plot_X = drive_powers
plot_Y = []
for jj, drive_power in enumerate(drive_powers):
thispower_results = Rabi_results.get_memory(jj)*scale_factor
plot_Y.append( thispower_results[qubit] )
import matplotlib.pyplot as plotter
plot_Y = plot_Y - np.mean(plot_Y)
plotter.plot(plot_X, plot_Y)
from scipy.optimize import curve_fit
fit_func = lambda x,A,B,T,phi: (A*np.cos(2*np.pi*x/T+phi)+B)
#Fit the data
fitparams, conv = curve_fit(fit_func, plot_X, plot_Y, [3.0 ,0.0 ,0.04 ,0])
#get the pi amplitude
first_peak = abs(np.pi-fitparams[3])*fitparams[2]/(2*np.pi)
pi_amp = abs(fitparams[2]/2)
plotter.scatter(plot_X, plot_Y)
plotter.plot(plot_X, fit_func(plot_X, *fitparams), color='red')
plotter.axvline(first_peak, color='black', linestyle='dashed')
plotter.axvline(first_peak + pi_amp, color='black', linestyle='dashed')
plotter.xlabel('Pulse amplitude, a.u.', fontsize=20)
plotter.ylabel('Signal, a.u.', fontsize=20)
plotter.title('Rough Pi Amplitude Calibration', fontsize=20)
print('Pi Amplitude %f'%(pi_amp))
# Rabi experiment parameters
num_shots_gndexc = 512
# drive parameters
drive_power = pi_amp
print(drive_power)
# create schedules for Rabi experiment
gndexc_schedules = []
gndexc_schedule_LOs = []
pi_pulse = pulse_lib.gaussian(duration=drive_samples, amp=pi_amp,
sigma=drive_sigma, name='pi_pulse'.format(ii))
pi_pulse_qubit = pi_pulse(backend_devicespec.q[qubit].drive)
# ground state schedule
gnd_schedule = pulse.Schedule(name="ground state")
gnd_schedule += measure_and_acquire_qubit << gnd_schedule.duration
thisLO = pulse.LoConfig({backend_devicespec.q[qubit].drive: rough_frequency_qubit})
# excited state schedule
exc_schedule = pulse.Schedule(name="excited state")
exc_schedule += pi_pulse_qubit
exc_schedule += measure_and_acquire_qubit << exc_schedule.duration
thisLO = pulse.LoConfig({backend_devicespec.q[qubit].drive: rough_frequency_qubit})
gndexc_schedules.append(gnd_schedule)
gndexc_schedules.append(exc_schedule)
gndexc_schedule_LOs.append(thisLO)
gndexc_schedule_LOs.append(thisLO)
gndexc_schedules[0].draw(channels_to_plot=[backend_devicespec.q[qubit].measure,
backend_devicespec.q[qubit].drive,
#backend_devicespec.q[qubit].acquire,
],
scaling=10.0)
gndexc_schedules[1].draw(channels_to_plot=[backend_devicespec.q[qubit].measure,
backend_devicespec.q[qubit].drive,
#backend_devicespec.q[qubit].acquire,
],
scaling=10.0)
gndexc_experiment_qobj = assemble (gndexc_schedules, backend = backend,
meas_level=1, meas_return='single',
shots=num_shots_gndexc,
schedule_los = gndexc_schedule_LOs
)
job = backend.run(gndexc_experiment_qobj)
print(job.job_id())
job_monitor(job, monitor_async=True)
job = backend.retrieve_job('5d2e2c3a61157a0018e22440')
gndexc_results = job.result(timeout=3600)
gnd_results = gndexc_results.get_memory(0)[:, qubit]*scale_factor
exc_results = gndexc_results.get_memory(1)[:, qubit]*scale_factor
plotter.scatter(np.real(gnd_results), np.imag(gnd_results),
s=5, cmap='viridis',c='blue',alpha=0.5, label='state_0')
plotter.scatter(np.real(exc_results), np.imag(exc_results),
s=5, cmap='viridis',c='red',alpha=0.5, label='state_1')
mean_gnd = np.mean(gnd_results) # takes mean of both real and imaginary parts
mean_exc = np.mean(exc_results)
plotter.scatter(np.real(mean_gnd), np.imag(mean_gnd),
s=200, cmap='viridis',c='blue',alpha=1.0, label='state_0_mean')
plotter.scatter(np.real(mean_exc), np.imag(mean_exc),
s=200, cmap='viridis',c='red',alpha=1.0, label='state_1_mean')
plotter.xlabel('I (a.u.)')
plotter.xlabel('Q (a.u.)')
def get_01(IQ_data):
dist_0 = np.linalg.norm(np.array([
np.real(IQ_data) - np.real(mean_gnd),
np.imag(IQ_data) - np.imag(mean_gnd)
]))
dist_1 = np.linalg.norm(np.array([
np.real(IQ_data) - np.real(mean_exc),
np.imag(IQ_data) - np.imag(mean_exc)
]))
if dist_1 <= dist_0:
return 1
else:
return 0
print(get_01(mean_gnd), get_01(mean_exc))
# T1 experiment parameters
time_max_us = 500
time_step_us = 2
times_us = np.arange(1, time_max_us, time_step_us)
num_shots_per_point = 512
# drive parameters
drive_power = pi_amp
print(drive_power)
# create schedules for Ramsey experiment
T1_schedules = []
T1_schedule_LOs = []
T1_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_power,
sigma=drive_sigma, name='T1_pulse')
T1_pulse_qubit = T1_pulse(backend_devicespec.q[qubit].drive)
thisLO = pulse.LoConfig({backend_devicespec.q[qubit].drive: rough_frequency_qubit})
for ii, delay_time_us in enumerate(times_us):
# start an empty schedule with a label
this_schedule = pulse.Schedule(name="T1 delay = {} us".format(delay_time_us))
this_schedule += T1_pulse_qubit
this_schedule |= (measure_and_acquire_qubit << int(delay_time_us*1000/dt))
T1_schedules.append(this_schedule)
T1_schedule_LOs.append(thisLO)
T1_schedules[0].draw(channels_to_plot=[backend_devicespec.q[qubit].measure,
backend_devicespec.q[qubit].drive,
#backend_devicespec.q[qubit].acquire,
],
scaling=10.0)
T1_experiment_qobj = assemble (T1_schedules, backend = backend,
meas_level=1, meas_return='avg',
shots=num_shots_per_point,
schedule_los = T1_schedule_LOs
)
job = backend.run(T1_experiment_qobj)
print(job.job_id())
job_monitor(job, monitor_async=True)
job = backend.retrieve_job('5d2e79ad99a509001888ab09')
T1_results = job.result(timeout=3600)
plot_X = times_us
plot_Y = []
for jj, delay_time_us in enumerate(times_us):
thisdelay_results = T1_results.get_memory(jj)*scale_factor
plot_Y.append( thisdelay_results[qubit] )
plotter.plot(plot_X, plot_Y)
from scipy.optimize import curve_fit
fit_func2 = lambda x,A,B: (A*np.exp(-x/59.8)+B)
#Fit the data
fitparams2, conv2 = curve_fit(fit_func2, plot_X,
plot_Y,
[-1.0,-11])
print(f"T1 from backend = {backend.properties().qubits[qubit][0].value} us")
plotter.scatter(plot_X, plot_Y)
plotter.plot(plot_X, fit_func2(plot_X, *fitparams2), color='black')
plotter.xlim(0, np.max(plot_X))
plotter.xlabel('Delay before measurement, ($\mu$s)', fontsize=20)
plotter.ylabel('Measured signal, a.u.', fontsize=20)
# Ramsey experiment parameters
time_max_us = 100
time_step_us = 0.25
times_us = np.arange(1, time_max_us, time_step_us)
num_shots_per_point = 256
# drive parameters
drive_power = pi_amp/2
print(drive_power)
# create schedules for Ramsey experiment
Ramsey_schedules = []
Ramsey_schedule_LOs = []
ramsey_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_power,
sigma=drive_sigma, name='ramsey_pulse')
ramsey_pulse_qubit = ramsey_pulse(backend_devicespec.q[qubit].drive)
thisLO = pulse.LoConfig({backend_devicespec.q[qubit].drive: rough_frequency_qubit})
for ii, delay_time_us in enumerate(times_us):
# start an empty schedule with a label
this_schedule = pulse.Schedule(name="Ramsey delay = {} us".format(delay_time_us))
this_schedule += ramsey_pulse_qubit
this_schedule |= (ramsey_pulse_qubit << int(this_schedule.duration+delay_time_us*1000/dt))
this_schedule |= (measure_and_acquire_qubit << this_schedule.duration)
Ramsey_schedules.append(this_schedule)
Ramsey_schedule_LOs.append(thisLO)
Ramsey_schedules[-1].draw(channels_to_plot=[backend_devicespec.q[qubit].measure,
backend_devicespec.q[qubit].drive,
#backend_devicespec.q[qubit].acquire,
],
scaling=10.0)
ramsey_experiment_qobj = assemble (Ramsey_schedules, backend = backend,
meas_level=1, meas_return='avg',
shots=num_shots_per_point,
schedule_los = Ramsey_schedule_LOs
)
job = backend.run(ramsey_experiment_qobj)
print(job.job_id())
job_monitor(job, monitor_async=True)
job = backend.retrieve_job('5d2e75dc137af400181be14a')
Ramsey_results = job.result(timeout=3600)
plot_X = times_us
plot_Y = []
for jj, delay_time_us in enumerate(times_us):
thisdelay_results = Ramsey_results.get_memory(jj)[qubit]*scale_factor
plot_Y.append(np.mean(thisdelay_results))
plotter.plot(plot_X, (plot_Y))
from scipy.optimize import curve_fit
fit_func = lambda x,A,T,phi,T2p,B: (A*np.exp(-x/T2p)*(np.sin(2*np.pi*x/T+phi))+B)
#Fit the data
fitparams, conv = curve_fit(fit_func, plot_X,
plot_Y,
[1.0,10,0,4,34])
#off-resonance component
delT = fitparams[1]
delf_MHz = 1./(delT)
print(f"df = {delf_MHz} MHz")
first_peak = (np.pi-fitparams[2])*delT/(2*np.pi) + delT/4
second_peak = first_peak + delT
print(f"T2p = {fitparams[3]} us")
print(f"T2 from backend = {backend.properties().qubits[qubit][1].value} us")
#get the pi amplitude
plotter.scatter(plot_X, plot_Y)
plotter.plot(plot_X, fit_func(plot_X, *fitparams), color='red')
plotter.axvline(first_peak, color='black', linestyle='dashed')
plotter.axvline(second_peak, color='red', linestyle='dashed')
plotter.xlim(0, np.max(plot_X))
plotter.xlabel('Ramsey delay, ($\mu$s)', fontsize=20)
plotter.ylabel('Ramsey signal, a.u.', fontsize=20)
plotter.title('Rough $\Delta$f Calibration', fontsize=20)
precise_frequency_qubit_plus = round(rough_frequency_qubit + delf_MHz/1e3, 5)
precise_frequency_qubit_minus = round(rough_frequency_qubit - delf_MHz/1e3, 5)
print(f"{rough_frequency_qubit}->{precise_frequency_qubit_plus} or {precise_frequency_qubit_minus}")
# T2 experiment parameters
time_max_us = 125
time_step_us = 0.5
times_us = np.arange(1, time_max_us, time_step_us)
num_shots_per_point = 512
# drive parameters
drive_power_1 = pi_amp/2
drive_power_2 = pi_amp
print(drive_power_1)
print(drive_power_2)
# create schedules for Ramsey experiment
T2_schedules = []
T2_schedule_LOs = []
T2_pulse_pio2 = pulse_lib.gaussian(duration=drive_samples, amp=drive_power_1,
sigma=drive_sigma, name='T2_pio2_pulse')
T2_pulse_pio2_qubit = T2_pulse_pio2(backend_devicespec.q[qubit].drive)
T2_pulse_pi = pulse_lib.gaussian(duration=drive_samples, amp=drive_power_2,
sigma=drive_sigma, name='T2_pi_pulse')
T2_pulse_pi_qubit = T2_pulse_pi(backend_devicespec.q[qubit].drive)
thisLO = pulse.LoConfig({backend_devicespec.q[qubit].drive: precise_frequency_qubit_minus})
for ii, delay_time_us in enumerate(times_us):
# start an empty schedule with a label
this_schedule = pulse.Schedule(name="T2 delay = {} us".format(delay_time_us))
this_schedule |= T2_pulse_pio2_qubit
this_schedule |= (T2_pulse_pi_qubit << int(this_schedule.duration +
delay_time_us*1000/dt))
this_schedule |= (T2_pulse_pio2_qubit << int(this_schedule.duration +
delay_time_us*1000/dt))
this_schedule |= (measure_and_acquire_qubit << int(this_schedule.duration))
T2_schedules.append(this_schedule)
T2_schedule_LOs.append(thisLO)
T2_schedules[0].draw(channels_to_plot=[backend_devicespec.q[qubit].measure,
backend_devicespec.q[qubit].drive,
#backend_devicespec.q[qubit].acquire,
],
scaling=10.0)
T2_experiment_qobj = assemble (T2_schedules, backend = backend,
meas_level=1, meas_return='avg',
shots=num_shots_per_point,
schedule_los = T2_schedule_LOs
)
job = backend.run(T2_experiment_qobj)
print(job.job_id())
job_monitor(job, monitor_async=True)
T2job = backend.retrieve_job('5d2f6c0ae741150012334c44')
T2_results = T2job.result(timeout=3600)
plot_X = 2.*times_us
plot_Y = []
for jj, delay_time_us in enumerate(times_us):
thisdelay_results = T2_results.get_memory(jj)*scale_factor
plot_Y.append( thisdelay_results[qubit] )
plotter.plot(plot_X, plot_Y)
T2y_echo = plot_Y
T2x_echo = plot_X
from scipy.optimize import curve_fit
T2guess = backend.properties().qubits[qubit][1].value
fit_func2 = lambda x,A,B: (A*np.exp(-x/T2guess)+B)
#Fit the data
fitparams2, conv2 = curve_fit(fit_func2, plot_X,
plot_Y,
[-2.0,1.0])
print(f"T2 from backend = {backend.properties().qubits[qubit][1].value} us")
plotter.scatter(plot_X, plot_Y)
plotter.plot(plot_X, fit_func2(plot_X, *fitparams2), color='black')
plotter.xlim(0, np.max(plot_X))
plotter.xlabel('Total time, ($\mu$s)', fontsize=20)
plotter.ylabel('Measured signal, a.u.', fontsize=20)
# measurement pulse parameters
meas_amp = 0.1
meas_samples = 1200
meas_sigma = 4
meas_risefall = 25
# creating measurement pulse
meas_pulse = pulse_lib.gaussian_square(duration=meas_samples, amp=meas_amp,
sigma=meas_sigma, risefall=meas_risefall,
name='mymeasurepulse')
meas_pulse_qubit = meas_pulse(backend_devicespec.q[qubit].measure)
# create acquire pulse
acq_cmd=pulse.Acquire(duration=meas_samples)
acq_cmd_qubit = acq_cmd(backend_devicespec.q, backend_devicespec.mem)
# combined measure and acquire pulse
measure_and_acquire_qubit = meas_pulse_qubit | acq_cmd_qubit
# scalefactor for received data
scale_factor = 1e-10
# T2 experiment parameters
tau_us_min = 1
tau_us_max = 30
tau_step_us = 0.1
taus_us = np.arange(tau_us_min, tau_us_max, tau_step_us)
num_shots_per_point = 512
ncpmg = 10
# drive parameters
drive_power_1 = pi_amp/2
drive_power_2 = pi_amp
print(f"Total time ranges from {2.*ncpmg*taus_us[0]} to {2.*ncpmg*taus_us[-1]} us")
# create schedules for Ramsey experiment
T2cpmg_schedules = []
T2cpmg_schedule_LOs = []
T2cpmg_pulse_pio2 = pulse_lib.gaussian(duration=drive_samples, amp=drive_power_1,
sigma=drive_sigma, name='T2cpmg_pio2_pulse')
T2cpmg_pulse_pio2_qubit = T2cpmg_pulse_pio2(backend_devicespec.q[qubit].drive)
T2cpmg_pulse_pi = pulse_lib.gaussian(duration=drive_samples, amp=drive_power_2,
sigma=drive_sigma, name='T2cpmg_pi_pulse')
T2cpmg_pulse_pi_qubit = T2cpmg_pulse_pi(backend_devicespec.q[qubit].drive)
thisLO = pulse.LoConfig({backend_devicespec.q[qubit].drive: precise_frequency_qubit_minus})
for ii, delay_time_us in enumerate(taus_us):
# start an empty schedule with a label
this_schedule = pulse.Schedule(name="T2cpmg delay = {} us".format(delay_time_us))
this_schedule |= T2cpmg_pulse_pio2_qubit
this_schedule |= (T2cpmg_pulse_pi_qubit << int(this_schedule.duration +
delay_time_us*1000/dt))
for _ in range(ncpmg-1):
this_schedule |= (T2cpmg_pulse_pi_qubit << int(this_schedule.duration +
2*delay_time_us*1000/dt))
this_schedule |= (T2cpmg_pulse_pio2_qubit << int(this_schedule.duration +
delay_time_us*1000/dt))
this_schedule |= (measure_and_acquire_qubit << int(this_schedule.duration))
T2cpmg_schedules.append(this_schedule)
T2cpmg_schedule_LOs.append(thisLO)
T2cpmg_schedules[0].draw(channels_to_plot=[backend_devicespec.q[qubit].measure,
backend_devicespec.q[qubit].drive,
#backend_devicespec.q[qubit].acquire,
],
scaling=10.0)
T2cpmg_experiment_qobj = assemble (T2cpmg_schedules, backend = backend,
meas_level=1, meas_return='avg',
shots=num_shots_per_point,
schedule_los = T2cpmg_schedule_LOs
)
job = backend.run(T2cpmg_experiment_qobj)
print(job.job_id())
job_monitor(job, monitor_async=True)
T2cpmgjob = backend.retrieve_job('5d2f6e1aca4ad70012795340')
T2cpmg_results = T2cpmgjob.result(timeout=3600)
plot_X = 2.*ncpmg*taus_us
plot_Y = []
for jj, delay_time_us in enumerate(taus_us):
thisdelay_results = T2cpmg_results.get_memory(jj)*scale_factor
plot_Y.append( thisdelay_results[qubit] )
plotter.plot(plot_X, plot_Y)
T2y_cpmg = plot_Y
T2x_cpmg = plot_X
from scipy.optimize import curve_fit
T2guess = backend.properties().qubits[qubit][1].value
fit_func2 = lambda x,A,B: (A*np.exp(-x/T2guess)+B)
#Fit the data
fitparams2, conv2 = curve_fit(fit_func2, plot_X,
plot_Y,
[-2.0,1.0])
print(f"T2 from backend = {T2guess} us")
plotter.scatter(plot_X, plot_Y)
plotter.plot(plot_X, fit_func2(plot_X, *fitparams2), color='black')
plotter.xlim(0, np.max(plot_X))
plotter.xlabel('Total time, ($\mu$s)', fontsize=20)
plotter.ylabel('Measured signal, a.u.', fontsize=20)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Class for a Variational Principle."""
from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Sequence
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.quantum_info.operators.base_operator import BaseOperator
from ....exceptions import AlgorithmError
from ....gradients import BaseEstimatorGradient, BaseQGT, DerivativeType
class VariationalPrinciple(ABC):
"""A Variational Principle class. It determines the time propagation of parameters in a
quantum state provided as a parametrized quantum circuit (ansatz).
Attributes:
qgt (BaseQGT): Instance of a class used to compute the GQT.
gradient (BaseEstimatorGradient): Instance of a class used to compute the
state gradient.
"""
def __init__(
self,
qgt: BaseQGT,
gradient: BaseEstimatorGradient,
) -> None:
"""
Args:
qgt: Instance of a class used to compute the GQT.
gradient: Instance of a class used to compute the state gradient.
"""
self.qgt = qgt
self.gradient = gradient
def metric_tensor(
self, ansatz: QuantumCircuit, param_values: Sequence[float]
) -> Sequence[float]:
"""
Calculates a metric tensor according to the rules of this variational principle.
Args:
ansatz: Quantum state in the form of a parametrized quantum circuit.
param_values: Values of parameters to be bound.
Returns:
Metric tensor.
Raises:
AlgorithmError: If a QFI job fails.
"""
self.qgt.derivative_type = DerivativeType.REAL
try:
metric_tensor = self.qgt.run([ansatz], [param_values], [None]).result().qgts[0]
except Exception as exc:
raise AlgorithmError("The QFI primitive job failed!") from exc
return metric_tensor
@abstractmethod
def evolution_gradient(
self,
hamiltonian: BaseOperator,
ansatz: QuantumCircuit,
param_values: Sequence[float],
gradient_params: Sequence[Parameter] | None = None,
) -> np.ndarray:
"""
Calculates an evolution gradient according to the rules of this variational principle.
Args:
hamiltonian: Operator used for Variational Quantum Time Evolution.
ansatz: Quantum state in the form of a parametrized quantum circuit.
param_values: Values of parameters to be bound.
gradient_params: List of parameters with respect to which gradients should be computed.
If ``None`` given, gradients w.r.t. all parameters will be computed.
Returns:
An evolution gradient.
"""
pass
|
https://github.com/abhik-99/Qiskit-Summer-School
|
abhik-99
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
# our backend is the Pulse Simulator
from resources import helper
from qiskit.providers.aer import PulseSimulator
backend_sim = PulseSimulator()
# sample duration for pulse instructions
dt = 1e-9
# create the model
duffing_model = helper.get_transmon(dt)
# get qubit frequency from Duffing model
qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift()
import numpy as np
# visualization tools
import matplotlib.pyplot as plt
plt.style.use('dark_background')
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
kHz = 1.0e3 # kilohertz
us = 1.0e-6 # microseconds
ns = 1.0e-9 # nanoseconds
from qiskit import pulse
from qiskit.pulse import Play, Acquire
from qiskit.pulse.pulse_lib import GaussianSquare
# qubit to be used throughout the notebook
qubit = 0
### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)
# Construct a measurement schedule and add it to an InstructionScheduleMap
meas_samples = 1200
meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150)
measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit))
inst_map = pulse.InstructionScheduleMap()
inst_map.add('measure', [qubit], measure_sched)
# save the measurement/acquire pulse for later
measure = inst_map.get('measure', qubits=[qubit])
from qiskit.pulse import pulse_lib
# the same spect pulse used in every schedule
drive_amp = 0.9
drive_sigma = 16
drive_duration = 128
spec_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp,
sigma=drive_sigma, name=f"Spec drive amplitude = {drive_amp}")
# Construct an np array of the frequencies for our experiment
spec_freqs_GHz = np.arange(5.0, 5.2, 0.005)
# Create the base schedule
# Start with drive pulse acting on the drive channel
spec_schedules = []
for freq in spec_freqs_GHz:
sb_spec_pulse = helper.apply_sideband(spec_pulse, qubit_lo_freq[0]-freq*GHz, dt)
spec_schedule = pulse.Schedule(name='SB Frequency = {}'.format(freq))
spec_schedule += Play(sb_spec_pulse, drive_chan)
# The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration
spec_schedule += measure << spec_schedule.duration
spec_schedules.append(spec_schedule)
spec_schedules[0].draw()
from qiskit import assemble
# assemble the schedules into a Qobj
spec01_qobj = assemble(**helper.get_params('spec01', globals()))
# run the simulation
spec01_result = backend_sim.run(spec01_qobj, duffing_model).result()
# retrieve the data from the experiment
spec01_values = helper.get_values_from_result(spec01_result, qubit)
fit_params, y_fit = helper.fit_lorentzian(spec_freqs_GHz, spec01_values, [5, 5, 1, 0])
f01 = fit_params[1]
plt.scatter(spec_freqs_GHz, np.real(spec01_values), color='white') # plot real part of sweep values
plt.plot(spec_freqs_GHz, y_fit, color='red')
plt.xlim([min(spec_freqs_GHz), max(spec_freqs_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
print("01 Spectroscopy yields %f GHz"%f01)
x180_amp = 0.629070 #from lab 6 Rabi experiment
x_pulse = pulse_lib.gaussian(duration=drive_duration,
amp=x180_amp,
sigma=drive_sigma,
name='x_pulse')
anharmonicity_guess_GHz = -0.3
def build_spec12_pulse_schedule(freq):
sb12_spec_pulse = helper.apply_sideband(spec_pulse, (freq + anharmonicity_guess_GHz)*GHz, dt)
### create a 12 spectroscopy pulse schedule spec12_schedule (already done)
### play an x pulse on the drive channel
### play sidebanded spec pulse on the drive channel
### add measurement pulse to schedule
spec12_schedule = pulse.Schedule()
### WRITE YOUR CODE BETWEEN THESE LINES - START
spec12_schedule += Play(x_pulse, drive_chan)
spec12_schedule += Play(sb12_spec_pulse, drive_chan)
spec12_schedule += measure << spec12_schedule.duration
### WRITE YOUR CODE BETWEEN THESE LINES - STOP
return spec12_schedule
sb_freqs_GHz = np.arange(-.1, .1, 0.005) # sweep +/- 100 MHz around guess
# now vary the sideband frequency for each spec pulse
spec_schedules = []
for freq in sb_freqs_GHz:
spec_schedules.append(build_spec12_pulse_schedule(freq))
spec_schedules[0].draw()
# assemble the schedules into a Qobj
spec12_qobj = assemble(**helper.get_params('spec12', globals()))
answer1 = spec12_qobj
# run the simulation
spec12_result = backend_sim.run(spec12_qobj, duffing_model).result()
# retrieve the data from the experiment
spec12_values = helper.get_values_from_result(spec12_result, qubit)
anharm_offset = qubit_lo_freq[0]/GHz + anharmonicity_guess_GHz
fit_params, y_fit = helper.fit_lorentzian(anharm_offset + sb_freqs_GHz, spec12_values, [5, 4.5, .1, 3])
f12 = fit_params[1]
plt.scatter(anharm_offset + sb_freqs_GHz, np.real(spec12_values), color='white') # plot real part of sweep values
plt.plot(anharm_offset + sb_freqs_GHz, y_fit, color='red')
plt.xlim([anharm_offset + min(sb_freqs_GHz), anharm_offset + max(sb_freqs_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
print("12 Spectroscopy yields %f GHz"%f12)
print("Measured transmon anharmonicity is %f MHz"%((f12-f01)*GHz/MHz))
from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();'));
from grading_tools import send_code;send_code('ex1.ipynb')
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
### Install Qiskit and relevant packages, if needed
### IMPORTANT: Make sure you are on 3.10 > python < 3.12
%pip install qiskit[visualization]==1.0.2
%pip install qiskit-ibm-runtime
%pip install qiskit-aer
%pip install graphviz
%pip install qiskit-serverless -U
%pip install qiskit-transpiler-service -U
%pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U
### Save API Token, if needed
%set_env QXToken=deleteThisAndPasteYourTokenHere
# Set Grade only mode
%set_env QC_GRADE_ONLY=true
# Make sure there is no space between the equal sign
# and the beginning of your token
# qc-grader should be 0.18.12 (or higher)
import qc_grader
qc_grader.__version__
# Import all in one cell
import numpy as np
import matplotlib.pyplot as plt
from timeit import default_timer as timer
import warnings
from qiskit import QuantumCircuit
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info import SparsePauliOp
from qiskit.circuit.library import TwoLocal, EfficientSU2
from qiskit_ibm_runtime import QiskitRuntimeService, Estimator, Session, Options
from qiskit_serverless import QiskitFunction, save_result, get_arguments, save_result, distribute_task, distribute_qiskit_function, IBMServerlessClient, QiskitFunction
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_transpiler_service.transpiler_service import TranspilerService
from qiskit_aer import AerSimulator
# Import for grader
from qc_grader.challenges.iqc_2024 import grade_lab3_qs_ex1, grade_lab3_qs_ex2
# If needed setup your QiskitRuntimeService
# QiskitRuntimeService.save_account(
# channel="ibm_quantum",
# token="Enter your IBM Quantum Token",
# set_as_default=True,
# # Use `overwrite=True` if you're updating your token.
# overwrite=True,
# )
service = QiskitRuntimeService(channel="ibm_quantum")
# Specify a system to use for transpilation
real_backend = service.backend("ibm_brisbane")
# Qiskit Pattern Step 1: Map quantum circuits and operators (Define Ansatz and operators)
num_qubits = 3
rotation_blocks = ['ry','rz']
entanglement_blocks = 'cz'
entanglement = 'full'
# Define Ansatz
ansatz = TwoLocal(num_qubits, rotation_blocks, entanglement_blocks, entanglement, reps=1, insert_barriers=True)
# Define parameters
num_params = ansatz.num_parameters
# Qiskit Pattern Step 2: Optimize the circuit for quantum execution
optimization_level = 2
pm = generate_preset_pass_manager(backend=real_backend, optimization_level=optimization_level)
isa_circuit = pm.run(ansatz)
# Define Hamiltonian for VQE
pauli_op = SparsePauliOp(['ZII', 'IZI', 'IIZ'])
hamiltonian_isa = pauli_op.apply_layout(layout=isa_circuit.layout)
# Setup Qiskit Serverless Client and Qiskit Runtime client
client = IBMServerlessClient("YOUR_IBM_QUANTUM_TOKEN") # Add in your IBM Quantum Token to QiskitServerless Client
# For the challenge, we will be using QiskitRuntime Local testing mode. Change to True only if you wish to use real backend.
USE_RUNTIME_SERVICE = False
if USE_RUNTIME_SERVICE:
service = QiskitRuntimeService(
channel='ibm_quantum',
verify=False
)
else:
service = None
# Define the Qiskit Function
if USE_RUNTIME_SERVICE:
function = QiskitFunction(title="vqe", entrypoint="vqe.py", working_dir="./vqe")
else:
function = QiskitFunction(title="vqe", entrypoint="vqe.py", working_dir="./vqe", dependencies=["qiskit_aer"])
# Upload the Qiskit Function using IBMServerlessClient
client.upload(function)
# Define input_arguments
input_arguments = {
"ansatz": isa_circuit, # Replace with your transpiled ansatz
"operator": hamiltonian_isa, # Replace with the hamiltonian operator
"method": "COBYLA", # Using COBYLA method for the optimizer
"service": service, # Add your code here
}
# Qiskit Pattern Step 3: Run the payload on backend
job = client.run("vqe", arguments=input_arguments) # Pass the arguments dict here)
# Submit your answer using following code
grade_lab3_qs_ex1(function, input_arguments, job)
# Expected result type: QiskitFunction, dict, Job
# Return jobid
job
# Check job completion status
job.status()
# Monitor log
logs = job.logs()
for log in logs.splitlines():
print(log)
# Return result from QiskitFunction job
job.result()
# Qiskit Pattern Step 4: Postprocess and analyze the Estimator V2 results
result = job.result()
fig, ax = plt.subplots()
plt.plot(range(result["iters"]), result["cost_history"])
plt.xlabel("Energy")
plt.ylabel("Cost")
plt.draw()
# Setup 3 circuits with Efficient SU2
num_qubits = [41, 51, 61]
circuits = [EfficientSU2(nq, su2_gates=["rz","ry"], entanglement="circular", reps=1).decompose() for nq in num_qubits]
# Setup Qiskit Runtime Service backend
# QiskitRuntimeService.save_account(
# channel="ibm_quantum",
# token="YOUR_IBM_QUANTUM_TOKEN",
# set_as_default=True,
# # Use 'overwrite=True' if you're updating your token.
# overwrite=True,
# )
service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.backend("ibm_brisbane")
# Define Configs
optimization_levels = [1, 2, 3]
pass_managers = [{'pass_manager': generate_preset_pass_manager(optimization_level=level, backend=backend), 'optimization_level': level} for level in optimization_levels]
transpiler_services = [
{'service': TranspilerService(backend_name=backend.name, ai=False, optimization_level=3), 'ai': False, 'optimization_level': 3},
{'service': TranspilerService(backend_name=backend.name, ai=True, optimization_level=3), 'ai': True, 'optimization_level': 3}
]
configs = pass_managers + transpiler_services
# Local transpilation setup
def transpile_parallel_local(circuit: QuantumCircuit, config):
"""Transpilation for an abstract circuit into an ISA circuit for a given config."""
transpiled_circuit = config.run(circuit)
return transpiled_circuit
# Run local transpilation
warnings.filterwarnings("ignore")
start = timer()
# Run transpilations locally for baseline
results = []
for circuit in circuits:
for config in configs:
if 'pass_manager' in config:
results.append(transpile_parallel_local(circuit, config['pass_manager']))
else:
results.append(transpile_parallel_local(circuit, config['service']))
end = timer()
# Record local execution time
execution_time_local = end - start
print("Execution time locally: ", execution_time_local)
# Authenticate to the remote cluster and submit the pattern for remote execution if not done in previous exercise
serverless = IBMServerlessClient("YOUR_IBM_QUANTUM_TOKEN")
transpile_parallel_circuit = QiskitFunction(
title="transpile_parallel",
entrypoint="transpile_parallel.py",
working_dir="./transpile_parallel",
dependencies=["qiskit-transpiler-service"]
)
serverless.upload(transpile_parallel_circuit)
# Get list of functions
serverless.list()
# Fetch the specific function titled "transpile_parallel"
transpile_parallel_serverless = serverless.get("transpile_parallel") # Add your code here
# Run the "transpile_parallel" function in the serverless environment
job = transpile_parallel_serverless.run(circuits=circuits, backend_name=backend.name)
# Submit your answer using following code
grade_lab3_qs_ex2(optimization_levels, transpiler_services, transpile_parallel_function, transpile_parallel_serverless, job)
# Expected result type: list, list, QiskitFunction, QiskitFunction, Job
job.status()
logs = job.logs()
for log in logs.splitlines():
print(log)
result = job.result()
result_transpiled = result["transpiled_circuits"]
# Compare execution times:
execution_time_serverless = result["execution_time"]
from utils import plot_execution_times
plot_execution_times(execution_time_serverless, execution_time_local)
from utils import process_transpiled_circuits
best_circuits, best_depths, best_methods = process_transpiled_circuits(configs, result_transpiled)
# Display the best circuits, depths, and methods
for i, (circuit, depth, method) in enumerate(zip(best_circuits, best_depths, best_methods)):
print(f"Best result for circuit {i + 1}:")
print(f" Depth: {depth}")
print(f" Method: {method}")
# Display or process the best circuit as needed
# e.g., circuit.draw(output="mpl")
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test linear reversible circuits synthesis functions."""
import unittest
import numpy as np
from ddt import ddt, data
from qiskit import QuantumCircuit
from qiskit.circuit.library import LinearFunction
from qiskit.synthesis.linear import (
synth_cnot_count_full_pmh,
synth_cnot_depth_line_kms,
random_invertible_binary_matrix,
check_invertible_binary_matrix,
calc_inverse_matrix,
)
from qiskit.synthesis.linear.linear_circuits_utils import transpose_cx_circ, optimize_cx_4_options
from qiskit.test import QiskitTestCase
@ddt
class TestLinearSynth(QiskitTestCase):
"""Test the linear reversible circuit synthesis functions."""
def test_lnn_circuit(self):
"""Test the synthesis of a CX circuit with LNN connectivity."""
n = 5
qc = QuantumCircuit(n)
for i in range(n - 1):
qc.cx(i, i + 1)
mat = LinearFunction(qc).linear
for optimized in [True, False]:
optimized_qc = optimize_cx_4_options(
synth_cnot_count_full_pmh, mat, optimize_count=optimized
)
self.assertEqual(optimized_qc.depth(), 4)
self.assertEqual(optimized_qc.count_ops()["cx"], 4)
def test_full_circuit(self):
"""Test the synthesis of a CX circuit with full connectivity."""
n = 5
qc = QuantumCircuit(n)
for i in range(n):
for j in range(i + 1, n):
qc.cx(i, j)
mat = LinearFunction(qc).linear
for optimized in [True, False]:
optimized_qc = optimize_cx_4_options(
synth_cnot_count_full_pmh, mat, optimize_count=optimized
)
self.assertEqual(optimized_qc.depth(), 4)
self.assertEqual(optimized_qc.count_ops()["cx"], 4)
def test_transpose_circ(self):
"""Test the transpose_cx_circ() function."""
n = 5
mat = random_invertible_binary_matrix(n, seed=1234)
qc = synth_cnot_count_full_pmh(mat)
transposed_qc = transpose_cx_circ(qc)
transposed_mat = LinearFunction(transposed_qc).linear.astype(int)
self.assertTrue((mat.transpose() == transposed_mat).all())
def test_example_circuit(self):
"""Test the synthesis of an example CX circuit which provides different CX count
and depth for different optimization methods."""
qc = QuantumCircuit(9)
qc.swap(8, 7)
qc.swap(7, 6)
qc.cx(5, 6)
qc.cx(6, 5)
qc.swap(4, 5)
qc.cx(3, 4)
qc.cx(4, 3)
qc.swap(2, 3)
qc.cx(1, 2)
qc.cx(2, 1)
qc.cx(0, 1)
qc.cx(1, 0)
mat = LinearFunction(qc).linear
optimized_qc = optimize_cx_4_options(synth_cnot_count_full_pmh, mat, optimize_count=True)
self.assertEqual(optimized_qc.depth(), 17)
self.assertEqual(optimized_qc.count_ops()["cx"], 20)
optimized_qc = optimize_cx_4_options(synth_cnot_count_full_pmh, mat, optimize_count=False)
self.assertEqual(optimized_qc.depth(), 15)
self.assertEqual(optimized_qc.count_ops()["cx"], 23)
@data(5, 6)
def test_invertible_matrix(self, n):
"""Test the functions for generating a random invertible matrix and inverting it."""
mat = random_invertible_binary_matrix(n, seed=1234)
out = check_invertible_binary_matrix(mat)
mat_inv = calc_inverse_matrix(mat, verify=True)
mat_out = np.dot(mat, mat_inv) % 2
self.assertTrue(np.array_equal(mat_out, np.eye(n)))
self.assertTrue(out)
@data(5, 6)
def test_synth_lnn_kms(self, num_qubits):
"""Test that synth_cnot_depth_line_kms produces the correct synthesis."""
rng = np.random.default_rng(1234)
num_trials = 10
for _ in range(num_trials):
mat = random_invertible_binary_matrix(num_qubits, seed=rng)
mat = np.array(mat, dtype=bool)
qc = synth_cnot_depth_line_kms(mat)
mat1 = LinearFunction(qc).linear
self.assertTrue((mat == mat1).all())
# Check that the circuit depth is bounded by 5*num_qubits
depth = qc.depth()
self.assertTrue(depth <= 5 * num_qubits)
# Check that the synthesized circuit qc fits LNN connectivity
for inst in qc.data:
self.assertEqual(inst.operation.name, "cx")
q0 = qc.find_bit(inst.qubits[0]).index
q1 = qc.find_bit(inst.qubits[1]).index
dist = abs(q0 - q1)
self.assertEqual(dist, 1)
if __name__ == "__main__":
unittest.main()
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
import numpy as np
IBMQ.enable_account('ENTER API KEY HERE)
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
pi = np.pi
q = QuantumRegister(1,'q')
c = ClassicalRegister(1,'c')
circuit = QuantumCircuit(q,c)
circuit.rx(pi,q[0])
circuit.measure(q,c)
print(circuit)
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit import Parameter
from qiskit import QuantumCircuit
theta = Parameter('$\\theta$')
chsh_circuits_no_meas = QuantumCircuit(2)
chsh_circuits_no_meas.h(0)
chsh_circuits_no_meas.cx(0, 1)
chsh_circuits_no_meas.ry(theta, 0)
chsh_circuits_no_meas.draw('mpl')
import numpy as np
number_of_phases = 21
phases = np.linspace(0, 2*np.pi, number_of_phases)
# Phases need to be expressed as list of lists in order to work
individual_phases = [[ph] for ph in phases]
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = "ibmq_qasm_simulator" # use the simulator
from qiskit_ibm_runtime import Estimator, Session
from qiskit.quantum_info import SparsePauliOp
ZZ = SparsePauliOp.from_list([("ZZ", 1)])
ZX = SparsePauliOp.from_list([("ZX", 1)])
XZ = SparsePauliOp.from_list([("XZ", 1)])
XX = SparsePauliOp.from_list([("XX", 1)])
ops = [ZZ, ZX, XZ, XX]
chsh_est_sim = []
# Simulator
with Session(service=service, backend=backend):
estimator = Estimator()
for op in ops:
job = estimator.run(
circuits=[chsh_circuits_no_meas]*len(individual_phases),
observables=[op]*len(individual_phases),
parameter_values=individual_phases)
est_result = job.result()
chsh_est_sim.append(est_result)
# <CHSH1> = <AB> - <Ab> + <aB> + <ab>
chsh1_est_sim = chsh_est_sim[0].values - chsh_est_sim[1].values + chsh_est_sim[2].values + chsh_est_sim[3].values
# <CHSH2> = <AB> + <Ab> - <aB> + <ab>
chsh2_est_sim = chsh_est_sim[0].values + chsh_est_sim[1].values - chsh_est_sim[2].values + chsh_est_sim[3].values
import matplotlib.pyplot as plt
import matplotlib.ticker as tck
fig, ax = plt.subplots(figsize=(10, 6))
# results from a simulator
ax.plot(phases/np.pi, chsh1_est_sim, 'o-', label='CHSH1 Simulation')
ax.plot(phases/np.pi, chsh2_est_sim, 'o-', label='CHSH2 Simulation')
# classical bound +-2
ax.axhline(y=2, color='r', linestyle='--')
ax.axhline(y=-2, color='r', linestyle='--')
# quantum bound, +-2√2
ax.axhline(y=np.sqrt(2)*2, color='b', linestyle='-.')
ax.axhline(y=-np.sqrt(2)*2, color='b', linestyle='-.')
# set x tick labels to the unit of pi
ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$'))
ax.xaxis.set_major_locator(tck.MultipleLocator(base=0.5))
# set title, labels, and legend
plt.title('Violation of CHSH Inequality')
plt.xlabel('Theta')
plt.ylabel('CHSH witness')
plt.legend()
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Marduk-42/Quantum-Algorithm-Tutorials
|
Marduk-42
|
from qiskit import *
import matplotlib.pyplot as plt
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg,creg)
circuit.reset(qreg[0])
circuit.reset(qreg[1])
circuit.h(qreg[0])
circuit.cx(qreg[0],qreg[1])
circuit.measure(qreg[0],creg[0])
circuit.measure(qreg[1],creg[1])
backend = Aer.get_backend('qasm_simulator')
job = execute(circuit, backend, shots=2048)
result = job.result()
ax1 = circuit.draw("mpl")
ax1.suptitle("Bell test circuit")
ax2 = visualization.plot_histogram(result.get_counts(circuit))
ax2.suptitle("Results")
plt.show()
|
https://github.com/carstenblank/dc-qiskit-stochastics
|
carstenblank
|
from hmmlearn import hmm
samples = 10*[[0], [1], [1], [1], [1], [2], [2], [0], [1], [1], [1], [0], [2]]
model = hmm.MultinomialHMM(n_components=4)
model.fit(samples)
model.emissionprob_
model.transmat_
|
https://github.com/usamisaori/qLipschitz
|
usamisaori
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
from qiskit import QuantumCircuit
# ## Create Circuit
# In[2]:
def createInputCircuit(data):
qubits_num = len(data)
qcircuit = QuantumCircuit(qubits_num, qubits_num)
qubits = qcircuit.qubits
for i, d in enumerate(data):
qcircuit.rx(d * np.pi, qubits[i])
return qcircuit
# In[3]:
def createModelCircuit(params):
qubits_num = len(params[0])
qcircuit = QuantumCircuit(qubits_num, qubits_num)
qubits = qcircuit.qubits
for i in range(qubits_num):
qcircuit.u3(*params[0][i], qubits[i])
for i in range(qubits_num - 1):
qcircuit.cz(qubits[i], qubits[i + 1])
qcircuit.cz(qubits[0], qubits[qubits_num - 1])
for i in range(qubits_num):
qcircuit.u3(*params[1][i], qubits[i])
return qcircuit
# In[4]:
def createCircuit(params, data):
input_circuit = createInputCircuit(data)
model_circuit = createModelCircuit(params)
full_circuit = input_circuit.compose(model_circuit)
return full_circuit
# ## Create Noisy Circuit
# In[8]:
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.utils import insert_noise
from qiskit.providers.aer.noise import pauli_error, depolarizing_error
# In[9]:
def createNoiseModel(p, errorType):
# QuantumError objects
if errorType == 'bit_flip':
error = pauli_error([('X', p), ('I', 1 - p)])
elif errorType == 'phase_flip':
error = pauli_error([('Z', p), ('I', 1 - p)])
elif errorType == 'depolarizing':
error = depolarizing_error(p, num_qubits=1)
## two-qubits quantumError objects
if errorType == 'depolarizing':
error_2qubits = depolarizing_error(p, num_qubits=2)
else:
error_2qubits = error.tensor(error)
# Add errors to noise model
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error, ['u3'])
noise_model.add_all_qubit_quantum_error(error_2qubits, ['cz'])
return noise_model
# In[10]:
def createNoisyModelCircuit(params, p, errorType):
noise_model = createNoiseModel(p, errorType)
model_circuit = createModelCircuit(params)
return insert_noise(model_circuit, noise_model)
# In[12]:
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.