repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/HQSquantumsimulations/qoqo-qiskit
HQSquantumsimulations
# Copyright © 2023 HQS Quantum Simulations GmbH. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under the License # is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express # or implied. See the License for the specific language governing permissions and limitations under # the License. """Test file for interface.py.""" import sys from typing import Union import pytest from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qoqo import Circuit from qoqo import operations as ops from qoqo_qiskit.interface import to_qiskit_circuit # type:ignore def test_basic_circuit() -> None: """Test basic circuit conversion.""" circuit = Circuit() circuit += ops.Hadamard(0) circuit += ops.PauliX(1) circuit += ops.Identity(1) qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.id(1) out_circ, sim_dict = to_qiskit_circuit(circuit) assert out_circ == qc assert len(sim_dict["MeasurementInfo"]) == 0 def test_qreg_creg_names() -> None: """Test qreg and creg qiskit names.""" circuit = Circuit() circuit += ops.DefinitionBit("cr", 2, is_output=True) circuit += ops.DefinitionBit("crr", 3, is_output=True) qr = QuantumRegister(1, "qrg") cr = ClassicalRegister(2, "cr") cr2 = ClassicalRegister(3, "crr") qc = QuantumCircuit(qr, cr, cr2) out_circ, _ = to_qiskit_circuit(circuit, qubit_register_name="qrg") assert out_circ == qc def test_setstatevector() -> None: """Test PragmaSetStateVector operation.""" circuit = Circuit() circuit += ops.PragmaSetStateVector([0, 1]) qc = QuantumCircuit(1) qc.initialize([0, 1]) out_circ, _ = to_qiskit_circuit(circuit) assert out_circ == qc circuit = Circuit() circuit += ops.PragmaSetStateVector([0, 1]) circuit += ops.RotateX(0, 0.23) qc = QuantumCircuit(1) qc.initialize([0, 1]) qc.rx(0.23, 0) out_circ, _ = to_qiskit_circuit(circuit) assert out_circ == qc def test_repeated_measurement() -> None: """Test PragmaRepeatedMeasurement operation.""" circuit = Circuit() circuit += ops.Hadamard(0) circuit += ops.Hadamard(1) circuit += ops.DefinitionBit("ri", 2, True) circuit += ops.PragmaRepeatedMeasurement("ri", 300) qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "ri") qc = QuantumCircuit(qr, cr) qc.h(0) qc.h(1) qc.measure(qr, cr) out_circ, sim_dict = to_qiskit_circuit(circuit) assert out_circ == qc assert ("ri", 300, None) in sim_dict["MeasurementInfo"]["PragmaRepeatedMeasurement"] def test_measure_qubit() -> None: """Test MeasureQubit operation.""" circuit = Circuit() circuit += ops.Hadamard(0) circuit += ops.PauliZ(1) circuit += ops.DefinitionBit("crg", 1, is_output=True) circuit += ops.MeasureQubit(0, "crg", 0) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "crg") qc = QuantumCircuit(qr, cr) qc.h(0) qc.z(1) qc.measure(0, cr) out_circ, sim_dict = to_qiskit_circuit(circuit) assert out_circ == qc assert (0, "crg", 0) in sim_dict["MeasurementInfo"]["MeasureQubit"] @pytest.mark.parametrize("repetitions", [0, 2, 4, "test"]) def test_pragma_loop(repetitions: Union[int, str]) -> None: """Test PragmaLoop operation.""" inner_circuit = Circuit() inner_circuit += ops.PauliX(1) inner_circuit += ops.PauliY(2) circuit = Circuit() circuit += ops.Hadamard(0) circuit += ops.PragmaLoop(repetitions=repetitions, circuit=inner_circuit) circuit += ops.Hadamard(3) qc = QuantumCircuit(4) qc.h(0) if not isinstance(repetitions, str): for _ in range(repetitions): qc.x(1) qc.y(2) qc.h(3) try: out_circ, _ = to_qiskit_circuit(circuit) assert out_circ == qc except ValueError as e: assert e.args == ("A symbolic PragmaLoop operation is not supported.",) def test_custom_gates_fix() -> None: """Test _custom_gates_fix method.""" qoqo_circuit = Circuit() qoqo_circuit += ops.PragmaSleep([0, 3], 1.0) qoqo_circuit += ops.PauliX(2) qoqo_circuit += ops.PragmaSleep([4], 0.004) qoqo_circuit += ops.RotateXY(3, 0.1, 0.1) qr = QuantumRegister(5, "q") qiskit_circuit = QuantumCircuit(qr) qiskit_circuit.delay(1.0, qr[0], unit="s") qiskit_circuit.delay(1.0, qr[3], unit="s") qiskit_circuit.x(qr[2]) qiskit_circuit.delay(0.004, qr[4], unit="s") qiskit_circuit.r(0.1, 0.1, qr[3]) out_circ, _ = to_qiskit_circuit(qoqo_circuit) assert out_circ == qiskit_circuit def test_simulation_info() -> None: """Test SimulationInfo dictionary.""" circuit = Circuit() circuit += ops.Hadamard(0) circuit += ops.CNOT(0, 1) circuit += ops.DefinitionBit("ro", 2, True) circuit += ops.PragmaGetStateVector("ro", None) circuit += ops.PragmaGetDensityMatrix("ro", None) _, sim_dict = to_qiskit_circuit(circuit) assert sim_dict["SimulationInfo"]["PragmaGetStateVector"] assert sim_dict["SimulationInfo"]["PragmaGetDensityMatrix"] # For pytest if __name__ == "__main__": pytest.main(sys.argv)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/qiskit-community/qiskit-dell-runtime
qiskit-community
import itertools import json import numpy as np from numpy.random import RandomState from qiskit import QuantumCircuit, QuantumRegister from qiskit.compiler import transpile from cvxopt import matrix, solvers # pylint: disable=import-error from .qka import QKA class FeatureMap: def __init__(self, feature_dimension, entangler_map=None): if isinstance(feature_dimension, int): if feature_dimension % 2 == 0: self._feature_dimension = feature_dimension else: raise ValueError("Feature dimension must be an even integer.") else: raise ValueError("Feature dimension must be an even integer.") self._num_qubits = int(feature_dimension / 2) if entangler_map is None: self._entangler_map = [ [i, j] for i in range(self._feature_dimension) for j in range(i + 1, self._feature_dimension) ] else: self._entangler_map = entangler_map self._num_parameters = self._num_qubits def construct_circuit(self, x=None, parameters=None, q=None, inverse=False, name=None): if parameters is not None: if isinstance(parameters, (int, float)): raise ValueError("Parameters must be a list.") if len(parameters) == 1: parameters = parameters * np.ones(self._num_qubits) else: if len(parameters) != self._num_parameters: raise ValueError( "The number of feature map parameters must be {}.".format( self._num_parameters ) ) if len(x) != self._feature_dimension: raise ValueError( "The input vector must be of length {}.".format(self._feature_dimension) ) if q is None: q = QuantumRegister(self._num_qubits, name="q") circuit = QuantumCircuit(q, name=name) for i in range(self._num_qubits): circuit.ry(-parameters[i], q[i]) for source, target in self._entangler_map: circuit.cz(q[source], q[target]) for i in range(self._num_qubits): circuit.rz(-2 * x[2 * i + 1], q[i]) circuit.rx(-2 * x[2 * i], q[i]) if inverse: return circuit.inverse() else: return circuit def to_json(self): return json.dumps( {"feature_dimension": self._feature_dimension, "entangler_map": self._entangler_map} ) @classmethod def from_json(cls, data): return cls(**json.loads(data))
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
''' This is a implementation of the quantum teleportation algorithm ''' from qiskit import * from qiskit.visualization import plot_histogram import os, shutil, numpy from matplotlib.pyplot import plot, draw, show LaTex_folder_Quantum_Teleportation = str(os.getcwd())+'/Latex_quantum_gates/Quantum_Teleportation/' if not os.path.exists(LaTex_folder_Quantum_Teleportation): os.makedirs(LaTex_folder_Quantum_Teleportation) else: shutil.rmtree(LaTex_folder_Quantum_Teleportation) os.makedirs(LaTex_folder_Quantum_Teleportation) qc = QuantumCircuit(3,3) ## prepare the state to be teleported phi = 0*numpy.pi theta= 0.5*numpy.pi lam = 0*numpy.pi qc.u(phi=phi, theta=theta,lam=lam,qubit=0) ## teleport the state qc.barrier() qc.h(1) qc.cx(1,2) qc.cz(0,1) qc.h(0) qc.h(1) qc.barrier() qc.measure([0,1],[0,1]) qc.barrier() qc.x(2).c_if(0,1) qc.z(2).c_if(1,1) qc.h(2) qc.measure(2,2) LaTex_code = qc.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit f_name = 'quantum_teleportation.tex' with open(LaTex_folder_Quantum_Teleportation+f_name, 'w') as f: f.write(LaTex_code) # simulation simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend=simulator, shots=100000).result() counts = {'0':0, '1': 0} print(result.get_counts().keys()) for key, value in result.get_counts().items(): if(key[0] == '0'): counts['0'] += value else: counts['1'] += value print(counts) plt = plot_histogram(counts) draw() show(block=True)
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. """Test the HoareOptimizer pass""" import unittest from numpy import pi from qiskit.utils import optionals from qiskit.transpiler.passes import HoareOptimizer from qiskit.converters import circuit_to_dag from qiskit import QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.circuit.library import XGate, RZGate, CSwapGate, SwapGate from qiskit.dagcircuit import DAGOpNode from qiskit.quantum_info import Statevector @unittest.skipUnless(optionals.HAS_Z3, "z3-solver needs to be installed to run these tests") class TestHoareOptimizer(QiskitTestCase): """Test the HoareOptimizer pass""" def test_phasegate_removal(self): """Should remove the phase on a classical state, but not on a superposition state. """ # ┌───┐ # q_0: ┤ Z ├────── # ├───┤┌───┐ # q_1:─┤ H ├┤ Z ├─ # └───┘└───┘ circuit = QuantumCircuit(3) circuit.z(0) circuit.h(1) circuit.z(1) # q_0: ─────────── # ┌───┐┌───┐ # q_1:─┤ H ├┤ Z ├─ # └───┘└───┘ expected = QuantumCircuit(3) expected.h(1) expected.z(1) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=0) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_cswap_removal(self): """Should remove Fredkin gates because the optimizer can deduce the targets are in the same state """ # ┌───┐┌───┐ ┌───┐ ┌───┐ ┌───┐ # q_0: ┤ X ├┤ X ├──■──┤ X ├──■──┤ X ├──■────■──┤ X ├───────────────────────────────── # └───┘└─┬─┘┌─┴─┐└─┬─┘ │ └─┬─┘┌─┴─┐ │ └─┬─┘ # q_1: ───────┼──┤ X ├──■────┼────┼──┤ X ├──┼────■───■──■──■──■─────■─────■────────── # │ └─┬─┘ ┌─┴─┐ │ └─┬─┘┌─┴─┐ │ │ │ │ │ │ │ # q_2: ───────┼────┼───────┤ X ├──■────┼──┤ X ├──■───┼──┼──┼──┼──■──┼──■──┼──■──■──■─ # ┌───┐ │ │ └─┬─┘ │ └─┬─┘ │ │ │ │ │ │ │ │ │ │ │ # q_3: ┤ H ├──■────┼─────────┼─────────┼────┼────────┼──┼──X──X──┼──┼──X──┼──┼──X──┼─ # ├───┤ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ # q_4: ┤ H ├───────■─────────┼─────────┼────┼────────┼──┼──┼──X──┼──X──┼──┼──X──┼──X─ # ├───┤ │ │ │ │ │ │ │ │ │ │ │ │ │ # q_5: ┤ H ├─────────────────■─────────┼────┼────────┼──┼──┼─────┼──X──┼──X──┼──X──┼─ # ├───┤ │ │ │ │ │ │ │ │ │ │ # q_6: ┤ H ├───────────────────────────■────■────────┼──┼──┼─────┼─────┼──X──┼─────X─ # └───┘ │ │ │ │ │ │ # q_7: ──────────────────────────────────────────────X──┼──┼─────X─────┼─────┼─────── # │ │ │ │ │ │ # q_8: ──────────────────────────────────────────────X──X──┼─────┼─────X─────┼─────── # │ │ │ │ # q_9: ─────────────────────────────────────────────────X──X─────X───────────X─────── circuit = QuantumCircuit(10) # prep circuit.x(0) circuit.h(3) circuit.h(4) circuit.h(5) circuit.h(6) # find first non-zero bit of reg(3-6), store position in reg(1-2) circuit.cx(3, 0) circuit.ccx(0, 4, 1) circuit.cx(1, 0) circuit.ccx(0, 5, 2) circuit.cx(2, 0) circuit.ccx(0, 6, 1) circuit.ccx(0, 6, 2) circuit.ccx(1, 2, 0) # shift circuit circuit.cswap(1, 7, 8) circuit.cswap(1, 8, 9) circuit.cswap(1, 9, 3) circuit.cswap(1, 3, 4) circuit.cswap(1, 4, 5) circuit.cswap(1, 5, 6) circuit.cswap(2, 7, 9) circuit.cswap(2, 8, 3) circuit.cswap(2, 9, 4) circuit.cswap(2, 3, 5) circuit.cswap(2, 4, 6) # ┌───┐┌───┐ ┌───┐ ┌───┐ ┌───┐ # q_0: ┤ X ├┤ X ├──■──┤ X ├──■──┤ X ├──■────■──┤ X ├─────────────── # └───┘└─┬─┘┌─┴─┐└─┬─┘ │ └─┬─┘┌─┴─┐ │ └─┬─┘ # q_1: ───────┼──┤ X ├──■────┼────┼──┤ X ├──┼────■───■──■──■─────── # │ └─┬─┘ ┌─┴─┐ │ └─┬─┘┌─┴─┐ │ │ │ │ # q_2: ───────┼────┼───────┤ X ├──■────┼──┤ X ├──■───┼──┼──┼──■──■─ # ┌───┐ │ │ └─┬─┘ │ └─┬─┘ │ │ │ │ │ # q_3: ┤ H ├──■────┼─────────┼─────────┼────┼────────X──┼──┼──X──┼─ # ├───┤ │ │ │ │ │ │ │ │ │ # q_4: ┤ H ├───────■─────────┼─────────┼────┼────────X──X──┼──┼──X─ # ├───┤ │ │ │ │ │ │ │ # q_5: ┤ H ├─────────────────■─────────┼────┼───────────X──X──X──┼─ # ├───┤ │ │ │ │ # q_6: ┤ H ├───────────────────────────■────■──────────────X─────X─ # └───┘ # q_7: ──────────────────────────────────────────────────────────── # # q_8: ──────────────────────────────────────────────────────────── # # q_9: ──────────────────────────────────────────────────────────── expected = QuantumCircuit(10) # prep expected.x(0) expected.h(3) expected.h(4) expected.h(5) expected.h(6) # find first non-zero bit of reg(3-6), store position in reg(1-2) expected.cx(3, 0) expected.ccx(0, 4, 1) expected.cx(1, 0) expected.ccx(0, 5, 2) expected.cx(2, 0) expected.ccx(0, 6, 1) expected.ccx(0, 6, 2) expected.ccx(1, 2, 0) # optimized shift circuit expected.cswap(1, 3, 4) expected.cswap(1, 4, 5) expected.cswap(1, 5, 6) expected.cswap(2, 3, 5) expected.cswap(2, 4, 6) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=0) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_lnn_cnot_removal(self): """Should remove some cnots from swaps introduced because of linear nearest architecture. Only uses single-gate optimization techniques. """ # ┌───┐ ┌───┐ » # q_0: ┤ H ├──■──┤ X ├──■────────────────────────────────────────────────────» # └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌───┐ » # q_1: ─────┤ X ├──■──┤ X ├──■──┤ X ├──■──────────────────────────────────■──» # └───┘ └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌───┐ ┌───┐┌─┴─┐» # q_2: ────────────────────┤ X ├──■──┤ X ├──■──┤ X ├──■─────────■──┤ X ├┤ X ├» # └───┘ └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌─┴─┐└─┬─┘└───┘» # q_3: ───────────────────────────────────┤ X ├──■──┤ X ├──■──┤ X ├──■───────» # └───┘ └───┘┌─┴─┐└───┘ » # q_4: ──────────────────────────────────────────────────┤ X ├───────────────» # └───┘ » # « ┌───┐ # «q_0: ───────■──┤ X ├ # « ┌───┐┌─┴─┐└─┬─┘ # «q_1: ┤ X ├┤ X ├──■── # « └─┬─┘└───┘ # «q_2: ──■──────────── # « # «q_3: ─────────────── # « # «q_4: ─────────────── circuit = QuantumCircuit(5) circuit.h(0) for i in range(0, 3): circuit.cx(i, i + 1) circuit.cx(i + 1, i) circuit.cx(i, i + 1) circuit.cx(3, 4) for i in range(3, 0, -1): circuit.cx(i - 1, i) circuit.cx(i, i - 1) # ┌───┐ ┌───┐ ┌───┐ # q_0: ┤ H ├──■──┤ X ├───────────────────────────────────┤ X ├ # └───┘┌─┴─┐└─┬─┘ ┌───┐ ┌───┐└─┬─┘ # q_1: ─────┤ X ├──■────■──┤ X ├────────────────────┤ X ├──■── # └───┘ ┌─┴─┐└─┬─┘ ┌───┐ ┌───┐└─┬─┘ # q_2: ───────────────┤ X ├──■────■──┤ X ├─────┤ X ├──■─────── # └───┘ ┌─┴─┐└─┬─┘ └─┬─┘ # q_3: ─────────────────────────┤ X ├──■────■────■──────────── # └───┘ ┌─┴─┐ # q_4: ───────────────────────────────────┤ X ├─────────────── # └───┘ expected = QuantumCircuit(5) expected.h(0) for i in range(0, 3): expected.cx(i, i + 1) expected.cx(i + 1, i) expected.cx(3, 4) for i in range(3, 0, -1): expected.cx(i, i - 1) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=0) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_lnncnot_advanced_removal(self): """Should remove all cnots from swaps introduced because of linear nearest architecture. This time using multi-gate optimization techniques. """ # ┌───┐ ┌───┐ » # q_0: ┤ H ├──■──┤ X ├──■────────────────────────────────────────────────────» # └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌───┐ » # q_1: ─────┤ X ├──■──┤ X ├──■──┤ X ├──■──────────────────────────────────■──» # └───┘ └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌───┐ ┌───┐┌─┴─┐» # q_2: ────────────────────┤ X ├──■──┤ X ├──■──┤ X ├──■─────────■──┤ X ├┤ X ├» # └───┘ └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌─┴─┐└─┬─┘└───┘» # q_3: ───────────────────────────────────┤ X ├──■──┤ X ├──■──┤ X ├──■───────» # └───┘ └───┘┌─┴─┐└───┘ » # q_4: ──────────────────────────────────────────────────┤ X ├───────────────» # └───┘ » # « ┌───┐ # «q_0: ───────■──┤ X ├ # « ┌───┐┌─┴─┐└─┬─┘ # «q_1: ┤ X ├┤ X ├──■── # « └─┬─┘└───┘ # «q_2: ──■──────────── # « # «q_3: ─────────────── # « # «q_4: ─────────────── circuit = QuantumCircuit(5) circuit.h(0) for i in range(0, 3): circuit.cx(i, i + 1) circuit.cx(i + 1, i) circuit.cx(i, i + 1) circuit.cx(3, 4) for i in range(3, 0, -1): circuit.cx(i - 1, i) circuit.cx(i, i - 1) # ┌───┐ # q_0: ┤ H ├──■───────────────── # └───┘┌─┴─┐ # q_1: ─────┤ X ├──■──────────── # └───┘┌─┴─┐ # q_2: ──────────┤ X ├──■─────── # └───┘┌─┴─┐ # q_3: ───────────────┤ X ├──■── # └───┘┌─┴─┐ # q_4: ────────────────────┤ X ├ # └───┘ expected = QuantumCircuit(5) expected.h(0) for i in range(0, 4): expected.cx(i, i + 1) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=6) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_successive_identity_removal(self): """Should remove a successive pair of H gates applying on the same qubit. """ circuit = QuantumCircuit(1) circuit.h(0) circuit.h(0) circuit.h(0) expected = QuantumCircuit(1) expected.h(0) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=4) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_targetsuccessive_identity_removal(self): """Should remove pair of controlled target successive which are the inverse of each other, if they can be identified to be executed as a unit (either both or none). """ # ┌───┐ ┌───┐┌───┐ # q_0: ┤ H ├──■──┤ X ├┤ X ├──■── # ├───┤ │ └─┬─┘└───┘ │ # q_1: ┤ H ├──■────■─────────■── # ├───┤┌─┴─┐ ┌─┴─┐ # q_2: ┤ H ├┤ X ├──────────┤ X ├ # └───┘└───┘ └───┘ circuit = QuantumCircuit(3) circuit.h(0) circuit.h(1) circuit.h(2) circuit.ccx(0, 1, 2) circuit.cx(1, 0) circuit.x(0) circuit.ccx(0, 1, 2) # ┌───┐┌───┐┌───┐ # q_0: ┤ H ├┤ X ├┤ X ├ # ├───┤└─┬─┘└───┘ # q_1: ┤ H ├──■─────── # ├───┤ # q_2: ┤ H ├────────── # └───┘ expected = QuantumCircuit(3) expected.h(0) expected.h(1) expected.h(2) expected.cx(1, 0) expected.x(0) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=4) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_targetsuccessive_identity_advanced_removal(self): """Should remove target successive identity gates with DIFFERENT sets of control qubits. In this case CCCX(4,5,6,7) & CCX(5,6,7). """ # ┌───┐┌───┐ » # q_0: ┤ H ├┤ X ├───────■─────────────────────────────■───────────────────■──» # ├───┤└─┬─┘ │ │ │ » # q_1: ┤ H ├──■─────────■─────────────────────────────■───────────────────■──» # ├───┤┌───┐ │ ┌───┐ │ │ » # q_2: ┤ H ├┤ X ├───────┼──┤ X ├──■──────────────■────┼───────────────────┼──» # ├───┤└─┬─┘ ┌─┴─┐└─┬─┘ │ │ ┌─┴─┐ ┌─┴─┐» # q_3: ┤ H ├──■────■──┤ X ├──■────■──────────────■──┤ X ├──■─────────■──┤ X ├» # ├───┤┌───┐ │ └───┘ │ ┌───┐ │ └───┘ │ │ └───┘» # q_4: ┤ H ├┤ X ├──┼──────────────┼──┤ X ├──■────┼─────────┼─────────┼───────» # ├───┤└─┬─┘┌─┴─┐ ┌─┴─┐└─┬─┘ │ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ » # q_5: ┤ H ├──■──┤ X ├──────────┤ X ├──■────■──┤ X ├─────┤ X ├──■──┤ X ├─────» # └───┘ └───┘ └───┘ ┌─┴─┐└───┘ └───┘┌─┴─┐├───┤ » # q_6: ───────────────────────────────────┤ X ├───────────────┤ X ├┤ X ├─────» # └───┘ └───┘└───┘ » # q_7: ──────────────────────────────────────────────────────────────────────» # » # « ┌───┐┌───┐ » # «q_0: ──────────────────────■──┤ X ├┤ X ├──■─────────────────────────────■──» # « │ └─┬─┘└─┬─┘ │ │ » # «q_1: ──────────────────────■────■────■────■─────────────────────────────■──» # « ┌───┐ │ │ │ ┌───┐ │ » # «q_2: ──■─────────■──┤ X ├──┼─────────┼────┼──┤ X ├──■──────────────■────┼──» # « │ │ └─┬─┘┌─┴─┐ │ ┌─┴─┐└─┬─┘ │ │ ┌─┴─┐» # «q_3: ──■─────────■────■──┤ X ├───────┼──┤ X ├──■────■──────────────■──┤ X ├» # « │ ┌───┐ │ └───┘ │ └───┘ │ │ ┌───┐ │ └───┘» # «q_4: ──┼──┤ X ├──┼───────────────────┼─────────┼────┼──┤ X ├──■────┼───────» # « ┌─┴─┐└─┬─┘┌─┴─┐ │ │ ┌─┴─┐└─┬─┘ │ ┌─┴─┐ » # «q_5: ┤ X ├──■──┤ X ├─────────────────┼─────────┼──┤ X ├──■────■──┤ X ├─────» # « └───┘ └───┘ │ │ └───┘ │ │ └───┘ » # «q_6: ────────────────────────────────■─────────■─────────■────■────────────» # « ┌─┴─┐ » # «q_7: ───────────────────────────────────────────────────────┤ X ├──────────» # « └───┘ » # « # «q_0: ─────────────── # « # «q_1: ─────────────── # « ┌───┐ # «q_2: ─────┤ X ├───── # « └─┬─┘ # «q_3: ──■────■─────── # « │ ┌───┐ # «q_4: ──┼──┤ X ├───── # « ┌─┴─┐└─┬─┘ # «q_5: ┤ X ├──■────■── # « └───┘ │ # «q_6: ────────────■── # « ┌─┴─┐ # «q_7: ──────────┤ X ├ # « └───┘ circuit = QuantumCircuit(8) circuit.h(0) circuit.h(1) circuit.h(2) circuit.h(3) circuit.h(4) circuit.h(5) for i in range(3): circuit.cx(i * 2 + 1, i * 2) circuit.cx(3, 5) for i in range(2): circuit.ccx(i * 2, i * 2 + 1, i * 2 + 3) circuit.cx(i * 2 + 3, i * 2 + 2) circuit.ccx(4, 5, 6) for i in range(1, -1, -1): circuit.ccx(i * 2, i * 2 + 1, i * 2 + 3) circuit.cx(3, 5) circuit.cx(5, 6) circuit.cx(3, 5) circuit.x(6) for i in range(2): circuit.ccx(i * 2, i * 2 + 1, i * 2 + 3) for i in range(1, -1, -1): circuit.cx(i * 2 + 3, i * 2 + 2) circuit.ccx(i * 2, i * 2 + 1, i * 2 + 3) circuit.cx(1, 0) circuit.ccx(6, 1, 0) circuit.ccx(0, 1, 3) circuit.ccx(6, 3, 2) circuit.ccx(2, 3, 5) circuit.ccx(6, 5, 4) circuit.append(XGate().control(3), [4, 5, 6, 7], []) for i in range(1, -1, -1): circuit.ccx(i * 2, i * 2 + 1, i * 2 + 3) circuit.cx(3, 5) for i in range(1, 3): circuit.cx(i * 2 + 1, i * 2) circuit.ccx(5, 6, 7) # ┌───┐┌───┐ » # q_0: ┤ H ├┤ X ├───────■─────────────────────────────■───────────────────■──» # ├───┤└─┬─┘ │ │ │ » # q_1: ┤ H ├──■─────────■─────────────────────────────■───────────────────■──» # ├───┤┌───┐ │ ┌───┐ │ │ » # q_2: ┤ H ├┤ X ├───────┼──┤ X ├──■──────────────■────┼───────────────────┼──» # ├───┤└─┬─┘ ┌─┴─┐└─┬─┘ │ │ ┌─┴─┐ ┌─┴─┐» # q_3: ┤ H ├──■────■──┤ X ├──■────■──────────────■──┤ X ├──■─────────■──┤ X ├» # ├───┤┌───┐ │ └───┘ │ ┌───┐ │ └───┘ │ │ └───┘» # q_4: ┤ H ├┤ X ├──┼──────────────┼──┤ X ├──■────┼─────────┼─────────┼───────» # ├───┤└─┬─┘┌─┴─┐ ┌─┴─┐└─┬─┘ │ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ » # q_5: ┤ H ├──■──┤ X ├──────────┤ X ├──■────■──┤ X ├─────┤ X ├──■──┤ X ├─────» # └───┘ └───┘ └───┘ ┌─┴─┐└───┘ └───┘┌─┴─┐├───┤ » # q_6: ───────────────────────────────────┤ X ├───────────────┤ X ├┤ X ├─────» # └───┘ └───┘└───┘ » # q_7: ──────────────────────────────────────────────────────────────────────» # » # « ┌───┐┌───┐ » # «q_0: ──────────────────────■──┤ X ├┤ X ├──■────────────────────────■───────» # « │ └─┬─┘└─┬─┘ │ │ » # «q_1: ──────────────────────■────■────■────■────────────────────────■───────» # « ┌───┐ │ │ │ ┌───┐ │ » # «q_2: ──■─────────■──┤ X ├──┼─────────┼────┼──┤ X ├──■─────────■────┼───────» # « │ │ └─┬─┘┌─┴─┐ │ ┌─┴─┐└─┬─┘ │ │ ┌─┴─┐ » # «q_3: ──■─────────■────■──┤ X ├───────┼──┤ X ├──■────■─────────■──┤ X ├──■──» # « │ ┌───┐ │ └───┘ │ └───┘ │ │ ┌───┐ │ └───┘ │ » # «q_4: ──┼──┤ X ├──┼───────────────────┼─────────┼────┼──┤ X ├──┼─────────┼──» # « ┌─┴─┐└─┬─┘┌─┴─┐ │ │ ┌─┴─┐└─┬─┘┌─┴─┐ ┌─┴─┐» # «q_5: ┤ X ├──■──┤ X ├─────────────────┼─────────┼──┤ X ├──■──┤ X ├─────┤ X ├» # « └───┘ └───┘ │ │ └───┘ │ └───┘ └───┘» # «q_6: ────────────────────────────────■─────────■─────────■─────────────────» # « » # «q_7: ──────────────────────────────────────────────────────────────────────» # « » # « # «q_0: ───── # « # «q_1: ───── # « ┌───┐ # «q_2: ┤ X ├ # « └─┬─┘ # «q_3: ──■── # « ┌───┐ # «q_4: ┤ X ├ # « └─┬─┘ # «q_5: ──■── # « # «q_6: ───── # « # «q_7: ───── # « expected = QuantumCircuit(8) expected.h(0) expected.h(1) expected.h(2) expected.h(3) expected.h(4) expected.h(5) for i in range(3): expected.cx(i * 2 + 1, i * 2) expected.cx(3, 5) for i in range(2): expected.ccx(i * 2, i * 2 + 1, i * 2 + 3) expected.cx(i * 2 + 3, i * 2 + 2) expected.ccx(4, 5, 6) for i in range(1, -1, -1): expected.ccx(i * 2, i * 2 + 1, i * 2 + 3) expected.cx(3, 5) expected.cx(5, 6) expected.cx(3, 5) expected.x(6) for i in range(2): expected.ccx(i * 2, i * 2 + 1, i * 2 + 3) for i in range(1, -1, -1): expected.cx(i * 2 + 3, i * 2 + 2) expected.ccx(i * 2, i * 2 + 1, i * 2 + 3) expected.cx(1, 0) expected.ccx(6, 1, 0) expected.ccx(0, 1, 3) expected.ccx(6, 3, 2) expected.ccx(2, 3, 5) expected.ccx(6, 5, 4) for i in range(1, -1, -1): expected.ccx(i * 2, i * 2 + 1, i * 2 + 3) expected.cx(3, 5) for i in range(1, 3): expected.cx(i * 2 + 1, i * 2) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=5) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_control_removal(self): """Should replace CX by X.""" # ┌───┐ # q_0: ┤ X ├──■── # └───┘┌─┴─┐ # q_1: ─────┤ X ├ # └───┘ circuit = QuantumCircuit(2) circuit.x(0) circuit.cx(0, 1) # ┌───┐ # q_0: ┤ X ├ # ├───┤ # q_1: ┤ X ├ # └───┘ expected = QuantumCircuit(2) expected.x(0) expected.x(1) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=5) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) # Should replace CZ by Z # # ┌───┐ ┌───┐ # q_0: ┤ H ├─■─┤ H ├ # ├───┤ │ └───┘ # q_1: ┤ X ├─■────── # └───┘ circuit = QuantumCircuit(2) circuit.h(0) circuit.x(1) circuit.cz(0, 1) circuit.h(0) # ┌───┐┌───┐┌───┐ # q_0: ┤ H ├┤ Z ├┤ H ├ # ├───┤└───┘└───┘ # q_1: ┤ X ├────────── # └───┘ expected = QuantumCircuit(2) expected.h(0) expected.x(1) expected.z(0) expected.h(0) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=5) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_is_identity(self): """The is_identity function determines whether a pair of gates forms the identity, when ignoring control qubits. """ seq = [DAGOpNode(op=XGate().control()), DAGOpNode(op=XGate().control(2))] self.assertTrue(HoareOptimizer()._is_identity(seq)) seq = [ DAGOpNode(op=RZGate(-pi / 2).control()), DAGOpNode(op=RZGate(pi / 2).control(2)), ] self.assertTrue(HoareOptimizer()._is_identity(seq)) seq = [DAGOpNode(op=CSwapGate()), DAGOpNode(op=SwapGate())] self.assertTrue(HoareOptimizer()._is_identity(seq)) def test_multiple_pass(self): """Verify that multiple pass can be run with the same Hoare instance. """ # ┌───┐┌───┐ # q_0:─┤ H ├┤ Z ├─ # ├───┤└───┘ # q_1: ┤ Z ├────── # └───┘ circuit1 = QuantumCircuit(2) circuit1.z(0) circuit1.h(1) circuit1.z(1) circuit2 = QuantumCircuit(2) circuit2.z(1) circuit2.h(0) circuit2.z(0) # ┌───┐┌───┐ # q_0:─┤ H ├┤ Z ├─ # └───┘└───┘ # q_1: ─────────── expected = QuantumCircuit(2) expected.h(0) expected.z(0) pass_ = HoareOptimizer() pass_.run(circuit_to_dag(circuit1)) result2 = pass_.run(circuit_to_dag(circuit2)) self.assertEqual(result2, circuit_to_dag(expected)) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) # plot using a Statevector state = Statevector(qc) plot_state_city(state)
https://github.com/Chibikuri/Quantum-Othello
Chibikuri
# -*- coding: utf-8 -*- """ Created on Tue Nov 19 20:45:54 2019 @author: User """ 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/Mreasurment.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 ReturnResult(self, result, error = 500): if abs(result['0'] - result['1']) < error: return 'tie' elif result['0'] > result['1']: return '0' else: return '1' def RandomBasis(self): Basis = ['X', 'Z'] return random.choices(Basis, k=self.num) def RandomGate(self, numTurn): Gate = ['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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the BarrierBeforeFinalMeasurements pass""" import unittest from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements from qiskit.converters import circuit_to_dag from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit.test import QiskitTestCase class TestBarrierBeforeFinalMeasurements(QiskitTestCase): """Tests the BarrierBeforeFinalMeasurements pass.""" def test_single_measure(self): """ A single measurement at the end | q:--[m]-- q:--|-[m]--- | -> | | c:---.--- c:-----.--- """ qr = QuantumRegister(1, 'q') cr = ClassicalRegister(1, 'c') circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) expected = QuantumCircuit(qr, cr) expected.barrier(qr) expected.measure(qr, cr) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_ignore_single_measure(self): """Ignore single measurement because it is not at the end q:--[m]-[H]- q:--[m]-[H]- | -> | c:---.------ c:---.------ """ qr = QuantumRegister(1, 'q') cr = ClassicalRegister(1, 'c') circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) circuit.h(qr[0]) expected = QuantumCircuit(qr, cr) expected.measure(qr, cr) expected.h(qr[0]) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_single_measure_mix(self): """Two measurements, but only one is at the end | q0:--[m]--[H]--[m]-- q0:--[m]--[H]--|-[m]--- | | -> | | | c:---.---------.--- c:---.-----------.--- """ qr = QuantumRegister(1, 'q') cr = ClassicalRegister(1, 'c') circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) circuit.h(qr) circuit.measure(qr, cr) expected = QuantumCircuit(qr, cr) expected.measure(qr, cr) expected.h(qr) expected.barrier(qr) expected.measure(qr, cr) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_two_qregs(self): """Two measurements in different qregs to different cregs | q0:--[H]--[m]------ q0:--[H]--|--[m]------ | | | q1:--------|--[m]-- -> q1:-------|---|--[m]-- | | | | | c0:--------.---|--- c0:----------.---|--- | | c1:------------.--- c0:--------------.--- """ qr0 = QuantumRegister(1, 'q0') qr1 = QuantumRegister(1, 'q1') cr0 = ClassicalRegister(1, 'c0') cr1 = ClassicalRegister(1, 'c1') circuit = QuantumCircuit(qr0, qr1, cr0, cr1) circuit.h(qr0) circuit.measure(qr0, cr0) circuit.measure(qr1, cr1) expected = QuantumCircuit(qr0, qr1, cr0, cr1) expected.h(qr0) expected.barrier(qr0, qr1) expected.measure(qr0, cr0) expected.measure(qr1, cr1) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_two_qregs_to_a_single_creg(self): """Two measurements in different qregs to the same creg | q0:--[H]--[m]------ q0:--[H]--|--[m]------ | | | q1:--------|--[m]-- -> q1:-------|---|--[m]-- | | | | | c0:--------.---|--- c0:-----------.---|--- ------------.--- ---------------.--- """ qr0 = QuantumRegister(1, 'q0') qr1 = QuantumRegister(1, 'q1') cr0 = ClassicalRegister(2, 'c0') circuit = QuantumCircuit(qr0, qr1, cr0) circuit.h(qr0) circuit.measure(qr0, cr0[0]) circuit.measure(qr1, cr0[1]) expected = QuantumCircuit(qr0, qr1, cr0) expected.h(qr0) expected.barrier(qr0, qr1) expected.measure(qr0, cr0[0]) expected.measure(qr1, cr0[1]) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_preserve_measure_for_conditional(self): """Test barrier is inserted after any measurements used for conditionals q0:--[H]--[m]------------ q0:--[H]--[m]--------------- | | q1:--------|--[ z]--[m]-- -> q1:--------|--[ z]--|--[m]-- | | | | | | c0:--------.--[=1]---|--- c0:--------.--[=1]------|--- | | c1:------------------.--- c1:---------------------.--- """ qr0 = QuantumRegister(1, 'q0') qr1 = QuantumRegister(1, 'q1') cr0 = ClassicalRegister(1, 'c0') cr1 = ClassicalRegister(1, 'c1') circuit = QuantumCircuit(qr0, qr1, cr0, cr1) circuit.h(qr0) circuit.measure(qr0, cr0) circuit.z(qr1).c_if(cr0, 1) circuit.measure(qr1, cr1) expected = QuantumCircuit(qr0, qr1, cr0, cr1) expected.h(qr0) expected.measure(qr0, cr0) expected.z(qr1).c_if(cr0, 1) expected.barrier(qr1) expected.measure(qr1, cr1) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) class TestBarrierBeforeMeasuremetsWhenABarrierIsAlreadyThere(QiskitTestCase): """Tests the BarrierBeforeFinalMeasurements pass when there is a barrier already""" def test_handle_redundancy(self): """The pass is idempotent | | q:--|-[m]-- q:--|-[m]--- | | -> | | c:-----.--- c:-----.--- """ qr = QuantumRegister(1, 'q') cr = ClassicalRegister(1, 'c') circuit = QuantumCircuit(qr, cr) circuit.barrier(qr) circuit.measure(qr, cr) expected = QuantumCircuit(qr, cr) expected.barrier(qr) expected.measure(qr, cr) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_remove_barrier_in_different_qregs(self): """Two measurements in different qregs to the same creg q0:--|--[m]------ q0:---|--[m]------ | | | q1:--|---|--[m]-- -> q1:---|---|--[m]-- | | | | c0:------.---|--- c0:-------.---|--- ----------.--- -----------.--- """ qr0 = QuantumRegister(1, 'q0') qr1 = QuantumRegister(1, 'q1') cr0 = ClassicalRegister(2, 'c0') circuit = QuantumCircuit(qr0, qr1, cr0) circuit.barrier(qr0) circuit.barrier(qr1) circuit.measure(qr0, cr0[0]) circuit.measure(qr1, cr0[1]) expected = QuantumCircuit(qr0, qr1, cr0) expected.barrier(qr0, qr1) expected.measure(qr0, cr0[0]) expected.measure(qr1, cr0[1]) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_preserve_barriers_for_measurement_ordering(self): """If the circuit has a barrier to enforce a measurement order, preserve it in the output. q:---[m]--|------- q:---|--[m]--|------- ----|---|--[m]-- -> ---|---|---|--[m]-- | | | | c:----.-------|--- c:-------.-------|--- ------------.--- ---------------.--- """ qr = QuantumRegister(2, 'q') cr = ClassicalRegister(2, 'c') circuit = QuantumCircuit(qr, cr) circuit.measure(qr[0], cr[0]) circuit.barrier(qr) circuit.measure(qr[1], cr[1]) expected = QuantumCircuit(qr, cr) expected.barrier(qr) expected.measure(qr[0], cr[0]) expected.barrier(qr) expected.measure(qr[1], cr[1]) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_measures_followed_by_barriers_should_be_final(self): """If a measurement is followed only by a barrier, insert the barrier before it. q:---[H]--|--[m]--|------- q:---[H]--|--[m]-|------- ---[H]--|---|---|--[m]-- -> ---[H]--|---|--|--[m]-- | | | | c:------------.-------|--- c:------------.------|--- --------------------.--- -------------------.--- """ qr = QuantumRegister(2, 'q') cr = ClassicalRegister(2, 'c') circuit = QuantumCircuit(qr, cr) circuit.h(qr) circuit.barrier(qr) circuit.measure(qr[0], cr[0]) circuit.barrier(qr) circuit.measure(qr[1], cr[1]) expected = QuantumCircuit(qr, cr) expected.h(qr) expected.barrier(qr) expected.measure(qr[0], cr[0]) expected.barrier(qr) expected.measure(qr[1], cr[1]) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_should_merge_with_smaller_duplicate_barrier(self): """If an equivalent barrier exists covering a subset of the qubits covered by the new barrier, it should be replaced. q:---|--[m]------------- q:---|--[m]------------- ---|---|---[m]-------- -> ---|---|---[m]-------- -------|----|---[m]--- ---|---|----|---[m]--- | | | | | | c:-------.----|----|---- c:-------.----|----|---- ------------.----|---- ------------.----|---- -----------------.---- -----------------.---- """ qr = QuantumRegister(3, 'q') cr = ClassicalRegister(3, 'c') circuit = QuantumCircuit(qr, cr) circuit.barrier(qr[0], qr[1]) circuit.measure(qr, cr) expected = QuantumCircuit(qr, cr) expected.barrier(qr) expected.measure(qr, cr) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_should_merge_with_larger_duplicate_barrier(self): """If a barrier exists and is stronger than the barrier to be inserted, preserve the existing barrier and do not insert a new barrier. q:---|--[m]--|------- q:---|--[m]-|------- ---|---|---|--[m]-- -> ---|---|--|--[m]-- ---|---|---|---|--- ---|---|--|---|--- | | | | c:-------.-------|--- c:-------.------|--- ---------------.--- --------------.--- ------------------- ------------------ """ qr = QuantumRegister(3, 'q') cr = ClassicalRegister(3, 'c') circuit = QuantumCircuit(qr, cr) circuit.barrier(qr) circuit.measure(qr[0], cr[0]) circuit.barrier(qr) circuit.measure(qr[1], cr[1]) expected = circuit pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barrier_doesnt_reorder_gates(self): """ A barrier should not allow the reordering of gates, as pointed out in #2102 q:--[u1(0)]-----------[m]--------- q:--[u1(0)]------------|--[m]--------- --[u1(1)]------------|-[m]------ -> --[u1(1)]------------|---|-[m]------ --[u1(2)]-|----------|--|-[m]---- --[u1(2)]-|----------|---|--|-[m]---- ----------|-[u1(03)]-|--|--|-[m]- ----------|-[u1(03)]-|---|--|--|-[m]- | | | | | | | | c:---------------------.--|--|--|- c:--------------------------.--|--|--|- ------------------------.--|--|- -----------------------------.--|--|- ---------------------------.--|- --------------------------------.--|- ------------------------------.- -----------------------------------.- """ qr = QuantumRegister(4) cr = ClassicalRegister(4) circuit = QuantumCircuit(qr, cr) circuit.u1(0, qr[0]) circuit.u1(1, qr[1]) circuit.u1(2, qr[2]) circuit.barrier(qr[2], qr[3]) circuit.u1(3, qr[3]) test_circuit = circuit.copy() test_circuit.measure(qr, cr) # expected circuit is the same, just with a barrier before the measurements expected = circuit.copy() expected.barrier(qr) expected.measure(qr, cr) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(test_circuit)) self.assertEqual(result, circuit_to_dag(expected)) if __name__ == '__main__': unittest.main()
https://github.com/bawejagb/Quantum_Computing
bawejagb
from qiskit import IBMQ IBMQ.providers() #https://quantum-computing.ibm.com/ #Craete account on IBM from above link and Paste 'YOUR-IBM-API-TOKEN' IBMQ.save_account('YOUR-IBM-API-TOKEN',overwrite=True) IBMQ.load_account() from qiskit import( QuantumCircuit, execute, Aer) from qiskit.visualization import plot_histogram # Use Aer's qasm_simulator simulator = Aer.get_backend('qasm_simulator') # Create a Quantum Circuit acting on the q register circuit = QuantumCircuit(2, 2) # Add a H gate on qubit 0 circuit.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1 circuit.cx(0, 1) # Map the quantum measurement to the classical bits circuit.measure([0,1], [0,1]) # Execute the circuit on the qasm simulator job = execute(circuit, simulator, shots=1000) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(circuit) print("\nTotal count for 00 and 11 are:",counts) # Draw the circuit circuit.draw(output='mpl') provider = IBMQ.get_provider('ibm-q') provider.backends() qcomp = provider.get_backend('ibmq_lima') job = execute(circuit, backend=qcomp) from qiskit.tools.monitor import job_monitor job_monitor(job) result = job.result() plot_histogram(result.get_counts(circuit))
https://github.com/zapatacomputing/qe-qiskit
zapatacomputing
################################################################################ # © Copyright 2021-2022 Zapata Computing Inc. ################################################################################ import os import pytest import qiskit.providers.aer.noise as AerNoise from qeqiskit.noise import get_qiskit_noise_model from qeqiskit.simulator import QiskitSimulator from zquantum.core.circuits import CNOT, Circuit, X from zquantum.core.estimation import estimate_expectation_values_by_averaging from zquantum.core.interfaces.backend_test import ( QuantumSimulatorGatesTest, QuantumSimulatorTests, ) from zquantum.core.interfaces.estimation import EstimationTask from zquantum.core.measurement import ExpectationValues from zquantum.core.openfermion.ops import QubitOperator @pytest.fixture( params=[ { "device_name": "aer_simulator", "api_token": os.getenv("ZAPATA_IBMQ_API_TOKEN"), }, ] ) def backend(request): return QiskitSimulator(**request.param) @pytest.fixture( params=[ { "device_name": "aer_simulator_statevector", }, ] ) def wf_simulator(request): return QiskitSimulator(**request.param) @pytest.fixture( params=[ { "device_name": "aer_simulator", }, { "device_name": "aer_simulator_statevector", }, ] ) def sampling_simulator(request): return QiskitSimulator(**request.param) @pytest.fixture( params=[ {"device_name": "aer_simulator", "optimization_level": 0}, ] ) def noisy_simulator(request): ibmq_api_token = os.getenv("ZAPATA_IBMQ_API_TOKEN") noise_model, connectivity = get_qiskit_noise_model( "ibm_nairobi", api_token=ibmq_api_token ) return QiskitSimulator( **request.param, noise_model=noise_model, device_connectivity=connectivity ) class TestQiskitSimulator(QuantumSimulatorTests): def test_run_circuitset_and_measure(self, sampling_simulator): # Given circuit = Circuit([X(0), CNOT(1, 2)]) # When measurements_set = sampling_simulator.run_circuitset_and_measure( [circuit], [100] ) # Then assert len(measurements_set) == 1 for measurements in measurements_set: assert len(measurements.bitstrings) == 100 assert all(bitstring == (1, 0, 0) for bitstring in measurements.bitstrings) # When n_circuits = 50 n_samples = 100 measurements_set = sampling_simulator.run_circuitset_and_measure( [circuit] * n_circuits, [n_samples] * n_circuits ) # Then assert len(measurements_set) == n_circuits for measurements in measurements_set: assert len(measurements.bitstrings) == n_samples assert all(bitstring == (1, 0, 0) for bitstring in measurements.bitstrings) def test_setup_basic_simulators(self): simulator = QiskitSimulator("aer_simulator") assert isinstance(simulator, QiskitSimulator) assert simulator.device_name == "aer_simulator" assert simulator.noise_model is None assert simulator.device_connectivity is None assert simulator.basis_gates is None simulator = QiskitSimulator("aer_simulator_statevector") assert isinstance(simulator, QiskitSimulator) assert simulator.device_name == "aer_simulator_statevector" assert simulator.noise_model is None assert simulator.device_connectivity is None assert simulator.basis_gates is None def test_simulator_that_does_not_exist(self): # Given/When/Then with pytest.raises(RuntimeError): QiskitSimulator("DEVICE DOES NOT EXIST") def test_expectation_value_with_noisy_simulator(self, noisy_simulator): # Given # Initialize in |1> state circuit = Circuit([X(0)]) # Flip qubit an even number of times to remain in the |1> state, but allow # decoherence to take effect circuit += Circuit([X(0) for i in range(10)]) qubit_operator = QubitOperator("Z0") n_samples = 8192 # When estimation_tasks = [EstimationTask(qubit_operator, circuit, n_samples)] expectation_values_10_gates = estimate_expectation_values_by_averaging( noisy_simulator, estimation_tasks )[0] # Then assert isinstance(expectation_values_10_gates, ExpectationValues) assert len(expectation_values_10_gates.values) == 1 assert expectation_values_10_gates.values[0] > -1 assert expectation_values_10_gates.values[0] < 0.0 assert isinstance(noisy_simulator, QiskitSimulator) assert noisy_simulator.device_name == "aer_simulator" assert isinstance(noisy_simulator.noise_model, AerNoise.NoiseModel) assert noisy_simulator.device_connectivity is not None assert noisy_simulator.basis_gates is not None # Given # Initialize in |1> state circuit = Circuit([X(0)]) # Flip qubit an even number of times to remain in the |1> state, but allow # decoherence to take effect circuit += Circuit([X(0) for i in range(50)]) qubit_operator = QubitOperator("Z0") # When estimation_tasks = [EstimationTask(qubit_operator, circuit, n_samples)] expectation_values_50_gates = estimate_expectation_values_by_averaging( noisy_simulator, estimation_tasks )[0] # Then assert isinstance(expectation_values_50_gates, ExpectationValues) assert len(expectation_values_50_gates.values) == 1 assert expectation_values_50_gates.values[0] > -1 assert expectation_values_50_gates.values[0] < 0.0 assert ( expectation_values_50_gates.values[0] > expectation_values_10_gates.values[0] ) assert isinstance(noisy_simulator, QiskitSimulator) assert noisy_simulator.device_name == "aer_simulator" assert isinstance(noisy_simulator.noise_model, AerNoise.NoiseModel) assert noisy_simulator.device_connectivity is not None assert noisy_simulator.basis_gates is not None def test_optimization_level_of_transpiler(self): # Given noise_model, connectivity = get_qiskit_noise_model( "ibm_nairobi", api_token=os.getenv("ZAPATA_IBMQ_API_TOKEN") ) n_samples = 8192 simulator = QiskitSimulator( "aer_simulator", noise_model=noise_model, device_connectivity=connectivity, optimization_level=0, ) qubit_operator = QubitOperator("Z0") # Initialize in |1> state circuit = Circuit([X(0)]) # Flip qubit an even number of times to remain in the |1> state, but allow # decoherence to take effect circuit += Circuit([X(0) for i in range(50)]) # When estimation_tasks = [EstimationTask(qubit_operator, circuit, n_samples)] expectation_values_no_compilation = estimate_expectation_values_by_averaging( simulator, estimation_tasks ) simulator.optimization_level = 3 expectation_values_full_compilation = estimate_expectation_values_by_averaging( simulator, estimation_tasks ) # Then assert ( expectation_values_full_compilation[0].values[0] < expectation_values_no_compilation[0].values[0] ) def test_run_circuit_and_measure_seed(self): # Given circuit = Circuit([X(0), CNOT(1, 2)]) n_samples = 100 simulator1 = QiskitSimulator("aer_simulator", seed=643) simulator2 = QiskitSimulator("aer_simulator", seed=643) # When measurements1 = simulator1.run_circuit_and_measure(circuit, n_samples) measurements2 = simulator2.run_circuit_and_measure(circuit, n_samples) # Then for (meas1, meas2) in zip(measurements1.bitstrings, measurements2.bitstrings): assert meas1 == meas2 def test_get_wavefunction_seed(self): # Given circuit = Circuit([X(0), CNOT(1, 2)]) simulator1 = QiskitSimulator("aer_simulator_statevector", seed=643) simulator2 = QiskitSimulator("aer_simulator_statevector", seed=643) # When wavefunction1 = simulator1.get_wavefunction(circuit) wavefunction2 = simulator2.get_wavefunction(circuit) # Then for (ampl1, ampl2) in zip(wavefunction1.amplitudes, wavefunction2.amplitudes): assert ampl1 == ampl2 class TestQiskitSimulatorGates(QuantumSimulatorGatesTest): gates_to_exclude = ["RH", "XY"] pass
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
https://github.com/MetalKyubit/Quantum-Algorithms-in-Qiskit
MetalKyubit
# initialization import numpy as np # importing Qiskit from qiskit import * # import basic plot tools from qiskit.visualization import plot_histogram from qiskit.providers.fake_provider import FakeJakarta from qiskit.providers.fake_provider import FakeNairobi #defining a function to create the BV Algorithm circuit. Function takes in the oracle and number of qubits and # ouputs the quantum circuit def BV_algo(oracle,n): # n input qubits and 1 helper qubit qc = QuantumCircuit(n+1,n) # helper qubit initialised to state ket_1 qc.x(n) # creating superposition of all the inputs. and making the state of the helper qubit as ket_minus. for i in range(n+1): qc.h(i) qc.barrier() # applying the oracle that has the funciton encoded in it to the circuit qc.append(oracle, range(n+1)) qc.barrier() #applying the hadamard gates again to collapse the superposition to one state that has the final result #encoded in it. for i in range(n): qc.h(i) # measuring the input qubits to find the final result. qc.measure(range(n),range(n)) return (qc) def bv_oracle(n:int, s:str): _circuit_oracle = QuantumCircuit(n+1) #reverse the bit string because qiskit uses inverse endianness s = s[::-1] for _bit_position in range(n): if(s[_bit_position] == '1'): # phase flippping the helper qubit (as it is in ket_minus state x will phase flip it) # flipping phase _circuit_oracle.cx(_bit_position, n) else: _circuit_oracle.i(_bit_position) _gate_oracle = _circuit_oracle.to_gate() s = s[::-1] _gate_oracle.name = "Oracle\n s: "+str(s) return _gate_oracle # Testing the algorithm for n=3 and a='101') n = 3 oracle = bv_oracle(n, '101') q1 = BV_algo(oracle, n) q1.draw('mpl') # Running on non-noisy simulator backend = Aer.get_backend('aer_simulator') job = execute(q1,backend) results = job.result() counts = results.get_counts() plot_histogram(counts) # Running on noisy simulator backend = FakeJakarta() job = execute(q1,backend) results = job.result() counts = results.get_counts() plot_histogram(counts) # Running on noisy simulator backend = FakeNairobi() job = execute(q1,backend) results = job.result() counts = results.get_counts() plot_histogram(counts) # Testing the algorithm for n=3 and a='101') n = 5 oracle = bv_oracle(n, '10101') q1 = BV_algo(oracle, n) q1.draw('mpl') # Running on non-noisy simulator backend = Aer.get_backend('aer_simulator') job = execute(q1,backend) results = job.result() counts = results.get_counts() plot_histogram(counts) # Running on noisy simulator backend = FakeJakarta() job = execute(q1,backend) results = job.result() counts = results.get_counts() plot_histogram(counts) # Running on noisy simulator backend = FakeNairobi() job = execute(q1,backend) results = job.result() counts = results.get_counts() plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits to represent the uncertainty num_uncertainty_qubits = 3 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = (r - 0.5 * vol**2) * T + np.log(S) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # construct circuit for uncertainty model uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high) ) # plot probability distribution x = uncertainty_model.values y = uncertainty_model.probabilities plt.bar(x, y, width=0.2) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.grid() plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15) plt.ylabel("Probability ($\%$)", size=15) plt.show() # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 1.438 strike_price_2 = 2.584 # set the approximation scaling for the payoff function rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, strike_price_2 - strike_price_1] f_min = 0 f_max = strike_price_2 - strike_price_1 bull_spread_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective bull_spread = bull_spread_objective.compose(uncertainty_model, front=True) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) plt.plot(x, y, "ro-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Spot Price", size=15) plt.ylabel("Payoff", size=15) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value (normalized to the [0, 1] interval) exact_value = np.dot(uncertainty_model.probabilities, y) exact_delta = sum( uncertainty_model.probabilities[np.logical_and(x >= strike_price_1, x <= strike_price_2)] ) print("exact expected value:\t%.4f" % exact_value) print("exact delta value: \t%.4f" % exact_delta) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread, objective_qubits=[num_uncertainty_qubits], post_processing=bull_spread_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 0, 0] offsets = [0, 1, 0] f_min = 0 f_max = 1 bull_spread_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # no approximation necessary, hence no rescaling factor # construct the A operator by stacking the uncertainty model and payoff function together bull_spread_delta = bull_spread_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval) print("Exact delta: \t%.4f" % exact_delta) print("Estimated value:\t%.4f" % result_delta.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) ghz.draw(output='mpl')
https://github.com/JayRGopal/Quantum-Error-Correction
JayRGopal
from qiskit import * import random def generate_oracle(oracle_length, random_cnot, cnot_count, fixed_string=""): if random_cnot == True: cnot_count = random.randint(0, oracle_length) random_cnots = random.sample(range(0, oracle_length), cnot_count) oracle = "" for i in range(oracle_length): if random_cnots.count(i) == 1: oracle = oracle + "1" else: oracle = oracle + "0" if fixed_string != "" and len(fixed_string) == oracle_length - 1: oracle = fixed_string circuit = QuantumCircuit(len(oracle)+1, len(oracle)) circuit.h(range(len(oracle))) circuit.x(len(oracle)) circuit.h(len(oracle)) circuit.barrier() for ii, yesno in enumerate(reversed(oracle)): if yesno == '1': circuit.cx(ii, len(oracle)) circuit.barrier() circuit.h(range(len(oracle))) circuit.barrier() circuit.measure(range(len(oracle)), range(len(oracle))) return [circuit, oracle] def validate_oracle(results,expected,cnt): print("ORACLE PASSES :)" if results.get_counts().most_frequent() == expected else "oracle failed... :(") acc = (results.get_counts()[expected] / cnt) * 100 print("Correct with %d%% accurary"%(acc))
https://github.com/quantumgenetics/quantumgenetics
quantumgenetics
#!/usr/bin/env python3 import logging from datetime import datetime from qiskit import QuantumCircuit logger = logging.getLogger(__name__) def initialized_empty_circuit(qubit_count, state): logger.info('Produce circuit') return initialized_circuit(QuantumCircuit(qubit_count, qubit_count), state) def initialized_circuit(circuit, state): qubit_count = len(circuit.qubits) assert len(state) == 2**qubit_count pre_circuit = QuantumCircuit(circuit.qregs[0], circuit.cregs[0]) logger.info('Initializing circuit...') before = datetime.now() pre_circuit.initialize(state, range(qubit_count)) delta = datetime.now() - before logger.info('Circuit initialized ({} s)'.format(delta.total_seconds())) post_circuit = circuit.copy() post_circuit.barrier(post_circuit.qregs[0]) post_circuit.measure(range(qubit_count), range(qubit_count)) return pre_circuit + post_circuit
https://github.com/qclib/qclib
qclib
# Copyright 2021 qclib project. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Linear-depth Multicontrolled Special Unitary """ from typing import Union, List import numpy as np from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library import UnitaryGate from qiskit.circuit import Gate, Qubit from qclib.gates.ldmcsu import Ldmcsu from qclib.gates.mcx import McxVchainDirty from qclib.gates.util import check_su2, isclose # pylint: disable=protected-access class MultiTargetMCSU2(Gate): """ Multi-target Multi-Controlled Gate for Special Unitary ------------------------------------------------ Linear decomposition of approximate multi-controlled single qubit gates https://arxiv.org/abs/2310.14974 Lemma 7 """ def __init__(self, unitaries, num_controls, num_target=1, ctrl_state: str = None): """ Parameters ---------- unitaries (list): List of SU(2) matrices num_controls (int): Number of control gastes num_target (int): Number of target gates ctrl_state (str): Control state in decimal or as a bitstring """ if isinstance(unitaries, list): for unitary in unitaries: check_su2(unitary) else: check_su2(unitaries) self.unitaries = unitaries self.controls = QuantumRegister(num_controls) self.target = QuantumRegister(num_target) self.num_controls = num_controls + 1 self.ctrl_state = ctrl_state super().__init__("ldmcsu", self.num_controls, [], "ldmcsu") def _define(self): if isinstance(self.unitaries, list): self.definition = QuantumCircuit(self.controls, self.target) is_main_diags_real = [] is_secondary_diags_real = [] for unitary in self.unitaries: is_main_diags_real.append( isclose(unitary[0, 0].imag, 0.0) and isclose(unitary[1, 1].imag, 0.0) ) is_secondary_diags_real.append( isclose(unitary[0, 1].imag, 0.0) and isclose(unitary[1, 0].imag, 0.0) ) for idx, unitary in enumerate(self.unitaries): if not is_secondary_diags_real[idx] and is_main_diags_real[idx]: self.definition.h(self.target[idx]) self.clinear_depth_mcv() for idx, unitary in enumerate(self.unitaries): if not is_secondary_diags_real[idx] and is_main_diags_real[idx]: self.definition.h(self.target[idx]) else: self.definition = Ldmcsu(self.unitaries, self.num_controls) def clinear_depth_mcv(self, general_su2_optimization=False): """ Multi-target version of Theorem 1 - https://arxiv.org/pdf/2302.06377.pdf """ # S gate definition gates_a = self._s_gate_definition(self.unitaries) num_ctrl = len(self.controls) target_size = len(self.target) k_1 = int(np.ceil(num_ctrl / 2.0)) k_2 = int(np.floor(num_ctrl / 2.0)) ctrl_state_k_1 = None ctrl_state_k_2 = None if self.ctrl_state is not None: ctrl_state_k_1 = self.ctrl_state[::-1][:k_1][::-1] ctrl_state_k_2 = self.ctrl_state[::-1][k_1:][::-1] if not general_su2_optimization: mcx_1 = McxVchainDirty( k_1, num_target_qubit=target_size, ctrl_state=ctrl_state_k_1 ).definition self.definition.append( mcx_1, self.controls[:k_1] + self.controls[k_1: 2 * k_1 - 2] + [*self.target], ) for idx, gate_a in enumerate(gates_a): self.definition.append(gate_a, [num_ctrl + idx]) mcx_2 = McxVchainDirty( k_2, num_target_qubit=target_size, ctrl_state=ctrl_state_k_2, action_only=general_su2_optimization, ).definition self.definition.append( mcx_2.inverse(), self.controls[k_1:] + self.controls[k_1 - k_2 + 2: k_1] + [*self.target], ) for idx, gate_a in enumerate(gates_a): self.definition.append(gate_a.inverse(), [num_ctrl + idx]) mcx_3 = McxVchainDirty( k_1, num_target_qubit=target_size, ctrl_state=ctrl_state_k_1 ).definition self.definition.append( mcx_3, self.controls[:k_1] + self.controls[k_1: 2 * k_1 - 2] + [*self.target], ) for idx, gate_a in enumerate(gates_a): self.definition.append(gate_a, [num_ctrl + idx]) mcx_4 = McxVchainDirty( k_2, num_target_qubit=target_size, ctrl_state=ctrl_state_k_2 ).definition self.definition.append( mcx_4, self.controls[k_1:] + self.controls[k_1 - k_2 + 2: k_1] + [*self.target], ) for idx, gate_a in enumerate(gates_a): self.definition.append(gate_a.inverse(), [num_ctrl + idx]) def _s_gate_definition(self, su2_unitaries): gates_a = [] for su2_unitary in su2_unitaries: x_value, z_value = Ldmcsu._get_x_z(su2_unitary) op_a = Ldmcsu._compute_gate_a(x_value, z_value) gates_a.append(UnitaryGate(op_a)) return gates_a @staticmethod def multi_target_mcsu2( circuit, unitary, controls: Union[QuantumRegister, List[Qubit]], target: Qubit, ctrl_state: str = None, ): """ Multi-target version of multi-controlled SU(2) https://arxiv.org/abs/2302.06377 """ if isinstance(unitary, list): num_target = len(unitary) circuit.append( MultiTargetMCSU2(unitary, len(controls), num_target=num_target).definition, [*controls, *target], ) else: circuit.append( Ldmcsu(unitary, len(controls), ctrl_state=ctrl_state), [*controls, target], )
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
# Run this cell using Shift+Enter (⌘+Enter on Mac). from typing import Tuple import math Complex = Tuple[float, float] Polar = Tuple[float, float] def imaginary_power(n : int) -> int: # If n is divisible by 4 if n % 4 == 0: return 1 else: return 1j ** (n % 4) imaginary_power(4) def complex_add(x : Complex, y : Complex) -> Complex: # You can extract elements from a tuple like this a = x[0] b = x[1] c = y[0] d = y[1] # This creates a new variable and stores the real component into it real = a + c # Replace the ... with code to calculate the imaginary component imaginary = b+d # You can create a tuple like this ans = (real, imaginary) return ans complex_add((1,2),(3,4)) def complex_mult(x, y): # Extract the real and imaginary components of x and y a = x[0] b = x[1] c = y[0] d = y[1] # Calculate the real component of the result real = a * c - b * d # Calculate the imaginary component of the result imaginary = a * d + b * c # Create a new tuple with the calculated real and imaginary components ans = (real, imaginary) return ans result = complex_mult((1, 2), (3, 4)) print(result) # Output: (-5, 10) def conjugate(x): # Extract the real and imaginary components of x real, imaginary = x # Calculate the conjugate by negating the imaginary component conjugate_imaginary = -imaginary # Create a new tuple with the original real component and the conjugate imaginary component conjugate = (real, conjugate_imaginary) return conjugate result = conjugate((3, 4)) print(result) # Output: (3, -4) def complex_div(x, y): # Extract the real and imaginary components of x and y a, b = x c, d = y # Calculate the denominator of the division denominator = c**2 + d**2 # Calculate the real and imaginary components of the result real = (a * c + b * d) / denominator imaginary = (b * c - a * d) / denominator # Create a new tuple with the calculated real and imaginary components result = (real, imaginary) return result result = complex_div((5, 2), (3, 1)) print(result) # Output: (1.6, 0.2) def modulus(x): # Extract the real and imaginary components of x a = x[0] b = x[1] # Calculate the modulus using the Pythagorean theorem modulus_value = (a**2 + b**2)**0.5 return modulus_value result = modulus((3, 4)) print(result) # Output: 5.0 import cmath def complex_exp(x): # Extract the real and imaginary components of x a = x[0] b = x[1] # Calculate the complex exponential using the cmath library result = cmath.exp(complex(a, b)) # Extract the real and imaginary components of the result g = result.real h = result.imag return (g, h) result = complex_exp((1, 1)) print(result) # Output: (1.4686939399158851+2.2873552871788423j) import cmath def complex_exp_real(r, x): # Extract the real and imaginary components of x a = x[0] b = x[1] # Calculate the complex power using the cmath library result = cmath.exp(complex(a, b) * cmath.log(r)) # Extract the real and imaginary components of the result g = result.real h = result.imag return (g, h) result = complex_exp_real(2, (1, 1)) print(result) # Output: (-1.1312043837568135+2.4717266720048188j) import cmath def polar_convert(x): # Extract the real and imaginary components of x a = x[0] b = x[1] # Calculate the modulus and phase using the cmath library modulus = abs(complex(a, b)) phase = cmath.phase(complex(a, b)) return (modulus, phase) result = polar_convert((3, 4)) print(result) # Output: (5.0, 0.9272952180016122) import cmath def cartesian_convert(x): # Extract the modulus and phase from x modulus = x[0] phase = x[1] # Calculate the real and imaginary components using cmath library real = modulus * cmath.cos(phase) imaginary = modulus * cmath.sin(phase) return (real, imaginary) result = cartesian_convert((5.0, 0.9272952180016122)) print(result) # Output: (3.0000000000000004, 3.9999999999999996) import math def polar_mult(x, y): # Extract the modulus and phase from x and y r1, theta1 = x r2, theta2 = y # Calculate the modulus of the product r3 = r1 * r2 # Calculate the phase of the product theta3 = theta1 + theta2 # Normalize theta3 to be between -pi and pi theta3 = math.atan2(math.sin(theta3), math.cos(theta3)) return (r3, theta3) result = polar_mult((2.0, 1.0471975511965979), (3.0, -0.5235987755982988)) print(result) # Output: (6.0, 0.5235987755982988) import cmath def complex_power(x, y): # Extract the real and imaginary components from x and y a, b = x c, d = y # Convert x and y to complex numbers x_complex = complex(a, b) y_complex = complex(c, d) # Calculate the result using the cmath library result = cmath.exp(y_complex * cmath.log(x_complex)) # Extract the real and imaginary components of the result g = result.real h = result.imag return (g, h) result = complex_power((2, 1), (1, 1)) print(result) # Output: (0.6466465358226179, 1.5353981633974483)
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # Author: Daniel Escanez-Exposito from abc import ABC, abstractmethod from qiskit import QuantumCircuit from qiskit.circuit.library import YGate, ZGate from qiskit.circuit.gate import Gate import qiskit.quantum_info as qi from numpy.random import randint import numpy as np from math import ceil ## An abstract class of a participant entity in the Six-State implementation ## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html class Participant(ABC): ## Constructor @abstractmethod def __init__(self, name='', original_bits_size=0): ## The name of the participant self.name = name ## The original size of the message self.original_bits_size = original_bits_size ## The values of the participant self.values = None ## The axes of the participant self.axes = None ## The key of the participant self.key = None ## If the key is determined safe self.is_safe_key = False ## The otp of the participant self.otp = None ## The gate measuring z and y axes self.set_hy() ## Values setter def set_values(self, values=None): if values == None: self.values = list(randint(2, size=self.original_bits_size)) else: self.values = values ## Axes setter def set_axes(self, axes=None): if axes == None: self.axes = list(randint(3, size=self.original_bits_size)) else: self.axes = axes ## Print values def show_values(self): print('\n' + self.name, 'Values:') print(self.values) ## Print axes def show_axes(self): print('\n' + self.name, 'Axes:') print(self.axes) ## Print key def show_key(self): print('\n' + self.name, 'Key:') print(self.key) ## Print otp def show_otp(self): print('\n' + self.name, 'OTP:') print(self.otp) ## Remove the values of the qubits that were measured on the wrong axis def remove_garbage(self, another_axes): self.key = [] for i in range(self.original_bits_size): if self.axes[i] == another_axes[i]: self.key.append(self.values[i]) ## Check if the shared key is equal to the current key def check_key(self, shared_key): return shared_key == self.key[:len(shared_key)] ## Use the rest of the key and validate it def confirm_key(self, shared_size): self.key = self.key[shared_size:] self.is_safe_key = True ## Generate an One-Time Pad def generate_otp(self, n_bits): self.otp = [] for i in range(ceil(len(self.key) / n_bits)): bits_string = ''.join(map(str, self.key[i * n_bits: (i + 1) * n_bits])) self.otp.append(int(bits_string, 2)) ## Performs an XOR operation between the message and the One-Time Pad def xor_otp_message(self, message): final_message = '' CHR_LIMIT = 1114112 if len(self.otp) > 0: for i, char in enumerate(message): final_message += chr((ord(char) ^ self.otp[i % len(self.otp)]) % CHR_LIMIT) return final_message ## New gate setter def set_hy(self): hy_op = qi.Operator(1/np.sqrt(2)*(YGate().to_matrix() + ZGate().to_matrix())) hy_gate = QuantumCircuit(1) hy_gate.unitary(hy_op, [0], label='h_y') self.hy = hy_gate.to_gate()
https://github.com/Interlin-q/diskit
Interlin-q
import sys sys.path.append("..") from diskit import * import warnings warnings.filterwarnings("ignore") circuit_topo = Topology() circuit_topo.create_qmap(3, [2, 3, 3], "sys") circuit_topo.qmap, circuit_topo.emap print("Total Number of Qubits in Topology : ", circuit_topo.num_qubits()) print("Total Number of QPUs in Topology: ", circuit_topo.num_hosts()) Qubit1 = circuit_topo.qmap["sys1"][2] Qubit2 = circuit_topo.qmap["sys2"][1] print("{} and {} are adjacent".format(Qubit1, Qubit2) if circuit_topo.are_adjacent(Qubit1, Qubit2) else "{} and {} are not adjacent".format(Qubit1, Qubit2)) for qubit in circuit_topo.qubits: print("Qubit: {} --------- Host: {}".format(qubit, circuit_topo.get_host(qubit))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/minnukota381/Quantum-Computing-Qiskit
minnukota381
from qiskit import * from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram # Create a quantum circuit with 2 qubits # The default initial state of qubits will be |0> or [1,0] qc = QuantumCircuit(2) #Applying the x gate to second qubit qc.x(1) #Draw the circuit # qc.draw() qc.draw('mpl') #Get the backend for the circuit to display unitary matrix backend = Aer.get_backend('unitary_simulator') #Get the backend for the circuit (simulator or realtime system) #backend = Aer.get_backend('statevector_simulator') #execute the circuit using the backend out = execute(qc,backend).result().get_unitary() #execute the circuit using the backend #out = execute(qc,backend).result().get_statevector() #import qiskit_textbook and display the statevector from qiskit_textbook.tools import array_to_latex array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ") #import qiskit_textbook and display the statevector #from qiskit_textbook.tools import array_to_latex #array_to_latex(out, pretext = "\\text{Statevector} = ") #plot the result as a bloch sphere visualization plot_bloch_multivector(out)
https://github.com/Pitt-JonesLab/mirror-gates
Pitt-JonesLab
# make a graph that shows convergence as a function of layout trials and swap trials # very important point to not forget # NOTE, these layout trials are after multiple SWAP trials and through forward-backwards pass # this means it has already gone through 2 stages of optimization and we still have large variance # ultimate question is how much time do we need to spend on swap restarts, forward-backward passes, and layout restarts # maybe we work from bottom up, collect data to get a fair estimate of how much time we need to spend on each? from qiskit.transpiler import CouplingMap from mirror_gates.pass_managers import Mirage, QiskitLevel3 from transpile_benchy.metrics.abc_metrics import MetricInterface from transpile_benchy.metrics.gate_counts import DepthMetric from mirror_gates.utilities import ( DoNothing, LayoutTrialsStdMetric, LayoutTrialsMetric, ) from mirror_gates.logging import transpile_benchy_logger from transpile_benchy.library import CircuitLibrary library = CircuitLibrary.from_txt("../../circuits/iters_select.txt") coupling_map = CouplingMap.from_heavy_hex(5) total_work = 80 transpilers = [ # QiskitLevel3(coupling_map), Mirage(coupling_map, name="Qiskit", fixed_aggression=0), Mirage(coupling_map, name="Mirage"), # Mirage( # coupling_map, # name="Mirage-b3", # layout_trials=20, # fb_iters=total_work // 20, # anneal_routing=True, # parallel=False, # something is broken # ), ] metrics = [LayoutTrialsMetric()] # , DepthMetric(consolidate=False)] # coupling_map = CouplingMap.from_heavy_hex(5) # transpilers = [ # # QiskitLevel3(coupling_map), # Mirage(coupling_map, name="Mirage-MinSwaps", cost_function="basic"), # Mirage(coupling_map, name="Mirage-MinDepth"), # ] # metrics = [DepthMetric(consolidate=False)] # , TotalMetric(consolidate=False)] from transpile_benchy.benchmark import Benchmark # only interested in TimeMetric, is there by default benchmark = Benchmark( transpilers=transpilers, circuit_library=library, metrics=metrics, num_runs=10, logger=transpile_benchy_logger, ) benchmark.run() print(benchmark) benchmark.metrics[0].saved_results import matplotlib.pyplot as plt import numpy as np # Assuming benchmark.metrics[0].saved_results.items() is a dictionary # where keys are circuit names and values are lists of costs for each trial for k, v in benchmark.metrics[0].saved_results.items(): print(k) for circuit, result in v.items(): # print(circuit) # print(result.data) # find cumulative min trial-wise min_trials = np.minimum.accumulate(result.data, axis=1) print(min_trials.shape) # print(min_trials) # average element-wise across all trials avg = np.mean(min_trials, axis=0) # print(avg) # plot cumulative min vs trial # also plot average cumulative min vs trial # at each trial we also want to scatter plot each individual trial, # plot with latex with plt.style.context(["ipynb", "colorsblind10"]): plt.rcParams["text.usetex"] = True for j, trials in enumerate(min_trials): plt.plot( trials, color="blue", alpha=0.1, label="Individual Trials" if j == 0 else None, ) plt.plot(avg, color="red", label="Average") plt.xlabel("Layout Trials") plt.ylabel("Cumulative Min Cost") plt.title(f"{k} {circuit}") plt.ticklabel_format(style="plain") # Turn off scientific notation plt.legend() plt.show() # # explictly print results # for k, v in benchmark.metrics[0].saved_results.items(): # for circuit, result in v.items(): # print(result.data)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse dc = pulse.DriveChannel d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4) with pulse.build(name='pulse_programming_in') as pulse_prog: pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3) pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4) pulse_prog.draw()
https://github.com/iqm-finland/qiskit-on-iqm
iqm-finland
# Copyright 2023 Qiskit on IQM developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This file is an example of using Qiskit on IQM to execute a simple but non-trivial quantum circuit on an IQM quantum computer. See the Qiskit on IQM user guide for instructions: https://iqm-finland.github.io/qiskit-on-iqm/user_guide.html """ import argparse from qiskit import QuantumCircuit, execute from iqm.qiskit_iqm import transpile_to_IQM from iqm.qiskit_iqm.iqm_provider import IQMProvider def transpile_example(server_url: str) -> tuple[QuantumCircuit, dict[str, int]]: """Execute a circuit transpiled using transpile_to_IQM function. Args: server_url: URL of the IQM Cortex server used for execution Returns: transpiled circuit, a mapping of bitstrings representing qubit measurement results to counts for each result """ backend = IQMProvider(server_url).get_backend() num_qubits = min(backend.num_qubits, 5) # use 5 qubits if available, otherwise maximum number of available qubits circuit = QuantumCircuit(num_qubits) circuit.h(0) for i in range(1, num_qubits): circuit.cx(0, i) circuit.measure_all() transpiled_circuit = transpile_to_IQM(circuit, backend) counts = execute(transpiled_circuit, backend, shots=1000).result().get_counts() return transpiled_circuit, counts if __name__ == '__main__': argparser = argparse.ArgumentParser() argparser.add_argument( '--url', help='URL of the IQM service', default='https://cocos.resonance.meetiqm.com/deneb', ) circuit_transpiled, results = transpile_example(argparser.parse_args().url) print(circuit_transpiled) print(results)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for Chi quantum channel representation class.""" import copy import unittest import numpy as np from numpy.testing import assert_allclose from qiskit import QiskitError from qiskit.quantum_info.states import DensityMatrix from qiskit.quantum_info.operators.channel import Chi from .channel_test_case import ChannelTestCase class TestChi(ChannelTestCase): """Tests for Chi channel representation.""" def test_init(self): """Test initialization""" mat4 = np.eye(4) / 2.0 chan = Chi(mat4) assert_allclose(chan.data, mat4) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) mat16 = np.eye(16) / 4 chan = Chi(mat16) assert_allclose(chan.data, mat16) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(chan.num_qubits, 2) # Wrong input or output dims should raise exception self.assertRaises(QiskitError, Chi, mat16, input_dims=2, output_dims=4) # Non multi-qubit dimensions should raise exception self.assertRaises(QiskitError, Chi, np.eye(6) / 2, input_dims=3, output_dims=2) def test_circuit_init(self): """Test initialization from a circuit.""" circuit, target = self.simple_circuit_no_measure() op = Chi(circuit) target = Chi(target) self.assertEqual(op, target) def test_circuit_init_except(self): """Test initialization from circuit with measure raises exception.""" circuit = self.simple_circuit_with_measure() self.assertRaises(QiskitError, Chi, circuit) def test_equal(self): """Test __eq__ method""" mat = self.rand_matrix(4, 4, real=True) self.assertEqual(Chi(mat), Chi(mat)) def test_copy(self): """Test copy method""" mat = np.eye(4) with self.subTest("Deep copy"): orig = Chi(mat) cpy = orig.copy() cpy._data[0, 0] = 0.0 self.assertFalse(cpy == orig) with self.subTest("Shallow copy"): orig = Chi(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_is_cptp(self): """Test is_cptp method.""" self.assertTrue(Chi(self.depol_chi(0.25)).is_cptp()) # Non-CPTP should return false self.assertFalse(Chi(1.25 * self.chiI - 0.25 * self.depol_chi(1)).is_cptp()) def test_compose_except(self): """Test compose different dimension exception""" self.assertRaises(QiskitError, Chi(np.eye(4)).compose, Chi(np.eye(16))) self.assertRaises(QiskitError, Chi(np.eye(4)).compose, 2) def test_compose(self): """Test compose method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Chi(self.chiX) chan2 = Chi(self.chiY) chan = chan1.compose(chan2) target = rho.evolve(Chi(self.chiZ)) output = rho.evolve(chan) self.assertEqual(output, target) # 50% depolarizing channel chan1 = Chi(self.depol_chi(0.5)) chan = chan1.compose(chan1) target = rho.evolve(Chi(self.depol_chi(0.75))) output = rho.evolve(chan) self.assertEqual(output, target) # Compose random chi1 = self.rand_matrix(4, 4, real=True) chi2 = self.rand_matrix(4, 4, real=True) chan1 = Chi(chi1, input_dims=2, output_dims=2) chan2 = Chi(chi2, input_dims=2, output_dims=2) target = rho.evolve(chan1).evolve(chan2) chan = chan1.compose(chan2) output = rho.evolve(chan) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(output, target) chan = chan1 & chan2 output = rho.evolve(chan) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(output, target) def test_dot(self): """Test dot method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Chi(self.chiX) chan2 = Chi(self.chiY) target = rho.evolve(Chi(self.chiZ)) output = rho.evolve(chan2.dot(chan1)) self.assertEqual(output, target) # Compose random chi1 = self.rand_matrix(4, 4, real=True) chi2 = self.rand_matrix(4, 4, real=True) chan1 = Chi(chi1, input_dims=2, output_dims=2) chan2 = Chi(chi2, input_dims=2, output_dims=2) target = rho.evolve(chan1).evolve(chan2) chan = chan2.dot(chan1) output = rho.evolve(chan) self.assertEqual(output, target) chan = chan2 @ chan1 output = rho.evolve(chan) self.assertEqual(output, target) def test_compose_front(self): """Test front compose method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Chi(self.chiX) chan2 = Chi(self.chiY) chan = chan2.compose(chan1, front=True) target = rho.evolve(Chi(self.chiZ)) output = rho.evolve(chan) self.assertEqual(output, target) # Compose random chi1 = self.rand_matrix(4, 4, real=True) chi2 = self.rand_matrix(4, 4, real=True) chan1 = Chi(chi1, input_dims=2, output_dims=2) chan2 = Chi(chi2, input_dims=2, output_dims=2) target = rho.evolve(chan1).evolve(chan2) chan = chan2.compose(chan1, front=True) output = rho.evolve(chan) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(output, target) def test_expand(self): """Test expand method.""" # Pauli channels paulis = [self.chiI, self.chiX, self.chiY, self.chiZ] targs = 4 * np.eye(16) # diagonals of Pauli channel Chi mats for i, chi1 in enumerate(paulis): for j, chi2 in enumerate(paulis): chan1 = Chi(chi1) chan2 = Chi(chi2) chan = chan1.expand(chan2) # Target for diagonal Pauli channel targ = Chi(np.diag(targs[i + 4 * j])) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(chan, targ) # Completely depolarizing rho = DensityMatrix(np.diag([1, 0, 0, 0])) chan_dep = Chi(self.depol_chi(1)) chan = chan_dep.expand(chan_dep) target = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) output = rho.evolve(chan) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(output, target) def test_tensor(self): """Test tensor method.""" # Pauli channels paulis = [self.chiI, self.chiX, self.chiY, self.chiZ] targs = 4 * np.eye(16) # diagonals of Pauli channel Chi mats for i, chi1 in enumerate(paulis): for j, chi2 in enumerate(paulis): chan1 = Chi(chi1) chan2 = Chi(chi2) chan = chan2.tensor(chan1) # Target for diagonal Pauli channel targ = Chi(np.diag(targs[i + 4 * j])) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(chan, targ) # Test overload chan = chan2 ^ chan1 self.assertEqual(chan.dim, (4, 4)) self.assertEqual(chan, targ) # Completely depolarizing rho = DensityMatrix(np.diag([1, 0, 0, 0])) chan_dep = Chi(self.depol_chi(1)) chan = chan_dep.tensor(chan_dep) target = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) output = rho.evolve(chan) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(output, target) # Test operator overload chan = chan_dep ^ chan_dep output = rho.evolve(chan) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(output, target) def test_power(self): """Test power method.""" # 10% depolarizing channel p_id = 0.9 depol = Chi(self.depol_chi(1 - p_id)) # Compose 3 times p_id3 = p_id**3 chan3 = depol.power(3) targ3 = Chi(self.depol_chi(1 - p_id3)) self.assertEqual(chan3, targ3) def test_add(self): """Test add method.""" mat1 = 0.5 * self.chiI mat2 = 0.5 * self.depol_chi(1) chan1 = Chi(mat1) chan2 = Chi(mat2) targ = Chi(mat1 + mat2) self.assertEqual(chan1._add(chan2), targ) self.assertEqual(chan1 + chan2, targ) targ = Chi(mat1 - mat2) self.assertEqual(chan1 - chan2, targ) def test_add_qargs(self): """Test add method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = Chi(mat) op0 = Chi(mat0) op1 = Chi(mat1) op01 = op1.tensor(op0) eye = Chi(self.chiI) with self.subTest(msg="qargs=[0]"): value = op + op0([0]) target = op + eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op + op0([1]) target = op + eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op + op0([2]) target = op + op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op + op01([0, 1]) target = op + eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op + op01([1, 0]) target = op + eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op + op01([0, 2]) target = op + op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op + op01([2, 0]) target = op + op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_sub_qargs(self): """Test subtract method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = Chi(mat) op0 = Chi(mat0) op1 = Chi(mat1) op01 = op1.tensor(op0) eye = Chi(self.chiI) with self.subTest(msg="qargs=[0]"): value = op - op0([0]) target = op - eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op - op0([1]) target = op - eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op - op0([2]) target = op - op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op - op01([0, 1]) target = op - eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op - op01([1, 0]) target = op - eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op - op01([0, 2]) target = op - op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op - op01([2, 0]) target = op - op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_add_except(self): """Test add method raises exceptions.""" chan1 = Chi(self.chiI) chan2 = Chi(np.eye(16)) self.assertRaises(QiskitError, chan1._add, chan2) self.assertRaises(QiskitError, chan1._add, 5) def test_multiply(self): """Test multiply method.""" chan = Chi(self.chiI) val = 0.5 targ = Chi(val * self.chiI) self.assertEqual(chan._multiply(val), targ) self.assertEqual(val * chan, targ) targ = Chi(self.chiI * val) self.assertEqual(chan * val, targ) def test_multiply_except(self): """Test multiply method raises exceptions.""" chan = Chi(self.chiI) self.assertRaises(QiskitError, chan._multiply, "s") self.assertRaises(QiskitError, chan.__rmul__, "s") self.assertRaises(QiskitError, chan._multiply, chan) self.assertRaises(QiskitError, chan.__rmul__, chan) def test_negate(self): """Test negate method""" chan = Chi(self.chiI) targ = Chi(-self.chiI) self.assertEqual(-chan, targ) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
input_3sat_instance = ''' c example DIMACS-CNF 3-SAT p cnf 3 5 -1 -2 -3 0 1 -2 3 0 1 2 -3 0 1 -2 -3 0 -1 2 3 0 ''' import os import tempfile from qiskit.exceptions import MissingOptionalLibraryError from qiskit.circuit.library.phase_oracle import PhaseOracle fp = tempfile.NamedTemporaryFile(mode='w+t', delete=False) fp.write(input_3sat_instance) file_name = fp.name fp.close() oracle = None try: oracle = PhaseOracle.from_dimacs_file(file_name) except MissingOptionalLibraryError as ex: print(ex) finally: os.remove(file_name) from qiskit.algorithms import AmplificationProblem problem = None if oracle is not None: problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring) from qiskit.algorithms import Grover from qiskit.primitives import Sampler grover = Grover(sampler=Sampler()) result = None if problem is not None: result = grover.amplify(problem) print(result.assignment) from qiskit.tools.visualization import plot_histogram if result is not None: display(plot_histogram(result.circuit_results[0])) expression = '(w ^ x) & ~(y ^ z) & (x & y & z)' try: oracle = PhaseOracle(expression) problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring) grover = Grover(sampler=Sampler()) result = grover.amplify(problem) display(plot_histogram(result.circuit_results[0])) except MissingOptionalLibraryError as ex: print(ex) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit 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/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import QuantumCircuit, Aer from qiskit.extensions import UnitaryGate,Initialize from qiskit.quantum_info import Statevector from qiskit.tools.visualization import plot_bloch_multivector import numpy as np import sys from scipy.stats import unitary_group import matplotlib.pyplot as plt from qiskit import IBMQ %matplotlib inline sys.path.append("..") from Modules.changed_SPEA import global_max_SPEA # IBMQ.load_account() # provider = IBMQ.get_provider(hub='??replace_with_your_hub_name??') sim = Aer.get_backend('qasm_simulator') U1 = UnitaryGate(data=np.array([[0,1], [1,0]])) spe = global_max_SPEA(U1,resolution= 30,error = 4,max_iters=12) result = spe.get_eigen_pair(progress = False,backend=sim) result t = [] for resolution in range(10,50,5): spe = global_max_SPEA(U1,resolution= resolution,error = 4,max_iters=10) res = spe.get_eigen_pair(backend = sim) theta = res['theta'] t.append(theta) plt.figure(figsize = (8,9)) plt.title("Eigenphase estimation for X gate, modified algo",fontsize = 15) plt.grid() plt.plot(list(range(10,50,5)),t,marker = 'o',color='g',label = 'Estimates',alpha=0.7) plt.plot([10,50],[0.5,0.5],color='black',label = "True") plt.plot([10,50],[0,0],color='black') plt.plot([10,50],[1,1],color='black') plt.legend() plt.xlabel("Resolution of theta ") plt.ylabel("Estimates") plt.savefig("Plots/SPE_PLOT1_global_max.jpg",dpi = 200) u2 = UnitaryGate(data=np.array([[1,0], [0, np.exp(2*np.pi*1j*(1/5))]])) t = [] for resolution in range(10,50,5): spe = global_max_SPEA(u2,resolution= resolution,error = 4,max_iters=10) res = spe.get_eigen_pair(backend = sim) theta = res['theta'] t.append(theta) plt.figure(figsize = (9,9)) plt.title("Eigenphase estimation for theta = 1/5, 0, 1, modified algo",fontsize = 15) plt.grid() plt.plot(list(range(10,50,5)),t,marker = 'o',color='g',label = 'Estimates',alpha=0.7) plt.plot([10,50],[0.2,0.2],color='black',label = "True") plt.plot([10,50],[0,0],color='black') plt.plot([10,50],[1,1],color='black') plt.legend() plt.xlabel("Resolution of theta ") plt.ylabel("Estimates") plt.savefig("Plots/SPE_PLOT2_global_max.jpg",dpi = 200) unitary_group.rvs() u_rand = unitary_group.rvs(2) print("Random Unitary :",u_rand) eigen_phases, eigen_vectors = np.linalg.eig(u_rand) print("Eigen states of Unitary :",eigen_vectors) eigen_phases = np.angle(eigen_phases) ep = [] for k in eigen_phases: if k < 0: ep.append(k + 2*np.pi) else: ep.append(k) eigen_phases = ep print("Eigen phases of unitary :",eigen_phases) ev1 , ev2 = eigen_vectors[0] , eigen_vectors[1] ev1 = ev1 / np.linalg.norm(ev1) ev2 = ev2 / np.linalg.norm(ev2) qc1 = QuantumCircuit(1) qc2 = QuantumCircuit(1) sv1 = Initialize(ev1) sv2 = Initialize(ev2) qc1 = qc1.compose(sv1,qubits = [0]) qc2 = qc2.compose(sv2,qubits = [0]) qc1.draw('mpl') sv = Statevector.from_instruction(qc1) plot_bloch_multivector(sv) sv = Statevector.from_instruction(qc2) plot_bloch_multivector(sv) spea = global_max_SPEA(resolution = 50, max_iters = 10, unitary = u_rand,error = 4) result = spea.get_eigen_pair(progress = False, randomize = True) print("Result of our estimation :",result) res_state = result['state'] res_state = res_state/ np.linalg.norm(res_state) qc_res = QuantumCircuit(1) sv_init = Initialize(res_state) qc_res = qc_res.compose(sv_init, qubits = [0]) qc_res.draw('mpl') statevector_res = Statevector.from_instruction(qc_res) plot_bloch_multivector(statevector_res) def generate_random_estimation(experiments=5,resolution = 40): sim = Aer.get_backend('qasm_simulator') best_costs, errors_in_phases = [] , [] for exp in range(experiments): u_rand = unitary_group.rvs(2) # generate the phases and vectors eigen_phases, eigen_vectors = np.linalg.eig(u_rand) eigen_phases = np.angle(eigen_phases) ep = [] # doing this as phase maybe be negative for k in eigen_phases: if k < 0: ep.append((k + 2*np.pi)/(2*np.pi)) else: ep.append(k/(2*np.pi)) eigen_phases = ep ev1 , ev2 = eigen_vectors[0] , eigen_vectors[1] ev1 = ev1 / np.linalg.norm(ev1) ev2 = ev2 / np.linalg.norm(ev2) # generate their corresponding init statevectors sv1 = Initialize(ev1) sv2 = Initialize(ev2) print("Eigenvectors",ev1,ev2) print("Eigenphases",eigen_phases) # run the algorithm spea = global_max_SPEA(resolution = resolution, max_iters = 10, unitary = u_rand,error = 4) result = spea.get_eigen_pair(backend = sim, progress = False, randomize = True) # get the results res_state = result['state'] res_theta = result['theta'] sv_res = Initialize(res_state) print("Result",result) print("Phase returned(0-> 2*pi) :",res_theta) # get the dot products d1 = np.linalg.norm(np.dot(ev1, res_state.conjugate().T))**2 d2 = np.linalg.norm(np.dot(ev2, res_state.conjugate().T))**2 # make a bloch sphere qc = QuantumCircuit(2) qc = qc.compose(sv_res,qubits = [0]) if d1 > d2: print(" Best overlap :",d1) # it is closer to the first qc = qc.compose(sv1,qubits = [1]) best_costs.append(result['cost']) errors_in_phases.append(abs(res_theta - eigen_phases[0])) else: # it is closer to the second print(" Best overlap :",d2) qc = qc.compose(sv2,qubits = [1]) best_costs.append(result['cost']) errors_in_phases.append(abs(res_theta - eigen_phases[1])) print("Bloch Sphere for the states...") s = Statevector.from_instruction(qc) display(plot_bloch_multivector(s)) plt.title("Experiments for Random Matrices",fontsize= 16) plt.xlabel("Experiment Number") plt.ylabel("Metric value") plt.plot([i for i in range(experiments)], best_costs, label = 'Best Costs', alpha = 0.5, color = 'g',marker='o') plt.plot([i for i in range(experiments)], errors_in_phases, label = 'Corresponding Error in Phase', alpha = 0.5, color = 'b',marker='s') plt.legend() plt.grid() return generate_random_estimation()
https://github.com/Spintronic6889/Introduction-of-Quantum-walk-its-application-on-search-and-decision-making
Spintronic6889
%matplotlib inline import matplotlib as mpl from random import randrange import numpy as np import matplotlib.pyplot as plt from random import randrange pose=[] for i in range(400): pose.append([]) #print(pose) #pose[-1]=1 #print(pose[-1]) pose[0]=200 for k in range(200): rand = randrange(0,2) if rand==0: #print(rand) pose[k+1]=pose[k]+1 if rand==1: pose[k+1]=pose[k]-1 #print(pose) yc=[] for e in range(400): yc.append([]) for q in range(400): yc[q]=0 for h in range(400): if pose[h]==q: yc[q]=yc[q]+1 #print((yc)) #print(len(yc)) xc = np.arange(0, 400, 1) plt.plot(yc) plt.xlim(150, 250)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import json import matplotlib.pyplot as plt import numpy as np from IPython.display import clear_output from qiskit import QuantumCircuit from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit import ParameterVector from qiskit.circuit.library import ZFeatureMap from qiskit.quantum_info import SparsePauliOp from qiskit.utils import algorithm_globals from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier from qiskit_machine_learning.neural_networks import EstimatorQNN from sklearn.model_selection import train_test_split algorithm_globals.random_seed = 12345 # We now define a two qubit unitary as defined in [3] def conv_circuit(params): target = QuantumCircuit(2) target.rz(-np.pi / 2, 1) target.cx(1, 0) target.rz(params[0], 0) target.ry(params[1], 1) target.cx(0, 1) target.ry(params[2], 1) target.cx(1, 0) target.rz(np.pi / 2, 0) return target # Let's draw this circuit and see what it looks like params = ParameterVector("θ", length=3) circuit = conv_circuit(params) circuit.draw("mpl") def conv_layer(num_qubits, param_prefix): qc = QuantumCircuit(num_qubits, name="Convolutional Layer") qubits = list(range(num_qubits)) param_index = 0 params = ParameterVector(param_prefix, length=num_qubits * 3) for q1, q2 in zip(qubits[0::2], qubits[1::2]): qc = qc.compose(conv_circuit(params[param_index : (param_index + 3)]), [q1, q2]) qc.barrier() param_index += 3 for q1, q2 in zip(qubits[1::2], qubits[2::2] + [0]): qc = qc.compose(conv_circuit(params[param_index : (param_index + 3)]), [q1, q2]) qc.barrier() param_index += 3 qc_inst = qc.to_instruction() qc = QuantumCircuit(num_qubits) qc.append(qc_inst, qubits) return qc circuit = conv_layer(4, "θ") circuit.decompose().draw("mpl") def pool_circuit(params): target = QuantumCircuit(2) target.rz(-np.pi / 2, 1) target.cx(1, 0) target.rz(params[0], 0) target.ry(params[1], 1) target.cx(0, 1) target.ry(params[2], 1) return target params = ParameterVector("θ", length=3) circuit = pool_circuit(params) circuit.draw("mpl") def pool_layer(sources, sinks, param_prefix): num_qubits = len(sources) + len(sinks) qc = QuantumCircuit(num_qubits, name="Pooling Layer") param_index = 0 params = ParameterVector(param_prefix, length=num_qubits // 2 * 3) for source, sink in zip(sources, sinks): qc = qc.compose(pool_circuit(params[param_index : (param_index + 3)]), [source, sink]) qc.barrier() param_index += 3 qc_inst = qc.to_instruction() qc = QuantumCircuit(num_qubits) qc.append(qc_inst, range(num_qubits)) return qc sources = [0, 1] sinks = [2, 3] circuit = pool_layer(sources, sinks, "θ") circuit.decompose().draw("mpl") def generate_dataset(num_images): images = [] labels = [] hor_array = np.zeros((6, 8)) ver_array = np.zeros((4, 8)) j = 0 for i in range(0, 7): if i != 3: hor_array[j][i] = np.pi / 2 hor_array[j][i + 1] = np.pi / 2 j += 1 j = 0 for i in range(0, 4): ver_array[j][i] = np.pi / 2 ver_array[j][i + 4] = np.pi / 2 j += 1 for n in range(num_images): rng = algorithm_globals.random.integers(0, 2) if rng == 0: labels.append(-1) random_image = algorithm_globals.random.integers(0, 6) images.append(np.array(hor_array[random_image])) elif rng == 1: labels.append(1) random_image = algorithm_globals.random.integers(0, 4) images.append(np.array(ver_array[random_image])) # Create noise for i in range(8): if images[-1][i] == 0: images[-1][i] = algorithm_globals.random.uniform(0, np.pi / 4) return images, labels images, labels = generate_dataset(50) train_images, test_images, train_labels, test_labels = train_test_split( images, labels, test_size=0.3 ) fig, ax = plt.subplots(2, 2, figsize=(10, 6), subplot_kw={"xticks": [], "yticks": []}) for i in range(4): ax[i // 2, i % 2].imshow( train_images[i].reshape(2, 4), # Change back to 2 by 4 aspect="equal", ) plt.subplots_adjust(wspace=0.1, hspace=0.025) feature_map = ZFeatureMap(8) feature_map.decompose().draw("mpl") feature_map = ZFeatureMap(8) ansatz = QuantumCircuit(8, name="Ansatz") # First Convolutional Layer ansatz.compose(conv_layer(8, "с1"), list(range(8)), inplace=True) # First Pooling Layer ansatz.compose(pool_layer([0, 1, 2, 3], [4, 5, 6, 7], "p1"), list(range(8)), inplace=True) # Second Convolutional Layer ansatz.compose(conv_layer(4, "c2"), list(range(4, 8)), inplace=True) # Second Pooling Layer ansatz.compose(pool_layer([0, 1], [2, 3], "p2"), list(range(4, 8)), inplace=True) # Third Convolutional Layer ansatz.compose(conv_layer(2, "c3"), list(range(6, 8)), inplace=True) # Third Pooling Layer ansatz.compose(pool_layer([0], [1], "p3"), list(range(6, 8)), inplace=True) # Combining the feature map and ansatz circuit = QuantumCircuit(8) circuit.compose(feature_map, range(8), inplace=True) circuit.compose(ansatz, range(8), inplace=True) observable = SparsePauliOp.from_list([("Z" + "I" * 7, 1)]) # we decompose the circuit for the QNN to avoid additional data copying qnn = EstimatorQNN( circuit=circuit.decompose(), observables=observable, input_params=feature_map.parameters, weight_params=ansatz.parameters, ) circuit.draw("mpl") def callback_graph(weights, obj_func_eval): clear_output(wait=True) objective_func_vals.append(obj_func_eval) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() with open("11_qcnn_initial_point.json", "r") as f: initial_point = json.load(f) classifier = NeuralNetworkClassifier( qnn, optimizer=COBYLA(maxiter=200), # Set max iterations here callback=callback_graph, initial_point=initial_point, ) x = np.asarray(train_images) y = np.asarray(train_labels) objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) classifier.fit(x, y) # score classifier print(f"Accuracy from the train data : {np.round(100 * classifier.score(x, y), 2)}%") y_predict = classifier.predict(test_images) x = np.asarray(test_images) y = np.asarray(test_labels) print(f"Accuracy from the test data : {np.round(100 * classifier.score(x, y), 2)}%") # Let's see some examples in our dataset fig, ax = plt.subplots(2, 2, figsize=(10, 6), subplot_kw={"xticks": [], "yticks": []}) for i in range(0, 4): ax[i // 2, i % 2].imshow(test_images[i].reshape(2, 4), aspect="equal") if y_predict[i] == -1: ax[i // 2, i % 2].set_title("The QCNN predicts this is a Horizontal Line") if y_predict[i] == +1: ax[i // 2, i % 2].set_title("The QCNN predicts this is a Vertical Line") plt.subplots_adjust(wspace=0.1, hspace=0.5) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
import sys sys.path.append('../../Pyfiles') import numpy as np from sklearn.utils import shuffle import matplotlib.pyplot as plt data1Path = r'../../dataset/data0test.txt' data1Label = r'../../dataset/data0testlabel.txt' dataCoords = np.loadtxt(data1Path) dataLabels = np.loadtxt(data1Label) # Make a data structure which is easier to work with # for shuffling. # Also, notice we change the data labels from {0, 1} to {-1, +1} data = list(zip(dataCoords, 2*dataLabels-1)) shuffled_data = shuffle(data) 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') from IPython.display import Image from circuits import * from qiskit.circuit import Parameter #circuit 1 qr = QuantumRegister(4) qc = QuantumCircuit(qr) theta=[] for i in range(62): theta.append((Parameter('θ'+str(i)))) qc=circuit1(qc,qr,theta,1,0) qc.draw('mpl') #load the simulation functcions from the quantumcircuit.py file from quantumcircuit import * #location,label,param,[circuit#,layer] loss_qubitF([0.5,0.5],-1,[0,0,0,-5,0,0,0,0],[0,1]) #load the SPSA optimizer from the optimizer.py file from optimizer import * c = 0.5 a = 0.5 # Do the updates lossList = [] coeffsList = [] paramsList = [] accuracyList = [] np.random.seed(2) currentParams = pi*np.random.uniform(size=8) for j in range(10): cj = c/(j+1)**(1/2) aj = a/(j+1) # Grab a subset of the data for minibatching #np.random.seed(j) np.random.seed(2) #data_ixs = np.random.choice(len(shuffled_data), size=len(shuffled_data)) data_ixs = np.random.choice(len(data), size=100) # Evaluate the loss over that subset # We include a regularization term at the end L = lambda x: np.sum([loss_qubitF(data[j][0],data[j][1],x,[0,1]) for j in data_ixs])/len(data_ixs) lossList.append(L(currentParams)) coeffsList.append((cj, aj)) paramsList.append(currentParams) accuracyList.append(np.sum([predict_qubitF(data[j][0],currentParams,[0,1]) ==data[j][1] for j in data_ixs])/len(data_ixs)) print(j,"th iteration L=",lossList[-1],"Accuracy =",accuracyList[-1]) currentParams = SPSA_update(L, currentParams, aj, cj) fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(2, 2, 1) ax.plot(lossList) ax.set_title('Loss function\nStart {0} Finish {1}'.format(np.round(lossList[0], 3), np.round(lossList[-1], 3))) ax.set_yscale('log') ax = fig.add_subplot(2, 2, 2) ax.plot(accuracyList) ax.set_title('Classification accuracy \nStart {0} Finish {1}'.format(np.round(accuracyList[0], 3), np.round(accuracyList[-1], 3))) ax.set_yscale('log') ax = fig.add_subplot(2, 2, 3) ax.plot([c[0] for c in coeffsList], label='a') ax.plot([c[1] for c in coeffsList], label='c') ax.legend(loc=0) ax.set_title('Update coefficients') ax = fig.add_subplot(2, 2, 4) for j in range(4): ax.plot([X[j] for X in paramsList], label='x{0}'.format(j)) ax.legend(loc=0) ax.set_title('Parameter values') ax.legend(loc=0) 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') X = np.linspace(0, 1, num=10) Z = np.zeros((len(X), len(X))) # Contour map for j in range(len(X)): for k in range(len(X)): # 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 Z[j, k] = predict_qubitF( np.array([X[k], X[j]]),currentParams,[0,1]) ax.contourf(X, X, Z, cmap='bwr', levels=30) #circuit 2 qr = QuantumRegister(4) qc = QuantumCircuit(qr) theta=[] for i in range(62): theta.append((Parameter('θ'+str(i)))) qc=circuit3(qc,qr,theta,1,0) qc.draw('mpl') data1Path = r'../../dataset/data1a.txt' data1Label = r'../../dataset/data1alabel.txt' dataCoords = np.loadtxt(data1Path) dataLabels = np.loadtxt(data1Label) # Make a data structure which is easier to work with # for shuffling. # Also, notice we change the data labels from {0, 1} to {-1, +1} data = list(zip(dataCoords, 2*dataLabels-1)) shuffled_data = shuffle(data) 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') c = 1 a = 1 # Do the updates lossList = [] coeffsList = [] paramsList = [] accuracyList = [] np.random.seed(2) currentParams = pi*np.random.uniform(size=12) for j in range(10): cj = c/(j+1)**(1/2) aj = a/(j+1) # Grab a subset of the data for minibatching #np.random.seed(j) np.random.seed(3) #data_ixs = np.random.choice(len(shuffled_data), size=len(shuffled_data)) data_ixs = np.random.choice(len(data), size=100) # Evaluate the loss over that subset # We include a regularization term at the end L = lambda x: np.sum([loss_qubitF(data[j][0],data[j][1],x,[2,1]) for j in data_ixs])/len(data_ixs) lossList.append(L(currentParams)) coeffsList.append((cj, aj)) paramsList.append(currentParams) accuracyList.append(np.sum([predict_qubitF(data[j][0],currentParams,[2,1]) ==data[j][1] for j in data_ixs])/len(data_ixs)) print(j,"th iteration L=",lossList[-1],"Accuracy =",accuracyList[-1]) currentParams = SPSA_update(L, currentParams, aj, cj) fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(2, 2, 1) ax.plot(lossList) ax.set_title('Loss function\nStart {0} Finish {1}'.format(np.round(lossList[0], 3), np.round(lossList[-1], 3))) ax.set_yscale('log') ax = fig.add_subplot(2, 2, 2) ax.plot(accuracyList) ax.set_title('Classification accuracy \nStart {0} Finish {1}'.format(np.round(accuracyList[0], 3), np.round(accuracyList[-1], 3))) ax.set_yscale('log') ax = fig.add_subplot(2, 2, 3) ax.plot([c[0] for c in coeffsList], label='a') ax.plot([c[1] for c in coeffsList], label='c') ax.legend(loc=0) ax.set_title('Update coefficients') ax = fig.add_subplot(2, 2, 4) for j in range(4): ax.plot([X[j] for X in paramsList], label='x{0}'.format(j)) ax.legend(loc=0) ax.set_title('Parameter values') ax.legend(loc=0) currentParams 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') X = np.linspace(0, 1, num=10) Z = np.zeros((len(X), len(X))) # Contour map for j in range(len(X)): for k in range(len(X)): # 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 Z[j, k] = predict_qubitF( np.array([X[k], X[j]]),currentParams,[1,1]) ax.contourf(X, X, Z, cmap='bwr', levels=30) #circuit 1 qr = QuantumRegister(4) qc = QuantumCircuit(qr) theta=[] for i in range(62): theta.append((Parameter('θ'+str(i)))) qc=circuit19(qc,qr,theta,2,0) qc.draw('mpl') data1Path = r'../../dataset/data2c.txt' data1Label = r'../../dataset/data2clabel.txt' dataCoords = np.loadtxt(data1Path) dataLabels = np.loadtxt(data1Label) # Make a data structure which is easier to work with # for shuffling. # Also, notice we change the data labels from {0, 1} to {-1, +1} data = list(zip(dataCoords, 2*dataLabels-1)) shuffled_data = shuffle(data) 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') c = 1 a = 1 # Do the updates lossList = [] coeffsList = [] paramsList = [] accuracyList = [] np.random.seed(2) currentParams = 2*np.random.uniform(size=40) for j in range(30): cj = c/(j+1)**(1/4) aj = a/(j+1) # Grab a subset of the data for minibatching #np.random.seed(j) np.random.seed(3) #data_ixs = np.random.choice(len(shuffled_data), size=len(shuffled_data)) data_ixs = np.random.choice(len(data), size=100) # Evaluate the loss over that subset # We include a regularization term at the end L = lambda x: np.sum([loss_qubitF(data[j][0],data[j][1],x,[18,2]) for j in data_ixs])/len(data_ixs) lossList.append(L(currentParams)) coeffsList.append((cj, aj)) paramsList.append(currentParams) accuracyList.append(np.sum([predict_qubitF(data[j][0],currentParams,[18,2]) ==data[j][1] for j in data_ixs])/len(data_ixs)) print(j,"th iteration L=",lossList[-1],"Accuracy =",accuracyList[-1]) currentParams = SPSA_update(L, currentParams, aj, cj) fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(2, 2, 1) ax.plot(lossList) ax.set_title('Loss function\nStart {0} Finish {1}'.format(np.round(lossList[0], 3), np.round(lossList[-1], 3))) ax.set_yscale('log') ax = fig.add_subplot(2, 2, 2) ax.plot(accuracyList) ax.set_title('Classification accuracy \nStart {0} Finish {1}'.format(np.round(accuracyList[0], 3), np.round(accuracyList[-1], 3))) ax.set_yscale('log') ax = fig.add_subplot(2, 2, 3) ax.plot([c[0] for c in coeffsList], label='a') ax.plot([c[1] for c in coeffsList], label='c') ax.legend(loc=0) ax.set_title('Update coefficients') ax = fig.add_subplot(2, 2, 4) for j in range(4): ax.plot([X[j] for X in paramsList], label='x{0}'.format(j)) ax.legend(loc=0) ax.set_title('Parameter values') ax.legend(loc=0) 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') X = np.linspace(0, 1, num=10) Z = np.zeros((len(X), len(X))) # Contour map for j in range(len(X)): for k in range(len(X)): # 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 Z[j, k] = predict_qubitF( np.array([X[k], X[j]]),currentParams,[18,2]) ax.contourf(X, X, Z, cmap='bwr', levels=30) currentParams
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import FakeVigo backend = FakeVigo() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) # Virtual -> physical # 0 -> 3 # 1 -> 4 # 2 -> 2 my_ghz = transpile(ghz, backend, initial_layout=[3, 4, 2]) plot_circuit_layout(my_ghz, backend)
https://github.com/spencerking/QiskitSummerJam-LocalSequenceAlignment
spencerking
pip install qiskit --upgrade pip install numpy --upgrade import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright a = "AACCAGTCG" b = "CACCGTAA" import itertools import numpy as np # Initialize an (n+1)*(m+1) matrix # Where n and m are len(a) and len(b) respectively H = np.zeros((len(a) + 1, len(b) + 1), np.int) # Compare every character in a against every character in b # Matches (white cells) are denoted with 1 for i, j in itertools.product(range(1, H.shape[0]), range(1, H.shape[1])): if a[i - 1] == b[j - 1]: H[i, j] = 1 # print("Before removing extra rows:") # print(H) # TODO # Verify this doesn't break if we swap a and b for x in range(0, abs(H.shape[0] - H.shape[1])): H = np.delete(H, 0, 0) H = np.delete(H, 0, 1) # print("After removing extra rows:") print(H) # print(H.shape[0]) # print(H.shape[1]) # I'm really unsure if this is the right approach diag_H = np.array([]) diagonal = np.diag(H, k=0) # print(diagonal) diag_len = len(diagonal) diag_H = diagonal for i in range(1, H.shape[1]): diagonal = np.diag(H, k=i) # print(diagonal) # If the diagonal is shorter than the rows, append zeros if diag_len > len(diagonal): zeros = np.zeros((1, (diag_len-len(diagonal))), dtype=int) diagonal = np.append(diagonal, zeros) diag_H = np.vstack((diag_H, diagonal)) # Otherwise append the diagonal as a row else: diag_H = np.vstack((diag_H, diagonal)) print(diag_H) # TODO from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.library import QFT # Create a 3 qubit quantum register # qr[0] is x, qr[1] is y, qr[2] is f(x,y) qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr, cr) %matplotlib inline circuit.h(qr[0]) circuit.h(qr[1]) # Feed the circuit into the BB # TODO sub_q = QuantumRegister(3) sub_circ = QuantumCircuit(sub_q, name='BB') sub_inst = sub_circ.to_instruction() circuit.append(sub_inst, [qr[0], qr[1], qr[2]]) # QFT on qr[0] and qr[1] qft = QFT(num_qubits=2) circuit.compose(qft, inplace=True) # Measure all 3 circuit.measure(qr, cr) circuit.draw(output='mpl')
https://github.com/qiskit-community/archiver4qiskit
qiskit-community
import os import qiskit from qiskit import IBMQ, Aer import uuid import pickle try: IBMQ.load_account() except: print('Unable to load IBMQ account') def _prep(): if 'archive' not in os.listdir(): os.mkdir('archive') _prep() class Archive(): ''' A serializable equivalent to the Qiskit job object. ''' def __init__(self, job, path='', note='', circuits=None): if 'job_id' in dir(job): self.archive_id = job.job_id() + '@' + job.backend().name() else: self.archive_id = uuid.uuid4().hex + '@' + job.backend().name() self.path = path self.note = note self._job_id = job.job_id() self._backend = job.backend() self._backend.properties() # just needs to be called to load self._metadata = job.metadata self.version = job.version if 'circuits' in dir(job): self._circuits = job.circuits() else: self._circuits = circuits if 'qobj' in dir(job): self._qobj = job.qobj() if 'aer' in self.backend().name(): self._result = job.result() else: self._result = None self.save() def save(self): with open(self.path + 'archive/'+self.archive_id, 'wb') as file: pickle.dump(self, file) def job_id(self): return self._job_id def backend(self): return self._backend def metadata(self): return self._job_id def circuits(self): return self._circuits def qobj(self): return self._qobj def result(self): if self._result==None: backend = get_backend(self.backend().name()) job = backend.retrieve_job(self.job_id()) self._result = job.result() self.save() return self._result def get_backend(backend_name): ''' Given a string that specifies a backend, returns the backend object ''' if type(backend_name) is str: if 'aer' in backend_name: backend = Aer.get_backend(backend_name) else: providers = IBMQ.providers() p = 0 no_backend = True for provider in providers: if no_backend: backends = provider.backends() for potential_backend in backends: if potential_backend.name()==backend_name: backend = potential_backend no_backend = False if no_backend: print('No backend was found matching '+backend_name+' with your providers.') else: backend = backend_name return backend def submit_job(circuits, backend_name, path='', note='', job_name=None, job_share_level=None, job_tags=None, experiment_id=None, header=None, shots=None, memory=None, qubit_lo_freq=None, meas_lo_freq=None, schedule_los=None, meas_level=None, meas_return=None, memory_slots=None, memory_slot_size=None, rep_time=None, rep_delay=None, init_qubits=None, parameter_binds=None, use_measure_esp=None, **run_config): ''' Given a backend name and the arguments for the `run` method of the backend object, submits the job and returns the archive id. ''' # get backend backend = get_backend(backend_name) backend_name = backend.name() # submit job job = backend.run(circuits, job_name=job_name, job_share_level=job_share_level, job_tags=job_tags, experiment_id=experiment_id, header=header, shots=shots, memory=memory, qubit_lo_freq=qubit_lo_freq, meas_lo_freq=meas_lo_freq, schedule_los=schedule_los, meas_level=meas_level, meas_return=meas_return, memory_slots=memory_slots, memory_slot_size=memory_slot_size, rep_time=rep_time, rep_delay=rep_delay, init_qubits=init_qubits, parameter_binds=parameter_binds, use_measure_esp=use_measure_esp, **run_config) # create archive archive = Archive(job, note=note, circuits=circuits) # if an Aer job, get the results if 'aer' in job.backend().name(): archive.result() # return the id return archive.archive_id def get_job(archive_id): ''' Returns the Qiskit job object corresponding to a given archive_id ''' job_id, backend_name = archive_id.split('@') backend = get_backend(backend_name) job = backend.retrieve_job(job_id) return job def get_archive(archive_id, path=''): ''' Returns the saved archive object corresponding to a given archive_id ''' with open(path + 'archive/'+archive_id, 'rb') as file: archive = pickle.load(file) return archive def jobid2archive(job_id, backend_name): backend = get_backend(backend_name) job = backend.retrieve_job(job_id) archive = Archive(job) archive.result() return archive.archive_id
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/acfilok96/Quantum-Computation
acfilok96
# Quantum Computation import qiskit print(qiskit.__version__) import qiskit.quantum_info as qi from qiskit.circuit.library import FourierChecking from qiskit.visualization import plot_histogram f = [1, -1, -1, -1] g = [1, 1, -1, -1] # How co-related fourier transform of function g to function f. # we will check for probability '00', if p(f,g) >= 0.05, then, # fourier transform of function g co-related to function f. circ = FourierChecking(f=f,g=g) circ.draw() zero = qi.Statevector.from_label('00') # '00' or '01' or '10' or '11' sv = zero.evolve(circ) probs = sv.probabilities_dict() plot_histogram(probs)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.mappers.second_quantization import LogarithmicMapper mapper = LogarithmicMapper(2) from qiskit_nature.second_q.mappers import LogarithmicMapper mapper = LogarithmicMapper(2) from qiskit_nature.second_q.mappers import LogarithmicMapper mapper = LogarithmicMapper(padding=2) from qiskit_nature.circuit.library import HartreeFock from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import JordanWignerMapper converter = QubitConverter(JordanWignerMapper()) init_state = HartreeFock(num_spin_orbitals=6, num_particles=(2, 1), qubit_converter=converter) print(init_state.draw()) from qiskit_nature.second_q.circuit.library import HartreeFock from qiskit_nature.second_q.mappers import JordanWignerMapper, QubitConverter converter = QubitConverter(JordanWignerMapper()) init_state = HartreeFock(num_spatial_orbitals=3, num_particles=(2, 1), qubit_converter=converter) print(init_state.draw()) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import WeightedAdder, LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = (r - 0.5 * vol**2) * T + np.log(S) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=list(zip(low, high))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_T^1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_T^2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 3.5 # map strike price from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price = ( (strike_price - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = 2 * (2**num_uncertainty_qubits - 1) - mapped_strike_price basket_objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar = AncillaRegister(max(n_aux, basket_objective.num_ancillas), "work") # additional qubits objective_index = u.num_qubits basket_option = QuantumCircuit(qr_state, qr_obj, ar_sum, ar) basket_option.append(u, qr_state) basket_option.append(agg, qr_state[:] + ar_sum[:] + ar[:n_aux]) basket_option.append(basket_objective, ar_sum[:] + qr_obj[:] + ar[: basket_objective.num_ancillas]) print(basket_option.draw()) print("objective qubit index", objective_index) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = np.linspace(sum(low), sum(high)) y = np.maximum(0, x - strike_price) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Sum of Spot Prices ($S_T^1 + S_T^2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) exact_value = np.dot( u.probabilities[sum_values >= strike_price], sum_values[sum_values >= strike_price] - strike_price, ) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = basket_option.num_qubits - basket_option.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(basket_option, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) basket_option_measure = basket_option.measure_all(inplace=False) sampler = Sampler() job = sampler.run(basket_option_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = ( basket_objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=basket_option, objective_qubits=[objective_index], post_processing=basket_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value: \t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits to represent the uncertainty num_uncertainty_qubits = 3 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = (r - 0.5 * vol**2) * T + np.log(S) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high) ) # plot probability distribution x = uncertainty_model.values y = uncertainty_model.probabilities plt.bar(x, y, width=0.2) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.grid() plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15) plt.ylabel("Probability ($\%$)", size=15) plt.show() # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 2.126 # set the approximation scaling for the payoff function rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [-1, 0] offsets = [strike_price - low, 0] f_min = 0 f_max = strike_price - low european_put_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective european_put = european_put_objective.compose(uncertainty_model, front=True) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.maximum(0, strike_price - x) plt.plot(x, y, "ro-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Spot Price", size=15) plt.ylabel("Payoff", size=15) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value (normalized to the [0, 1] interval) exact_value = np.dot(uncertainty_model.probabilities, y) exact_delta = -sum(uncertainty_model.probabilities[x <= strike_price]) print("exact expected value:\t%.4f" % exact_value) print("exact delta value: \t%.4f" % exact_delta) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put, objective_qubits=[num_uncertainty_qubits], post_processing=european_put_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 0] offsets = [1, 0] f_min = 0 f_max = 1 european_put_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # construct circuit for payoff function european_put_delta = european_put_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = -np.array(result_delta.confidence_interval)[::-1] print("Exact delta: \t%.4f" % exact_delta) print("Esimated value: \t%.4f" % -result_delta.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/rubenandrebarreiro/summer-school-on-quantum-computing-software-for-near-term-quantum-devices-2020
rubenandrebarreiro
#initialization import matplotlib.pyplot as plt %matplotlib inline import numpy as np import math # 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 from qiskit.visualization import plot_state_qsphere # Loading your IBM Q account(s) provider = IBMQ.load_account() ##############################EXERCISE 1############################################# #Define multi-qubit controlled Z-gate for n=2,3 or 4. #n=2 def cz(circuit,qr): circuit.h(qr[1]) circuit.cx(qr[0],qr[1]) circuit.h(qr[1]) #n=3 def ccz(circuit,qr): circuit.h(qr[2]) # ccx is the Toffoli gate circuit.ccx(qr[0], qr[1], qr[2]) circuit.h(qr[2]) #n=4 def cccz(circuit,qr): pi = math.pi circuit.cu1(pi/4,qr[0],qr[3]) circuit.cx(qr[0], qr[1]) circuit.cu1(-pi/4, qr[1],qr[3]) circuit.cx(qr[0], qr[1]) circuit.cu1(pi/4, qr[1],qr[3]) circuit.cx(qr[1], qr[2]) circuit.cu1(-pi/4, qr[2],qr[3]) circuit.cx(qr[0], qr[2]) circuit.cu1(pi/4, qr[2],qr[3]) circuit.cx(qr[1], qr[2]) circuit.cu1(-pi/4, qr[2],qr[3]) circuit.cx(qr[0], qr[2]) circuit.cu1(pi/4, qr[2],qr[3]) #Definition def n_controlled_Z(circuit, qr): """Implement a Z gate with multiple controls""" if (len(qr) > 4): raise ValueError('The controlled Z with more than 3 controls is not implemented') # This is the case n = 2 (1 control + 1 target qubit) elif (len(qr) == 2): cz(circuit,qr) # This is the case n = 3 (2 control + 1 target qubit) elif (len(qr) == 3): ccz(circuit,qr) # This is the case n = 4 (3 control + 1 target qubit) elif (len(qr) == 4): cccz(circuit,qr) #Now we check if this fuction ihas the same function as a multi-qubit controlled Z-gate. (ex.|11>->-|11>). #####n=2#### ##Circuitn2, input=all posible states. #Create the circuit qrn2=QuantumRegister(2) crn2=ClassicalRegister(2) circuitn2=QuantumCircuit(qrn2,crn2) #Built all the posible input states using H-gates. circuitn2.h(0) circuitn2.h(1) #Apply our function. n_controlled_Z(circuitn2, qrn2) #Draw the circuit. circuitn2.draw() #Execute the quantum circuit using qasm simulator. backend = BasicAer.get_backend('statevector_simulator') result = execute(circuitn2, backend).result() psin2 = result.get_statevector(circuitn2) #Print and plot the results. plot_state_qsphere(psin2) #Measure. circuitn2.measure([0,1],[0,1]) #Execute the quantum circuit using qasm simulator. backend = BasicAer.get_backend('qasm_simulator') result = execute(circuitn2, backend, shots=10000).result() countsn2 = result.get_counts(circuitn2) #Print and plot the results. print(countsn2) plot_histogram(countsn2) ##Circuitn2Z, input=all posible states. #Create the circuit qrn2Z=QuantumRegister(2) crn2Z=ClassicalRegister(2) circuitn2Z=QuantumCircuit(qrn2Z,crn2Z) #Built all the posible input states using H-gates. circuitn2Z.h(0) circuitn2Z.h(1) #Apply our function. circuitn2Z.cz(qrn2Z[0],qrn2Z[1]) #Draw the circuit. circuitn2Z.draw() #Execute the quantum circuit using state vector simulator. backend = BasicAer.get_backend('statevector_simulator') result = execute(circuitn2Z, backend).result() psin2Z = result.get_statevector(circuitn2Z) #Print and plot the results. plot_state_qsphere(psin2Z) #####n=3#### ##Circuitn3, input=all posible states. #Create the circuit qrn3=QuantumRegister(3) crn3=ClassicalRegister(3) circuitn3=QuantumCircuit(qrn3,crn3) #Built all the posible input states using H-gates. circuitn3.h(0) circuitn3.h(1) circuitn3.h(2) #Apply our function. n_controlled_Z(circuitn3, qrn3) #Draw the circuit. circuitn3.draw() #Execute the quantum circuit using statevector simulator. backend = BasicAer.get_backend('statevector_simulator') result = execute(circuitn3, backend).result() psin3 = result.get_statevector(circuitn3) #Print and plot the results. plot_state_qsphere(psin3) #Measure. circuitn3.measure([0,1,2],[0,1,2]) #Execute the quantum circuit using qasm simulator. backend = BasicAer.get_backend('qasm_simulator') result = execute(circuitn3, backend, shots=10000).result() countsn3 = result.get_counts(circuitn3) #Print and plot the results. print(countsn3) plot_histogram(countsn3) #####n=4#### ##Circuitn4, input=all posible states. #Create the circuit qrn4=QuantumRegister(4) crn4=ClassicalRegister(4) circuitn4=QuantumCircuit(qrn4,crn4) #Built all the posible input states using H-gates. circuitn4.h(0) circuitn4.h(1) circuitn4.h(2) circuitn4.h(3) #Apply our function. n_controlled_Z(circuitn4, qrn4) #Draw the circuit. circuitn4.draw() #Execute the quantum circuit using statevector simulator. backend = BasicAer.get_backend('statevector_simulator') result = execute(circuitn4, backend).result() psin4 = result.get_statevector(circuitn4) #Print and plot the results. plot_state_qsphere(psin4) #Measure. circuitn4.measure([0,1,2,3],[0,1,2,3]) #Execute the quantum circuit using qasm simulator. backend = BasicAer.get_backend('qasm_simulator') result = execute(circuitn4, backend, shots=10000).result() countsn4 = result.get_counts(circuitn4) #Print and plot the results. print(countsn4) plot_histogram(countsn4) ##Circuit0n4, input=|0000>. #Create the circuit qr0n4=QuantumRegister(4) cr0n4=ClassicalRegister(4) circuit0n4=QuantumCircuit(qr0n4,crn4) #The states are already 0. #Apply our function. n_controlled_Z(circuit0n4, qr0n4) #Draw the circuit. circuit0n4.draw() #Execute the quantum circuit using statevector simulator. backend = BasicAer.get_backend('statevector_simulator') result = execute(circuit0n4, backend).result() psi0n4 = result.get_statevector(circuit0n4) #Print and plot the results. plot_state_qsphere(psi0n4) ##############################EXERCISE 2############################################# #Check whether Oracle acts as expected. #Define Oracle def phase_oracle(circuit,qr,element): # element is an array that defines the searched element, for example, element = [0,1,0,1] n = len(element) for j,x in enumerate(element): if (x == 0): circuit.x(qr[j]) n_controlled_Z(circuit,qr) for j,x in enumerate(element): if (x == 0): circuit.x(qr[j]) # Create Circuite2, input=all posible states. #Create the circuit qre2=QuantumRegister(4) cre2=ClassicalRegister(4) circuite2=QuantumCircuit(qre2,cre2) #Built all the posible input states using H-gates. circuite2.h(0) circuite2.h(1) circuite2.h(2) circuite2.h(3) #Chose element to search. elemente2=[0,1,1,0] #Apply Oracle. phase_oracle(circuite2,qre2,elemente2) #Draw the circuit. circuite2.draw() #Execute the quantum circuit using statevector simulator. backend = BasicAer.get_backend('statevector_simulator') result = execute(circuite2, backend).result() psie2 = result.get_statevector(circuite2) #Print and plot the results. plot_state_qsphere(psie2) #Measure. circuite2.measure([0,1,2,3],[0,1,2,3]) #Execute the quantum circuit using qasm simulator. backend = BasicAer.get_backend('qasm_simulator') result = execute(circuite2, backend, shots=10000).result() countse2 = result.get_counts(circuite2) #Print and plot the results. print(countse2) plot_histogram(countse2) ##############################EXERCISE 3############################################# #Define Inversion def inversion_about_average(circuit, register): """Apply inversion about the average step of Grover's algorithm.""" circuit.h(register) circuit.x(register) n_controlled_Z(circuit, qr) circuit.x(register) circuit.h(register) #Circuit that implements the Grover's Algorithm (we define a function in which we introduce our parameters). def grovers_algorithm(element,R,circuit,qr): #circuit=defined input of the circuit. #element=[a,b,c,d] with a,b=0,1, array representing the searched element. #R=number of repetitions. #Apply the algorithm R times. for i in range(1,R): #Apply Oracle. phase_oracle(circuit,qr,element) #Apply Inversion. inversion_about_average(circuit,qr) #Ex. searching |1010> #Create the circuit and set it with input=all posible states (2^4). qr=QuantumRegister(4) cr=ClassicalRegister(4) circuit=QuantumCircuit(qr,cr) circuit.h(0) circuit.h(1) circuit.h(2) circuit.h(3) #Apply the algorithm. grovers_algorithm([0,1,0,1],2,circuit,qr) #Plot the circuit. circuit.draw() #Measure. circuit.measure([0,1,2,3],[0,1,2,3]) #Execute the quantum circuit using qasm simulator. backend = BasicAer.get_backend('qasm_simulator') result = execute(circuit, backend, shots=1000).result() counts = result.get_counts(circuit) #Print and plot the results. print(counts) plot_histogram(counts) #Ex. searching |111> #Create the circuit and set it with input=all posible states (2^4). qr=QuantumRegister(3) cr=ClassicalRegister(3) circuit=QuantumCircuit(qr,cr) circuit.h(0) circuit.h(1) circuit.h(2) #Apply the algorithm. grovers_algorithm([1,1,1],3,circuit,qr) #Plot the circuit. circuit.draw() #Measure. circuit.measure([0,1,2],[0,1,2]) #Execute the quantum circuit using qasm simulator. backend = BasicAer.get_backend('qasm_simulator') result = execute(circuit, backend, shots=1000).result() counts = result.get_counts(circuit) #Print and plot the results. print(counts) plot_histogram(counts) #Ex. searching |00> #Create the circuit and set it with input=all posible states (2^4). qr=QuantumRegister(2) cr=ClassicalRegister(2) circuit=QuantumCircuit(qr,cr) circuit.h(0) circuit.h(1) #Apply the algorithm. grovers_algorithm([0,1],2,circuit,qr) #Plot the circuit. circuit.draw() #Measure. circuit.measure([0,1],[0,1]) #Execute the quantum circuit using qasm simulator. backend = BasicAer.get_backend('qasm_simulator') result = execute(circuit, backend, shots=1000).result() counts = result.get_counts(circuit) #Print and plot the results. print(counts) plot_histogram(counts) ##############################EXERCISE 4############################################# #number of measurements: it's easy to see by changing the parameter shoots that it doesn't really affect the results. #number of iterations: it must be chosen carefully because it follows a repetitive structure, being R~sqrt(n) a good election.
https://github.com/Ilan-Bondarevsky/qiskit_algorithm
Ilan-Bondarevsky
import numpy as np import math from qiskit import BasicAer, execute from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, Aer, transpile from qiskit.tools.visualization import plot_histogram, plot_bloch_multivector from shor_algo_adder_method import * from qiskit.circuit.library import DraperQFTAdder, QFT n = 8 q = QuantumRegister(n, 'q') c = ClassicalRegister(math.ceil(n/2), 'c') thiers = QuantumCircuit(q, c) main = QuantumCircuit(q, c) a = 15 b = 12 set_start_state(thiers, a, 0) set_start_state(thiers, b, n//2) set_start_state(main, a, 0) set_start_state(main, b, n//2) main.append(qft(math.ceil(n/2), False), range(n//2, n)) main = main.compose(adder(n//2, kind="fixed"), qubits=range(n)) # main.append(adder(n//2, kind="fixed"), range(n)) main.append(qft_dagger(math.ceil(n/2), False), range(n//2, n)) thiers = thiers.compose(DraperQFTAdder(n//2, kind="fixed").decompose(), range(n)) # thiers.append(DraperQFTAdder(n//2, kind="fixed"), range(n)) thiers.measure(range(n//2, n), range(math.ceil(n/2))) main.measure(range(n//2, n), range(math.ceil(n/2))) thiers.draw("mpl") b = 12 a = 15 n = 4 q = QuantumRegister(n, 'q') c = ClassicalRegister(n, 'c') classic_a = QuantumCircuit(q, c) set_start_state(classic_a, b, 0) classic_a.append(qft(n, False), range(n)) classic_a = classic_a.compose(adder_classic_a(n, a, kind="fixed"), range(n)) classic_a.append(qft_dagger(n, False), range(n)) classic_a.measure(range(n), range(n)) classic_a.draw('mpl') main.draw('mpl') sim = Aer.get_backend("aer_simulator") qc_init = ft.copy() qc_init.save_statevector() statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) aer_sim = Aer.get_backend('aer_simulator') t_thiers = transpile(thiers, aer_sim) t_main = transpile(main, aer_sim) t_classic = transpile(classic_a, aer_sim) counts_thiers = aer_sim.run(t_thiers).result().get_counts() count_main = aer_sim.run(t_main).result().get_counts() count_cls = aer_sim.run(t_classic).result().get_counts() plot_histogram([count_main, counts_thiers, count_cls], legend=["main", "thiers", "cls"]) n = 5 q = QuantumRegister(n, 'q') c = ClassicalRegister(math.ceil(n/2), 'c') subtract = QuantumCircuit(q, c) q = QuantumRegister(math.ceil(n/2), 'q') c = ClassicalRegister(math.ceil(n/2), 'c') subtract2 = QuantumCircuit(q, c) a = 1 b = 3 set_start_state(subtract, a, 0) set_start_state(subtract, b, n//2) set_start_state(subtract2, b, 0) subtract.append(qft(math.ceil(n/2), False), range(n//2, n)) # main = main.compose(adder(n//2, kind="half"), qubits=range(n)) # subtract = subtract.compose(adder(n//2, kind="half").inverse(), range(n)) subtract.append(subtracter(n//2), range(n)) subtract.append(qft_dagger(math.ceil(n/2), False), range(n//2, n)) subtract2.append(qft(math.ceil(n/2), False), range(math.ceil(n/2))) # main = main.compose(adder(n//2, kind="half"), qubits=range(n)) # subtract = subtract.compose(adder(n//2, kind="half").inverse(), range(n)) subtract2.append(subtracter_classic_a(n//2, a), range(math.ceil(n/2))) subtract2.append(qft_dagger(math.ceil(n/2), False), range(math.ceil(n/2))) # thiers = thiers.compose(DraperQFTAdder(n//2, kind="half").decompose(), range(n)) subtract.measure(range(n//2, n), range(math.ceil(n/2))) subtract2.measure(range(math.ceil(n/2)), range(math.ceil(n/2))) subtract.draw("mpl") subtract2.draw("mpl") aer_sim = Aer.get_backend('aer_simulator') t_subtract = transpile(subtract, aer_sim) t_subtract2 = transpile(subtract2, aer_sim) counts_subtract = aer_sim.run(t_subtract).result().get_counts() counts_subtract2 = aer_sim.run(t_subtract2).result().get_counts() plot_histogram([counts_subtract, counts_subtract2], legend=["draper", "a inside"]) n = 4 N = 11 a = 2 b = 0 x = 6 a_mod_n = QuantumCircuit(2*n + 4, n+1) a_mod_n.x(0) set_start_state(a_mod_n, x, 1) set_start_state(a_mod_n, b, n+2) # a_mod_n = a_mod_n.compose(add_mod_n(a, N), range(n+3)) a_mod_n = a_mod_n.compose(U(a, N).decompose(), range(2*n + 4)) a_mod_n.measure(range(1, n+2), range(n+1)) a_mod_n.draw('mpl', fold=-1) aer_sim = Aer.get_backend('aer_simulator') t_subtract = transpile(a_mod_n, aer_sim) counts_subtract = aer_sim.run(t_subtract).result().get_counts() plot_histogram(counts_subtract)
https://github.com/Chibikuri/qwopt
Chibikuri
import numpy as np import matplotlib.pyplot as plt import seaborn as sns import copy import itertools from qiskit import transpile from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit import Aer, execute from qiskit.tools.visualization import plot_histogram from torch import optim # qiskit AQUA from qiskit.aqua.components.optimizers import ADAM from qiskit.aqua.components.uncertainty_models import UniformDistribution, UnivariateVariationalDistribution from qiskit.aqua.components.variational_forms import RY from qiskit.aqua.algorithms.adaptive import QGAN from qiskit.aqua.components.neural_networks.quantum_generator import QuantumGenerator from qiskit.aqua.components.neural_networks.numpy_discriminator import NumpyDiscriminator from qiskit.aqua import aqua_globals, QuantumInstance from qiskit.aqua.components.initial_states import Custom alpha = 0.85 target_graph = np.array([[0, 1, 0, 1], [0, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]) E = np.array([[1/4, 1/2, 0, 1/2], [1/4, 0, 1/2, 0], [1/4, 1/2, 0, 1/2], [1/4, 0, 1/2, 0]]) # use google matrix prob_dist = alpha*E + ((1-alpha)/4)*np.ones((4, 4)) init_state = 1/2*np.array([np.sqrt(prob_dist[j][i]) for i in range(4) for j in range(4)]) # Number training data samples N = 1000 # Load data samples from log-normal distribution with mean=1 and standard deviation=1 mu = 1 sigma = 1 real_data = np.random.lognormal(mean = mu, sigma=sigma, size=N) # Set the data resolution # Set upper and lower data values as list of k min/max data values [[min_0,max_0],...,[min_k-1,max_k-1]] bounds = np.array([0.,3.]) # Set number of qubits per data dimension as list of k qubit values[#q_0,...,#q_k-1] num_qubits = [2] k = len(num_qubits) print(real_data) plt.hist(real_data) # QGAN # Set number of training epochs # Note: The algorithm's runtime can be shortened by reducing the number of training epochs. num_epochs = 3000 # Batch size batch_size = 100 # Initialize qGAN qgan = QGAN(real_data, bounds, num_qubits, batch_size, num_epochs, snapshot_dir=None) qgan.seed = 1 # Set quantum instance to run the quantum generator quantum_instance = QuantumInstance(backend=Aer.get_backend('statevector_simulator')) # Set entangler map entangler_map = [[0, 1]] # Set an initial state for the generator circuit init_dist = UniformDistribution(sum(num_qubits), low=bounds[0], high=bounds[1]) print(init_dist.probabilities) q = QuantumRegister(sum(num_qubits), name='q') qc = QuantumCircuit(q) init_dist.build(qc, q) init_distribution = Custom(num_qubits=sum(num_qubits), circuit=qc) var_form = RY(int(np.sum(num_qubits)), depth=1, initial_state = init_distribution, entangler_map=entangler_map, entanglement_gate='cz') # Set generator's initial parameters init_params = aqua_globals.random.rand(var_form._num_parameters) * 2 * np.pi # Set generator circuit g_circuit = UnivariateVariationalDistribution(int(sum(num_qubits)), var_form, init_params, low=bounds[0], high=bounds[1]) # Set quantum generator qgan.set_generator(generator_circuit=g_circuit) # Set classical discriminator neural network discriminator = NumpyDiscriminator(len(num_qubits)) qgan.set_discriminator(discriminator) # Run qGAN qgan.run(quantum_instance) # Plot progress w.r.t the generator's and the discriminator's loss function t_steps = np.arange(num_epochs) plt.figure(figsize=(6,5)) plt.title("Progress in the loss function") plt.plot(t_steps, qgan.g_loss, label = "Generator loss function", color = 'mediumvioletred', linewidth = 2) plt.plot(t_steps, qgan.d_loss, label = "Discriminator loss function", color = 'rebeccapurple', linewidth = 2) plt.grid() plt.legend(loc = 'best') plt.xlabel('time steps') plt.ylabel('loss') plt.show() # Plot progress w.r.t relative entropy plt.figure(figsize=(6,5)) plt.title("Relative Entropy ") plt.plot(np.linspace(0, num_epochs, len(qgan.rel_entr)), qgan.rel_entr, color ='mediumblue', lw=4, ls=':') plt.grid() plt.xlabel('time steps') plt.ylabel('relative entropy') plt.show() #Plot the PDF of the resulting distribution against the target distribution, i.e. log-normal log_normal = np.random.lognormal(mean=1, sigma=1, size=100000) log_normal = np.round(log_normal) log_normal = log_normal[log_normal <= bounds[1]] temp = [] for i in range(int(bounds[1]+1)): temp += [np.sum(log_normal==i)] log_normal = np.array(temp / sum(temp)) plt.figure(figsize=(6,5)) plt.title("CDF") samples_g, prob_g = qgan.generator.get_output(qgan.quantum_instance, shots=10000) samples_g = np.array(samples_g) samples_g = samples_g.flatten() num_bins = len(prob_g) print(prob_g) print(samples_g) plt.bar(samples_g, np.cumsum(prob_g), color='royalblue', width= 0.8, label='simulation') plt.plot( np.cumsum(log_normal),'-o', label='log-normal', color='deepskyblue', linewidth=4, markersize=12) plt.xticks(np.arange(min(samples_g), max(samples_g)+1, 1.0)) plt.grid() plt.xlabel('x') plt.ylabel('p(x)') plt.legend(loc='best') plt.show() print(len(qgan._ret['params_g'])) for i in qgan._ret['params_g']: print(i) gp = qgan._ret['params_g'] q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q) qc.ry(gp[0], q[0]) qc.ry(gp[1], q[1]) qc.cz(q[0], q[1]) qc.ry(gp[2], q[0]) qc.ry(gp[3], q[1]) job = execute(qc, backend=Aer.get_backend('statevector_simulator')) vec = job.result().get_statevector(qc) print(vec) qc.measure(q[0], c[1]) qc.measure(q[1], c[0]) shots = 10000 job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=shots) count = job.result().get_counts(qc) bins = [format(i, "0%db"%num_qubits[0]) for i in range(2**num_qubits[0])] pros = itertools.accumulate([count.get(i, 0)/shots for i in bins]) print(list(pros)) # plot_histogram(pros) # Circuit # Hardcoded now! num_qubits = [2] bins = [format(i, "0%db"%num_qubits[0]) for i in range(2**num_qubits[0])] def four_node(step): rotation = np.radians(31.788) cq = QuantumRegister(2, 'control') tq = QuantumRegister(2, 'target') c = ClassicalRegister(2, 'classical') anc = QuantumRegister(2, 'ancilla') qc = QuantumCircuit(cq, tq, anc, c) # initialize with probability distribution matrix initial = 1/2*np.array([np.sqrt(prob_dist[j][i]) for i in range(4) for j in range(4)]) qc.initialize(initial, [*cq, *tq]) for t in range(step): # Ti operation qc.x(cq[1]) qc.ccx(cq[0], cq[1], tq[1]) qc.x(cq[1]) qc.barrier() # Kdg operation qc.x(cq) qc.rccx(cq[0], cq[1], anc[0]) qc.barrier() qc.ch(anc[0], tq[0]) qc.ch(anc[0], tq[1]) qc.x(anc[0]) qc.cry(-rotation, anc[0], tq[1]) qc.ch(anc[0], tq[0]) qc.barrier() # D operation qc.x(tq) qc.cz(tq[0], tq[1]) qc.x(tq) qc.barrier() # K operation qc.ch(anc[0], tq[0]) qc.cry(rotation, anc[0], tq[1]) qc.x(anc[0]) qc.ch(anc[0], tq[1]) qc.ch(anc[0], tq[0]) qc.rccx(cq[0], cq[1], anc[0]) qc.x(cq) qc.barrier() # Tidg operation qc.x(cq[1]) qc.ccx(cq[0], cq[1], tq[1]) qc.x(cq[1]) qc.barrier() # swap qc.swap(tq[0], cq[0]) qc.swap(tq[1], cq[1]) qc.measure(tq, c) return qc step = 1 qwqc = four_node(step) shots = 10000 job = execute(qwqc, backend=Aer.get_backend("qasm_simulator"), shots=shots) counts = job.result().get_counts(qwqc) probs = np.array(([0] * counts.get('00'), [1]* counts.get('01'), [2] * counts.get('10'), [3] * counts.get('11'))) real_data = [] for i in probs: for j in i: real_data.append(j) bounds = np.array([0.,3.]) # Set number of qubits per data dimension as list of k qubit values[#q_0,...,#q_k-1] num_qubits = [2] k = len(num_qubits) # QGAN # Set number of training epochs # Note: The algorithm's runtime can be shortened by reducing the number of training epochs. num_epochs = 3000 # Batch size batch_size = 100 # Initialize qGAN qgan = QGAN(real_data, bounds, num_qubits, batch_size, num_epochs, snapshot_dir=None) qgan.seed = 1 # Set quantum instance to run the quantum generator quantum_instance = QuantumInstance(backend=Aer.get_backend('statevector_simulator')) # Set entangler map entangler_map = [[0, 1]] # Set an initial state for the generator circuit init_dist = UniformDistribution(sum(num_qubits), low=bounds[0], high=bounds[1]) print(init_dist.probabilities) q = QuantumRegister(sum(num_qubits), name='q') qc = QuantumCircuit(q) init_dist.build(qc, q) init_distribution = Custom(num_qubits=sum(num_qubits), circuit=qc) var_form = RY(int(np.sum(num_qubits)), depth=1, initial_state = init_distribution, entangler_map=entangler_map, entanglement_gate='cz') # Set generator's initial parameters init_params = aqua_globals.random.rand(var_form._num_parameters) * 2 * np.pi # Set generator circuit g_circuit = UnivariateVariationalDistribution(int(sum(num_qubits)), var_form, init_params, low=bounds[0], high=bounds[1]) # Set quantum generator qgan.set_generator(generator_circuit=g_circuit) # Set classical discriminator neural network discriminator = NumpyDiscriminator(len(num_qubits)) qgan.set_discriminator(discriminator) # Run qGAN qgan.run(quantum_instance)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import NormalDistribution # can be used in case a principal component analysis has been done to derive the uncertainty model, ignored in this example. A = np.eye(2) b = np.zeros(2) # specify the number of qubits that are used to represent the different dimenions of the uncertainty model num_qubits = [2, 2] # specify the lower and upper bounds for the different dimension low = [0, 0] high = [0.12, 0.24] mu = [0.12, 0.24] sigma = 0.01 * np.eye(2) # construct corresponding distribution bounds = list(zip(low, high)) u = NormalDistribution(num_qubits, mu, sigma, bounds) # plot contour of probability density function x = np.linspace(low[0], high[0], 2 ** num_qubits[0]) y = np.linspace(low[1], high[1], 2 ** num_qubits[1]) z = u.probabilities.reshape(2 ** num_qubits[0], 2 ** num_qubits[1]) plt.contourf(x, y, z) plt.xticks(x, size=15) plt.yticks(y, size=15) plt.grid() plt.xlabel("$r_1$ (%)", size=15) plt.ylabel("$r_2$ (%)", size=15) plt.colorbar() plt.show() # specify cash flow cf = [1.0, 2.0] periods = range(1, len(cf) + 1) # plot cash flow plt.bar(periods, cf) plt.xticks(periods, size=15) plt.yticks(size=15) plt.grid() plt.xlabel("periods", size=15) plt.ylabel("cashflow ($)", size=15) plt.show() # estimate real value cnt = 0 exact_value = 0.0 for x1 in np.linspace(low[0], high[0], pow(2, num_qubits[0])): for x2 in np.linspace(low[1], high[1], pow(2, num_qubits[1])): prob = u.probabilities[cnt] for t in range(len(cf)): # evaluate linear approximation of real value w.r.t. interest rates exact_value += prob * ( cf[t] / pow(1 + b[t], t + 1) - (t + 1) * cf[t] * np.dot(A[:, t], np.asarray([x1, x2])) / pow(1 + b[t], t + 2) ) cnt += 1 print("Exact value: \t%.4f" % exact_value) # specify approximation factor c_approx = 0.125 # create fixed income pricing application from qiskit_finance.applications.estimation import FixedIncomePricing fixed_income = FixedIncomePricing( num_qubits=num_qubits, pca_matrix=A, initial_interests=b, cash_flow=cf, rescaling_factor=c_approx, bounds=bounds, uncertainty_model=u, ) fixed_income._objective.draw() fixed_income_circ = QuantumCircuit(fixed_income._objective.num_qubits) # load probability distribution fixed_income_circ.append(u, range(u.num_qubits)) # apply function fixed_income_circ.append(fixed_income._objective, range(fixed_income._objective.num_qubits)) fixed_income_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 # construct amplitude estimation problem = fixed_income.to_estimation_problem() ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (fixed_income.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import random from qiskit.quantum_info import Statevector secret = random.randint(0,7) # the owner is randomly picked secret_string = format(secret, '03b') # format the owner in 3-bit string oracle = Statevector.from_label(secret_string) # let the oracle know the owner from qiskit.algorithms import AmplificationProblem problem = AmplificationProblem(oracle, is_good_state=secret_string) from qiskit.algorithms import Grover grover_circuits = [] for iteration in range(1,3): grover = Grover(iterations=iteration) circuit = grover.construct_circuit(problem) circuit.measure_all() grover_circuits.append(circuit) # Grover's circuit with 1 iteration grover_circuits[0].draw() # Grover's circuit with 2 iterations grover_circuits[1].draw() from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() backend = "ibmq_qasm_simulator" # use the simulator from qiskit_ibm_runtime import Sampler, Session with Session(service=service, backend=backend): sampler = Sampler() job = sampler.run(circuits=grover_circuits, shots=1000) result = job.result() print(result) from qiskit.tools.visualization import plot_histogram # Extract bit string with highest probability from results as the answer result_dict = result.quasi_dists[1].binary_probabilities() answer = max(result_dict, key=result_dict.get) print(f"As you can see, the quantum computer returned '{answer}' as the answer with highest probability.\n" "And the results with 2 iterations have higher probability than the results with 1 iteration." ) # Plot the results plot_histogram(result.quasi_dists, legend=['1 iteration', '2 iterations']) # Print the results and the correct answer. print(f"Quantum answer: {answer}") print(f"Correct answer: {secret_string}") print('Success!' if answer == secret_string else 'Failure!') import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
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/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 = [] for _ in range(100): depths.append( transpile( ghz, backend, layout_method='trivial' # Fixed layout mapped in circuit order ).depth() ) plt.figure(figsize=(8, 6)) plt.hist(depths, align='left', color='#AC557C') plt.xlabel('Depth', fontsize=14) plt.ylabel('Counts', fontsize=14);
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_aer.utils import approximate_quantum_error, approximate_noise_model import numpy as np # Import Aer QuantumError functions that will be used from qiskit_aer.noise import amplitude_damping_error, reset_error, pauli_error from qiskit.quantum_info import Kraus gamma = 0.23 error = amplitude_damping_error(gamma) results = approximate_quantum_error(error, operator_string="reset") print(results) p = (1 + gamma - np.sqrt(1 - gamma)) / 2 q = 0 print("") print("Expected results:") print("P(0) = {}".format(1-(p+q))) print("P(1) = {}".format(p)) print("P(2) = {}".format(q)) gamma = 0.23 K0 = np.array([[1,0],[0,np.sqrt(1-gamma)]]) K1 = np.array([[0,np.sqrt(gamma)],[0,0]]) results = approximate_quantum_error(Kraus([K0, K1]), operator_string="reset") print(results) reset_to_0 = Kraus([np.array([[1,0],[0,0]]), np.array([[0,1],[0,0]])]) reset_to_1 = Kraus([np.array([[0,0],[1,0]]), np.array([[0,0],[0,1]])]) reset_kraus = [reset_to_0, reset_to_1] gamma = 0.23 error = amplitude_damping_error(gamma) results = approximate_quantum_error(error, operator_list=reset_kraus) print(results) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/tanvipenumudy/Quantum-Computing-Mini-Projects
tanvipenumudy
pip install qiskit from qiskit.aqua.algorithms import Shor from qiskit.aqua import QuantumInstance from qiskit import Aer key = 21 base = 2 backend = Aer.get_backend('qasm_simulator') qi = QuantumInstance(backend=backend, shots=18240) shors = Shor(N=key, a=base, quantum_instance = qi) results = shors.run() print(results['factors'])
https://github.com/drobiu/quantum-project
drobiu
from qiskit import BasicAer, execute from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit.library.standard_gates import PhaseGate from qiskit.circuit.library.basis_change import QFT import math from src.util.util import run_qc q = QuantumRegister(3) b = QuantumRegister(1) c = ClassicalRegister(3) qc = QuantumCircuit(q, b, c) qc.x(q[0]) qc.draw(output='mpl') def increment(circuit, register, apply_QFT=True): q = register num = len(q) qc = circuit if apply_QFT == True: qc.barrier() qc = qc.compose(QFT(num_qubits=num, approximation_degree=0, do_swaps=True, \ inverse=False, insert_barriers=True, name='qft')) qc.barrier() for i, qubit in enumerate(q): qc.rz(math.pi/2**(num-1-i), qubit) if apply_QFT == True: qc.barrier() qc = qc.compose(QFT(num_qubits=num, approximation_degree=0, do_swaps=True, \ inverse=True, insert_barriers=True, name='iqft')) qc.barrier() return qc test = increment(qc, q) test.draw(output='mpl') def control_increment(circuit, qregister, cregister, apply_QFT=True): q = qregister c = cregister numq = len(q) numc = len(c) qc = circuit if apply_QFT == True: qc.barrier() qc = qc.compose(QFT(num_qubits=numq, approximation_degree=0, do_swaps=True, \ inverse=False, insert_barriers=True, name='qft')) qc.barrier() for i, qubit in enumerate(q): ncp = PhaseGate(math.pi/2**(numq-i-1)).control(numc) qc.append(ncp, [*c, qubit]) if apply_QFT == True: qc.barrier() qc = qc.compose(QFT(num_qubits=numq, approximation_degree=0, do_swaps=True, \ inverse=True, insert_barriers=True, name='iqft')) qc.barrier() return qc test2 = control_increment(qc, q, b) test2.draw(output='mpl') ## Test increment without control test = increment(qc, q) test.measure(q[:], c[:]) run_qc(qc) test.draw(output='mpl') # Test control increment q = QuantumRegister(3) b = QuantumRegister(1) c = ClassicalRegister(3) qc = QuantumCircuit(q, b, c) qc.x(q[0]) qc = control_increment(qc, q, b) # Flipping control qubit to 1 qc.x(b[0]) qc = control_increment(qc, q, b) # Flipping control qubit to 1 qc.x(b[0]) qc = control_increment(qc, q, b) # Should equal 010 qc.measure(q[:], c[:]) run_qc(qc) qc.draw(output="mpl")
https://github.com/WhenTheyCry96/qiskitHackathon2022
WhenTheyCry96
%load_ext autoreload %autoreload 2 import os import warnings import qiskit_metal as metal from numpy import pi from scipy.constants import c, h, pi, hbar, e, mu_0, epsilon_0 from qiskit_metal import Dict from qiskit_metal.analyses.quantization.lumped_capacitive import load_q3d_capacitance_matrix from qiskit_metal.analyses.quantization.lom_core_analysis import CompositeSystem, Cell, Subsystem, QuantumSystemRegistry ws_path = os.getcwd() warnings.filterwarnings("ignore") #constants: phi0 = h/(2*e) varphi0 = phi0/(2*pi) #project parameters: L_JJ = 10 # nH C_JJ = 2 # fF f_r = 8 # GHz Z_r = 50 # Ohm v_r = 0.404314 # relative velocity to c #parameter extraction: eps_eff = (1/v_r)**2 # effective eps_r eps_r = 2*eps_eff-1 # approximation I_JJ = varphi0/(L_JJ*1e-9)/1e-9 # nA E_JJ = (varphi0)**2/(L_JJ*1e-9)/h/1e9 # GHz #print print(eps_r, I_JJ, E_JJ) QuantumSystemRegistry.registry() capfile = ws_path+"/Transmon_Readout_CapMatrix.txt" t1_mat, _, _, _ = load_q3d_capacitance_matrix(capfile) t1_mat opt1 = dict( cap_mat = t1_mat, ind_dict = {('pad_top_Q1', 'pad_bot_Q1'): L_JJ}, # junction inductance in nH jj_dict = {('pad_top_Q1', 'pad_bot_Q1'): 'j1'}, cj_dict = {('pad_top_Q1', 'pad_bot_Q1'): C_JJ}, # junction capacitance in fF ) cell_1 = Cell(opt1) transmon1 = Subsystem(name='transmon1', sys_type='TRANSMON', nodes=['j1']) trans_read = Subsystem(name='readout1', sys_type='TL_RESONATOR', nodes=['readout_connector_pad_Q1'], q_opts=dict(f_res = f_r, Z0=Z_r, vp=v_r*c)) composite_sys = CompositeSystem( subsystems=[transmon1, trans_read], cells=[cell_1], grd_node='ground_main_plane', nodes_force_keep=['readout_connector_pad_Q1'] ) cg = composite_sys.circuitGraph() print(cg) hilbertspace = composite_sys.create_hilbertspace() print(hilbertspace) hilbertspace = composite_sys.add_interaction() hilbertspace.hamiltonian() hamiltonian_results = composite_sys.hamiltonian_results(hilbertspace, evals_count=30) composite_sys.compute_gs()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """FilterOpNodes pass testing""" from qiskit import QuantumCircuit from qiskit.transpiler.passes import FilterOpNodes from test import QiskitTestCase # pylint: disable=wrong-import-order class TestFilterOpNodes(QiskitTestCase): """Tests for FilterOpNodes transformation pass.""" def test_empty_circuit(self): """Empty DAG has does nothing.""" circuit = QuantumCircuit() self.assertEqual(FilterOpNodes(lambda x: False)(circuit), circuit) def test_remove_x_gate(self): """Test filter removes matching gates.""" circuit = QuantumCircuit(2) circuit.x(0) circuit.x(1) circuit.cx(0, 1) circuit.cx(1, 0) circuit.cx(0, 1) circuit.measure_all() filter_pass = FilterOpNodes(lambda node: node.op.name != "x") expected = QuantumCircuit(2) expected.cx(0, 1) expected.cx(1, 0) expected.cx(0, 1) expected.measure_all() self.assertEqual(filter_pass(circuit), expected) def test_filter_exception(self): """Test a filter function exception passes through.""" circuit = QuantumCircuit(2) circuit.x(0) circuit.x(1) circuit.cx(0, 1) circuit.cx(1, 0) circuit.cx(0, 1) circuit.measure_all() def filter_fn(node): raise TypeError("Failure") filter_pass = FilterOpNodes(filter_fn) with self.assertRaises(TypeError): filter_pass(circuit) def test_no_matches(self): """Test the pass does nothing if there are no filter matches.""" circuit = QuantumCircuit(2) circuit.x(0) circuit.x(1) circuit.cx(0, 1) circuit.cx(1, 0) circuit.cx(0, 1) circuit.measure_all() filter_pass = FilterOpNodes(lambda node: node.op.name != "cz") self.assertEqual(filter_pass(circuit), circuit)
https://github.com/adiazcarral/QHarmony
adiazcarral
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 27 11:07:17 2022 @author: angel """ # http://lampx.tugraz.at/~hadley/ss1/bzones/fcc.php # https://aiida-tutorials.readthedocs.io/en/tutorial-2020-intro-week/source/sections/bands.html from jarvis.db.figshare import get_wann_electron, get_wann_phonon, get_hk_tb from jarvis.io.qiskit.inputs import HermitianSolver, get_bandstruct, get_dos from jarvis.core.kpoints import generate_kgrid import numpy as np import qiskit from qiskit import Aer from jarvis.core.circuits import QuantumCircuitLibrary import matplotlib.pyplot as plt # JVASP-816 Al # JVASP-1002 Si # JVASP-35680 PbS ######################### ##### Download WTBH ##### wtbh, Ef, atoms = get_wann_electron(jid="JVASP-1002") # wtbh, atoms = get_wann_phonon(jid="JVASP-1002", factor=34.3) ######################### kpt = [0.5, 0., 0.5] #X-point jarvis # kpt = [0., 0., 0.] #gamma-point ################################################ ##### Transform WTBH into Hermitian matrix ##### # kpt = [0.5, 0., 0.5] #X-point jarvis kpt = [0., 0., 0.] #gamma-point ########## hk = get_hk_tb(w=wtbh, k=kpt) HS = HermitianSolver(hk) n_qubits = HS.n_qubits() reps = 1 circ = QuantumCircuitLibrary(n_qubits=n_qubits, reps=reps).circuit6() backend = Aer.get_backend("statevector_simulator") ########### ### VQE ### en, vqe_result, vqe = HS.run_vqe(mode='min_val',var_form=circ,backend=backend) vals, vecs = HS.run_numpy() params = vqe.optimal_params circuit = vqe.construct_circuit(params) print('Classical, VQE (eV)', (vals[0] - Ef),(en - Ef)) print('Classical, VQE (eV)', (vals[0]),(en)) print(Ef) ########### ##### PbS X Plot Example ####### y = [-5.527449487783215, -8.057364907488996, -8.262343159928434, -8.247681114397821, -8.30798759954503, -8.310212504542353 ] x = [1, 2, 3, 4, 5, 6] plt.plot(x,y, color='black', marker = 'o') plt.axhline(y=-8.310902072462328, color='b', linestyle='-.', linewidth=1) plt.xlabel('Repetitions') plt.ylabel('Energy (eV)') plt.title('PbS X-point (Circuit 6)') plt.xlim(0.5, 6.5) plt.ylim(-10, -5) plt.savefig('PbSX6.png', dpi=150, format=None, metadata=None, bbox_inches='tight')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.circuit.library import IntegerComparator, WeightedAdder, LinearAmplitudeFunction from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = (r - 0.5 * vol**2) * T + np.log(S) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=(list(zip(low, high)))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 3 strike_price_2 = 4 # set the barrier threshold barrier = 2.5 # map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price_1 = ( (strike_price_1 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_strike_price_2 = ( (strike_price_2 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1) # condition and condition result conditions = [] barrier_thresholds = [2] * dimension n_aux_conditions = 0 for i in range(dimension): # target dimension of random distribution and corresponding condition (which is required to be True) comparator = IntegerComparator(num_qubits[i], mapped_barrier[i] + 1, geq=False) n_aux_conditions = max(n_aux_conditions, comparator.num_ancillas) conditions += [comparator] # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1] f_min = 0 f_max = mapped_strike_price_2 - mapped_strike_price_1 objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar_cond = AncillaRegister(len(conditions) + 1, "conditions") ar = AncillaRegister( max(n_aux, n_aux_conditions, objective.num_ancillas), "work" ) # additional qubits objective_index = u.num_qubits # define the circuit asian_barrier_spread = QuantumCircuit(qr_state, qr_obj, ar_cond, ar_sum, ar) # load the probability distribution asian_barrier_spread.append(u, qr_state) # apply the conditions for i, cond in enumerate(conditions): state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append(cond, state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas]) # aggregate the conditions on a single qubit asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) # apply the aggregation function controlled on the condition asian_barrier_spread.append(agg.control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux]) # apply the payoff function asian_barrier_spread.append(objective, ar_sum[:] + qr_obj[:] + ar[: objective.num_ancillas]) # uncompute the aggregation asian_barrier_spread.append( agg.inverse().control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux] ) # uncompute the conditions asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) for j, cond in enumerate(reversed(conditions)): i = len(conditions) - j - 1 state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append( cond.inverse(), state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas] ) print(asian_barrier_spread.draw()) print("objective qubit index", objective_index) # plot exact payoff function plt.figure(figsize=(7, 5)) x = np.linspace(sum(low), sum(high)) y = (x <= 5) * np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function (for $S_1 = S_2$)", size=15) plt.xlabel("Sum of Spot Prices ($S_1 + S_2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # plot contour of payoff function with respect to both time steps, including barrier plt.figure(figsize=(7, 5)) z = np.zeros((17, 17)) x = np.linspace(low[0], high[0], 17) y = np.linspace(low[1], high[1], 17) for i, x_ in enumerate(x): for j, y_ in enumerate(y): z[i, j] = np.minimum( np.maximum(0, x_ + y_ - strike_price_1), strike_price_2 - strike_price_1 ) if x_ > barrier or y_ > barrier: z[i, j] = 0 plt.title("Payoff Function", size=15) plt.contourf(x, y, z) plt.colorbar() plt.xlabel("Spot Price $S_1$", size=15) plt.ylabel("Spot Price $S_2$", size=15) plt.xticks(size=15) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) payoff = np.minimum(np.maximum(sum_values - strike_price_1, 0), strike_price_2 - strike_price_1) leq_barrier = [np.max(v) <= barrier for v in u.values] exact_value = np.dot(u.probabilities[leq_barrier], payoff[leq_barrier]) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = asian_barrier_spread.num_qubits - asian_barrier_spread.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(asian_barrier_spread, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) asian_barrier_spread_measure = asian_barrier_spread.measure_all(inplace=False) sampler = Sampler() job = sampler.run(asian_barrier_spread_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=asian_barrier_spread, objective_qubits=[objective_index], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value:\t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/tomtuamnuq/compare-qiskit-ocean
tomtuamnuq
from pyqubo import Binary x_0, x_1, x_2 = (Binary('x_'+str(i)) for i in range(3)) linear_obj = - x_0 - x_2 quadratic_obj = - x_0 + x_0*x_2 + x_1 - 2*x_1*x_2 linear_cstr = 8*(x_1 - x_2)**2 qubo_bqm = (linear_obj + quadratic_obj + linear_cstr).compile().to_bqm() print(qubo)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit.tools.visualization import plot_histogram from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, BasicAer q = QuantumRegister(2) c = ClassicalRegister(2) # quantum circuit to make a Bell state bell = QuantumCircuit(q,c) bell.h(q[0]) bell.cx(q[0],q[1]) meas = QuantumCircuit(q,c) meas.measure(q, c) # execute the quantum circuit backend = BasicAer.get_backend('qasm_simulator') # the device to run on circ = bell+meas result = execute(circ, backend, shots=1000).result() counts = result.get_counts(circ) print(counts) plot_histogram(counts) # Execute 2 qubit Bell state again second_result = execute(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.tools.visualization import iplot_histogram # Run in interactive mode iplot_histogram(counts) from qiskit.tools.visualization import plot_state_city, plot_bloch_multivector, plot_state_paulivec, plot_state_hinton, plot_state_qsphere # execute the quantum circuit backend = BasicAer.get_backend('statevector_simulator') # the device to run on result = execute(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.tools.visualization import iplot_state_paulivec # Generate an interactive pauli vector plot iplot_state_paulivec(psi) from qiskit.tools.visualization import plot_bloch_vector plot_bloch_vector([0,1,0]) plot_bloch_vector([0,1,0], title='My Bloch Sphere')
https://github.com/jfraxanet/BasQ_industry_workshop_Qiskit
jfraxanet
import rustworkx as rx from rustworkx.visualization import mpl_draw num_nodes = 5 edges = [(0, 1, 1), (0, 2, 1), (0, 3, 1), (0, 4, 1)]# The edge syntax is (start, end, weight) G = rx.PyGraph() G.add_nodes_from(range(num_nodes)) G.add_edges_from(edges) mpl_draw( G, pos=rx.bipartite_layout(G, {0}), with_labels=True, node_color='tab:purple', font_color='white' ) import numpy as np from qiskit.quantum_info import SparsePauliOp # Problem to Hamiltonian operator hamiltonian = SparsePauliOp.from_list([("IIIZZ", 1), ("IIZIZ", 1), ("IZIIZ", 1), ("ZIIIZ", 1)]) print(hamiltonian) from qiskit.circuit.library import QAOAAnsatz # QAOA ansatz circuit ansatz = QAOAAnsatz(hamiltonian, reps=2) ansatz.decompose(reps=3).draw(output="mpl", style="clifford") ansatz.decompose(reps=1).draw(output="mpl", style="clifford") from qiskit.primitives import Estimator estimator = Estimator() # If we want to run it on the real device, use these lines instead: #from qiskit_ibm_runtime import QiskitRuntimeService #from qiskit_ibm_runtime import Estimator, Sampler, Session, Options #service = QiskitRuntimeService(channel="ibm_quantum", token=<YOUR TOKEN>) #backend = service.least_busy(operational=True, simulator=False) #print(backend.name) #options = Options() #options.resilience_level = 1 #options.optimization_level = 3 #estimator = Estimator(backend, options=options) def cost_func(params, ansatz, hamiltonian, estimator): """Return estimate of energy from estimator Parameters: params (ndarray): Array of ansatz parameters ansatz (QuantumCircuit): Parameterized ansatz circuit hamiltonian (SparsePauliOp): Operator representation of Hamiltonian estimator (Estimator): Estimator primitive instance Returns: float: Energy estimate """ cost = estimator.run(ansatz, hamiltonian, parameter_values=params).result().values[0] return cost from scipy.optimize import minimize # Randomly initialize the parameters of the ansatz x0 = 2 * np.pi * np.random.rand(ansatz.num_parameters) # Run the variational algorithm res = minimize(cost_func, x0, args=(ansatz, hamiltonian, estimator), method="COBYLA") print(res) from qiskit.primitives import Sampler sampler = Sampler() # If instead we want to run it on the device # we need the sampler from runtime # sampler = Sampler(backend, options=options) # Assign solution parameters to ansatz qc = ansatz.assign_parameters(res.x) qc.measure_all() # Draw circuit with optimal parameters #qc_ibm.draw(output="mpl", idle_wires=False, style="iqp") from qiskit.visualization import plot_distribution # Sample ansatz at optimal parameters samp_dist = sampler.run(qc).result().quasi_dists[0] plot_distribution(samp_dist.binary_probabilities(), figsize=(15, 5))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.problems import ElectronicBasis driver = PySCFDriver() driver.run_pyscf() ao_problem = driver.to_problem(basis=ElectronicBasis.AO) print(ao_problem.basis) ao_hamil = ao_problem.hamiltonian print(ao_hamil.electronic_integrals.alpha) from qiskit_nature.second_q.formats.qcschema_translator import get_ao_to_mo_from_qcschema qcschema = driver.to_qcschema() basis_transformer = get_ao_to_mo_from_qcschema(qcschema) print(basis_transformer.initial_basis) print(basis_transformer.final_basis) mo_problem = basis_transformer.transform(ao_problem) print(mo_problem.basis) mo_hamil = mo_problem.hamiltonian print(mo_hamil.electronic_integrals.alpha) import numpy as np from qiskit_nature.second_q.operators import ElectronicIntegrals from qiskit_nature.second_q.problems import ElectronicBasis from qiskit_nature.second_q.transformers import BasisTransformer ao2mo_alpha = np.random.random((2, 2)) ao2mo_beta = np.random.random((2, 2)) basis_transformer = BasisTransformer( ElectronicBasis.AO, ElectronicBasis.MO, ElectronicIntegrals.from_raw_integrals(ao2mo_alpha, h1_b=ao2mo_beta), ) from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver(atom="Li 0 0 0; H 0 0 1.5") full_problem = driver.run() print(full_problem.molecule) print(full_problem.num_particles) print(full_problem.num_spatial_orbitals) from qiskit_nature.second_q.transformers import FreezeCoreTransformer fc_transformer = FreezeCoreTransformer() fc_problem = fc_transformer.transform(full_problem) print(fc_problem.num_particles) print(fc_problem.num_spatial_orbitals) print(fc_problem.hamiltonian.constants) fc_transformer = FreezeCoreTransformer(remove_orbitals=[4, 5]) fc_problem = fc_transformer.transform(full_problem) print(fc_problem.num_particles) print(fc_problem.num_spatial_orbitals) from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver(atom="Li 0 0 0; H 0 0 1.5") full_problem = driver.run() print(full_problem.num_particles) print(full_problem.num_spatial_orbitals) from qiskit_nature.second_q.transformers import ActiveSpaceTransformer as_transformer = ActiveSpaceTransformer(2, 2) as_problem = as_transformer.transform(full_problem) print(as_problem.num_particles) print(as_problem.num_spatial_orbitals) print(as_problem.hamiltonian.electronic_integrals.alpha) as_transformer = ActiveSpaceTransformer(2, 2, active_orbitals=[0, 4]) as_problem = as_transformer.transform(full_problem) print(as_problem.num_particles) print(as_problem.num_spatial_orbitals) print(as_problem.hamiltonian.electronic_integrals.alpha) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the QAOA algorithm.""" import unittest from functools import partial from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np import rustworkx as rx from ddt import ddt, idata, unpack from scipy.optimize import minimize as scipy_minimize from qiskit import QuantumCircuit from qiskit_algorithms.minimum_eigensolvers import QAOA from qiskit_algorithms.optimizers import COBYLA, NELDER_MEAD from qiskit.circuit import Parameter from qiskit.primitives import Sampler from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.result import QuasiDistribution from qiskit.utils import algorithm_globals W1 = np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) P1 = 1 M1 = SparsePauliOp.from_list( [ ("IIIX", 1), ("IIXI", 1), ("IXII", 1), ("XIII", 1), ] ) S1 = {"0101", "1010"} W2 = np.array( [ [0.0, 8.0, -9.0, 0.0], [8.0, 0.0, 7.0, 9.0], [-9.0, 7.0, 0.0, -8.0], [0.0, 9.0, -8.0, 0.0], ] ) P2 = 1 M2 = None S2 = {"1011", "0100"} CUSTOM_SUPERPOSITION = [1 / np.sqrt(15)] * 15 + [0] @ddt class TestQAOA(QiskitAlgorithmsTestCase): """Test QAOA with MaxCut.""" def setUp(self): super().setUp() self.seed = 10598 algorithm_globals.random_seed = self.seed self.sampler = Sampler() @idata( [ [W1, P1, M1, S1], [W2, P2, M2, S2], ] ) @unpack def test_qaoa(self, w, reps, mixer, solutions): """QAOA test""" self.log.debug("Testing %s-step QAOA with MaxCut on graph\n%s", reps, w) qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, COBYLA(), reps=reps, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) @idata( [ [W1, P1, S1], [W2, P2, S2], ] ) @unpack def test_qaoa_qc_mixer(self, w, prob, solutions): """QAOA test with a mixer as a parameterized circuit""" self.log.debug( "Testing %s-step QAOA with MaxCut on graph with a mixer as a parameterized circuit\n%s", prob, w, ) optimizer = COBYLA() qubit_op, _ = self._get_operator(w) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) theta = Parameter("θ") mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=prob, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) def test_qaoa_qc_mixer_many_parameters(self): """QAOA test with a mixer as a parameterized circuit with the num of parameters > 1.""" optimizer = COBYLA() qubit_op, _ = self._get_operator(W1) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) for i in range(num_qubits): theta = Parameter("θ" + str(i)) mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=2, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) self.log.debug(x) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, S1) def test_qaoa_qc_mixer_no_parameters(self): """QAOA test with a mixer as a parameterized circuit with zero parameters.""" qubit_op, _ = self._get_operator(W1) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) # just arbitrary circuit mixer.rx(np.pi / 2, range(num_qubits)) qaoa = QAOA(self.sampler, COBYLA(), reps=1, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) # we just assert that we get a result, it is not meaningful. self.assertIsNotNone(result.eigenstate) def test_change_operator_size(self): """QAOA change operator size test""" qubit_op, _ = self._get_operator( np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) ) qaoa = QAOA(self.sampler, COBYLA(), reps=1) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 4x4"): self.assertIn(graph_solution, {"0101", "1010"}) qubit_op, _ = self._get_operator( np.array( [ [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], ] ) ) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 6x6"): self.assertIn(graph_solution, {"010101", "101010"}) @idata([[W2, S2, None], [W2, S2, [0.0, 0.0]], [W2, S2, [1.0, 0.8]]]) @unpack def test_qaoa_initial_point(self, w, solutions, init_pt): """Check first parameter value used is initial point as expected""" qubit_op, _ = self._get_operator(w) first_pt = [] def cb_callback(eval_count, parameters, mean, metadata): nonlocal first_pt if eval_count == 1: first_pt = list(parameters) qaoa = QAOA( self.sampler, COBYLA(), initial_point=init_pt, callback=cb_callback, ) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest("Initial Point"): # If None the preferred random initial point of QAOA variational form if init_pt is None: self.assertLess(result.eigenvalue, -0.97) else: self.assertListEqual(init_pt, first_pt) with self.subTest("Solution"): self.assertIn(graph_solution, solutions) def test_qaoa_random_initial_point(self): """QAOA random initial point""" w = rx.adjacency_matrix( rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed) ) qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, NELDER_MEAD(disp=True), reps=2) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) self.assertLess(result.eigenvalue, -0.97) def test_optimizer_scipy_callable(self): """Test passing a SciPy optimizer directly as callable.""" w = rx.adjacency_matrix( rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed) ) qubit_op, _ = self._get_operator(w) qaoa = QAOA( self.sampler, partial(scipy_minimize, method="Nelder-Mead", options={"maxiter": 2}), ) result = qaoa.compute_minimum_eigenvalue(qubit_op) self.assertEqual(result.cost_function_evals, 5) def _get_operator(self, weight_matrix): """Generate Hamiltonian for the max-cut problem of a graph. Args: weight_matrix (numpy.ndarray) : adjacency matrix. Returns: PauliSumOp: operator for the Hamiltonian float: a constant shift for the obj function. """ num_nodes = weight_matrix.shape[0] pauli_list = [] shift = 0 for i in range(num_nodes): for j in range(i): if weight_matrix[i, j] != 0: x_p = np.zeros(num_nodes, dtype=bool) z_p = np.zeros(num_nodes, dtype=bool) z_p[i] = True z_p[j] = True pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))]) shift -= 0.5 * weight_matrix[i, j] lst = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list] return SparsePauliOp.from_list(lst), shift def _get_graph_solution(self, x: np.ndarray) -> str: """Get graph solution from binary string. Args: x : binary string as numpy array. Returns: a graph solution as string. """ return "".join([str(int(i)) for i in 1 - x]) def _sample_most_likely(self, state_vector: QuasiDistribution) -> np.ndarray: """Compute the most likely binary string from state vector. Args: state_vector: Quasi-distribution. Returns: Binary string as numpy.ndarray of ints. """ values = list(state_vector.values()) n = int(np.log2(len(values))) k = np.argmax(np.abs(values)) x = np.zeros(n) for i in range(n): x[i] = k % 2 k >>= 1 return x if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/community.qiskit.org
qiskit-community
from qiskit import QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram n = 8 n_q = 8 n_b = 8 qc_output = QuantumCircuit(n_q,n_b) for j in range(n): qc_output.measure(j,j) qc_output.draw(output='mpl') counts = execute(qc_output,Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(counts) qc_encode = QuantumCircuit(n) qc_encode.x(7) qc_encode.draw(output='mpl') qc = qc_encode + qc_output qc.draw(output='mpl',justify='none') counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(counts) qc_encode = QuantumCircuit(n) qc_encode.x(1) qc_encode.x(5) qc_encode.draw(output='mpl') qc_cnot = QuantumCircuit(2) qc_cnot.cx(0,1) qc_cnot.draw(output='mpl') qc = QuantumCircuit(2,2) qc.x(0) qc.cx(0,1) qc.measure(0,0) qc.measure(1,1) qc.draw(output='mpl') qc_ha = QuantumCircuit(4,2) # encode inputs in qubits 0 and 1 qc_ha.x(0) # For a=0, remove this line. For a=1, leave it. qc_ha.x(1) # For b=0, remove this line. For b=1, leave it. qc_ha.barrier() # use cnots to write the XOR of the inputs on qubit 2 qc_ha.cx(0,2) qc_ha.cx(1,2) qc_ha.barrier() # extract outputs qc_ha.measure(2,0) # extract XOR value qc_ha.measure(3,0) qc_ha.draw(output='mpl') qc_ha = QuantumCircuit(4,2) # encode inputs in qubits 0 and 1 qc_ha.x(0) # For a=0, remove the this line. For a=1, leave it. qc_ha.x(1) # For b=0, remove the this line. For b=1, leave it. qc_ha.barrier() # use cnots to write the XOR of the inputs on qubit 2 qc_ha.cx(0,2) qc_ha.cx(1,2) # use ccx to write the AND of the inputs on qubit 3 qc_ha.ccx(0,1,3) qc_ha.barrier() # extract outputs qc_ha.measure(2,0) # extract XOR value qc_ha.measure(3,1) # extract AND value qc_ha.draw(output='mpl') counts = execute(qc_ha,Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(counts)
https://github.com/usamisaori/quantum-expressibility-entangling-capability
usamisaori
import numpy as np import matplotlib.pyplot as plt import matplotlib.mlab as mlab from mpl_toolkits.mplot3d import Axes3D plt.rc('font',family='Microsoft YaHei') plt.rcParams['axes.unicode_minus'] = False palettes = [ "#999999", "#FFEE00", "#FF9900", "#FF3636", "#99CC33", "#66CCCC", "#3399CC", "#9966CC" ] plt.scatter(0.1, 0.1, color=palettes[0]) plt.scatter(0.2, 0.2, color=palettes[1]) plt.scatter(0.3, 0.3, color=palettes[2]) plt.scatter(0.4, 0.4, color=palettes[3]) plt.scatter(0.5, 0.5, color=palettes[4]) plt.scatter(0.6, 0.6, color=palettes[5]) plt.scatter(0.7, 0.7, color=palettes[6]) plt.scatter(0.8, 0.8, color=palettes[7]) # Expressibility Entanglement plt.figure(figsize=(8, 5)) c1 = "#FF6666" c2 = "#FF9900" c3 = "#66CCFF" # layer 1 # layer 1 qubit 3 plt.grid() plt.xticks([1, 2, 3, 4, 5, 6]) plt.ylim(0.13, 0.7) plt.title("角度编码方案与表达能力", fontsize=14) plt.xlabel("Qubit数", fontsize=13) plt.ylabel("Expr", fontsize=13) plt.scatter(3, 0.1974, color=c1, label="Rx(θ)(·)") plt.scatter(3, 0.1997, color=c2, label="Ry(θ)H(·)") plt.scatter(3, 0.1918, color=c3, label="Rz(θ)H(·)") plt.scatter(4, 0.1462, color=c1) plt.scatter(4, 0.1442, color=c2) plt.scatter(4, 0.1331, color=c3) plt.scatter(5, 0.1711, color=c1) plt.scatter(5, 0.1824, color=c2) plt.scatter(5, 0.1741, color=c3) plt.scatter(1, 0.6515, color=c1) plt.scatter(1, 0.6613, color=c2) plt.scatter(1, 0.6260, color=c3) plt.scatter(2, 0.3435, color=c1) plt.scatter(2, 0.3355, color=c2) plt.scatter(2, 0.3304, color=c3) plt.scatter(6, 0.2582, color=c1) plt.scatter(6, 0.2748, color=c2) plt.scatter(6, 0.2644, color=c3) plt.legend(loc='upper center') plt.figure(figsize=(15, 3.8)) # layer 1 # layer 1 qubit 3 ax = plt.subplot(1,3,1) plt.grid() plt.ylim(0.3, 0.8) plt.xlim(0.4, 2.4) plt.title("Quibts: 3, Layers: 1") plt.xlabel("Expr", fontsize=13) plt.ylabel("Ent", fontsize=13) plt.scatter(1.189, 0.625, color=palettes[0], label="C1") plt.scatter(0.704, 0.377, color=palettes[1], label="C2") plt.scatter(2.175, 0.702, color=palettes[2], label="C3") plt.scatter(2.352, 0.540, color=palettes[3], label="C4") plt.scatter(1.799, 0.542, color=palettes[4], label="C5") plt.scatter(2.287, 0.720, color=palettes[5], label="C6") plt.scatter(1.546, 0.338, color=palettes[6], label="C7") plt.scatter(1.905, 0.456, color=palettes[7], label="C8") ax.legend(loc='upper left', ncol=3, bbox_to_anchor=(0, 1.01)) plt.axvline(2.352, linestyle="--", color="#FF363666") plt.axvline(2.175, linestyle="--", color="#FF990066") plt.axhline(0.540, linestyle="--", color="#FF363666") plt.axhline(0.702, linestyle="--", color="#FF990066") # # layer 1 qubit 4 plt.subplot(1,3,2) plt.grid() plt.ylim(0.3, 0.8) plt.xlim(0.4, 2.4) plt.title("Quibts: 4, Layers: 1") plt.xlabel("Expr", fontsize=13) plt.scatter(1.724, 0.625, color=palettes[0]) plt.scatter(0.503, 0.375, color=palettes[1]) plt.scatter(1.881, 0.704, color=palettes[2]) plt.scatter(1.982, 0.537, color=palettes[3]) plt.scatter(1.837, 0.545, color=palettes[4]) plt.scatter(2.115, 0.721, color=palettes[5]) plt.scatter(1.219, 0.337, color=palettes[6]) plt.scatter(1.390, 0.457, color=palettes[7]) plt.axvline(1.982, linestyle="--", color="#FF363666") plt.axvline(1.881, linestyle="--", color="#FF990066") plt.axhline(0.537, linestyle="--", color="#FF363666") plt.axhline(0.704, linestyle="--", color="#FF990066") # # layer 1 qubit 5 plt.subplot(1,3,3) plt.grid() plt.ylim(0.3, 0.8) plt.xlim(0.4, 2.4) plt.title("Quibts: 5, Layers: 1") plt.xlabel("Expr", fontsize=13) plt.scatter(1.376, 0.625, color=palettes[0]) plt.scatter(0.456, 0.377, color=palettes[1]) plt.scatter(1.465, 0.703, color=palettes[2]) plt.scatter(1.557, 0.536, color=palettes[3]) plt.scatter(1.424, 0.547, color=palettes[4]) plt.scatter(2.113, 0.722, color=palettes[5]) plt.scatter(0.942, 0.339, color=palettes[6]) plt.scatter(1.152, 0.456, color=palettes[7]) plt.axvline(1.557, linestyle="--", color="#FF363666") plt.axvline(1.465, linestyle="--", color="#FF990066") plt.axhline(0.536, linestyle="--", color="#FF363666") plt.axhline(0.703, linestyle="--", color="#FF990066") def depth(circuit_type, n, L): if circuit_type == 1: return (2 * n + 1) * L elif circuit_type >= 2 and circuit_type <= 4: return (n + 1) * L + 1 elif circuit_type == 5: return (2 + n + n // np.gcd(n, 3)) * L elif circuit_type == 6: return (n ** 2 - n + 4) * L elif circuit_type == 7: return 6 * L elif circuit_type == 8: return (n + 2) * L colors2 = ['#FFCC33', '#FF9900', '#FF9966', '#FF6666', '#CC3333'] colors = ['#99CCFF', '#66CCFF', '#0088CC', '#6666FF', '#0000FF'] types = ['o', '^', ',', 'p', 'X'] plt.grid() plt.title("线路深度同量子比特数量关系") plt.xlabel("线路类型", fontsize=13) plt.ylabel("线路深度", fontsize=13) for n in range(2, 7): for ct in range(1, 9): if ct == 1: plt.scatter(ct, depth(ct, n, 1), color=colors[n - 2], marker=types[n - 2], label=f"n={n}, L=1") else: plt.scatter(ct, depth(ct, n, 1), color=colors[n - 2], marker=types[n - 2]) for n in range(2, 7): for ct in range(1, 9): if ct == 1: plt.scatter(ct, depth(ct, n, 3), color=colors2[n - 2], marker=types[n - 2], label=f"n={n}, L=3") else: plt.scatter(ct, depth(ct, n, 3), color=colors2[n - 2], marker=types[n - 2]) plt.axhline(22, 0, 8, linestyle="--", color="#CC6666") plt.legend() plt.figure(figsize=(7, 5)) # layer 1 # layer 1 qubit 3 plt.grid() plt.ylim(0.4, 0.6) plt.xlim(1, 1.7) plt.title("原始线路与丢弃处理后线路的可表达性与纠缠能力", fontsize=13) plt.xlabel("Expr", fontsize=13) plt.ylabel("Ent", fontsize=13) plt.scatter(1.6105, 0.5622, color="#FF9966", label="原始线路") plt.scatter(1.4415, 0.5158, color="#FF6666", label="纠缠丢弃") plt.scatter(1.1185, 0.4283, color="#3399CC", label="旋转丢弃") plt.legend(loc='upper left')
https://github.com/rochisha0/stock-picking
rochisha0
from qiskit.finance.data_providers import RandomDataProvider import numpy as np import matplotlib.pyplot as plt import datetime import pandas as pd from nsepy import get_history from docplex.mp.model import Model from qiskit.optimization import QuadraticProgram from qiskit.optimization.converters import LinearEqualityToPenalty from qiskit.aqua.algorithms import NumPyMinimumEigensolver import pennylane as qml num_assets = 3 # Generate expected return and covariance matrix from (random) time-series stocks = [("TICKER%s" % i) for i in range(num_assets)] data = RandomDataProvider(tickers=stocks, start=datetime.datetime(2016,1,1), end=datetime.datetime(2016,1,30)) data.run() mu = data.get_period_return_mean_vector() sigma = data.get_period_return_covariance_matrix() q = 0.5 # set risk factor budget = 2 # set budget penalty = num_assets # set parameter to scale the budget penalty term mdl = Model('docplex model') x = mdl.binary_var_list(num_assets) # set objective function: # # maximize { mu^T * x - q * x^T * sigma * x } # objective = mdl.sum([mu[i] * x[i] for i in range(num_assets)]) # mu^T * x objective -= q * mdl.sum([sigma[i][j]*x[i]*x[j] for i in range(num_assets) for j in range(num_assets)]) mdl.maximize(objective) # add budget constraint: # # 1^T * x == budget # cost = mdl.sum([x[i] for i in range(num_assets)]) mdl.add_constraint(cost == budget, ctname='budget') # converting to Quadratic Program mod = QuadraticProgram() mod.from_docplex(mdl) #removing the constraint to create the QUBO lineq2penalty = LinearEqualityToPenalty(penalty) qubo = lineq2penalty.convert(mod) #converting QUBO to an Ising Hamiltonian H, offset = qubo.to_ising() H.num_qubits H = H.to_legacy_op() H.print_details() def ansatz(theta): qml.RX(theta[0], wires=0) qml.RX(theta[1], wires=1) qml.RX(theta[2], wires=2) qml.CNOT(wires=[0,1]) qml.CNOT(wires=[0,2]) qml.CNOT(wires=[1,2]) qml.RX(theta[3], wires=0) qml.RX(theta[4], wires=1) qml.RX(theta[5], wires=2) qml.CNOT(wires=[0,1]) qml.CNOT(wires=[0,2]) qml.CNOT(wires=[1,2]) qml.RX(theta[6], wires=0) qml.RX(theta[7], wires=1) qml.RX(theta[8], wires=2) return ansatz dev1 = qml.device("default.qubit", wires=3) @qml.qnode(dev1) def circuit_IIZ(params): ansatz(params) return qml.expval(qml.Identity(0)@qml.Identity(1)@qml.PauliZ(2)) @qml.qnode(dev1) def circuit_IZI(params): ansatz(params) return qml.expval(qml.Identity(0)@qml.PauliZ(1)@qml.Identity(2)) @qml.qnode(dev1) def circuit_ZII(params): ansatz(params) return qml.expval(qml.PauliZ(0)@qml.Identity(1)@qml.Identity(2)) @qml.qnode(dev1) def circuit_IZZ(params): ansatz(params) return qml.expval(qml.Identity(0)@qml.PauliZ(1)@qml.PauliZ(2)) @qml.qnode(dev1) def circuit_ZIZ(params): ansatz(params) return qml.expval(qml.PauliZ(0)@qml.Identity(1)@qml.PauliZ(2)) @qml.qnode(dev1) def circuit_ZZI(params): ansatz(params) return qml.expval(qml.PauliZ(0)@qml.PauliZ(1)@qml.Identity(2)) def pauli_operator_to_dict(pauli_operator): d = pauli_operator.to_dict() paulis = d['paulis'] paulis_dict = {} for x in paulis: label = x['label'] coeff = x['coeff']['real'] paulis_dict[label] = coeff return paulis_dict pauli_dict = pauli_operator_to_dict(H) def vqe(parameters): expval_ZII = pauli_dict['ZII'] * circuit_ZII(parameters) expval_IIZ = pauli_dict['IIZ'] * circuit_IIZ(parameters) expval_IZI = pauli_dict['IZI'] * circuit_IZI(parameters) expval_ZZI = pauli_dict['ZZI'] * circuit_ZZI(parameters) expval_ZIZ = pauli_dict['ZIZ'] * circuit_ZIZ(parameters) expval_IZZ = pauli_dict['IZZ'] * circuit_IZZ(parameters) # summing the measurement results classical_adder = expval_ZII + expval_IIZ + expval_ZIZ + expval_ZZI + expval_ZIZ + expval_IZZ return classical_adder opt = qml.GradientDescentOptimizer(stepsize=0.5) value = [] # optimize parameters in objective params = np.random.rand(9) steps = 200 for i in range(steps): params = opt.step(vqe, params) value.append(vqe(params)) plt.plot(value) @qml.qnode(dev1) def final_circ(params): ansatz(params) return qml.probs(wires=[0,1,2]) params plt.bar(['000', '001', '010', '011', '100', '101', '110', '111'], final_circ(params)) from qiskit.optimization.applications.ising.common import sample_most_likely exact_eigensolver = NumPyMinimumEigensolver(H) result = exact_eigensolver.run() sample_most_likely(result.eigenstate) pauli_dict H.print_details()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ResourceEstimation pass testing""" import unittest from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler import PassManager from qiskit.transpiler.passes import ResourceEstimation from qiskit.test import QiskitTestCase class TestResourceEstimationPass(QiskitTestCase): """Tests for PropertySet methods.""" def test_empty_dag(self): """Empty DAG.""" circuit = QuantumCircuit() passmanager = PassManager() passmanager.append(ResourceEstimation()) passmanager.run(circuit) self.assertEqual(passmanager.property_set["size"], 0) self.assertEqual(passmanager.property_set["depth"], 0) self.assertEqual(passmanager.property_set["width"], 0) self.assertDictEqual(passmanager.property_set["count_ops"], {}) def test_just_qubits(self): """A dag with 8 operations and no classic bits""" qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[1], qr[0]) passmanager = PassManager() passmanager.append(ResourceEstimation()) passmanager.run(circuit) self.assertEqual(passmanager.property_set["size"], 8) self.assertEqual(passmanager.property_set["depth"], 7) self.assertEqual(passmanager.property_set["width"], 2) self.assertDictEqual(passmanager.property_set["count_ops"], {"cx": 6, "h": 2}) if __name__ == "__main__": unittest.main()
https://github.com/IBMSystemsCenterMontpellier/Qiskit-Tips-and-Tricks
IBMSystemsCenterMontpellier
# Set up imports, IBMQ account, and backend from qiskit import QuantumCircuit, execute, IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_qasm_simulator') # Create 2 circuits circuit_1 = QuantumCircuit(2, 2) circuit_1.h(0) circuit_1.cx(0, 1) circuit_1.measure([0, 1], [0, 1]) circuit_2 = QuantumCircuit(2, 2) circuit_2.h(1) circuit_2.cx(1, 0) circuit_2.measure([0, 1], [0, 1]) # Submit a job for each circuit job_1 = execute(circuit_1, backend) job_2 = execute(circuit_2, backend) print("Job 1: {}".format(job_1.result().get_counts(circuit_1))) print("Job 2: {}".format(job_2.result().get_counts(circuit_2))) # Set up imports, IBMQ account, and backend from qiskit import QuantumCircuit, execute, IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_qasm_simulator') circuit_list = [] # This will be what we send with our job # Create 2 circuits circuit_1 = QuantumCircuit(2, 2) circuit_1.h(0) circuit_1.cx(0, 1) circuit_1.measure([0, 1], [0, 1]) circuit_2 = QuantumCircuit(2, 2) circuit_2.h(1) circuit_2.cx(1, 0) circuit_2.measure([0, 1], [0, 1]) # Add both circuits to the list circuit_list.append(circuit_1) circuit_list.append(circuit_2) # Submit a single job that contains both circuits job = execute(circuit_list, backend) results = job.result() # Option 1: Use the circuit name circuit_1_counts = results.get_counts(circuit_1) circuit_2_counts = results.get_counts(circuit_2) print("Circuit 1 using circuit name: {}".format(circuit_1_counts)) print("Circuit 2 using circuit name: {}".format(circuit_2_counts)) # Option 2: Use the list index circuit_1_counts = results.get_counts(circuit_list[0]) circuit_2_counts = results.get_counts(circuit_list[1]) print("Circuit 1 using list index: {}".format(circuit_1_counts)) print("Circuit 2 using list index: {}".format(circuit_2_counts)) import time circuit_list = [] total_time_taken_individual = 0 # This will be the total runtime for the individual job method total_execution_time_individual = 0 # This will be the total execution time for the individual job method for __ in range(5): # Create a new circuit qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) # Add the circuit to circuit_list circuit_list.append(qc) # Execute the circuit in its own individual job and get total time taken start_time = time.time() job_individual = execute(qc, backend) if job_individual.result(): # Once job has finished executing get end time end_time = time.time() total_time_taken_individual += (end_time - start_time) # Retrieve time_taken executing and add to total time taken total_execution_time_individual += job_individual.result().time_taken # Create single job and execute, and get total time taken start_time = time.time() job_bundled = execute(circuit_list, backend) if job_bundled.result(): # Once job has finished executing get end time end_time = time.time() total_time_taken_bundled = (end_time - start_time) total_execution_time_bundled = job_bundled.result().time_taken # Compare execution time and total time taken between the two methods. Round to 5 decimal places. print("Total execution time with individual jobs: {} seconds".format(round(total_execution_time_individual, 5))) print("Total execution time with a single job: {} seconds".format(round(total_execution_time_bundled, 5))) print("Total time taken with individual jobs: {} seconds".format(round(total_time_taken_individual, 5))) print("Total time taken with a single job: {} seconds".format(round(total_time_taken_bundled, 5)))
https://github.com/JamesTheZhang/Qiskit2023
JamesTheZhang
######################################## # ENTER YOUR NAME AND WISC EMAIL HERE: # ######################################## # Name: Rochelle Li # Email: rli484@wisc.edu ## Run this cell to make sure your grader is setup correctly %set_env QC_GRADE_ONLY=true %set_env QC_GRADING_ENDPOINT=https://qac-grading.quantum-computing.ibm.com from qiskit import QuantumCircuit from qiskit.circuit import QuantumRegister, ClassicalRegister qr = QuantumRegister(1) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) # unpack the qubit and classical bits from the registers (q0,) = qr b0, b1 = cr # apply Hadamard qc.h(q0) # measure qc.measure(q0, b0) # begin if test block. the contents of the block are executed if b0 == 1 with qc.if_test((b0, 1)): # if the condition is satisfied (b0 == 1), then flip the bit back to 0 qc.x(q0) # finally, measure q0 again qc.measure(q0, b1) qc.draw(output="mpl", idle_wires=False) from qiskit_aer import AerSimulator # initialize the simulator backend_sim = AerSimulator() # run the circuit reset_sim_job = backend_sim.run(qc) # get the results reset_sim_result = reset_sim_job.result() # retrieve the bitstring counts reset_sim_counts = reset_sim_result.get_counts() print(f"Counts: {reset_sim_counts}") from qiskit.visualization import * # plot histogram plot_histogram(reset_sim_counts) qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) q0, q1 = qr b0, b1 = cr qc.h(q0) qc.measure(q0, b0) ## Write your code below this line ## with qc.if_test((b0, 0)) as else_: qc.x(1) with else_: qc.h(1) ## Do not change the code below this line ## qc.measure(q1, b1) qc.draw(output="mpl", idle_wires=False) backend_sim = AerSimulator() job_1 = backend_sim.run(qc) result_1 = job_1.result() counts_1 = result_1.get_counts() print(f"Counts: {counts_1}") # Grader Cell: Run this to submit your answer from qc_grader.challenges.fall_fest23 import grade_ex3b grade_ex3b(qc) controls = QuantumRegister(2, name="control") target = QuantumRegister(1, name="target") mid_measure = ClassicalRegister(2, name="mid") final_measure = ClassicalRegister(1, name="final") base = QuantumCircuit(controls, target, mid_measure, final_measure) def trial( circuit: QuantumCircuit, target: QuantumRegister, controls: QuantumRegister, measures: ClassicalRegister, ): """Probabilistically perform Rx(theta) on the target, where cos(theta) = 3/5.""" ## Write your code below this line, making sure it's indented to where this comment begins from ## c0,c1 = controls (t0,) = target b0, b1 = mid_measure circuit.h(c0) circuit.h(c1) circuit.h(t0) circuit.ccx(c0, c1, t0) circuit.s(t0) circuit.ccx(c0, c1, t0) circuit.h(c0) circuit.h(c1) circuit.h(t0) circuit.measure(c0, b0) circuit.measure(c1, b1) ## Do not change the code below this line ## qc = base.copy_empty_like() trial(qc, target, controls, mid_measure) qc.draw("mpl", cregbundle=False) # Grader Cell: Run this to submit your answer from qc_grader.challenges.fall_fest23 import grade_ex3c grade_ex3c(qc) def reset_controls( circuit: QuantumCircuit, controls: QuantumRegister, measures: ClassicalRegister ): """Reset the control qubits if they are in |1>.""" ## Write your code below this line, making sure it's indented to where this comment begins from ## c0, c1 = controls r0, r1 = measures # circuit.h(c0) # circuit.h(c1) # circuit.measure(c0, r0) # circuit.measure(c1, r1) with circuit.if_test((r0, 1)): circuit.x(c0) with circuit.if_test((r1, 1)): circuit.x(c1) ## Do not change the code below this line ## qc = base.copy_empty_like() trial(qc, target, controls, mid_measure) reset_controls(qc, controls, mid_measure) qc.measure(controls, mid_measure) qc.draw("mpl", cregbundle=False) # Grader Cell: Run this to submit your answer from qc_grader.challenges.fall_fest23 import grade_ex3d grade_ex3d(qc) # Set the maximum number of trials max_trials = 2 # Create a clean circuit with the same structure (bits, registers, etc) as the initial base we set up. circuit = base.copy_empty_like() # The first trial does not need to reset its inputs, since the controls are guaranteed to start in the |0> state. trial(circuit, target, controls, mid_measure) # Manually add the rest of the trials. In the future, we will be able to use a dynamic `while` loop to do this, but for now, # we statically add each loop iteration with a manual condition check on each one. # This involves more classical synchronizations than the while loop, but will suffice for now. for _ in range(max_trials - 1): reset_controls(circuit, controls, mid_measure) with circuit.if_test((mid_measure, 0b00)) as else_: # This is the success path, but Qiskit can't directly # represent a negative condition yet, so we have an # empty `true` block in order to use the `else` branch. pass with else_: ## Write your code below this line, making sure it's indented to where this comment begins from ## # (t0,) = target circuit.x(2) trial(circuit, target, controls, mid_measure) ## Do not change the code below this line ## # We need to measure the control qubits again to ensure we get their final results; this is a hardware limitation. circuit.measure(controls, mid_measure) # Finally, let's measure our target, to check that we're getting the rotation we desired. circuit.measure(target, final_measure) circuit.draw("mpl", cregbundle=False) # Grader Cell: Run this to submit your answer from qc_grader.challenges.fall_fest23 import grade_ex3e grade_ex3e(circuit) sim = AerSimulator() job = sim.run(circuit, shots=1000) result = job.result() counts = result.get_counts() plot_histogram(counts)
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
# transpile_parallel.py from qiskit import QuantumCircuit from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_transpiler_service.transpiler_service import TranspilerService from qiskit_serverless import get_arguments, save_result, distribute_task, get from qiskit_ibm_runtime import QiskitRuntimeService from timeit import default_timer as timer @distribute_task(target={"cpu": 2}) def transpile_parallel(circuit: QuantumCircuit, config): """Distributed transpilation for an abstract circuit into an ISA circuit for a given backend.""" transpiled_circuit = config.run(circuit) return transpiled_circuit # Get program arguments arguments = get_arguments() circuits = arguments.get("circuits") backend_name = arguments.get("backend_name") # Get backend service = QiskitRuntimeService(channel="ibm_quantum") backend = service.get_backend(backend_name) # Define Configs optimization_levels = [1,2,3] pass_managers = [generate_preset_pass_manager(optimization_level=level, backend=backend) for level in optimization_levels] transpiler_services = [ {'service': TranspilerService(backend_name="ibm_brisbane", ai="false", optimization_level=3,), 'ai': False, 'optimization_level': 3}, {'service': TranspilerService(backend_name="ibm_brisbane", ai="false", optimization_level=3,), 'ai': True, 'optimization_level': 3} ] configs = pass_managers + transpiler_services # Start process print("Starting timer") start = timer() # run distributed tasks as async function # we get task references as a return type sample_task_references = [] for circuit in circuits: sample_task_references.append([transpile_parallel(circuit, config) for config in configs]) # now we need to collect results from task references results = get([task for subtasks in sample_task_references for task in subtasks]) end = timer() # Record execution time execution_time_serverless = end-start print("Execution time: ", execution_time_serverless) save_result({ "transpiled_circuits": results, "execution_time" : execution_time_serverless })
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """The n-local circuit class.""" from __future__ import annotations import typing from collections.abc import Callable, Mapping, Sequence from itertools import combinations import numpy from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.quantumregister import QuantumRegister from qiskit.circuit import Instruction, Parameter, ParameterVector, ParameterExpression from qiskit.exceptions import QiskitError from ..blueprintcircuit import BlueprintCircuit if typing.TYPE_CHECKING: import qiskit # pylint: disable=cyclic-import class NLocal(BlueprintCircuit): """The n-local circuit class. The structure of the n-local circuit are alternating rotation and entanglement layers. In both layers, parameterized circuit-blocks act on the circuit in a defined way. In the rotation layer, the blocks are applied stacked on top of each other, while in the entanglement layer according to the ``entanglement`` strategy. The circuit blocks can have arbitrary sizes (smaller equal to the number of qubits in the circuit). Each layer is repeated ``reps`` times, and by default a final rotation layer is appended. For instance, a rotation block on 2 qubits and an entanglement block on 4 qubits using ``'linear'`` entanglement yields the following circuit. .. parsed-literal:: ┌──────┐ ░ ┌──────┐ ░ ┌──────┐ ┤0 ├─░─┤0 ├──────────────── ... ─░─┤0 ├ │ Rot │ ░ │ │┌──────┐ ░ │ Rot │ ┤1 ├─░─┤1 ├┤0 ├──────── ... ─░─┤1 ├ ├──────┤ ░ │ Ent ││ │┌──────┐ ░ ├──────┤ ┤0 ├─░─┤2 ├┤1 ├┤0 ├ ... ─░─┤0 ├ │ Rot │ ░ │ ││ Ent ││ │ ░ │ Rot │ ┤1 ├─░─┤3 ├┤2 ├┤1 ├ ... ─░─┤1 ├ ├──────┤ ░ └──────┘│ ││ Ent │ ░ ├──────┤ ┤0 ├─░─────────┤3 ├┤2 ├ ... ─░─┤0 ├ │ Rot │ ░ └──────┘│ │ ░ │ Rot │ ┤1 ├─░─────────────────┤3 ├ ... ─░─┤1 ├ └──────┘ ░ └──────┘ ░ └──────┘ | | +---------------------------------+ repeated reps times If specified, barriers can be inserted in between every block. If an initial state object is provided, it is added in front of the NLocal. """ def __init__( self, num_qubits: int | None = None, rotation_blocks: QuantumCircuit | list[QuantumCircuit] | qiskit.circuit.Instruction | list[qiskit.circuit.Instruction] | None = None, entanglement_blocks: QuantumCircuit | list[QuantumCircuit] | qiskit.circuit.Instruction | list[qiskit.circuit.Instruction] | None = None, entanglement: list[int] | list[list[int]] | None = None, reps: int = 1, insert_barriers: bool = False, parameter_prefix: str = "θ", overwrite_block_parameters: bool | list[list[Parameter]] = True, skip_final_rotation_layer: bool = False, skip_unentangled_qubits: bool = False, initial_state: QuantumCircuit | None = None, name: str | None = "nlocal", flatten: bool | None = None, ) -> None: """ Args: num_qubits: The number of qubits of the circuit. rotation_blocks: The blocks used in the rotation layers. If multiple are passed, these will be applied one after another (like new sub-layers). entanglement_blocks: The blocks used in the entanglement layers. If multiple are passed, these will be applied one after another. To use different entanglements for the sub-layers, see :meth:`get_entangler_map`. entanglement: The indices specifying on which qubits the input blocks act. If ``None``, the entanglement blocks are applied at the top of the circuit. reps: Specifies how often the rotation blocks and entanglement blocks are repeated. insert_barriers: If ``True``, barriers are inserted in between each layer. If ``False``, no barriers are inserted. parameter_prefix: The prefix used if default parameters are generated. overwrite_block_parameters: If the parameters in the added blocks should be overwritten. If ``False``, the parameters in the blocks are not changed. skip_final_rotation_layer: Whether a final rotation layer is added to the circuit. skip_unentangled_qubits: If ``True``, the rotation gates act only on qubits that are entangled. If ``False``, the rotation gates act on all qubits. initial_state: A :class:`.QuantumCircuit` object which can be used to describe an initial state prepended to the NLocal circuit. name: The name of the circuit. flatten: Set this to ``True`` to output a flat circuit instead of nesting it inside multiple layers of gate objects. By default currently the contents of the output circuit will be wrapped in nested objects for cleaner visualization. However, if you're using this circuit for anything besides visualization its **strongly** recommended to set this flag to ``True`` to avoid a large performance overhead for parameter binding. Raises: ValueError: If ``reps`` parameter is less than or equal to 0. TypeError: If ``reps`` parameter is not an int value. """ super().__init__(name=name) self._num_qubits: int | None = None self._insert_barriers = insert_barriers self._reps = reps self._entanglement_blocks: list[QuantumCircuit] = [] self._rotation_blocks: list[QuantumCircuit] = [] self._prepended_blocks: list[QuantumCircuit] = [] self._prepended_entanglement: list[list[list[int]] | str] = [] self._appended_blocks: list[QuantumCircuit] = [] self._appended_entanglement: list[list[list[int]] | str] = [] self._entanglement = None self._entangler_maps = None self._ordered_parameters: ParameterVector | list[Parameter] = ParameterVector( name=parameter_prefix ) self._overwrite_block_parameters = overwrite_block_parameters self._skip_final_rotation_layer = skip_final_rotation_layer self._skip_unentangled_qubits = skip_unentangled_qubits self._initial_state: QuantumCircuit | None = None self._initial_state_circuit: QuantumCircuit | None = None self._bounds: list[tuple[float | None, float | None]] | None = None self._flatten = flatten if int(reps) != reps: raise TypeError("The value of reps should be int") if reps < 0: raise ValueError("The value of reps should be larger than or equal to 0") if num_qubits is not None: self.num_qubits = num_qubits if entanglement_blocks is not None: self.entanglement_blocks = entanglement_blocks if rotation_blocks is not None: self.rotation_blocks = rotation_blocks if entanglement is not None: self.entanglement = entanglement if initial_state is not None: self.initial_state = initial_state @property def num_qubits(self) -> int: """Returns the number of qubits in this circuit. Returns: The number of qubits. """ return self._num_qubits if self._num_qubits is not None else 0 @num_qubits.setter def num_qubits(self, num_qubits: int) -> None: """Set the number of qubits for the n-local circuit. Args: The new number of qubits. """ if self._num_qubits != num_qubits: # invalidate the circuit self._invalidate() self._num_qubits = num_qubits self.qregs = [QuantumRegister(num_qubits, name="q")] @property def flatten(self) -> bool: """Returns whether the circuit is wrapped in nested gates/instructions or flattened.""" return bool(self._flatten) @flatten.setter def flatten(self, flatten: bool) -> None: self._invalidate() self._flatten = flatten def _convert_to_block(self, layer: typing.Any) -> QuantumCircuit: """Try to convert ``layer`` to a QuantumCircuit. Args: layer: The object to be converted to an NLocal block / Instruction. Returns: The layer converted to a circuit. Raises: TypeError: If the input cannot be converted to a circuit. """ if isinstance(layer, QuantumCircuit): return layer if isinstance(layer, Instruction): circuit = QuantumCircuit(layer.num_qubits) circuit.append(layer, list(range(layer.num_qubits))) return circuit try: circuit = QuantumCircuit(layer.num_qubits) circuit.append(layer.to_instruction(), list(range(layer.num_qubits))) return circuit except AttributeError: pass raise TypeError(f"Adding a {type(layer)} to an NLocal is not supported.") @property def rotation_blocks(self) -> list[QuantumCircuit]: """The blocks in the rotation layers. Returns: The blocks in the rotation layers. """ return self._rotation_blocks @rotation_blocks.setter def rotation_blocks( self, blocks: QuantumCircuit | list[QuantumCircuit] | Instruction | list[Instruction] ) -> None: """Set the blocks in the rotation layers. Args: blocks: The new blocks for the rotation layers. """ # cannot check for the attribute ``'__len__'`` because a circuit also has this attribute if not isinstance(blocks, (list, numpy.ndarray)): blocks = [blocks] self._invalidate() self._rotation_blocks = [self._convert_to_block(block) for block in blocks] @property def entanglement_blocks(self) -> list[QuantumCircuit]: """The blocks in the entanglement layers. Returns: The blocks in the entanglement layers. """ return self._entanglement_blocks @entanglement_blocks.setter def entanglement_blocks( self, blocks: QuantumCircuit | list[QuantumCircuit] | Instruction | list[Instruction] ) -> None: """Set the blocks in the entanglement layers. Args: blocks: The new blocks for the entanglement layers. """ # cannot check for the attribute ``'__len__'`` because a circuit also has this attribute if not isinstance(blocks, (list, numpy.ndarray)): blocks = [blocks] self._invalidate() self._entanglement_blocks = [self._convert_to_block(block) for block in blocks] @property def entanglement( self, ) -> str | list[str] | list[list[str]] | list[int] | list[list[int]] | list[ list[list[int]] ] | list[list[list[list[int]]]] | Callable[[int], str] | Callable[[int], list[list[int]]]: """Get the entanglement strategy. Returns: The entanglement strategy, see :meth:`get_entangler_map` for more detail on how the format is interpreted. """ return self._entanglement @entanglement.setter def entanglement( self, entanglement: str | list[str] | list[list[str]] | list[int] | list[list[int]] | list[list[list[int]]] | list[list[list[list[int]]]] | Callable[[int], str] | Callable[[int], list[list[int]]] | None, ) -> None: """Set the entanglement strategy. Args: entanglement: The entanglement strategy. See :meth:`get_entangler_map` for more detail on the supported formats. """ self._invalidate() self._entanglement = entanglement @property def num_layers(self) -> int: """Return the number of layers in the n-local circuit. Returns: The number of layers in the circuit. """ return 2 * self._reps + int(not self._skip_final_rotation_layer) def _check_configuration(self, raise_on_failure: bool = True) -> bool: """Check if the configuration of the NLocal class is valid. Args: raise_on_failure: Whether to raise on failure. Returns: True, if the configuration is valid and the circuit can be constructed. Otherwise an ValueError is raised. Raises: ValueError: If the blocks are not set. ValueError: If the number of repetitions is not set. ValueError: If the qubit indices are not set. ValueError: If the number of qubit indices does not match the number of blocks. ValueError: If an index in the repetitions list exceeds the number of blocks. ValueError: If the number of repetitions does not match the number of block-wise parameters. ValueError: If a specified qubit index is larger than the (manually set) number of qubits. """ valid = True if self.num_qubits is None: valid = False if raise_on_failure: raise ValueError("No number of qubits specified.") # check no needed parameters are None if self.entanglement_blocks is None and self.rotation_blocks is None: valid = False if raise_on_failure: raise ValueError("The blocks are not set.") return valid @property def ordered_parameters(self) -> list[Parameter]: """The parameters used in the underlying circuit. This includes float values and duplicates. Examples: >>> # prepare circuit ... >>> print(nlocal) ┌───────┐┌──────────┐┌──────────┐┌──────────┐ q_0: ┤ Ry(1) ├┤ Ry(θ[1]) ├┤ Ry(θ[1]) ├┤ Ry(θ[3]) ├ └───────┘└──────────┘└──────────┘└──────────┘ >>> nlocal.parameters {Parameter(θ[1]), Parameter(θ[3])} >>> nlocal.ordered_parameters [1, Parameter(θ[1]), Parameter(θ[1]), Parameter(θ[3])] Returns: The parameters objects used in the circuit. """ if isinstance(self._ordered_parameters, ParameterVector): self._ordered_parameters.resize(self.num_parameters_settable) return list(self._ordered_parameters) return self._ordered_parameters @ordered_parameters.setter def ordered_parameters(self, parameters: ParameterVector | list[Parameter]) -> None: """Set the parameters used in the underlying circuit. Args: The parameters to be used in the underlying circuit. Raises: ValueError: If the length of ordered parameters does not match the number of parameters in the circuit and they are not a ``ParameterVector`` (which could be resized to fit the number of parameters). """ if ( not isinstance(parameters, ParameterVector) and len(parameters) != self.num_parameters_settable ): raise ValueError( "The length of ordered parameters must be equal to the number of " "settable parameters in the circuit ({}), but is {}".format( self.num_parameters_settable, len(parameters) ) ) self._ordered_parameters = parameters self._invalidate() @property def insert_barriers(self) -> bool: """If barriers are inserted in between the layers or not. Returns: ``True``, if barriers are inserted in between the layers, ``False`` if not. """ return self._insert_barriers @insert_barriers.setter def insert_barriers(self, insert_barriers: bool) -> None: """Specify whether barriers should be inserted in between the layers or not. Args: insert_barriers: If True, barriers are inserted, if False not. """ # if insert_barriers changes, we have to invalidate the circuit definition, # if it is the same as before we can leave the NLocal instance as it is if insert_barriers is not self._insert_barriers: self._invalidate() self._insert_barriers = insert_barriers def get_unentangled_qubits(self) -> set[int]: """Get the indices of unentangled qubits in a set. Returns: The unentangled qubits. """ entangled_qubits = set() for i in range(self._reps): for j, block in enumerate(self.entanglement_blocks): entangler_map = self.get_entangler_map(i, j, block.num_qubits) entangled_qubits.update([idx for indices in entangler_map for idx in indices]) unentangled_qubits = set(range(self.num_qubits)) - entangled_qubits return unentangled_qubits @property def num_parameters_settable(self) -> int: """The number of total parameters that can be set to distinct values. This does not change when the parameters are bound or exchanged for same parameters, and therefore is different from ``num_parameters`` which counts the number of unique :class:`~qiskit.circuit.Parameter` objects currently in the circuit. Returns: The number of parameters originally available in the circuit. Note: This quantity does not require the circuit to be built yet. """ num = 0 for i in range(self._reps): for j, block in enumerate(self.entanglement_blocks): entangler_map = self.get_entangler_map(i, j, block.num_qubits) num += len(entangler_map) * len(get_parameters(block)) if self._skip_unentangled_qubits: unentangled_qubits = self.get_unentangled_qubits() num_rot = 0 for block in self.rotation_blocks: block_indices = [ list(range(j * block.num_qubits, (j + 1) * block.num_qubits)) for j in range(self.num_qubits // block.num_qubits) ] if self._skip_unentangled_qubits: block_indices = [ indices for indices in block_indices if set(indices).isdisjoint(unentangled_qubits) ] num_rot += len(block_indices) * len(get_parameters(block)) num += num_rot * (self._reps + int(not self._skip_final_rotation_layer)) return num @property def reps(self) -> int: """The number of times rotation and entanglement block are repeated. Returns: The number of repetitions. """ return self._reps @reps.setter def reps(self, repetitions: int) -> None: """Set the repetitions. If the repetitions are `0`, only one rotation layer with no entanglement layers is applied (unless ``self.skip_final_rotation_layer`` is set to ``True``). Args: repetitions: The new repetitions. Raises: ValueError: If reps setter has parameter repetitions < 0. """ if repetitions < 0: raise ValueError("The repetitions should be larger than or equal to 0") if repetitions != self._reps: self._invalidate() self._reps = repetitions def print_settings(self) -> str: """Returns information about the setting. Returns: The class name and the attributes/parameters of the instance as ``str``. """ ret = f"NLocal: {self.__class__.__name__}\n" params = "" for key, value in self.__dict__.items(): if key[0] == "_": params += f"-- {key[1:]}: {value}\n" ret += f"{params}" return ret @property def preferred_init_points(self) -> list[float] | None: """The initial points for the parameters. Can be stored as initial guess in optimization. Returns: The initial values for the parameters, or None, if none have been set. """ return None # pylint: disable=too-many-return-statements def get_entangler_map( self, rep_num: int, block_num: int, num_block_qubits: int ) -> Sequence[Sequence[int]]: """Get the entangler map for in the repetition ``rep_num`` and the block ``block_num``. The entangler map for the current block is derived from the value of ``self.entanglement``. Below the different cases are listed, where ``i`` and ``j`` denote the repetition number and the block number, respectively, and ``n`` the number of qubits in the block. =================================== ======================================================== entanglement type entangler map =================================== ======================================================== ``None`` ``[[0, ..., n - 1]]`` ``str`` (e.g ``'full'``) the specified connectivity on ``n`` qubits ``List[int]`` [``entanglement``] ``List[List[int]]`` ``entanglement`` ``List[List[List[int]]]`` ``entanglement[i]`` ``List[List[List[List[int]]]]`` ``entanglement[i][j]`` ``List[str]`` the connectivity specified in ``entanglement[i]`` ``List[List[str]]`` the connectivity specified in ``entanglement[i][j]`` ``Callable[int, str]`` same as ``List[str]`` ``Callable[int, List[List[int]]]`` same as ``List[List[List[int]]]`` =================================== ======================================================== Note that all indices are to be taken modulo the length of the array they act on, i.e. no out-of-bounds index error will be raised but we re-iterate from the beginning of the list. Args: rep_num: The current repetition we are in. block_num: The block number within the entanglement layers. num_block_qubits: The number of qubits in the block. Returns: The entangler map for the current block in the current repetition. Raises: ValueError: If the value of ``entanglement`` could not be cast to a corresponding entangler map. """ i, j, n = rep_num, block_num, num_block_qubits entanglement = self._entanglement # entanglement is None if entanglement is None: return [list(range(n))] # entanglement is callable if callable(entanglement): entanglement = entanglement(i) # entanglement is str if isinstance(entanglement, str): return get_entangler_map(n, self.num_qubits, entanglement, offset=i) # check if entanglement is list of something if not isinstance(entanglement, (tuple, list)): raise ValueError(f"Invalid value of entanglement: {entanglement}") num_i = len(entanglement) # entanglement is List[str] if all(isinstance(en, str) for en in entanglement): return get_entangler_map(n, self.num_qubits, entanglement[i % num_i], offset=i) # entanglement is List[int] if all(isinstance(en, (int, numpy.integer)) for en in entanglement): return [[int(en) for en in entanglement]] # check if entanglement is List[List] if not all(isinstance(en, (tuple, list)) for en in entanglement): raise ValueError(f"Invalid value of entanglement: {entanglement}") num_j = len(entanglement[i % num_i]) # entanglement is List[List[str]] if all(isinstance(e2, str) for en in entanglement for e2 in en): return get_entangler_map( n, self.num_qubits, entanglement[i % num_i][j % num_j], offset=i ) # entanglement is List[List[int]] if all(isinstance(e2, (int, numpy.int32, numpy.int64)) for en in entanglement for e2 in en): for ind, en in enumerate(entanglement): entanglement[ind] = tuple(map(int, en)) return entanglement # check if entanglement is List[List[List]] if not all(isinstance(e2, (tuple, list)) for en in entanglement for e2 in en): raise ValueError(f"Invalid value of entanglement: {entanglement}") # entanglement is List[List[List[int]]] if all( isinstance(e3, (int, numpy.int32, numpy.int64)) for en in entanglement for e2 in en for e3 in e2 ): for en in entanglement: for ind, e2 in enumerate(en): en[ind] = tuple(map(int, e2)) return entanglement[i % num_i] # check if entanglement is List[List[List[List]]] if not all(isinstance(e3, (tuple, list)) for en in entanglement for e2 in en for e3 in e2): raise ValueError(f"Invalid value of entanglement: {entanglement}") # entanglement is List[List[List[List[int]]]] if all( isinstance(e4, (int, numpy.int32, numpy.int64)) for en in entanglement for e2 in en for e3 in e2 for e4 in e3 ): for en in entanglement: for e2 in en: for ind, e3 in enumerate(e2): e2[ind] = tuple(map(int, e3)) return entanglement[i % num_i][j % num_j] raise ValueError(f"Invalid value of entanglement: {entanglement}") @property def initial_state(self) -> QuantumCircuit: """Return the initial state that is added in front of the n-local circuit. Returns: The initial state. """ return self._initial_state @initial_state.setter def initial_state(self, initial_state: QuantumCircuit) -> None: """Set the initial state. Args: initial_state: The new initial state. Raises: ValueError: If the number of qubits has been set before and the initial state does not match the number of qubits. """ self._initial_state = initial_state self._invalidate() @property def parameter_bounds(self) -> list[tuple[float, float]] | None: """The parameter bounds for the unbound parameters in the circuit. Returns: A list of pairs indicating the bounds, as (lower, upper). None indicates an unbounded parameter in the corresponding direction. If ``None`` is returned, problem is fully unbounded. """ if not self._is_built: self._build() return self._bounds @parameter_bounds.setter def parameter_bounds(self, bounds: list[tuple[float, float]]) -> None: """Set the parameter bounds. Args: bounds: The new parameter bounds. """ self._bounds = bounds def add_layer( self, other: QuantumCircuit | qiskit.circuit.Instruction, entanglement: list[int] | str | list[list[int]] | None = None, front: bool = False, ) -> "NLocal": """Append another layer to the NLocal. Args: other: The layer to compose, can be another NLocal, an Instruction or Gate, or a QuantumCircuit. entanglement: The entanglement or qubit indices. front: If True, ``other`` is appended to the front, else to the back. Returns: self, such that chained composes are possible. Raises: TypeError: If `other` is not compatible, i.e. is no Instruction and does not have a `to_instruction` method. """ block = self._convert_to_block(other) if entanglement is None: entanglement = [list(range(block.num_qubits))] elif isinstance(entanglement, list) and not isinstance(entanglement[0], list): entanglement = [entanglement] if front: self._prepended_blocks += [block] self._prepended_entanglement += [entanglement] else: self._appended_blocks += [block] self._appended_entanglement += [entanglement] if isinstance(entanglement, list): num_qubits = 1 + max(max(indices) for indices in entanglement) if num_qubits > self.num_qubits: self._invalidate() # rebuild circuit self.num_qubits = num_qubits # modify the circuit accordingly if front is False and self._is_built: if self._insert_barriers and len(self.data) > 0: self.barrier() if isinstance(entanglement, str): entangler_map: Sequence[Sequence[int]] = get_entangler_map( block.num_qubits, self.num_qubits, entanglement ) else: entangler_map = entanglement layer = QuantumCircuit(self.num_qubits) for i in entangler_map: params = self.ordered_parameters[-len(get_parameters(block)) :] parameterized_block = self._parameterize_block(block, params=params) layer.compose(parameterized_block, i, inplace=True) self.compose(layer, inplace=True) else: # cannot prepend a block currently, just rebuild self._invalidate() return self def assign_parameters( self, parameters: Mapping[Parameter, ParameterExpression | float] | Sequence[ParameterExpression | float], inplace: bool = False, **kwargs, ) -> QuantumCircuit | None: """Assign parameters to the n-local circuit. This method also supports passing a list instead of a dictionary. If a list is passed, the list must have the same length as the number of unbound parameters in the circuit. The parameters are assigned in the order of the parameters in :meth:`ordered_parameters`. Returns: A copy of the NLocal circuit with the specified parameters. Raises: AttributeError: If the parameters are given as list and do not match the number of parameters. """ if parameters is None or len(parameters) == 0: return self if not self._is_built: self._build() return super().assign_parameters(parameters, inplace=inplace, **kwargs) def _parameterize_block( self, block, param_iter=None, rep_num=None, block_num=None, indices=None, params=None ): """Convert ``block`` to a circuit of correct width and parameterized using the iterator.""" if self._overwrite_block_parameters: # check if special parameters should be used # pylint: disable=assignment-from-none if params is None: params = self._parameter_generator(rep_num, block_num, indices) if params is None: params = [next(param_iter) for _ in range(len(get_parameters(block)))] update = dict(zip(block.parameters, params)) return block.assign_parameters(update) return block.copy() def _build_rotation_layer(self, circuit, param_iter, i): """Build a rotation layer.""" # if the unentangled qubits are skipped, compute the set of qubits that are not entangled if self._skip_unentangled_qubits: unentangled_qubits = self.get_unentangled_qubits() # iterate over all rotation blocks for j, block in enumerate(self.rotation_blocks): # create a new layer layer = QuantumCircuit(*self.qregs) # we apply the rotation gates stacked on top of each other, i.e. # if we have 4 qubits and a rotation block of width 2, we apply two instances block_indices = [ list(range(k * block.num_qubits, (k + 1) * block.num_qubits)) for k in range(self.num_qubits // block.num_qubits) ] # if unentangled qubits should not be acted on, remove all operations that # touch an unentangled qubit if self._skip_unentangled_qubits: block_indices = [ indices for indices in block_indices if set(indices).isdisjoint(unentangled_qubits) ] # apply the operations in the layer for indices in block_indices: parameterized_block = self._parameterize_block(block, param_iter, i, j, indices) layer.compose(parameterized_block, indices, inplace=True) # add the layer to the circuit circuit.compose(layer, inplace=True) def _build_entanglement_layer(self, circuit, param_iter, i): """Build an entanglement layer.""" # iterate over all entanglement blocks for j, block in enumerate(self.entanglement_blocks): # create a new layer and get the entangler map for this block layer = QuantumCircuit(*self.qregs) entangler_map = self.get_entangler_map(i, j, block.num_qubits) # apply the operations in the layer for indices in entangler_map: parameterized_block = self._parameterize_block(block, param_iter, i, j, indices) layer.compose(parameterized_block, indices, inplace=True) # add the layer to the circuit circuit.compose(layer, inplace=True) def _build_additional_layers(self, circuit, which): if which == "appended": blocks = self._appended_blocks entanglements = self._appended_entanglement elif which == "prepended": blocks = reversed(self._prepended_blocks) entanglements = reversed(self._prepended_entanglement) else: raise ValueError("`which` must be either `appended` or `prepended`.") for block, ent in zip(blocks, entanglements): layer = QuantumCircuit(*self.qregs) if isinstance(ent, str): ent = get_entangler_map(block.num_qubits, self.num_qubits, ent) for indices in ent: layer.compose(block, indices, inplace=True) circuit.compose(layer, inplace=True) def _build(self) -> None: """If not already built, build the circuit.""" if self._is_built: return super()._build() if self.num_qubits == 0: return if not self._flatten: circuit = QuantumCircuit(*self.qregs, name=self.name) else: circuit = self # use the initial state as starting circuit, if it is set if self.initial_state: circuit.compose(self.initial_state.copy(), inplace=True) param_iter = iter(self.ordered_parameters) # build the prepended layers self._build_additional_layers(circuit, "prepended") # main loop to build the entanglement and rotation layers for i in range(self.reps): # insert barrier if specified and there is a preceding layer if self._insert_barriers and (i > 0 or len(self._prepended_blocks) > 0): circuit.barrier() # build the rotation layer self._build_rotation_layer(circuit, param_iter, i) # barrier in between rotation and entanglement layer if self._insert_barriers and len(self._rotation_blocks) > 0: circuit.barrier() # build the entanglement layer self._build_entanglement_layer(circuit, param_iter, i) # add the final rotation layer if not self._skip_final_rotation_layer: if self.insert_barriers and self.reps > 0: circuit.barrier() self._build_rotation_layer(circuit, param_iter, self.reps) # add the appended layers self._build_additional_layers(circuit, "appended") # cast global phase to float if it has no free parameters if isinstance(circuit.global_phase, ParameterExpression): try: circuit.global_phase = float(circuit.global_phase) except TypeError: # expression contains free parameters pass if not self._flatten: try: block = circuit.to_gate() except QiskitError: block = circuit.to_instruction() self.append(block, self.qubits) # pylint: disable=unused-argument def _parameter_generator(self, rep: int, block: int, indices: list[int]) -> Parameter | None: """If certain blocks should use certain parameters this method can be overridden.""" return None def get_parameters(block: QuantumCircuit | Instruction) -> list[Parameter]: """Return the list of Parameters objects inside a circuit or instruction. This is required since, in a standard gate the parameters are not necessarily Parameter objects (e.g. U3Gate(0.1, 0.2, 0.3).params == [0.1, 0.2, 0.3]) and instructions and circuits do not have the same interface for parameters. """ if isinstance(block, QuantumCircuit): return list(block.parameters) else: return [p for p in block.params if isinstance(p, ParameterExpression)] def get_entangler_map( num_block_qubits: int, num_circuit_qubits: int, entanglement: str, offset: int = 0 ) -> Sequence[tuple[int, ...]]: """Get an entangler map for an arbitrary number of qubits. Args: num_block_qubits: The number of qubits of the entangling block. num_circuit_qubits: The number of qubits of the circuit. entanglement: The entanglement strategy. offset: The block offset, can be used if the entanglements differ per block. See mode ``sca`` for instance. Returns: The entangler map using mode ``entanglement`` to scatter a block of ``num_block_qubits`` qubits on ``num_circuit_qubits`` qubits. Raises: ValueError: If the entanglement mode ist not supported. """ n, m = num_circuit_qubits, num_block_qubits if m > n: raise ValueError( "The number of block qubits must be smaller or equal to the number of " "qubits in the circuit." ) if entanglement == "pairwise" and num_block_qubits > 2: raise ValueError("Pairwise entanglement is not defined for blocks with more than 2 qubits.") if entanglement == "full": return list(combinations(list(range(n)), m)) elif entanglement == "reverse_linear": # reverse linear connectivity. In the case of m=2 and the entanglement_block='cx' # then it's equivalent to 'full' entanglement reverse = [tuple(range(n - i - m, n - i)) for i in range(n - m + 1)] return reverse elif entanglement in ["linear", "circular", "sca", "pairwise"]: linear = [tuple(range(i, i + m)) for i in range(n - m + 1)] # if the number of block qubits is 1, we don't have to add the 'circular' part if entanglement == "linear" or m == 1: return linear if entanglement == "pairwise": return linear[::2] + linear[1::2] # circular equals linear plus top-bottom entanglement (if there's space for it) if n > m: circular = [tuple(range(n - m + 1, n)) + (0,)] + linear else: circular = linear if entanglement == "circular": return circular # sca is circular plus shift and reverse shifted = circular[-offset:] + circular[:-offset] if offset % 2 == 1: # if odd, reverse the qubit indices sca = [ind[::-1] for ind in shifted] else: sca = shifted return sca else: raise ValueError(f"Unsupported entanglement type: {entanglement}")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit.utils import algorithm_globals from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.applications.vertex_cover import VertexCover import networkx as nx seed = 123 algorithm_globals.random_seed = seed graph = nx.random_regular_graph(d=3, n=6, seed=seed) pos = nx.spring_layout(graph, seed=seed) prob = VertexCover(graph) prob.draw(pos=pos) qp = prob.to_quadratic_program() print(qp.prettyprint()) # Numpy Eigensolver meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver()) result = meo.solve(qp) print(result.prettyprint()) print("\nsolution:", prob.interpret(result)) prob.draw(result, pos=pos) # QAOA meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, sampler=Sampler(), optimizer=COBYLA())) result = meo.solve(qp) print(result.prettyprint()) print("\nsolution:", prob.interpret(result)) print("\ntime:", result.min_eigen_solver_result.optimizer_time) prob.draw(result, pos=pos) from qiskit_optimization.applications import Knapsack prob = Knapsack(values=[3, 4, 5, 6, 7], weights=[2, 3, 4, 5, 6], max_weight=10) qp = prob.to_quadratic_program() print(qp.prettyprint()) # Numpy Eigensolver meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver()) result = meo.solve(qp) print(result.prettyprint()) print("\nsolution:", prob.interpret(result)) # QAOA meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, sampler=Sampler(), optimizer=COBYLA())) result = meo.solve(qp) print(result.prettyprint()) print("\nsolution:", prob.interpret(result)) print("\ntime:", result.min_eigen_solver_result.optimizer_time) from qiskit_optimization.converters import QuadraticProgramToQubo # the same knapsack problem instance as in the previous section prob = Knapsack(values=[3, 4, 5, 6, 7], weights=[2, 3, 4, 5, 6], max_weight=10) qp = prob.to_quadratic_program() print(qp.prettyprint()) # intermediate QUBO form of the optimization problem conv = QuadraticProgramToQubo() qubo = conv.convert(qp) print(qubo.prettyprint()) # qubit Hamiltonian and offset op, offset = qubo.to_ising() print(f"num qubits: {op.num_qubits}, offset: {offset}\n") print(op) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.735", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) problem = driver.run() print(problem) hamiltonian = problem.hamiltonian coefficients = hamiltonian.electronic_integrals print(coefficients.alpha) second_q_op = hamiltonian.second_q_op() print(second_q_op) hamiltonian.nuclear_repulsion_energy # NOT included in the second_q_op above problem.molecule problem.reference_energy problem.num_particles problem.num_spatial_orbitals problem.basis problem.properties problem.properties.particle_number problem.properties.angular_momentum problem.properties.magnetization problem.properties.electronic_dipole_moment from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms import GroundStateEigensolver from qiskit_nature.second_q.mappers import JordanWignerMapper solver = GroundStateEigensolver( JordanWignerMapper(), NumPyMinimumEigensolver(), ) result = solver.solve(problem) print(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-alt
qiskit-community
import pytest import qiskit_alt project = qiskit_alt.project project.ensure_init() # calljulia="pyjulia" import qiskit_alt.electronic_structure Main = project.julia.Main def test_always_passes(): assert True def test_interface_lib(): assert qiskit_alt.project.julia.__name__ == 'julia' def test_import_QuantumOps(): project.simple_import("QuantumOps") assert True def test_import_ElectronicStructure(): project.simple_import("ElectronicStructure") assert True def test_import_QiskitQuantumInfo(): project.simple_import("QiskitQuantumInfo") assert True @pytest.fixture def conv_geometry(): geometry = [['H', [0., 0., 0.]], ['H', [0., 0., 0.7414]]] # geometry = [['O', [0., 0., 0.]], # ['H', [0.757, 0.586, 0.]], # ['H', [-0.757, 0.586, 0.]]] return qiskit_alt.electronic_structure.Geometry(geometry) def test_Geometry_length(conv_geometry): assert Main.length(conv_geometry) == 2 def test_Geometry_atom(conv_geometry): atom = Main.getindex(conv_geometry, 1) assert atom.coords == (0.0, 0.0, 0.0) def test_fermionic_hamiltonian(conv_geometry): fermi_op = Main.fermionic_hamiltonian(conv_geometry, "sto3g") assert Main.length(fermi_op) == 25
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeManilaV2 from qiskit import transpile from qiskit.tools.visualization import plot_histogram # Get a fake backend from the fake provider backend = FakeManilaV2() # Create a simple circuit circuit = QuantumCircuit(3) circuit.h(0) circuit.cx(0,1) circuit.cx(0,2) circuit.measure_all() circuit.draw('mpl') # Transpile the ideal circuit to a circuit that can be directly executed by the backend transpiled_circuit = transpile(circuit, backend) transpiled_circuit.draw('mpl') # Run the transpiled circuit using the simulated fake backend job = backend.run(transpiled_circuit) counts = job.result().get_counts() plot_histogram(counts)
https://github.com/Manish-Sudhir/QiskitCheck
Manish-Sudhir
import warnings from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute, Aer, transpile, IBMQ from qiskit.tools.monitor import job_monitor from qiskit.circuit.library import QFT from qiskit.visualization import plot_histogram, plot_bloch_multivector warnings.filterwarnings("ignore", category=DeprecationWarning) import numpy as np import math pi = np.pi qc2 = QuantumCircuit(2) # qc2.x(1) # qc2.h(0) # qc2.cnot(0,1) # THIS DOESNT WORK # qc2.h(0) # qc2.cnot(0,1) # qc2.h(1) # qc2.h(0) # qc2.x(0) # qc2.h(0) # qc2.cnot(0,1) # qc2.h(1) # qc2.h(0) qc2.x(0) print(qc2) backend = Aer.get_backend('aer_simulator') qc2.measure_all() job = execute(qc2, backend, shots=10000)#run the circuit 1000000 times counts = job.result().get_counts()#return the result counts print(counts) def getList(dict): return list(dict.keys()) umar = {0: [1,0], 1: [0,1]} values = getList(counts) if(len(values) == 1): print("They are not entangled") else: abStr = values[0] cdStr = values[1] print(abStr) print(cdStr) aStr = abStr[0] bStr = abStr[1] cStr = cdStr[0] dStr = cdStr[1] a = int(aStr) b = int(bStr) c = int(cStr) d = int(dStr) haha = [a,b,c,d] abArr = np.array([umar[a], umar[b]]) cdArr = np.array([umar[c], umar[d]]) print("lol") print(abArr) print(cdArr) print("jahja") tensorprod_ab= np.tensordot(abArr[0], abArr[1], axes=0) tensorprod_cd = np.tensordot(cdArr[0], cdArr[1], axes=0) print(type(tensorprod_ab)) print(tensorprod_cd) print("final") column = np.add(tensorprod_ab,tensorprod_cd) print(column) abVal = column[0] cdVal = column[1] aVal = abVal[0] bVal = abVal[1] cVal = cdVal[0] dVal = cdVal[1] if(aVal*dVal!=bVal*cVal): print("They are entangled") else: print("Not Entangled") print("first " + values[0]) print("second " + values[1]) def set_measure_x(circuit, n): for num in range(n): circuit.h(num) def measure_x(circuit, qubitIndexes): cBitIndex = 0 for index in qubitIndexes: circuit.h(index) circuit.measure(index, cBitIndex) cBitIndex+=1 return circuit def set_measure_y(circuit, n): for num in range(n): circuit.sdg(num) circuit.h(num) def qft_rotations(circuit, n): #if qubit amount is 0, then do nothing and return if n == 0: #set it to measure the x axis # set_measure_x(qc, 4) # qc.measure_all() return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) return qft_rotations(circuit, n) backend = Aer.get_backend('aer_simulator') qc = QuantumCircuit(2) qc.x(0) qc.x(1) print(qc) after = qft_rotations(qc,2)#call the recursive qft method print(after) #set it to measure the x axis after.measure_all() job = execute(after, backend, shots=1000)#run the circuit 1000000 times counts = job.result().get_counts()#return the result counts print(counts) print(max(counts, key=counts.get)) def qft_dagger(qc, n): for j in range(n): for m in range(j): qc.cp(math.pi/float(2**(j-m)), m, j) qc.h(j) qc = QuantumCircuit(2) # qc.x(0) qc.x(0) qc.x(1) qc.measure_all() print(qc) qft_dagger(qc,2)#call the recursive qft method backend = Aer.get_backend('aer_simulator') job = execute(qc, backend, shots=1000000)#run the circuit 1000000 times counts = job.result().get_counts() print(counts)#return the result counts highest = max(counts, key=counts.get) reverse = highest[::-1] print(reverse) print(type(highest)) print(str(highest)) lol3 = [0,1] yes1 = [0,0,0,0] for i in lol3: qc.x(i) yes1[i] = 1 answer = ''.join(map(str,yes1)) print(answer) if (reverse == answer): print("True") else: print("False") #OTHER QFT def qft_rotations(circuit, n): """Performs qft on the first n qubits in circuit (without swaps)""" if n == 0: # set_measure_x(qc, 3) # set_measure_y(qc,3) # qc.measure_all() return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) # At the end of our function, we call the same function again on # the next qubits (we reduced n by one earlier in the function) qft_rotations(circuit, n) # Let's see how it looks: qc = QuantumCircuit(3) qc.x(0) qc.x(2) lol= [0,0,0] print(lol) qft_rotations(qc,3) qc.measure_all() qc.draw() # set_measure_x(qc, 3) backend = Aer.get_backend('aer_simulator') job = execute(qc, backend, shots=2048) counts = job.result().get_counts() print(counts) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft(circuit, n): """QFT on the first n qubits in circuit""" qft_rotations(circuit, n) swap_registers(circuit, n) return circuit # Let's see how it looks: qc = QuantumCircuit(2) qc.x(0) qc.x(1) qft(qc,2) qc.draw() def inverse_qft(circuit, n): """Does the inverse QFT on the first n qubits in circuit""" # First we create a QFT circuit of the correct size: qft_circ = qft(QuantumCircuit(n), n) # Then we take the inverse of this circuit invqft_circ = qft_circ.inverse() # And add it to the first n qubits in our existing circuit circuit.append(invqft_circ, circuit.qubits[:n]) return circuit.decompose() # .decompose() allows us to see the individual gates nqubits = 3 number = 5 qc = QuantumCircuit(nqubits) for qubit in range(nqubits): qc.h(qubit) qc.p(number*pi/4,0) qc.p(number*pi/2,1) qc.p(number*pi,2) qc.draw() qc = inverse_qft(qc, nqubits) qc.measure_all() qc.draw() backend = Aer.get_backend('aer_simulator') shots = 2048 transpiled_qc = transpile(qc, backend, optimization_level=3) # transpiled_qc = transpile(qc, backend) job = backend.run(transpiled_qc, shots=shots) job_monitor(job) counts = job.result().get_counts() print(counts) pip install hypothesis import unittest import hypothesis.strategies as st from hypothesis import given, settings # @st.composite # def qubit_combos(draw): # qubit_string = draw(st.sampled_from(['000','001','010','011','100','101','110','111'])) # return int(qubit_string) # qubit_combos().example() @st.composite def circuit(draw): nQubits = [0,1,2,3] nQubitsLength = len(nQubits) n= draw(st.sampled_from(nQubits)) x1 = [] x1.append(n) nQubits.remove(n) m = draw(st.sampled_from(nQubits)) x1.append(m) nQubits.remove(m) # l = draw(st.sampled_from(nQubits)) # x1.append(l) # nQubits.remove(l) noOfRegisters = nQubitsLength return [x1,noOfRegisters] print(circuit().example()) # ex = circuit().example() # print(type(ex[0])) # print(type(ex[1])) # print(type(ex)) # lol = [1,2,0,4,6,0] # for i in lol: # if i == 0: # lol.remove(0) # print(lol) lol2 = [0,1] yes = [0,0,0,0] qc = QuantumCircuit(4) for i in lol2: qc.x(i) yes[i] = 1 answer = ''.join(map(str,yes)) # strings = [str(integer) for integer in yes] # a_string = "".join(strings) # an_integer = int(a_string) print (qc) # print(an_integer) print(answer) qc.measure_all() qft_dagger(qc,4) backend = Aer.get_backend('aer_simulator') job = execute(qc, backend, shots=2048) counts = job.result().get_counts() inverseOutput = max(counts, key=counts.get) print(inverseOutput) reverse = inverseOutput[::-1] print(reverse) if(reverse == answer): print("They are equal") @given(circuit()) @settings(deadline=None) def test_inverse_holds_true(xList): x1 = xList[0] noOfRegisters = xList[1] baseQubit = [0,0,0,0] qc= QuantumCircuit(noOfRegisters) for i in x1: qc.x(i) baseQubit[i] = 1 iQFT = ''.join(map(str,baseQubit)) qc.measure_all() qft_dagger(qc,noOfRegisters) backend = Aer.get_backend('aer_simulator') job = execute(qc, backend, shots=2048) counts = job.result().get_counts() inverseOutput = max(counts, key=counts.get) reverse = inverseOutput[::-1] assert(reverse == iQFT) if __name__ == "__main__": test_inverse_holds_true() _bits_types = dict() bits_template = """""" def mk_bits( nbits ): assert nbits > 0, "We don't allow Bits0" # assert nbits < 512, "We don't allow bitwidth to exceed 512." if nbits not in _bits_types: custom_exec(compile( bits_template.format(nbits), filename=f"Bits{nbits}", mode="exec" ), globals(), locals() ) return _bits_types[nbits] def custom_exec( prog, _globals, _locals ): assert _globals is not None assert _locals is not None norm_globals = _globals norm_locals = _locals if _globals is not None: norm_globals = _normalize_dict( _globals ) if _locals is not None: norm_locals = _normalize_dict( _locals ) exec( prog, norm_globals, norm_locals ) # Local may have more stuff generated by the code. # We need to put this back to the original _locals if _locals is not None: _locals.update( norm_locals ) def bits( nbits, signed=False, min_value=None, max_value=None ): BitsN = mk_bits( nbits ) if (min_value is not None or max_value is not None) and signed: raise ValueError("bits strategy currently doesn't support setting " "signedness and min/max value at the same time") if min_value is None: min_value = (-(2**(nbits-1))) if signed else 0 if max_value is None: max_value = (2**(nbits-1)-1) if signed else (2**nbits - 1) strat = st.booleans() if nbits == 1 else st.integers( min_value, max_value ) @st.composite def strategy_bits( draw ): return BitsN( draw( strat ) ) strategy_bits().example() return strategy_bits().example() bits(3).example() @st.composite def list_and_index(draw, elements=st.integers()): xs = draw(st.lists(elements, min_size=1)) i = draw(st.integers(min_value=0, max_value=len(xs) - 1)) return (xs, i) list_and_index().example()
https://github.com/quantastica/qiskit-toaster
quantastica
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the QAOA algorithm.""" import unittest from functools import partial from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np import rustworkx as rx from ddt import ddt, idata, unpack from scipy.optimize import minimize as scipy_minimize from qiskit import QuantumCircuit from qiskit_algorithms.minimum_eigensolvers import QAOA from qiskit_algorithms.optimizers import COBYLA, NELDER_MEAD from qiskit.circuit import Parameter from qiskit.primitives import Sampler from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.result import QuasiDistribution from qiskit.utils import algorithm_globals W1 = np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) P1 = 1 M1 = SparsePauliOp.from_list( [ ("IIIX", 1), ("IIXI", 1), ("IXII", 1), ("XIII", 1), ] ) S1 = {"0101", "1010"} W2 = np.array( [ [0.0, 8.0, -9.0, 0.0], [8.0, 0.0, 7.0, 9.0], [-9.0, 7.0, 0.0, -8.0], [0.0, 9.0, -8.0, 0.0], ] ) P2 = 1 M2 = None S2 = {"1011", "0100"} CUSTOM_SUPERPOSITION = [1 / np.sqrt(15)] * 15 + [0] @ddt class TestQAOA(QiskitAlgorithmsTestCase): """Test QAOA with MaxCut.""" def setUp(self): super().setUp() self.seed = 10598 algorithm_globals.random_seed = self.seed self.sampler = Sampler() @idata( [ [W1, P1, M1, S1], [W2, P2, M2, S2], ] ) @unpack def test_qaoa(self, w, reps, mixer, solutions): """QAOA test""" self.log.debug("Testing %s-step QAOA with MaxCut on graph\n%s", reps, w) qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, COBYLA(), reps=reps, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) @idata( [ [W1, P1, S1], [W2, P2, S2], ] ) @unpack def test_qaoa_qc_mixer(self, w, prob, solutions): """QAOA test with a mixer as a parameterized circuit""" self.log.debug( "Testing %s-step QAOA with MaxCut on graph with a mixer as a parameterized circuit\n%s", prob, w, ) optimizer = COBYLA() qubit_op, _ = self._get_operator(w) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) theta = Parameter("θ") mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=prob, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) def test_qaoa_qc_mixer_many_parameters(self): """QAOA test with a mixer as a parameterized circuit with the num of parameters > 1.""" optimizer = COBYLA() qubit_op, _ = self._get_operator(W1) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) for i in range(num_qubits): theta = Parameter("θ" + str(i)) mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=2, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) self.log.debug(x) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, S1) def test_qaoa_qc_mixer_no_parameters(self): """QAOA test with a mixer as a parameterized circuit with zero parameters.""" qubit_op, _ = self._get_operator(W1) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) # just arbitrary circuit mixer.rx(np.pi / 2, range(num_qubits)) qaoa = QAOA(self.sampler, COBYLA(), reps=1, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) # we just assert that we get a result, it is not meaningful. self.assertIsNotNone(result.eigenstate) def test_change_operator_size(self): """QAOA change operator size test""" qubit_op, _ = self._get_operator( np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) ) qaoa = QAOA(self.sampler, COBYLA(), reps=1) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 4x4"): self.assertIn(graph_solution, {"0101", "1010"}) qubit_op, _ = self._get_operator( np.array( [ [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], ] ) ) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 6x6"): self.assertIn(graph_solution, {"010101", "101010"}) @idata([[W2, S2, None], [W2, S2, [0.0, 0.0]], [W2, S2, [1.0, 0.8]]]) @unpack def test_qaoa_initial_point(self, w, solutions, init_pt): """Check first parameter value used is initial point as expected""" qubit_op, _ = self._get_operator(w) first_pt = [] def cb_callback(eval_count, parameters, mean, metadata): nonlocal first_pt if eval_count == 1: first_pt = list(parameters) qaoa = QAOA( self.sampler, COBYLA(), initial_point=init_pt, callback=cb_callback, ) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest("Initial Point"): # If None the preferred random initial point of QAOA variational form if init_pt is None: self.assertLess(result.eigenvalue, -0.97) else: self.assertListEqual(init_pt, first_pt) with self.subTest("Solution"): self.assertIn(graph_solution, solutions) def test_qaoa_random_initial_point(self): """QAOA random initial point""" w = rx.adjacency_matrix( rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed) ) qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, NELDER_MEAD(disp=True), reps=2) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) self.assertLess(result.eigenvalue, -0.97) def test_optimizer_scipy_callable(self): """Test passing a SciPy optimizer directly as callable.""" w = rx.adjacency_matrix( rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed) ) qubit_op, _ = self._get_operator(w) qaoa = QAOA( self.sampler, partial(scipy_minimize, method="Nelder-Mead", options={"maxiter": 2}), ) result = qaoa.compute_minimum_eigenvalue(qubit_op) self.assertEqual(result.cost_function_evals, 5) def _get_operator(self, weight_matrix): """Generate Hamiltonian for the max-cut problem of a graph. Args: weight_matrix (numpy.ndarray) : adjacency matrix. Returns: PauliSumOp: operator for the Hamiltonian float: a constant shift for the obj function. """ num_nodes = weight_matrix.shape[0] pauli_list = [] shift = 0 for i in range(num_nodes): for j in range(i): if weight_matrix[i, j] != 0: x_p = np.zeros(num_nodes, dtype=bool) z_p = np.zeros(num_nodes, dtype=bool) z_p[i] = True z_p[j] = True pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))]) shift -= 0.5 * weight_matrix[i, j] lst = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list] return SparsePauliOp.from_list(lst), shift def _get_graph_solution(self, x: np.ndarray) -> str: """Get graph solution from binary string. Args: x : binary string as numpy array. Returns: a graph solution as string. """ return "".join([str(int(i)) for i in 1 - x]) def _sample_most_likely(self, state_vector: QuasiDistribution) -> np.ndarray: """Compute the most likely binary string from state vector. Args: state_vector: Quasi-distribution. Returns: Binary string as numpy.ndarray of ints. """ values = list(state_vector.values()) n = int(np.log2(len(values))) k = np.argmax(np.abs(values)) x = np.zeros(n) for i in range(n): x[i] = k % 2 k >>= 1 return x if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. r""" .. _pulse_builder: ============= Pulse Builder ============= .. We actually want people to think of these functions as being defined within the ``qiskit.pulse`` namespace, not the submodule ``qiskit.pulse.builder``. .. currentmodule: qiskit.pulse Use the pulse builder DSL to write pulse programs with an imperative syntax. .. warning:: The pulse builder interface is still in active development. It may have breaking API changes without deprecation warnings in future releases until otherwise indicated. The pulse builder provides an imperative API for writing pulse programs with less difficulty than the :class:`~qiskit.pulse.Schedule` API. It contextually constructs a pulse schedule and then emits the schedule for execution. For example, to play a series of pulses on channels is as simple as: .. plot:: :include-source: from qiskit import pulse dc = pulse.DriveChannel d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4) with pulse.build(name='pulse_programming_in') as pulse_prog: pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3) pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4) pulse_prog.draw() To begin pulse programming we must first initialize our program builder context with :func:`build`, after which we can begin adding program statements. For example, below we write a simple program that :func:`play`\s a pulse: .. plot:: :include-source: from qiskit import execute, pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(100, 1.0), d0) pulse_prog.draw() The builder initializes a :class:`.pulse.Schedule`, ``pulse_prog`` and then begins to construct the program within the context. The output pulse schedule will survive after the context is exited and can be executed like a normal Qiskit schedule using ``qiskit.execute(pulse_prog, backend)``. Pulse programming has a simple imperative style. This leaves the programmer to worry about the raw experimental physics of pulse programming and not constructing cumbersome data structures. We can optionally pass a :class:`~qiskit.providers.Backend` to :func:`build` to enable enhanced functionality. Below, we prepare a Bell state by automatically compiling the required pulses from their gate-level representations, while simultaneously applying a long decoupling pulse to a neighboring qubit. We terminate the experiment with a measurement to observe the state we prepared. This program which mixes circuits and pulses will be automatically lowered to be run as a pulse program: .. plot:: :include-source: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse3Q # TODO: This example should use a real mock backend. backend = FakeOpenPulse3Q() d2 = pulse.DriveChannel(2) with pulse.build(backend) as bell_prep: pulse.u2(0, math.pi, 0) pulse.cx(0, 1) with pulse.build(backend) as decoupled_bell_prep_and_measure: # We call our bell state preparation schedule constructed above. with pulse.align_right(): pulse.call(bell_prep) pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2) pulse.barrier(0, 1, 2) registers = pulse.measure_all() decoupled_bell_prep_and_measure.draw() With the pulse builder we are able to blend programming on qubits and channels. While the pulse schedule is based on instructions that operate on channels, the pulse builder automatically handles the mapping from qubits to channels for you. In the example below we demonstrate some more features of the pulse builder: .. code-block:: import math from qiskit import pulse, QuantumCircuit from qiskit.pulse import library from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: # Create a pulse. gaussian_pulse = library.gaussian(10, 1.0, 2) # Get the qubit's corresponding drive channel from the backend. d0 = pulse.drive_channel(0) d1 = pulse.drive_channel(1) # Play a pulse at t=0. pulse.play(gaussian_pulse, d0) # Play another pulse directly after the previous pulse at t=10. pulse.play(gaussian_pulse, d0) # The default scheduling behavior is to schedule pulses in parallel # across channels. For example, the statement below # plays the same pulse on a different channel at t=0. pulse.play(gaussian_pulse, d1) # We also provide pulse scheduling alignment contexts. # The default alignment context is align_left. # The sequential context schedules pulse instructions sequentially in time. # This context starts at t=10 due to earlier pulses above. with pulse.align_sequential(): pulse.play(gaussian_pulse, d0) # Play another pulse after at t=20. pulse.play(gaussian_pulse, d1) # We can also nest contexts as each instruction is # contained in its local scheduling context. # The output of a child context is a context-schedule # with the internal instructions timing fixed relative to # one another. This is schedule is then called in the parent context. # Context starts at t=30. with pulse.align_left(): # Start at t=30. pulse.play(gaussian_pulse, d0) # Start at t=30. pulse.play(gaussian_pulse, d1) # Context ends at t=40. # Alignment context where all pulse instructions are # aligned to the right, ie., as late as possible. with pulse.align_right(): # Shift the phase of a pulse channel. pulse.shift_phase(math.pi, d1) # Starts at t=40. pulse.delay(100, d0) # Ends at t=140. # Starts at t=130. pulse.play(gaussian_pulse, d1) # Ends at t=140. # Acquire data for a qubit and store in a memory slot. pulse.acquire(100, 0, pulse.MemorySlot(0)) # We also support a variety of macros for common operations. # Measure all qubits. pulse.measure_all() # Delay on some qubits. # This requires knowledge of which channels belong to which qubits. # delay for 100 cycles on qubits 0 and 1. pulse.delay_qubits(100, 0, 1) # Call a quantum circuit. The pulse builder lazily constructs a quantum # circuit which is then transpiled and scheduled before inserting into # a pulse schedule. # NOTE: Quantum register indices correspond to physical qubit indices. qc = QuantumCircuit(2, 2) qc.cx(0, 1) pulse.call(qc) # Calling a small set of standard gates and decomposing to pulses is # also supported with more natural syntax. pulse.u3(0, math.pi, 0, 0) pulse.cx(0, 1) # It is also be possible to call a preexisting schedule tmp_sched = pulse.Schedule() tmp_sched += pulse.Play(gaussian_pulse, d0) pulse.call(tmp_sched) # We also support: # frequency instructions pulse.set_frequency(5.0e9, d0) # phase instructions pulse.shift_phase(0.1, d0) # offset contexts with pulse.phase_offset(math.pi, d0): pulse.play(gaussian_pulse, d0) The above is just a small taste of what is possible with the builder. See the rest of the module documentation for more information on its capabilities. .. autofunction:: build Channels ======== Methods to return the correct channels for the respective qubit indices. .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) print(d0) .. parsed-literal:: DriveChannel(0) .. autofunction:: acquire_channel .. autofunction:: control_channels .. autofunction:: drive_channel .. autofunction:: measure_channel Instructions ============ Pulse instructions are available within the builder interface. Here's an example: .. plot:: :include-source: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) a0 = pulse.acquire_channel(0) pulse.play(pulse.library.Constant(10, 1.0), d0) pulse.delay(20, d0) pulse.shift_phase(3.14/2, d0) pulse.set_phase(3.14, d0) pulse.shift_frequency(1e7, d0) pulse.set_frequency(5e9, d0) with pulse.build() as temp_sched: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0) pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0) pulse.call(temp_sched) pulse.acquire(30, a0, pulse.MemorySlot(0)) drive_sched.draw() .. autofunction:: acquire .. autofunction:: barrier .. autofunction:: call .. autofunction:: delay .. autofunction:: play .. autofunction:: reference .. autofunction:: set_frequency .. autofunction:: set_phase .. autofunction:: shift_frequency .. autofunction:: shift_phase .. autofunction:: snapshot Contexts ======== Builder aware contexts that modify the construction of a pulse program. For example an alignment context like :func:`align_right` may be used to align all pulses as late as possible in a pulse program. .. plot:: :include-source: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_right(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=80 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog.draw() .. autofunction:: align_equispaced .. autofunction:: align_func .. autofunction:: align_left .. autofunction:: align_right .. autofunction:: align_sequential .. autofunction:: circuit_scheduler_settings .. autofunction:: frequency_offset .. autofunction:: phase_offset .. autofunction:: transpiler_settings Macros ====== Macros help you add more complex functionality to your pulse program. .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as measure_sched: mem_slot = pulse.measure(0) print(mem_slot) .. parsed-literal:: MemorySlot(0) .. autofunction:: measure .. autofunction:: measure_all .. autofunction:: delay_qubits Circuit Gates ============= To use circuit level gates within your pulse program call a circuit with :func:`call`. .. warning:: These will be removed in future versions with the release of a circuit builder interface in which it will be possible to calibrate a gate in terms of pulses and use that gate in a circuit. .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as u3_sched: pulse.u3(math.pi, 0, math.pi, 0) .. autofunction:: cx .. autofunction:: u1 .. autofunction:: u2 .. autofunction:: u3 .. autofunction:: x Utilities ========= The utility functions can be used to gather attributes about the backend and modify how the program is built. .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as u3_sched: print('Number of qubits in backend: {}'.format(pulse.num_qubits())) samples = 160 print('There are {} samples in {} seconds'.format( samples, pulse.samples_to_seconds(160))) seconds = 1e-6 print('There are {} seconds in {} samples.'.format( seconds, pulse.seconds_to_samples(1e-6))) .. parsed-literal:: Number of qubits in backend: 1 There are 160 samples in 3.5555555555555554e-08 seconds There are 1e-06 seconds in 4500 samples. .. autofunction:: active_backend .. autofunction:: active_transpiler_settings .. autofunction:: active_circuit_scheduler_settings .. autofunction:: num_qubits .. autofunction:: qubit_channels .. autofunction:: samples_to_seconds .. autofunction:: seconds_to_samples """ import collections import contextvars import functools import itertools import uuid import warnings from contextlib import contextmanager from functools import singledispatchmethod from typing import ( Any, Callable, ContextManager, Dict, Iterable, List, Mapping, Optional, Set, Tuple, TypeVar, Union, NewType, ) import numpy as np from qiskit import circuit from qiskit.circuit.library import standard_gates as gates from qiskit.circuit.parameterexpression import ParameterExpression, ParameterValueType from qiskit.pulse import ( channels as chans, configuration, exceptions, instructions, macros, library, transforms, ) from qiskit.providers.backend import BackendV2 from qiskit.pulse.instructions import directives from qiskit.pulse.schedule import Schedule, ScheduleBlock from qiskit.pulse.transforms.alignments import AlignmentKind #: contextvars.ContextVar[BuilderContext]: active builder BUILDER_CONTEXTVAR = contextvars.ContextVar("backend") T = TypeVar("T") StorageLocation = NewType("StorageLocation", Union[chans.MemorySlot, chans.RegisterSlot]) def _compile_lazy_circuit_before(function: Callable[..., T]) -> Callable[..., T]: """Decorator thats schedules and calls the lazily compiled circuit before executing the decorated builder method.""" @functools.wraps(function) def wrapper(self, *args, **kwargs): self._compile_lazy_circuit() return function(self, *args, **kwargs) return wrapper def _requires_backend(function: Callable[..., T]) -> Callable[..., T]: """Decorator a function to raise if it is called without a builder with a set backend. """ @functools.wraps(function) def wrapper(self, *args, **kwargs): if self.backend is None: raise exceptions.BackendNotSet( 'This function requires the builder to have a "backend" set.' ) return function(self, *args, **kwargs) return wrapper class _PulseBuilder: """Builder context class.""" __alignment_kinds__ = { "left": transforms.AlignLeft(), "right": transforms.AlignRight(), "sequential": transforms.AlignSequential(), } def __init__( self, backend=None, block: Optional[ScheduleBlock] = None, name: Optional[str] = None, default_alignment: Union[str, AlignmentKind] = "left", default_transpiler_settings: Mapping = None, default_circuit_scheduler_settings: Mapping = None, ): """Initialize the builder context. .. note:: At some point we may consider incorporating the builder into the :class:`~qiskit.pulse.Schedule` class. However, the risk of this is tying the user interface to the intermediate representation. For now we avoid this at the cost of some code duplication. Args: backend (Backend): Input backend to use in builder. If not set certain functionality will be unavailable. block: Initital ``ScheduleBlock`` to build on. name: Name of pulse program to be built. default_alignment: Default scheduling alignment for builder. One of ``left``, ``right``, ``sequential`` or an instance of :class:`~qiskit.pulse.transforms.alignments.AlignmentKind` subclass. default_transpiler_settings: Default settings for the transpiler. default_circuit_scheduler_settings: Default settings for the circuit to pulse scheduler. Raises: PulseError: When invalid ``default_alignment`` or `block` is specified. """ #: Backend: Backend instance for context builder. self._backend = backend #: Union[None, ContextVar]: Token for this ``_PulseBuilder``'s ``ContextVar``. self._backend_ctx_token = None #: QuantumCircuit: Lazily constructed quantum circuit self._lazy_circuit = None #: Dict[str, Any]: Transpiler setting dictionary. self._transpiler_settings = default_transpiler_settings or {} #: Dict[str, Any]: Scheduler setting dictionary. self._circuit_scheduler_settings = default_circuit_scheduler_settings or {} #: List[ScheduleBlock]: Stack of context. self._context_stack = [] #: str: Name of the output program self._name = name # Add root block if provided. Schedule will be built on top of this. if block is not None: if isinstance(block, ScheduleBlock): root_block = block elif isinstance(block, Schedule): root_block = self._naive_typecast_schedule(block) else: raise exceptions.PulseError( f"Input `block` type {block.__class__.__name__} is " "not a valid format. Specify a pulse program." ) self._context_stack.append(root_block) # Set default alignment context alignment = _PulseBuilder.__alignment_kinds__.get(default_alignment, default_alignment) if not isinstance(alignment, AlignmentKind): raise exceptions.PulseError( f"Given `default_alignment` {repr(default_alignment)} is " "not a valid transformation. Set one of " f'{", ".join(_PulseBuilder.__alignment_kinds__.keys())}, ' "or set an instance of `AlignmentKind` subclass." ) self.push_context(alignment) def __enter__(self) -> ScheduleBlock: """Enter this builder context and yield either the supplied schedule or the schedule created for the user. Returns: The schedule that the builder will build on. """ self._backend_ctx_token = BUILDER_CONTEXTVAR.set(self) output = self._context_stack[0] output._name = self._name or output.name return output @_compile_lazy_circuit_before def __exit__(self, exc_type, exc_val, exc_tb): """Exit the builder context and compile the built pulse program.""" self.compile() BUILDER_CONTEXTVAR.reset(self._backend_ctx_token) @property def backend(self): """Returns the builder backend if set. Returns: Optional[Backend]: The builder's backend. """ return self._backend @_compile_lazy_circuit_before def push_context(self, alignment: AlignmentKind): """Push new context to the stack.""" self._context_stack.append(ScheduleBlock(alignment_context=alignment)) @_compile_lazy_circuit_before def pop_context(self) -> ScheduleBlock: """Pop the last context from the stack.""" if len(self._context_stack) == 1: raise exceptions.PulseError("The root context cannot be popped out.") return self._context_stack.pop() def get_context(self) -> ScheduleBlock: """Get current context. Notes: New instruction can be added by `.append_subroutine` or `.append_instruction` method. Use above methods rather than directly accessing to the current context. """ return self._context_stack[-1] @property @_requires_backend def num_qubits(self): """Get the number of qubits in the backend.""" # backendV2 if isinstance(self.backend, BackendV2): return self.backend.num_qubits return self.backend.configuration().n_qubits @property def transpiler_settings(self) -> Mapping: """The builder's transpiler settings.""" return self._transpiler_settings @transpiler_settings.setter @_compile_lazy_circuit_before def transpiler_settings(self, settings: Mapping): self._compile_lazy_circuit() self._transpiler_settings = settings @property def circuit_scheduler_settings(self) -> Mapping: """The builder's circuit to pulse scheduler settings.""" return self._circuit_scheduler_settings @circuit_scheduler_settings.setter @_compile_lazy_circuit_before def circuit_scheduler_settings(self, settings: Mapping): self._compile_lazy_circuit() self._circuit_scheduler_settings = settings @_compile_lazy_circuit_before def compile(self) -> ScheduleBlock: """Compile and output the built pulse program.""" # Not much happens because we currently compile as we build. # This should be offloaded to a true compilation module # once we define a more sophisticated IR. while len(self._context_stack) > 1: current = self.pop_context() self.append_subroutine(current) return self._context_stack[0] def _compile_lazy_circuit(self): """Call a context QuantumCircuit (lazy circuit) and append the output pulse schedule to the builder's context schedule. Note that the lazy circuit is not stored as a call instruction. """ if self._lazy_circuit: lazy_circuit = self._lazy_circuit # reset lazy circuit self._lazy_circuit = self._new_circuit() self.call_subroutine(self._compile_circuit(lazy_circuit)) def _compile_circuit(self, circ) -> Schedule: """Take a QuantumCircuit and output the pulse schedule associated with the circuit.""" from qiskit import compiler # pylint: disable=cyclic-import transpiled_circuit = compiler.transpile(circ, self.backend, **self.transpiler_settings) sched = compiler.schedule( transpiled_circuit, self.backend, **self.circuit_scheduler_settings ) return sched def _new_circuit(self): """Create a new circuit for lazy circuit scheduling.""" return circuit.QuantumCircuit(self.num_qubits) @_compile_lazy_circuit_before def append_instruction(self, instruction: instructions.Instruction): """Add an instruction to the builder's context schedule. Args: instruction: Instruction to append. """ self._context_stack[-1].append(instruction) def append_reference(self, name: str, *extra_keys: str): """Add external program as a :class:`~qiskit.pulse.instructions.Reference` instruction. Args: name: Name of subroutine. extra_keys: Assistance keys to uniquely specify the subroutine. """ inst = instructions.Reference(name, *extra_keys) self.append_instruction(inst) @_compile_lazy_circuit_before def append_subroutine(self, subroutine: Union[Schedule, ScheduleBlock]): """Append a :class:`ScheduleBlock` to the builder's context schedule. This operation doesn't create a reference. Subroutine is directly appended to current context schedule. Args: subroutine: ScheduleBlock to append to the current context block. Raises: PulseError: When subroutine is not Schedule nor ScheduleBlock. """ if not isinstance(subroutine, (ScheduleBlock, Schedule)): raise exceptions.PulseError( f"'{subroutine.__class__.__name__}' is not valid data format in the builder. " "'Schedule' and 'ScheduleBlock' can be appended to the builder context." ) if len(subroutine) == 0: return if isinstance(subroutine, Schedule): subroutine = self._naive_typecast_schedule(subroutine) self._context_stack[-1].append(subroutine) @singledispatchmethod def call_subroutine( self, subroutine: Union[circuit.QuantumCircuit, Schedule, ScheduleBlock], name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): """Call a schedule or circuit defined outside of the current scope. The ``subroutine`` is appended to the context schedule as a call instruction. This logic just generates a convenient program representation in the compiler. Thus, this doesn't affect execution of inline subroutines. See :class:`~pulse.instructions.Call` for more details. Args: subroutine: Target schedule or circuit to append to the current context. name: Name of subroutine if defined. value_dict: Parameter object and assigned value mapping. This is more precise way to identify a parameter since mapping is managed with unique object id rather than name. Especially there is any name collision in a parameter table. kw_params: Parameter values to bind to the target subroutine with string parameter names. If there are parameter name overlapping, these parameters are updated with the same assigned value. Raises: PulseError: - When input subroutine is not valid data format. """ raise exceptions.PulseError( f"Subroutine type {subroutine.__class__.__name__} is " "not valid data format. Call QuantumCircuit, " "Schedule, or ScheduleBlock." ) @call_subroutine.register def _( self, target_block: ScheduleBlock, name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): if len(target_block) == 0: return # Create local parameter assignment local_assignment = {} for param_name, value in kw_params.items(): params = target_block.get_parameters(param_name) if not params: raise exceptions.PulseError( f"Parameter {param_name} is not defined in the target subroutine. " f'{", ".join(map(str, target_block.parameters))} can be specified.' ) for param in params: local_assignment[param] = value if value_dict: if local_assignment.keys() & value_dict.keys(): warnings.warn( "Some parameters provided by 'value_dict' conflict with one through " "keyword arguments. Parameter values in the keyword arguments " "are overridden by the dictionary values.", UserWarning, ) local_assignment.update(value_dict) if local_assignment: target_block = target_block.assign_parameters(local_assignment, inplace=False) if name is None: # Add unique string, not to accidentally override existing reference entry. keys = (target_block.name, uuid.uuid4().hex) else: keys = (name,) self.append_reference(*keys) self.get_context().assign_references({keys: target_block}, inplace=True) @call_subroutine.register def _( self, target_schedule: Schedule, name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): if len(target_schedule) == 0: return self.call_subroutine( self._naive_typecast_schedule(target_schedule), name=name, value_dict=value_dict, **kw_params, ) @call_subroutine.register def _( self, target_circuit: circuit.QuantumCircuit, name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): if len(target_circuit) == 0: return self._compile_lazy_circuit() self.call_subroutine( self._compile_circuit(target_circuit), name=name, value_dict=value_dict, **kw_params, ) @_requires_backend def call_gate(self, gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True): """Call the circuit ``gate`` in the pulse program. The qubits are assumed to be defined on physical qubits. If ``lazy == True`` this circuit will extend a lazily constructed quantum circuit. When an operation occurs that breaks the underlying circuit scheduling assumptions such as adding a pulse instruction or changing the alignment context the circuit will be transpiled and scheduled into pulses with the current active settings. Args: gate: Gate to call. qubits: Qubits to call gate on. lazy: If false the circuit will be transpiled and pulse scheduled immediately. Otherwise, it will extend the active lazy circuit as defined above. """ try: iter(qubits) except TypeError: qubits = (qubits,) if lazy: self._call_gate(gate, qubits) else: self._compile_lazy_circuit() self._call_gate(gate, qubits) self._compile_lazy_circuit() def _call_gate(self, gate, qargs): if self._lazy_circuit is None: self._lazy_circuit = self._new_circuit() self._lazy_circuit.append(gate, qargs=qargs) @staticmethod def _naive_typecast_schedule(schedule: Schedule): # Naively convert into ScheduleBlock from qiskit.pulse.transforms import inline_subroutines, flatten, pad preprocessed_schedule = inline_subroutines(flatten(schedule)) pad(preprocessed_schedule, inplace=True, pad_with=instructions.TimeBlockade) # default to left alignment, namely ASAP scheduling target_block = ScheduleBlock(name=schedule.name) for _, inst in preprocessed_schedule.instructions: target_block.append(inst, inplace=True) return target_block def get_dt(self): """Retrieve dt differently based on the type of Backend""" if isinstance(self.backend, BackendV2): return self.backend.dt return self.backend.configuration().dt def build( backend=None, schedule: Optional[ScheduleBlock] = None, name: Optional[str] = None, default_alignment: Optional[Union[str, AlignmentKind]] = "left", default_transpiler_settings: Optional[Dict[str, Any]] = None, default_circuit_scheduler_settings: Optional[Dict[str, Any]] = None, ) -> ContextManager[ScheduleBlock]: """Create a context manager for launching the imperative pulse builder DSL. To enter a building context and starting building a pulse program: .. code-block:: from qiskit import execute, pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(100, 0.5), d0) While the output program ``pulse_prog`` cannot be executed as we are using a mock backend. If a real backend is being used, executing the program is done with: .. code-block:: python qiskit.execute(pulse_prog, backend) Args: backend (Backend): A Qiskit backend. If not supplied certain builder functionality will be unavailable. schedule: A pulse ``ScheduleBlock`` in which your pulse program will be built. name: Name of pulse program to be built. default_alignment: Default scheduling alignment for builder. One of ``left``, ``right``, ``sequential`` or an alignment context. default_transpiler_settings: Default settings for the transpiler. default_circuit_scheduler_settings: Default settings for the circuit to pulse scheduler. Returns: A new builder context which has the active builder initialized. """ return _PulseBuilder( backend=backend, block=schedule, name=name, default_alignment=default_alignment, default_transpiler_settings=default_transpiler_settings, default_circuit_scheduler_settings=default_circuit_scheduler_settings, ) # Builder Utilities def _active_builder() -> _PulseBuilder: """Get the active builder in the active context. Returns: The active active builder in this context. Raises: exceptions.NoActiveBuilder: If a pulse builder function is called outside of a builder context. """ try: return BUILDER_CONTEXTVAR.get() except LookupError as ex: raise exceptions.NoActiveBuilder( "A Pulse builder function was called outside of " "a builder context. Try calling within a builder " 'context, eg., "with pulse.build() as schedule: ...".' ) from ex def active_backend(): """Get the backend of the currently active builder context. Returns: Backend: The active backend in the currently active builder context. Raises: exceptions.BackendNotSet: If the builder does not have a backend set. """ builder = _active_builder().backend if builder is None: raise exceptions.BackendNotSet( 'This function requires the active builder to have a "backend" set.' ) return builder def append_schedule(schedule: Union[Schedule, ScheduleBlock]): """Call a schedule by appending to the active builder's context block. Args: schedule: Schedule or ScheduleBlock to append. """ _active_builder().append_subroutine(schedule) def append_instruction(instruction: instructions.Instruction): """Append an instruction to the active builder's context schedule. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.builder.append_instruction(pulse.Delay(10, d0)) print(pulse_prog.instructions) .. parsed-literal:: ((0, Delay(10, DriveChannel(0))),) """ _active_builder().append_instruction(instruction) def num_qubits() -> int: """Return number of qubits in the currently active backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.num_qubits()) .. parsed-literal:: 2 .. note:: Requires the active builder context to have a backend set. """ if isinstance(active_backend(), BackendV2): return active_backend().num_qubits return active_backend().configuration().n_qubits def seconds_to_samples(seconds: Union[float, np.ndarray]) -> Union[int, np.ndarray]: """Obtain the number of samples that will elapse in ``seconds`` on the active backend. Rounds down. Args: seconds: Time in seconds to convert to samples. Returns: The number of samples for the time to elapse """ dt = _active_builder().get_dt() if isinstance(seconds, np.ndarray): return (seconds / dt).astype(int) return int(seconds / dt) def samples_to_seconds(samples: Union[int, np.ndarray]) -> Union[float, np.ndarray]: """Obtain the time in seconds that will elapse for the input number of samples on the active backend. Args: samples: Number of samples to convert to time in seconds. Returns: The time that elapses in ``samples``. """ return samples * _active_builder().get_dt() def qubit_channels(qubit: int) -> Set[chans.Channel]: """Returns the set of channels associated with a qubit. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.qubit_channels(0)) .. parsed-literal:: {MeasureChannel(0), ControlChannel(0), DriveChannel(0), AcquireChannel(0), ControlChannel(1)} .. note:: Requires the active builder context to have a backend set. .. note:: A channel may still be associated with another qubit in this list such as in the case where significant crosstalk exists. """ # implement as the inner function to avoid API change for a patch release in 0.24.2. def get_qubit_channels_v2(backend: BackendV2, qubit: int): r"""Return a list of channels which operate on the given ``qubit``. Returns: List of ``Channel``\s operated on my the given ``qubit``. """ channels = [] # add multi-qubit channels for node_qubits in backend.coupling_map: if qubit in node_qubits: control_channel = backend.control_channel(node_qubits) if control_channel: channels.extend(control_channel) # add single qubit channels channels.append(backend.drive_channel(qubit)) channels.append(backend.measure_channel(qubit)) channels.append(backend.acquire_channel(qubit)) return channels # backendV2 if isinstance(active_backend(), BackendV2): return set(get_qubit_channels_v2(active_backend(), qubit)) return set(active_backend().configuration().get_qubit_channels(qubit)) def _qubits_to_channels(*channels_or_qubits: Union[int, chans.Channel]) -> Set[chans.Channel]: """Returns the unique channels of the input qubits.""" channels = set() for channel_or_qubit in channels_or_qubits: if isinstance(channel_or_qubit, int): channels |= qubit_channels(channel_or_qubit) elif isinstance(channel_or_qubit, chans.Channel): channels.add(channel_or_qubit) else: raise exceptions.PulseError( f'{channel_or_qubit} is not a "Channel" or qubit (integer).' ) return channels def active_transpiler_settings() -> Dict[str, Any]: """Return the current active builder context's transpiler settings. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() transpiler_settings = {'optimization_level': 3} with pulse.build(backend, default_transpiler_settings=transpiler_settings): print(pulse.active_transpiler_settings()) .. parsed-literal:: {'optimization_level': 3} """ return dict(_active_builder().transpiler_settings) def active_circuit_scheduler_settings() -> Dict[str, Any]: """Return the current active builder context's circuit scheduler settings. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() circuit_scheduler_settings = {'method': 'alap'} with pulse.build( backend, default_circuit_scheduler_settings=circuit_scheduler_settings): print(pulse.active_circuit_scheduler_settings()) .. parsed-literal:: {'method': 'alap'} """ return dict(_active_builder().circuit_scheduler_settings) # Contexts @contextmanager def align_left() -> ContextManager[None]: """Left alignment pulse scheduling context. Pulse instructions within this context are scheduled as early as possible by shifting them left to the earliest available time. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_left(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=0 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog = pulse.transforms.block_to_schedule(pulse_prog) assert pulse_prog.ch_start_time(d0) == pulse_prog.ch_start_time(d1) Yields: None """ builder = _active_builder() builder.push_context(transforms.AlignLeft()) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_right() -> AlignmentKind: """Right alignment pulse scheduling context. Pulse instructions within this context are scheduled as late as possible by shifting them right to the latest available time. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_right(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=80 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog = pulse.transforms.block_to_schedule(pulse_prog) assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_stop_time(d1) Yields: None """ builder = _active_builder() builder.push_context(transforms.AlignRight()) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_sequential() -> AlignmentKind: """Sequential alignment pulse scheduling context. Pulse instructions within this context are scheduled sequentially in time such that no two instructions will be played at the same time. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_sequential(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will also start at t=100 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog = pulse.transforms.block_to_schedule(pulse_prog) assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_start_time(d1) Yields: None """ builder = _active_builder() builder.push_context(transforms.AlignSequential()) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_equispaced(duration: Union[int, ParameterExpression]) -> AlignmentKind: """Equispaced alignment pulse scheduling context. Pulse instructions within this context are scheduled with the same interval spacing such that the total length of the context block is ``duration``. If the total free ``duration`` cannot be evenly divided by the number of instructions within the context, the modulo is split and then prepended and appended to the returned schedule. Delay instructions are automatically inserted in between pulses. This context is convenient to write a schedule for periodical dynamic decoupling or the Hahn echo sequence. Examples: .. plot:: :include-source: from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) with pulse.build() as hahn_echo: with pulse.align_equispaced(duration=100): pulse.play(x90, d0) pulse.play(x180, d0) pulse.play(x90, d0) hahn_echo.draw() Args: duration: Duration of this context. This should be larger than the schedule duration. Yields: None Notes: The scheduling is performed for sub-schedules within the context rather than channel-wise. If you want to apply the equispaced context for each channel, you should use the context independently for channels. """ builder = _active_builder() builder.push_context(transforms.AlignEquispaced(duration=duration)) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_func( duration: Union[int, ParameterExpression], func: Callable[[int], float] ) -> AlignmentKind: """Callback defined alignment pulse scheduling context. Pulse instructions within this context are scheduled at the location specified by arbitrary callback function `position` that takes integer index and returns the associated fractional location within [0, 1]. Delay instruction is automatically inserted in between pulses. This context may be convenient to write a schedule of arbitrary dynamical decoupling sequences such as Uhrig dynamical decoupling. Examples: .. plot:: :include-source: import numpy as np from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) def udd10_pos(j): return np.sin(np.pi*j/(2*10 + 2))**2 with pulse.build() as udd_sched: pulse.play(x90, d0) with pulse.align_func(duration=300, func=udd10_pos): for _ in range(10): pulse.play(x180, d0) pulse.play(x90, d0) udd_sched.draw() Args: duration: Duration of context. This should be larger than the schedule duration. func: A function that takes an index of sub-schedule and returns the fractional coordinate of of that sub-schedule. The returned value should be defined within [0, 1]. The pulse index starts from 1. Yields: None Notes: The scheduling is performed for sub-schedules within the context rather than channel-wise. If you want to apply the numerical context for each channel, you need to apply the context independently to channels. """ builder = _active_builder() builder.push_context(transforms.AlignFunc(duration=duration, func=func)) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def general_transforms(alignment_context: AlignmentKind) -> ContextManager[None]: """Arbitrary alignment transformation defined by a subclass instance of :class:`~qiskit.pulse.transforms.alignments.AlignmentKind`. Args: alignment_context: Alignment context instance that defines schedule transformation. Yields: None Raises: PulseError: When input ``alignment_context`` is not ``AlignmentKind`` subclasses. """ if not isinstance(alignment_context, AlignmentKind): raise exceptions.PulseError("Input alignment context is not `AlignmentKind` subclass.") builder = _active_builder() builder.push_context(alignment_context) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def transpiler_settings(**settings) -> ContextManager[None]: """Set the currently active transpiler settings for this context. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.active_transpiler_settings()) with pulse.transpiler_settings(optimization_level=3): print(pulse.active_transpiler_settings()) .. parsed-literal:: {} {'optimization_level': 3} """ builder = _active_builder() curr_transpiler_settings = builder.transpiler_settings builder.transpiler_settings = collections.ChainMap(settings, curr_transpiler_settings) try: yield finally: builder.transpiler_settings = curr_transpiler_settings @contextmanager def circuit_scheduler_settings(**settings) -> ContextManager[None]: """Set the currently active circuit scheduler settings for this context. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.active_circuit_scheduler_settings()) with pulse.circuit_scheduler_settings(method='alap'): print(pulse.active_circuit_scheduler_settings()) .. parsed-literal:: {} {'method': 'alap'} """ builder = _active_builder() curr_circuit_scheduler_settings = builder.circuit_scheduler_settings builder.circuit_scheduler_settings = collections.ChainMap( settings, curr_circuit_scheduler_settings ) try: yield finally: builder.circuit_scheduler_settings = curr_circuit_scheduler_settings @contextmanager def phase_offset(phase: float, *channels: chans.PulseChannel) -> ContextManager[None]: """Shift the phase of input channels on entry into context and undo on exit. Examples: .. code-block:: import math from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: with pulse.phase_offset(math.pi, d0): pulse.play(pulse.Constant(10, 1.0), d0) assert len(pulse_prog.instructions) == 3 Args: phase: Amount of phase offset in radians. channels: Channels to offset phase of. Yields: None """ for channel in channels: shift_phase(phase, channel) try: yield finally: for channel in channels: shift_phase(-phase, channel) @contextmanager def frequency_offset( frequency: float, *channels: chans.PulseChannel, compensate_phase: bool = False ) -> ContextManager[None]: """Shift the frequency of inputs channels on entry into context and undo on exit. Examples: .. code-block:: python :emphasize-lines: 7, 16 from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build(backend) as pulse_prog: # shift frequency by 1GHz with pulse.frequency_offset(1e9, d0): pulse.play(pulse.Constant(10, 1.0), d0) assert len(pulse_prog.instructions) == 3 with pulse.build(backend) as pulse_prog: # Shift frequency by 1GHz. # Undo accumulated phase in the shifted frequency frame # when exiting the context. with pulse.frequency_offset(1e9, d0, compensate_phase=True): pulse.play(pulse.Constant(10, 1.0), d0) assert len(pulse_prog.instructions) == 4 Args: frequency: Amount of frequency offset in Hz. channels: Channels to offset frequency of. compensate_phase: Compensate for accumulated phase accumulated with respect to the channels' frame at its initial frequency. Yields: None """ builder = _active_builder() # TODO: Need proper implementation of compensation. t0 may depend on the parent context. # For example, the instruction position within the equispaced context depends on # the current total number of instructions, thus adding more instruction after # offset context may change the t0 when the parent context is transformed. t0 = builder.get_context().duration for channel in channels: shift_frequency(frequency, channel) try: yield finally: if compensate_phase: duration = builder.get_context().duration - t0 accumulated_phase = 2 * np.pi * ((duration * builder.get_dt() * frequency) % 1) for channel in channels: shift_phase(-accumulated_phase, channel) for channel in channels: shift_frequency(-frequency, channel) # Channels def drive_channel(qubit: int) -> chans.DriveChannel: """Return ``DriveChannel`` for ``qubit`` on the active builder backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.drive_channel(0) == pulse.DriveChannel(0) .. note:: Requires the active builder context to have a backend set. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().drive_channel(qubit) return active_backend().configuration().drive(qubit) def measure_channel(qubit: int) -> chans.MeasureChannel: """Return ``MeasureChannel`` for ``qubit`` on the active builder backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.measure_channel(0) == pulse.MeasureChannel(0) .. note:: Requires the active builder context to have a backend set. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().measure_channel(qubit) return active_backend().configuration().measure(qubit) def acquire_channel(qubit: int) -> chans.AcquireChannel: """Return ``AcquireChannel`` for ``qubit`` on the active builder backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.acquire_channel(0) == pulse.AcquireChannel(0) .. note:: Requires the active builder context to have a backend set. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().acquire_channel(qubit) return active_backend().configuration().acquire(qubit) def control_channels(*qubits: Iterable[int]) -> List[chans.ControlChannel]: """Return ``ControlChannel`` for ``qubit`` on the active builder backend. Return the secondary drive channel for the given qubit -- typically utilized for controlling multi-qubit interactions. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.control_channels(0, 1) == [pulse.ControlChannel(0)] .. note:: Requires the active builder context to have a backend set. Args: qubits: Tuple or list of ordered qubits of the form `(control_qubit, target_qubit)`. Returns: List of control channels associated with the supplied ordered list of qubits. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().control_channel(qubits) return active_backend().configuration().control(qubits=qubits) # Base Instructions def delay(duration: int, channel: chans.Channel, name: Optional[str] = None): """Delay on a ``channel`` for a ``duration``. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.delay(10, d0) Args: duration: Number of cycles to delay for on ``channel``. channel: Channel to delay on. name: Name of the instruction. """ append_instruction(instructions.Delay(duration, channel, name=name)) def play( pulse: Union[library.Pulse, np.ndarray], channel: chans.PulseChannel, name: Optional[str] = None ): """Play a ``pulse`` on a ``channel``. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(10, 1.0), d0) Args: pulse: Pulse to play. channel: Channel to play pulse on. name: Name of the pulse. """ if not isinstance(pulse, library.Pulse): pulse = library.Waveform(pulse) append_instruction(instructions.Play(pulse, channel, name=name)) def acquire( duration: int, qubit_or_channel: Union[int, chans.AcquireChannel], register: StorageLocation, **metadata: Union[configuration.Kernel, configuration.Discriminator], ): """Acquire for a ``duration`` on a ``channel`` and store the result in a ``register``. Examples: .. code-block:: from qiskit import pulse acq0 = pulse.AcquireChannel(0) mem0 = pulse.MemorySlot(0) with pulse.build() as pulse_prog: pulse.acquire(100, acq0, mem0) # measurement metadata kernel = pulse.configuration.Kernel('linear_discriminator') pulse.acquire(100, acq0, mem0, kernel=kernel) .. note:: The type of data acquire will depend on the execution ``meas_level``. Args: duration: Duration to acquire data for qubit_or_channel: Either the qubit to acquire data for or the specific :class:`~qiskit.pulse.channels.AcquireChannel` to acquire on. register: Location to store measured result. metadata: Additional metadata for measurement. See :class:`~qiskit.pulse.instructions.Acquire` for more information. Raises: exceptions.PulseError: If the register type is not supported. """ if isinstance(qubit_or_channel, int): qubit_or_channel = chans.AcquireChannel(qubit_or_channel) if isinstance(register, chans.MemorySlot): append_instruction( instructions.Acquire(duration, qubit_or_channel, mem_slot=register, **metadata) ) elif isinstance(register, chans.RegisterSlot): append_instruction( instructions.Acquire(duration, qubit_or_channel, reg_slot=register, **metadata) ) else: raise exceptions.PulseError(f'Register of type: "{type(register)}" is not supported') def set_frequency(frequency: float, channel: chans.PulseChannel, name: Optional[str] = None): """Set the ``frequency`` of a pulse ``channel``. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.set_frequency(1e9, d0) Args: frequency: Frequency in Hz to set channel to. channel: Channel to set frequency of. name: Name of the instruction. """ append_instruction(instructions.SetFrequency(frequency, channel, name=name)) def shift_frequency(frequency: float, channel: chans.PulseChannel, name: Optional[str] = None): """Shift the ``frequency`` of a pulse ``channel``. Examples: .. code-block:: python :emphasize-lines: 6 from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.shift_frequency(1e9, d0) Args: frequency: Frequency in Hz to shift channel frequency by. channel: Channel to shift frequency of. name: Name of the instruction. """ append_instruction(instructions.ShiftFrequency(frequency, channel, name=name)) def set_phase(phase: float, channel: chans.PulseChannel, name: Optional[str] = None): """Set the ``phase`` of a pulse ``channel``. Examples: .. code-block:: python :emphasize-lines: 8 import math from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.set_phase(math.pi, d0) Args: phase: Phase in radians to set channel carrier signal to. channel: Channel to set phase of. name: Name of the instruction. """ append_instruction(instructions.SetPhase(phase, channel, name=name)) def shift_phase(phase: float, channel: chans.PulseChannel, name: Optional[str] = None): """Shift the ``phase`` of a pulse ``channel``. Examples: .. code-block:: import math from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.shift_phase(math.pi, d0) Args: phase: Phase in radians to shift channel carrier signal by. channel: Channel to shift phase of. name: Name of the instruction. """ append_instruction(instructions.ShiftPhase(phase, channel, name)) def snapshot(label: str, snapshot_type: str = "statevector"): """Simulator snapshot. Examples: .. code-block:: from qiskit import pulse with pulse.build() as pulse_prog: pulse.snapshot('first', 'statevector') Args: label: Label for snapshot. snapshot_type: Type of snapshot. """ append_instruction(instructions.Snapshot(label, snapshot_type=snapshot_type)) def call( target: Optional[Union[circuit.QuantumCircuit, Schedule, ScheduleBlock]], name: Optional[str] = None, value_dict: Optional[Dict[ParameterValueType, ParameterValueType]] = None, **kw_params: ParameterValueType, ): """Call the subroutine within the currently active builder context with arbitrary parameters which will be assigned to the target program. .. note:: If the ``target`` program is a :class:`.ScheduleBlock`, then a :class:`.Reference` instruction will be created and appended to the current context. The ``target`` program will be immediately assigned to the current scope as a subroutine. If the ``target`` program is :class:`.Schedule`, it will be wrapped by the :class:`.Call` instruction and appended to the current context to avoid a mixed representation of :class:`.ScheduleBlock` and :class:`.Schedule`. If the ``target`` program is a :class:`.QuantumCircuit` it will be scheduled and the new :class:`.Schedule` will be added as a :class:`.Call` instruction. Examples: 1. Calling a schedule block (recommended) .. code-block:: from qiskit import circuit, pulse from qiskit.providers.fake_provider import FakeBogotaV2 backend = FakeBogotaV2() with pulse.build() as x_sched: pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) with pulse.build() as pulse_prog: pulse.call(x_sched) print(pulse_prog) .. parsed-literal:: ScheduleBlock( ScheduleBlock( Play( Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0) ), name="block0", transform=AlignLeft() ), name="block1", transform=AlignLeft() ) The actual program is stored in the reference table attached to the schedule. .. code-block:: print(pulse_prog.references) .. parsed-literal:: ReferenceManager: - ('block0', '634b3b50bd684e26a673af1fbd2d6c81'): ScheduleBlock(Play(Gaussian(... In addition, you can call a parameterized target program with parameter assignment. .. code-block:: amp = circuit.Parameter("amp") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0)) with pulse.build() as pulse_prog: pulse.call(subroutine, amp=0.1) pulse.call(subroutine, amp=0.3) print(pulse_prog) .. parsed-literal:: ScheduleBlock( ScheduleBlock( Play( Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0) ), name="block2", transform=AlignLeft() ), ScheduleBlock( Play( Gaussian(duration=160, amp=(0.3+0j), sigma=40), DriveChannel(0) ), name="block2", transform=AlignLeft() ), name="block3", transform=AlignLeft() ) If there is a name collision between parameters, you can distinguish them by specifying each parameter object in a python dictionary. For example, .. code-block:: amp1 = circuit.Parameter('amp') amp2 = circuit.Parameter('amp') with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp1, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, amp2, 40), pulse.DriveChannel(1)) with pulse.build() as pulse_prog: pulse.call(subroutine, value_dict={amp1: 0.1, amp2: 0.3}) print(pulse_prog) .. parsed-literal:: ScheduleBlock( ScheduleBlock( Play(Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0)), Play(Gaussian(duration=160, amp=(0.3+0j), sigma=40), DriveChannel(1)), name="block4", transform=AlignLeft() ), name="block5", transform=AlignLeft() ) 2. Calling a schedule .. code-block:: x_sched = backend.instruction_schedule_map.get("x", (0,)) with pulse.build(backend) as pulse_prog: pulse.call(x_sched) print(pulse_prog) .. parsed-literal:: ScheduleBlock( Call( Schedule( ( 0, Play( Drag( duration=160, amp=(0.18989731546729305+0j), sigma=40, beta=-1.201258305015517, name='drag_86a8' ), DriveChannel(0), name='drag_86a8' ) ), name="x" ), name='x' ), name="block6", transform=AlignLeft() ) Currently, the backend calibrated gates are provided in the form of :class:`~.Schedule`. The parameter assignment mechanism is available also for schedules. However, the called schedule is not treated as a reference. 3. Calling a quantum circuit .. code-block:: backend = FakeBogotaV2() qc = circuit.QuantumCircuit(1) qc.x(0) with pulse.build(backend) as pulse_prog: pulse.call(qc) print(pulse_prog) .. parsed-literal:: ScheduleBlock( Call( Schedule( ( 0, Play( Drag( duration=160, amp=(0.18989731546729305+0j), sigma=40, beta=-1.201258305015517, name='drag_86a8' ), DriveChannel(0), name='drag_86a8' ) ), name="circuit-87" ), name='circuit-87' ), name="block7", transform=AlignLeft() ) .. warning:: Calling a circuit from a schedule is not encouraged. Currently, the Qiskit execution model is migrating toward the pulse gate model, where schedules are attached to circuits through the :meth:`.QuantumCircuit.add_calibration` method. Args: target: Target circuit or pulse schedule to call. name: Optional. A unique name of subroutine if defined. When the name is explicitly provided, one cannot call different schedule blocks with the same name. value_dict: Optional. Parameters assigned to the ``target`` program. If this dictionary is provided, the ``target`` program is copied and then stored in the main built schedule and its parameters are assigned to the given values. This dictionary is keyed on :class:`~.Parameter` objects, allowing parameter name collision to be avoided. kw_params: Alternative way to provide parameters. Since this is keyed on the string parameter name, the parameters having the same name are all updated together. If you want to avoid name collision, use ``value_dict`` with :class:`~.Parameter` objects instead. """ _active_builder().call_subroutine(target, name, value_dict, **kw_params) def reference(name: str, *extra_keys: str): """Refer to undefined subroutine by string keys. A :class:`~qiskit.pulse.instructions.Reference` instruction is implicitly created and a schedule can be separately registered to the reference at a later stage. .. code-block:: python from qiskit import pulse with pulse.build() as main_prog: pulse.reference("x_gate", "q0") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) main_prog.assign_references(subroutine_dict={("x_gate", "q0"): subroutine}) Args: name: Name of subroutine. extra_keys: Helper keys to uniquely specify the subroutine. """ _active_builder().append_reference(name, *extra_keys) # Directives def barrier(*channels_or_qubits: Union[chans.Channel, int], name: Optional[str] = None): """Barrier directive for a set of channels and qubits. This directive prevents the compiler from moving instructions across the barrier. Consider the case where we want to enforce that one pulse happens after another on separate channels, this can be done with: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build(backend) as barrier_pulse_prog: pulse.play(pulse.Constant(10, 1.0), d0) pulse.barrier(d0, d1) pulse.play(pulse.Constant(10, 1.0), d1) Of course this could have been accomplished with: .. code-block:: from qiskit.pulse import transforms with pulse.build(backend) as aligned_pulse_prog: with pulse.align_sequential(): pulse.play(pulse.Constant(10, 1.0), d0) pulse.play(pulse.Constant(10, 1.0), d1) barrier_pulse_prog = transforms.target_qobj_transform(barrier_pulse_prog) aligned_pulse_prog = transforms.target_qobj_transform(aligned_pulse_prog) assert barrier_pulse_prog == aligned_pulse_prog The barrier allows the pulse compiler to take care of more advanced scheduling alignment operations across channels. For example in the case where we are calling an outside circuit or schedule and want to align a pulse at the end of one call: .. code-block:: import math d0 = pulse.DriveChannel(0) with pulse.build(backend) as pulse_prog: with pulse.align_right(): pulse.x(1) # Barrier qubit 1 and d0. pulse.barrier(1, d0) # Due to barrier this will play before the gate on qubit 1. pulse.play(pulse.Constant(10, 1.0), d0) # This will end at the same time as the pulse above due to # the barrier. pulse.x(1) .. note:: Requires the active builder context to have a backend set if qubits are barriered on. Args: channels_or_qubits: Channels or qubits to barrier. name: Name for the barrier """ channels = _qubits_to_channels(*channels_or_qubits) if len(channels) > 1: append_instruction(directives.RelativeBarrier(*channels, name=name)) # Macros def macro(func: Callable): """Wrap a Python function and activate the parent builder context at calling time. This enables embedding Python functions as builder macros. This generates a new :class:`pulse.Schedule` that is embedded in the parent builder context with every call of the decorated macro function. The decorated macro function will behave as if the function code was embedded inline in the parent builder context after parameter substitution. Examples: .. plot:: :include-source: from qiskit import pulse @pulse.macro def measure(qubit: int): pulse.play(pulse.GaussianSquare(16384, 256, 15872), pulse.measure_channel(qubit)) mem_slot = pulse.MemorySlot(qubit) pulse.acquire(16384, pulse.acquire_channel(qubit), mem_slot) return mem_slot with pulse.build(backend=backend) as sched: mem_slot = measure(0) print(f"Qubit measured into {mem_slot}") sched.draw() Args: func: The Python function to enable as a builder macro. There are no requirements on the signature of the function, any calls to pulse builder methods will be added to builder context the wrapped function is called from. Returns: Callable: The wrapped ``func``. """ func_name = getattr(func, "__name__", repr(func)) @functools.wraps(func) def wrapper(*args, **kwargs): _builder = _active_builder() # activate the pulse builder before calling the function with build(backend=_builder.backend, name=func_name) as built: output = func(*args, **kwargs) _builder.call_subroutine(built) return output return wrapper def measure( qubits: Union[List[int], int], registers: Union[List[StorageLocation], StorageLocation] = None, ) -> Union[List[StorageLocation], StorageLocation]: """Measure a qubit within the currently active builder context. At the pulse level a measurement is composed of both a stimulus pulse and an acquisition instruction which tells the systems measurement unit to acquire data and process it. We provide this measurement macro to automate the process for you, but if desired full control is still available with :func:`acquire` and :func:`play`. To use the measurement it is as simple as specifying the qubit you wish to measure: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() qubit = 0 with pulse.build(backend) as pulse_prog: # Do something to the qubit. qubit_drive_chan = pulse.drive_channel(0) pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan) # Measure the qubit. reg = pulse.measure(qubit) For now it is not possible to do much with the handle to ``reg`` but in the future we will support using this handle to a result register to build up ones program. It is also possible to supply this register: .. code-block:: with pulse.build(backend) as pulse_prog: pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan) # Measure the qubit. mem0 = pulse.MemorySlot(0) reg = pulse.measure(qubit, mem0) assert reg == mem0 .. note:: Requires the active builder context to have a backend set. Args: qubits: Physical qubit to measure. registers: Register to store result in. If not selected the current behavior is to return the :class:`MemorySlot` with the same index as ``qubit``. This register will be returned. Returns: The ``register`` the qubit measurement result will be stored in. """ backend = active_backend() try: qubits = list(qubits) except TypeError: qubits = [qubits] if registers is None: registers = [chans.MemorySlot(qubit) for qubit in qubits] else: try: registers = list(registers) except TypeError: registers = [registers] measure_sched = macros.measure( qubits=qubits, backend=backend, qubit_mem_slots={qubit: register.index for qubit, register in zip(qubits, registers)}, ) # note this is not a subroutine. # just a macro to automate combination of stimulus and acquisition. # prepare unique reference name based on qubit and memory slot index. qubits_repr = "&".join(map(str, qubits)) mslots_repr = "&".join((str(r.index) for r in registers)) _active_builder().call_subroutine(measure_sched, name=f"measure_{qubits_repr}..{mslots_repr}") if len(qubits) == 1: return registers[0] else: return registers def measure_all() -> List[chans.MemorySlot]: r"""Measure all qubits within the currently active builder context. A simple macro function to measure all of the qubits in the device at the same time. This is useful for handling device ``meas_map`` and single measurement constraints. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: # Measure all qubits and return associated registers. regs = pulse.measure_all() .. note:: Requires the active builder context to have a backend set. Returns: The ``register``\s the qubit measurement results will be stored in. """ backend = active_backend() qubits = range(num_qubits()) registers = [chans.MemorySlot(qubit) for qubit in qubits] measure_sched = macros.measure( qubits=qubits, backend=backend, qubit_mem_slots={qubit: qubit for qubit in qubits}, ) # note this is not a subroutine. # just a macro to automate combination of stimulus and acquisition. _active_builder().call_subroutine(measure_sched, name="measure_all") return registers def delay_qubits(duration: int, *qubits: Union[int, Iterable[int]]): r"""Insert delays on all of the :class:`channels.Channel`\s that correspond to the input ``qubits`` at the same time. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse3Q backend = FakeOpenPulse3Q() with pulse.build(backend) as pulse_prog: # Delay for 100 cycles on qubits 0, 1 and 2. regs = pulse.delay_qubits(100, 0, 1, 2) .. note:: Requires the active builder context to have a backend set. Args: duration: Duration to delay for. qubits: Physical qubits to delay on. Delays will be inserted based on the channels returned by :func:`pulse.qubit_channels`. """ qubit_chans = set(itertools.chain.from_iterable(qubit_channels(qubit) for qubit in qubits)) with align_left(): for chan in qubit_chans: delay(duration, chan) # Gate instructions def call_gate(gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True): """Call a gate and lazily schedule it to its corresponding pulse instruction. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: from qiskit import pulse from qiskit.pulse import builder from qiskit.circuit.library import standard_gates as gates from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: builder.call_gate(gates.CXGate(), (0, 1)) We can see the role of the transpiler in scheduling gates by optimizing away two consecutive CNOT gates: .. code-block:: with pulse.build(backend) as pulse_prog: with pulse.transpiler_settings(optimization_level=3): builder.call_gate(gates.CXGate(), (0, 1)) builder.call_gate(gates.CXGate(), (0, 1)) assert pulse_prog == pulse.Schedule() .. note:: If multiple gates are called in a row they may be optimized by the transpiler, depending on the :func:`pulse.active_transpiler_settings``. .. note:: Requires the active builder context to have a backend set. Args: gate: Circuit gate instance to call. qubits: Qubits to call gate on. lazy: If ``false`` the gate will be compiled immediately, otherwise it will be added onto a lazily evaluated quantum circuit to be compiled when the builder is forced to by a circuit assumption being broken, such as the inclusion of a pulse instruction or new alignment context. """ _active_builder().call_gate(gate, qubits, lazy=lazy) def cx(control: int, target: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.CXGate` on the input physical qubits. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.cx(0, 1) """ call_gate(gates.CXGate(), (control, target)) def u1(theta: float, qubit: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.U1Gate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.u1(math.pi, 1) """ call_gate(gates.U1Gate(theta), qubit) def u2(phi: float, lam: float, qubit: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.U2Gate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.u2(0, math.pi, 1) """ call_gate(gates.U2Gate(phi, lam), qubit) def u3(theta: float, phi: float, lam: float, qubit: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.U3Gate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.u3(math.pi, 0, math.pi, 1) """ call_gate(gates.U3Gate(theta, phi, lam), qubit) def x(qubit: int): """Call a :class:`~qiskit.circuit.library.standard_gates.XGate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.x(0) """ call_gate(gates.XGate(), qubit)
https://github.com/gustavomirapalheta/Quantum-Computing-with-Qiskit
gustavomirapalheta
# Setup básico !pip install qiskit -q !pip install qiskit[visualization] -q import qiskit as qk !pip install qiskit-aer -q import qiskit_aer as qk_aer import numpy as np np.set_printoptions(precision=3, suppress=True) from matplotlib import pyplot as plt %matplotlib inline import pandas as pd import sklearn as sk import qiskit as qk qrx = qk.QuantumRegister(2,'x') qry = qk.QuantumRegister(2,'y') qc = qk.QuantumCircuit(qrx,qry) qc.barrier() qc.cx(0,2) qc.cx(0,3) qc.cx(1,2) qc.cx(1,3) qc.barrier() qc.draw('mpl') def histograma(qc): simulador = qk_aer.Aer.get_backend('aer_simulator') resultado = simulator.run(qk.transpile(qc,simulator),shots=10000).result() contagens = resultado.get_counts() grafico = qk.visualization.plot_histogram(contagens) return(grafico) def simon(initial_y, initial_x): import qiskit as qk qrx = qk.QuantumRegister(2,'x') crx = qk.ClassicalRegister(4,'c') qry = qk.QuantumRegister(2,'y') qc = qk.QuantumCircuit(qrx,qry,crx) qc.initialize(initial_x,qrx) qc.initialize(initial_y,qry) qc.barrier() qc.cx(0,2) qc.cx(0,3) qc.cx(1,2) qc.cx(1,3) qc.barrier() qc.measure([0,1,2,3],[0,1,2,3]) display(qc.draw('mpl')) grafico = histograma(qc) return(grafico) simon([1,0,0,0],[1,0,0,0]) simon([1,0,0,0],[0,0,0,1]) simon([1,0,0,0],[0,1,0,0]) simon([1,0,0,0],[0,0,1,0]) import qiskit as qk qrx = qk.QuantumRegister(2,'x') crx = qk.ClassicalRegister(2,'c') qry = qk.QuantumRegister(2,'y') qc = qk.QuantumCircuit(qrx,qry,crx) qc.initialize([1,0,0,0],qrx) qc.initialize([1,0,0,0],qry) qc.h([0,1]) qc.barrier() qc.cx(0,2) qc.cx(0,3) qc.cx(1,2) qc.cx(1,3) qc.barrier() qc.h([0,1]) qc.measure([0,1],[0,1]) display(qc.draw('mpl')) histograma(qc) import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T x1x0 = np.kron(x1,x0) y0 = np.array([[1,0]]).T y1 = np.array([[1,0]]).T y1y0 = np.kron(y1,y0) psi0 = np.kron(y1y0,x1x0) psi0.T H = np.array([[1,1],[1,-1]],dtype='int') H2 = np.kron(H,H) I2 = np.eye(4) I2H2 = np.kron(I2,H2) psi1 = I2H2.dot(psi0)/(np.sqrt(2)*np.sqrt(2)) I2H2.dot(psi0).T Tf1_2 = np.eye(16) Tf1_2 = Tf1_2[:,[0,5,2,7,4,1,6,3,8,9,10,11,12,13,14,15]] psi2 = Tf1_2.dot(psi1); psi2.T*2 Tf2_3 = np.eye(16) Tf2_3 = Tf2_3[:,[0,1,2,3,4,13,6,15,8,9,10,11,12,5,14,7]] psi3 = Tf2_3.dot(psi2); psi3.T*2 Tf3_4 = np.eye(16) Tf3_4 = Tf3_4[:,[0,1,6,3,4,5,2,7,8,9,10,15,12,13,14,11]] psi4 = Tf3_4.dot(psi3); psi4.T*2 Tf4_5 = np.eye(16) Tf4_5 = Tf4_5[:,[0,1,2,11,4,5,14,7,8,9,10,3,12,13,6,15]] psi5 = Tf4_5.dot(psi4); psi5.T*2 I2 = np.eye(4) H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) I2H2 = np.kron(I2,H2) psi6 = I2H2.dot(psi5) print(psi6.T*2) import numpy as np I2 = np.eye(4, dtype='int'); H2 = np.array([[1, 1, 1, 1], [1,-1, 1,-1], [1, 1,-1,-1], [1,-1,-1, 1]])/2; I2H2 = np.kron(I2,H2); print(I2H2*2) import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T x2 = np.array([[1,0]]).T x2x1x0 = np.kron(x2,np.kron(x1,x0)) x2x1x0.T y0 = np.array([[1,0]]).T y1 = np.array([[1,0]]).T y2 = np.array([[1,0]]).T y2y1y0 = np.kron(y2,np.kron(y1,y0)) y2y1y0.T psi0 = np.kron(y2y1y0,x2x1x0) psi0.T I3 = np.eye(2**3) H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H3 = np.kron(H,H2) I3H3 = np.kron(I3,H3) psi1 = I3H3.dot(psi0) psi1.T.round(2) n = 2*3 # 2 números de 3 digitos cada Uf = np.eye(2**n) # 2^6 = 64 posições Uf = Uf[:,[ 0, 9,18,27,12, 5,30,23, 8, 1,10,11, 4,13,14,15, 16,17, 2,19,20,21,22, 7, 24,25,26, 3,28,29, 6,31, 32,33,34,35,36,37,38,39, 40,41,42,43,44,45,46,47, 48,49,50,51,52,53,54,55, 56,57,58,59,60,61,62,63]] psi5 = Uf.dot(psi1) psi5.T.round(2) psi6 = I3H3.dot(psi5) psi6.T np.where(psi6 > 0)[0] [format(i,'#08b')[2:] for i in np.where(psi6 > 0)[0]] import numpy as np CCNOT = np.eye(8) CCNOT = CCNOT[:,[0,1,2,7,4,5,6,3]] CCNOT.dot(CCNOT) import qiskit as qk def qNAND(y0,x0): x = qk.QuantumRegister(1,"x") y = qk.QuantumRegister(1,"y") z = qk.QuantumRegister(1,"z") u = qk.QuantumRegister(1,"u") c = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(x,y,z,u,c) # Put qubits u and z in state |0> qc.initialize([1,0],z) qc.initialize([1,0],u) qc.initialize(y0,y) qc.initialize(x0,x) # Perform computation qc.barrier() qc.ccx(x,y,z) qc.x(z) # Copy CLASSICALY state of z to u qc.cx(z,u) qc.barrier() # Reverse computation qc.x(z) qc.ccx(x,y,z) qc.barrier() # Measure results qc.measure(x,c[0]) qc.measure(y,c[1]) qc.measure(u,c[2]) display(qc.draw('mpl')) simulator = qk_aer.Aer.get_backend("aer_simulator") results = simulator.run(qk.transpile(qc,simulator), shots=10000).result().get_counts() grafico = qk.visualization.plot_histogram(results) return(grafico) print("0 NAND 0 = 1") qNAND([1,0],[1,0]) print("0 NAND 1 = 1") qNAND([1,0],[0,1]) print("1 NAND 0 = 1") qNAND([0,1],[1,0]) print("1 NAND 1 = 0") qNAND([0,1],[0,1]) import qiskit as qk def qOR(y0,x0): x = qk.QuantumRegister(1,"x") y = qk.QuantumRegister(1,"y") z = qk.QuantumRegister(1,"z") u = qk.QuantumRegister(1,"u") c = qk.ClassicalRegister(3,'c') # Initialize qubits qc = qk.QuantumCircuit(x,y,z,u,c) qc.initialize(x0,x) qc.initialize(y0,y) qc.initialize([1,0],z) qc.initialize([1,0],u) # Compute function qc.barrier() qc.x(x) qc.x(y) qc.ccx(x,y,z) qc.x(z) qc.cx(z,u) qc.barrier() # Reverse computation qc.x(z) qc.ccx(x,y,z) qc.x(y) qc.x(x) qc.barrier() # Measure results qc.measure(x,c[0]) qc.measure(y,c[1]) qc.measure(u,c[2]) display(qc.draw('mpl')) # Simulate circuit simulator = qk_aer.Aer.get_backend('aer_simulator') results = simulator.run(qk.transpile(qc,simulator),shots=10000).result().get_counts() grafico = qk.visualization.plot_histogram(results) return(grafico) qOR([1,0],[1,0]) qOR([1,0],[0,1]) qOR([0,1],[1,0]) qOR([0,1],[0,1]) import qiskit as qk def qNXOR(y0,x0,calc=True,show=False): ################################################## # Create registers # ################################################## # Base registers x = qk.QuantumRegister(1,"x") y = qk.QuantumRegister(1,"y") # Auxiliary register (for x and y) z = qk.QuantumRegister(1,"z") # Auxiliary register (to store x AND y) a1 = qk.QuantumRegister(1,"a1") # Auxiliary register (to store NOT(x) AND NOT(y)) a2 = qk.QuantumRegister(1,"a2") # Auxiliary register (for a1 and a2) b1 = qk.QuantumRegister(1,"b1") # Auxiliary register (to store a1 OR a2) b2 = qk.QuantumRegister(1,"b2") # Classical Registers to store x,y and final measurement c = qk.ClassicalRegister(3,"c") ################################################## # Create Circuit # ################################################## qc = qk.QuantumCircuit(x,y,z,a1,a2,b1,b2,c) ################################################## # Initialize registers # ################################################## qc.initialize(x0,x) qc.initialize(y0,y) qc.initialize([1,0],z) qc.initialize([1,0],a1) qc.initialize([1,0],a2) qc.initialize([1,0],b1) qc.initialize([1,0],b2) ################################################### # Calculate x AND y. Copy result to a1. Reverse z # ################################################### qc.barrier() qc.ccx(x,y,z) qc.cx(z,a1) qc.ccx(x,y,z) qc.barrier() ######################################################### # Calc. NOT(x) AND NOT(y). Copy result to a2. Reverse z # ######################################################### qc.barrier() qc.x(x) qc.x(y) qc.ccx(x,y,z) qc.cx(z,a2) qc.ccx(x,y,z) qc.x(y) qc.x(x) qc.barrier() ################################################# # Calc. a1 OR a2. Copy result to b2. Reverse b1 # ################################################# qc.barrier() qc.x(a1) qc.x(a2) qc.ccx(a1,a2,b1) qc.x(b1) qc.cx(b1,b2) qc.x(b1) qc.ccx(a1,a2,b1) qc.barrier() ################################################# # Measure b2 # ################################################# qc.measure(x,c[0]) qc.measure(y,c[1]) qc.measure(b2,c[2]) ################################################# # Draw circuit # ################################################# if show: display(qc.draw("mpl")) ################################################# # Run circuit. Collect results # ################################################# if calc: simulator = qk_aer.Aer.get_backend("aer_simulator") results = simulator.run(qk.transpile(qc,simulator),shots=10000).result().get_counts() grafico = qk.visualization.plot_histogram(results) return(grafico) else: return() qNXOR([1,0],[1,0],False,True) qNXOR([1,0],[1,0]) qNXOR([1,0],[0,1]) qNXOR([0,1],[1,0]) qNXOR([0,1],[0,1]) x0 = np.array([1,1])/np.sqrt(2) y0 = np.array([1,1])/np.sqrt(2) qNXOR(y0,x0) import qiskit as qk from qiskit.quantum_info.operators import Operator qr = qk.QuantumRegister(6,"q") cr = qk.ClassicalRegister(6,"c") qc = qk.QuantumCircuit(qr,cr) for i in range(6): qc.initialize([1,0],i) for i in range(3): qc.h(i) oracle = np.eye(2**6) oracle[:,[ 0, 0]] = oracle[:,[ 0, 0]] oracle[:,[ 1, 9]] = oracle[:,[ 9, 1]] oracle[:,[ 2, 18]] = oracle[:,[ 18, 2]] oracle[:,[ 3, 27]] = oracle[:,[ 27, 3]] oracle[:,[ 4, 12]] = oracle[:,[ 12, 4]] oracle[:,[ 5, 5]] = oracle[:,[ 5, 5]] oracle[:,[ 6, 30]] = oracle[:,[ 30, 6]] oracle[:,[ 7, 23]] = oracle[:,[ 23, 7]] oracle = Operator(oracle) qc.append(oracle,qr) for i in range(3): qc.h(i) qc.barrier() for i in range(3): qc.measure(i,i) display(qc.draw("mpl")) simulator = qk_aer.Aer.get_backend("aer_simulator") results = simulator.run(qk.transpile(qc,simulator),shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np oracle = np.eye(8) oracle[:,[2,6]] = oracle[:,[6,2]] oracle import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T psi0 = np.kron(x1,x0) H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) psi1 = H2.dot(psi0) psi1.T # Initialize a qubit y in state |1> y = np.array([[0,1]]).T # Pass it through a Hadamard gate and obtain state psi2a H = np.array([[1,1],[1,-1]])/np.sqrt(2) psi2a = H.dot(y) psi2a.T psi2 = np.kron(psi2a,psi1) psi2.T oracle = np.eye(8) oracle[:,[2,6]] = oracle[:,[6,2]] oracle psi3 = oracle.dot(psi2) psi3.T v0 = np.array([[10,20,-30,40,50]]).T mu = np.mean(v0) v0.T, mu D = v0 - mu D.T v1 = 2*np.mean(v0)-v0 v1.T import numpy as np A = np.ones(5**2).reshape(5,5) A = A/5 I = np.eye(5) R = 2*A-I R R.dot(R) n = 4 I = np.eye(n) A = np.ones(n**2).reshape(n,n)/n R = 2*A-I R I2 = np.eye(2) I2R = np.kron(I2,R) I2R psi4 = I2R.dot(psi3) psi4.T import qiskit as qk import numpy as np from qiskit.quantum_info.operators import Operator q = qk.QuantumRegister(3,'q') c = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(q,c) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.h(1) qc.initialize([0,1],2) qc.h(2) qc.barrier() oracle = np.eye(8) oracle[:,[2,6]] = oracle[:,[6,2]] oracle = Operator(oracle) qc.append(oracle,q) # n = 2 (two digits number to look for) A = np.ones(4*4).reshape(4,4)/4 I4 = np.eye(4) R = 2*A - I4 I2 = np.eye(2) boost = np.kron(I2,R) boost = Operator(boost) qc.append(boost,q) qc.barrier() qc.measure(q[:2],c[:2]) display(qc.draw('mpl')) simulator = qk_aer.Aer.get_backend('aer_simulator') results = simulator.run(qk.transpile(qc,simulator),shots=1000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T x2 = np.array([[1,0]]).T x2x1x0 = np.kron(x2,np.kron(x1,x0)) x2x1x0.T H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H3 = np.kron(H,H2) x = H3.dot(x2x1x0) x.T y0 = np.array([[0,1]]).T y0.T H = np.array([[1,1],[1,-1]])/np.sqrt(2) y = H.dot(y0) y.T psi0 = np.kron(y,x) psi0.T oracle = np.eye(16) oracle[:,[5,13]] = oracle[:,[13,5]] psi1 = oracle.dot(psi0) psi1.T # n = 8 A = np.ones(8*8).reshape(8,8)/8 I8 = np.eye(8) R = 2*A-I8 R I2 = np.eye(2) I2R = np.kron(I2,R) psi2 = I2R.dot(psi1) psi2.T 0.625**2 + 0.625**2 psi3 = I2R.dot(oracle).dot(psi2) psi3.T 0.687**2 + 0.687**2 I2R.dot(oracle).dot(psi3).T T = I2R.dot(oracle) psi = psi1 prob = [] for i in range(25): prob.append(psi[5,0]**2 + psi[13,0]**2) psi = T.dot(psi) from matplotlib import pyplot as plt plt.plot(list(range(25)), prob); import qiskit as qk import numpy as np from qiskit.quantum_info.operators import Operator q = qk.QuantumRegister(4,'q') c = qk.ClassicalRegister(4,'c') qc = qk.QuantumCircuit(q,c) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([1,0],2) qc.h(0) qc.h(1) qc.h(2) qc.initialize([0,1],3) qc.h(3) qc.barrier() # Create oracle matrix oracle = np.eye(16) oracle[:,[5,13]] = oracle[:,[13,5]] # Create rotation about the mean matrix # n = 3 (three digits number to look for) A = np.ones(8*8).reshape(8,8)/8 I8 = np.eye(8) R = 2*A - I8 # Identity matrix to leave fourth qubit undisturbed I2 = np.eye(2) # Create second transformation matrix boost = np.kron(I2,R) # Combine oracle with second transformation matrix in # an unique operator T = boost.dot(oracle) T = Operator(T) # Apply operator twice (2 phase inversions and # rotations about the mean) qc.append(T,q) qc.append(T,q) qc.barrier() qc.measure(q[:3],c[:3]) display(qc.draw('mpl')) simulator = qk_aer.Aer.get_backend('aer_simulator') results = simulator.run(qk.transpile(qc,simulator),shots=1000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk import numpy as np from qiskit.quantum_info.operators import Operator q = qk.QuantumRegister(5,'q') c = qk.ClassicalRegister(5,'c') qc = qk.QuantumCircuit(q,c) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([1,0],2) qc.initialize([1,0],3) qc.h(0) qc.h(1) qc.h(2) qc.h(3) qc.initialize([0,1],4) qc.h(4) qc.barrier() # Create oracle matrix oracle = np.eye(32) oracle[:,[13,29]] = oracle[:,[29,13]] # Create rotation about the mean matrix # n = 4 (four digits number to look for) A = np.ones(16*16).reshape(16,16)/16 I16 = np.eye(16) R = 2*A - I16 # Identity matrix to leave fifth qubit undisturbed I2 = np.eye(2) # Create second transformation matrix boost = np.kron(I2,R) # Combine oracle with second transformation matrix in # an unique operator T = boost.dot(oracle) # n = 4. Therefore it will be necessary 4 T operations # to get maximum probability. Tn = T.dot(T).dot(T) Tn = Operator(Tn) # Apply operator Tn once (n phase inversions and # rotations about the mean) qc.append(Tn,q) qc.barrier() qc.measure(q[:4],c[:4]) display(qc.draw('mpl')) simulator = qk_aer.Aer.get_backend('aer_simulator') results = simulator.run(qk.transpile(qc,simulator),shots=1000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np import pandas as pd N = 35; a = 6 GCD = pd.DataFrame({'N':[N], 'a':[a], 'N-a':[N-a]}) while GCD.iloc[-1,2] != 0: temp = GCD.iloc[-1].values temp = np.sort(temp); temp[-1] = temp[-2] - temp[-3] temp = pd.DataFrame(data = temp.reshape(-1,3), columns = ['N','a','N-a']) GCD = pd.concat([GCD,temp], ignore_index=True) GCD import numpy as np import pandas as pd N = 15; a = 9 GCD = pd.DataFrame({'N':[N], 'a':[a], 'N-a':[N-a]}) while GCD.iloc[-1,2] != 0: temp = GCD.iloc[-1].values temp = np.sort(temp); temp[-1] = temp[-2] - temp[-3] temp = pd.DataFrame(data = temp.reshape(-1,3), columns = ['N','a','N-a']) GCD = pd.concat([GCD,temp], ignore_index=True) GCD import numpy as np np.gcd(6,35), np.gcd(9,15) import numpy as np np.gcd(215,35), np.gcd(217,35) 20 % 7 import numpy as np f = lambda x,a,N: a**x % N [f(x,2,15) for x in range(10)] import numpy as np (13*35)%11, ((2%11)*(24%11))%11 import numpy as np def f(x,a,N): a0 = 1 for i in range(x): a0 = ((a%N)*(a0))%N return(a0) [f(x,2,371) for x in range(8)] [f(x,2,371) for x in range(154,159)] [f(x,24,371) for x in range(77,81)] import numpy as np def fr(a,N): ax = ((a%N)*(1))%N x = 1 while ax != 1: ax = ((a%N)*(ax))%N x = x+1 return(x) fr(2,371), fr(6,371), fr(24,371) import numpy as np def fr(a,N): a0 = 1 a0 = ((a%N)*a0)%N x = 2 find = False while find==False: a0 = ((a%N)*(a0))%N if a0 == 1: find = True x = x+1 return(x-1) N = 35 a = 2 fr(a,N) 2**(12/2)-1, 2**(12/2)+1 np.gcd(63,35), np.gcd(65,35) import numpy as np # Function to calculate the period of f(x) = a^x MOD N def fr(a,N): a1 = ((a%N)*(1))%N x = 1 while a1 != 1: a1 = ((a%N)*a1)%N x = x+1 return(x) # Function to factor N based on a def factor(N, a=2): r = fr(a,N) g1 = a**(int(r/2)) - 1 g2 = a**(int(r/2)) + 1 f1 = np.gcd(g1,N) f2 = np.gcd(g2,N) return(f1,f2, f1*f2) factor(247) factor(1045)
https://github.com/ncitron/qiskit-hack
ncitron
from qiskit import * from qiskit.tools.visualization import plot_histogram as ph %matplotlib inline import math #0 1 2 #3 4 5 #6 7 8 mat = [0,1,0,0,0,0,1,0,0] circuit = QuantumCircuit(len(mat)) circuit.h(range(len(mat))) circuit.barrier() for i in range(len(mat)): if mat[i] == 1: circuit.y(i) circuit.barrier() circuit.h(range(len(mat))) circuit.measure_all() circuit.draw('mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend = simulator, shots = 100).result() counts = result.get_counts() print(counts) def oracle(circuit): circuit.cz(0,2) circuit.cz(1,2) def diffuser(circuit): """Apply inversion about the average step of Grover's algorithm.""" qbits = circuit.qubits nqbits = len(qbits) for q in range(nqbits): circuit.h(q) circuit.x(q) #Do controlled-Z circuit.h(2) circuit.ccx(0,1,2) circuit.h(2) for q in range(nqbits): circuit.x(q) circuit.h(q) n=3 barriers = True grover = QuantumCircuit(n) for qb in range(n): grover.h(qb) if barriers: grover.barrier() oracle(grover) if barriers: grover.barrier() diffuser(grover) grover.measure_all() grover.draw('mpl') be = Aer.get_backend('qasm_simulator') sh = 1024 ph(execute(grover,backend=be,shots=sh).result().get_counts()) from qiskit.quantum_info.operators import Operator controls = QuantumRegister(2) circuit = QuantumCircuit(controls) dd = Operator([ [0, 0, 1, 0], [0, 0, 0, 1], [0, 1, 0, 0], [1, 0, 0, 0] ]) circuit.unitary(dd, [0, 1], label='dd') circuit.h(0) circuit.draw('mpl') # 4-qubit grover's algorithm pi = math.pi qc = QuantumCircuit(4) shots = 2048 qc.h([0,1,2,3]) ## Oracle for 0010 AND 1100 ## qc.barrier() qc.x([0,2,3]) qc.cu1(pi/4, 0, 3) qc.cx(0, 1) qc.cu1(-pi/4, 1, 3) qc.cx(0, 1) qc.cu1(pi/4, 1, 3) qc.cx(1, 2) qc.cu1(-pi/4, 2, 3) qc.cx(0, 2) qc.cu1(pi/4, 2, 3) qc.cx(1, 2) qc.cu1(-pi/4, 2, 3) qc.cx(0, 2) qc.cu1(pi/4, 2, 3) qc.x([0,2,3]) qc.x([0,1]) qc.cu1(pi/4, 0, 3) qc.cx(0, 1) qc.cu1(-pi/4, 1, 3) qc.cx(0, 1) qc.cu1(pi/4, 1, 3) qc.cx(1, 2) qc.cu1(-pi/4, 2, 3) qc.cx(0, 2) qc.cu1(pi/4, 2, 3) qc.cx(1, 2) qc.cu1(-pi/4, 2, 3) qc.cx(0, 2) qc.cu1(pi/4, 2, 3) qc.x([0,1]) qc.barrier() ## Amplification ## qc.h([0,1,2,3]) qc.x([0,1,2,3]) #Start cccz qc.cu1(pi/4, 0, 3) qc.cx(0, 1) qc.cu1(-pi/4, 1, 3) qc.cx(0, 1) qc.cu1(pi/4, 1, 3) qc.cx(1, 2) qc.cu1(-pi/4, 2, 3) qc.cx(0, 2) qc.cu1(pi/4, 2, 3) qc.cx(1, 2) qc.cu1(-pi/4, 2, 3) qc.cx(0, 2) qc.cu1(pi/4, 2, 3) #end cccz qc.x([0,1,2,3]) qc.h([0,1,2,3]) qc.barrier() #### Repeat 1 ## Oracle for 0010 AND 1100 ## qc.x([0,2,3]) qc.cu1(pi/4, 0, 3) qc.cx(0, 1) qc.cu1(-pi/4, 1, 3) qc.cx(0, 1) qc.cu1(pi/4, 1, 3) qc.cx(1, 2) qc.cu1(-pi/4, 2, 3) qc.cx(0, 2) qc.cu1(pi/4, 2, 3) qc.cx(1, 2) qc.cu1(-pi/4, 2, 3) qc.cx(0, 2) qc.cu1(pi/4, 2, 3) qc.x([0,2,3]) qc.x([0,1]) qc.cu1(pi/4, 0, 3) qc.cx(0, 1) qc.cu1(-pi/4, 1, 3) qc.cx(0, 1) qc.cu1(pi/4, 1, 3) qc.cx(1, 2) qc.cu1(-pi/4, 2, 3) qc.cx(0, 2) qc.cu1(pi/4, 2, 3) qc.cx(1, 2) qc.cu1(-pi/4, 2, 3) qc.cx(0, 2) qc.cu1(pi/4, 2, 3) qc.x([0,1]) qc.barrier() ## Amplification ## qc.h([0,1,2,3]) qc.x([0,1,2,3]) #Start cccz qc.cu1(pi/4, 0, 3) qc.cx(0, 1) qc.cu1(-pi/4, 1, 3) qc.cx(0, 1) qc.cu1(pi/4, 1, 3) qc.cx(1, 2) qc.cu1(-pi/4, 2, 3) qc.cx(0, 2) qc.cu1(pi/4, 2, 3) qc.cx(1, 2) qc.cu1(-pi/4, 2, 3) qc.cx(0, 2) qc.cu1(pi/4, 2, 3) #end cccz qc.x([0,1,2,3]) qc.h([0,1,2,3]) qc.measure_all() qc.draw('mpl') bcn = Aer.get_backend('qasm_simulator') ph(execute(qc,backend=bcn,shots=shots).result().get_counts()) # one acceptable answer (0010) circ = QuantumCircuit(4) circ.h([0,1,2,3]) circ.barrier() circ.x([0,2,3]) circ.h(3) circ.mct([0,1,2], 3) circ.h(3) circ.x([0,2,3]) circ.barrier() circ.h([0,1,2,3]) circ.x([0,1,2,3]) circ.h(3) circ.mct([0,1,2], 3) circ.h(3) circ.x([0,1,2,3]) circ.h([0,1,2,3]) circ.barrier() circ.x([0,2,3]) circ.h(3) circ.mct([0,1,2], 3) circ.h(3) circ.x([0,2,3]) circ.barrier() circ.h([0,1,2,3]) circ.x([0,1,2,3]) circ.h(3) circ.mct([0,1,2], 3) circ.h(3) circ.x([0,1,2,3]) circ.h([0,1,2,3]) circ.barrier() circ.x([0,2,3]) circ.h(3) circ.mct([0,1,2], 3) circ.h(3) circ.x([0,2,3]) circ.barrier() circ.h([0,1,2,3]) circ.x([0,1,2,3]) circ.h(3) circ.mct([0,1,2], 3) circ.h(3) circ.x([0,1,2,3]) circ.h([0,1,2,3]) circ.measure_all() circ.draw('mpl') bcnd = Aer.get_backend('qasm_simulator') ph(execute(circ,backend=bcnd,shots=1024).result().get_counts()) # three acceptable answers (0101, 1111, 1000) n = 7 s = [] for i in range(n-1): s.append(i) qcqc = QuantumCircuit(n) qcqc.h(range(n)) qcqc.barrier() qcqc.x([1,3]) qcqc.h(n-1) qcqc.mct(s, n-1) qcqc.h(n-1) qcqc.x([1,3]) qcqc.h(n-1) qcqc.mct(s, n-1) qcqc.h(n-1) qcqc.x([0,1,2]) qcqc.h(n-1) qcqc.mct(s, n-1) qcqc.h(n-1) qcqc.x([0,1,2]) qcqc.barrier() qcqc.h(range(n)) qcqc.x(range(n)) qcqc.h(n-1) qcqc.mct(s, n-1) qcqc.h(n-1) qcqc.x(range(n)) qcqc.h(range(n)) qcqc.barrier() qcqc.x([1,3]) qcqc.h(n-1) qcqc.mct(s, n-1) qcqc.h(n-1) qcqc.x([1,3]) qcqc.h(n-1) qcqc.mct(s, n-1) qcqc.h(n-1) qcqc.x([0,1,2]) qcqc.h(n-1) qcqc.mct(s, n-1) qcqc.h(n-1) qcqc.x([0,1,2]) qcqc.barrier() qcqc.h(range(n)) qcqc.x(range(n)) qcqc.h(n-1) qcqc.mct(s, n-1) qcqc.h(n-1) qcqc.x(range(n)) qcqc.h(range(n)) qcqc.barrier() qcqc.x([1,3]) qcqc.h(n-1) qcqc.mct(s, n-1) qcqc.h(n-1) qcqc.x([1,3]) qcqc.h(n-1) qcqc.mct(s, n-1) qcqc.h(n-1) qcqc.x([0,1,2]) qcqc.h(n-1) qcqc.mct(s, n-1) qcqc.h(n-1) qcqc.x([0,1,2]) qcqc.barrier() qcqc.h(range(n)) qcqc.x(range(n)) qcqc.h(n-1) qcqc.mct(s, n-1) qcqc.h(n-1) qcqc.x(range(n)) qcqc.h(range(n)) qcqc.barrier() qcqc.x([1,3]) qcqc.h(n-1) qcqc.mct(s, n-1) qcqc.h(n-1) qcqc.x([1,3]) qcqc.h(n-1) qcqc.mct(s, n-1) qcqc.h(n-1) qcqc.x([0,1,2]) qcqc.h(n-1) qcqc.mct(s, n-1) qcqc.h(n-1) qcqc.x([0,1,2]) qcqc.barrier() qcqc.h(range(n)) qcqc.x(range(n)) qcqc.h(n-1) qcqc.mct(s, n-1) qcqc.h(n-1) qcqc.x(range(n)) qcqc.h(range(n)) qcqc.barrier() qcqc.x([1,3]) qcqc.h(n-1) qcqc.mct(s, n-1) qcqc.h(n-1) qcqc.x([1,3]) qcqc.h(n-1) qcqc.mct(s, n-1) qcqc.h(n-1) qcqc.x([0,1,2]) qcqc.h(n-1) qcqc.mct(s, n-1) qcqc.h(n-1) qcqc.x([0,1,2]) qcqc.barrier() qcqc.h(range(n)) qcqc.x(range(n)) qcqc.h(n-1) qcqc.mct(s, n-1) qcqc.h(n-1) qcqc.x(range(n)) qcqc.h(range(n)) qcqc.measure_all() qcqc.draw('mpl') bknd = Aer.get_backend('qasm_simulator') ph(execute(qcqc,backend=bknd,shots=1024).result().get_counts())
https://github.com/UST-QuAntiL/nisq-analyzer-content
UST-QuAntiL
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute, Aer # https://quantum-circuit.com/app_details/about/66bpe6Jf5mgQMahgd # oracle = '(A | B) & (A | ~B) & (~A | B)' qc = QuantumCircuit() q = QuantumRegister(8, 'q') c = ClassicalRegister(2, 'c') qc.add_register(q) qc.add_register(c) qc.h(q[0]) qc.h(q[1]) qc.x(q[2]) qc.x(q[3]) qc.x(q[4]) qc.x(q[7]) qc.x(q[0]) qc.x(q[1]) qc.h(q[7]) qc.ccx(q[0], q[1], q[2]) qc.x(q[0]) qc.x(q[1]) qc.x(q[1]) qc.ccx(q[0], q[1], q[3]) qc.x(q[0]) qc.x(q[1]) qc.ccx(q[1], q[0], q[4]) qc.x(q[0]) qc.ccx(q[3], q[2], q[5]) qc.x(q[0]) qc.ccx(q[5], q[4], q[6]) qc.cx(q[6], q[7]) qc.ccx(q[4], q[5], q[6]) qc.ccx(q[2], q[3], q[5]) qc.x(q[4]) qc.ccx(q[0], q[1], q[4]) qc.x(q[0]) qc.x(q[1]) qc.x(q[3]) qc.ccx(q[0], q[1], q[3]) qc.x(q[0]) qc.x(q[1]) qc.x(q[2]) qc.x(q[1]) qc.ccx(q[0], q[1], q[2]) qc.x(q[0]) qc.x(q[1]) qc.h(q[0]) qc.h(q[1]) qc.x(q[0]) qc.x(q[1]) qc.cz(q[0], q[1]) qc.x(q[0]) qc.x(q[1]) qc.h(q[0]) qc.h(q[1]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1])
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/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # Author: Daniel Escanez-Exposito from crypto.six_state.participant import Participant from qiskit import QuantumCircuit ## The Sender entity in the Six-State implementation ## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html class Sender(Participant): ## Constructor def __init__(self, name='', original_bits_size=0): super().__init__(name, original_bits_size) ## Encode the message (values) using a quantum circuit def encode_quantum_message(self): encoded_message = [] for i in range(len(self.axes)): qc = QuantumCircuit(1, 1) if self.values[i] == 1: qc.x(0) if self.axes[i] == 1: qc.h(0) elif self.axes[i] == 2: qc.append(self.hy, [0]) encoded_message.append(qc) return encoded_message
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Amplitude Estimation Benchmark Program via Phase Estimation - QSim """ import copy import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = ["_common", "_common/qsim", "quantum-fourier-transform/qsim"] sys.path[1:1] = ["../../_common", "../../_common/qsim", "../../quantum-fourier-transform/qsim"] import execute as ex import metrics as metrics from execute import BenchmarkResult from qft_benchmark import inv_qft_gate # Benchmark Name benchmark_name = "Amplitude Estimation" np.random.seed(0) verbose = False # saved subcircuits circuits for printing A_ = None Q_ = None cQ_ = None QC_ = None QFTI_ = None ############### Circuit Definition def AmplitudeEstimation(num_state_qubits, num_counting_qubits, a, psi_zero=None, psi_one=None): num_qubits = num_state_qubits + 1 + num_counting_qubits qr_state = QuantumRegister(num_state_qubits+1) qr_counting = QuantumRegister(num_counting_qubits) cr = ClassicalRegister(num_counting_qubits) qc = QuantumCircuit(qr_counting, qr_state, cr, name=f"qae-{num_qubits}-{a}") # create the Amplitude Generator circuit A = A_gen(num_state_qubits, a, psi_zero, psi_one) # create the Quantum Operator circuit and a controlled version of it cQ, Q = Ctrl_Q(num_state_qubits, A) # save small example subcircuits for visualization global A_, Q_, cQ_, QFTI_ if (cQ_ and Q_) == None or num_state_qubits <= 6: if num_state_qubits < 9: cQ_ = cQ; Q_ = Q; A_ = A if QFTI_ == None or num_qubits <= 5: if num_qubits < 9: QFTI_ = inv_qft_gate(num_counting_qubits) # Prepare state from A, and counting qubits with H transform qc.append(A, [qr_state[i] for i in range(num_state_qubits+1)]) for i in range(num_counting_qubits): qc.h(qr_counting[i]) repeat = 1 for j in reversed(range(num_counting_qubits)): for _ in range(repeat): qc.append(cQ, [qr_counting[j]] + [qr_state[l] for l in range(num_state_qubits+1)]) repeat *= 2 qc.barrier() # inverse quantum Fourier transform only on counting qubits qc.append(inv_qft_gate(num_counting_qubits), qr_counting) qc.barrier() # measure counting qubits qc.measure([qr_counting[m] for m in range(num_counting_qubits)], list(range(num_counting_qubits))) # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc return qc # Construct A operator that takes |0>_{n+1} to sqrt(1-a) |psi_0>|0> + sqrt(a) |psi_1>|1> def A_gen(num_state_qubits, a, psi_zero=None, psi_one=None): if psi_zero==None: psi_zero = '0'*num_state_qubits if psi_one==None: psi_one = '1'*num_state_qubits theta = 2 * np.arcsin(np.sqrt(a)) # Let the objective be qubit index n; state is on qubits 0 through n-1 qc_A = QuantumCircuit(num_state_qubits+1, name=f"A") # takes state to |0>_{n} (sqrt(1-a) |0> + sqrt(a) |1>) qc_A.ry(theta, num_state_qubits) # takes state to sqrt(1-a) |psi_0>|0> + sqrt(a) |0>_{n}|1> qc_A.x(num_state_qubits) for i in range(num_state_qubits): if psi_zero[i]=='1': qc_A.cnot(num_state_qubits,i) qc_A.x(num_state_qubits) # takes state to sqrt(1-a) |psi_0>|0> + sqrt(a) |psi_1>|1> for i in range(num_state_qubits): if psi_one[i]=='1': qc_A.cnot(num_state_qubits,i) return qc_A # Construct the grover-like operator and a controlled version of it def Ctrl_Q(num_state_qubits, A_circ): # index n is the objective qubit, and indexes 0 through n-1 are state qubits qc = QuantumCircuit(num_state_qubits+1, name=f"Q") temp_A = copy.copy(A_circ) A_gate = temp_A.to_gate() A_gate_inv = temp_A.inverse().to_gate() ### Each cycle in Q applies in order: -S_chi, A_circ_inverse, S_0, A_circ # -S_chi qc.x(num_state_qubits) qc.z(num_state_qubits) qc.x(num_state_qubits) # A_circ_inverse qc.append(A_gate_inv, [i for i in range(num_state_qubits+1)]) # S_0 for i in range(num_state_qubits+1): qc.x(i) qc.h(num_state_qubits) qc.mcx([x for x in range(num_state_qubits)], num_state_qubits) qc.h(num_state_qubits) for i in range(num_state_qubits+1): qc.x(i) # A_circ qc.append(A_gate, [i for i in range(num_state_qubits+1)]) # Create a gate out of the Q operator qc.to_gate(label='Q') # and also a controlled version of it Ctrl_Q_ = qc.control(1) # and return both return Ctrl_Q_, qc # Analyze and print measured results # Expected result is always the secret_int (which encodes alpha), so fidelity calc is simple def analyze_and_print_result(qc, result, num_counting_qubits, s_int, num_shots): if result.backend_name == 'dm_simulator': benchmark_result = BenchmarkResult(result, num_shots) probs = benchmark_result.get_probs(num_shots) # get results as measured probability else: probs = result.get_counts(qc) # get results as measured counts # calculate expected output histogram a = a_from_s_int(s_int, num_counting_qubits) correct_dist = a_to_bitstring(a, num_counting_qubits) # print("correct_dist ====== ", correct_dist) # generate thermal_dist for polarization calculation thermal_dist = metrics.uniform_dist(num_counting_qubits) # print("thermal_dist ====== ", thermal_dist) # convert probs, expectation, and thermal_dist to app form for visibility # app form of correct distribution is measuring amplitude a 100% of the time app_counts = bitstring_to_a(probs, num_counting_qubits) app_correct_dist = {a: 1.0} app_thermal_dist = bitstring_to_a(thermal_dist, num_counting_qubits) # print("app_counts ====== ", app_counts) # print("app_correct_dist ====== ", app_correct_dist) # print("app_thermal_dist ====== ", app_thermal_dist) if verbose: print(f"For amplitude {a}, expected: {correct_dist} measured: {probs}") print(f" ... For amplitude {a} thermal_dist: {thermal_dist}") print(f"For amplitude {a}, app expected: {app_correct_dist} measured: {app_counts}") print(f" ... For amplitude {a} app_thermal_dist: {app_thermal_dist}") # use polarization fidelity with rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist, thermal_dist) #fidelity = metrics.polarization_fidelity(app_counts, app_correct_dist, app_thermal_dist) # print("fidelity ====== ", fidelity) hf_fidelity = metrics.hellinger_fidelity_with_expected(probs, correct_dist) if verbose: print(f" ... fidelity: {fidelity} hf_fidelity: {hf_fidelity}") return probs, fidelity def a_to_bitstring(a, num_counting_qubits): m = num_counting_qubits # solution 1 num1 = round(np.arcsin(np.sqrt(a)) / np.pi * 2**m) num2 = round( (np.pi - np.arcsin(np.sqrt(a))) / np.pi * 2**m) if num1 != num2 and num2 < 2**m and num1 < 2**m: counts = {format(num1, "0"+str(m)+"b"): 0.5, format(num2, "0"+str(m)+"b"): 0.5} else: counts = {format(num1, "0"+str(m)+"b"): 1} return counts def bitstring_to_a(counts, num_counting_qubits): est_counts = {} m = num_counting_qubits precision = int(num_counting_qubits / (np.log2(10))) + 2 for key in counts.keys(): r = counts[key] num = int(key,2) / (2**m) a_est = round((np.sin(np.pi * num) )** 2, precision) if a_est not in est_counts.keys(): est_counts[a_est] = 0 est_counts[a_est] += r return est_counts def a_from_s_int(s_int, num_counting_qubits): theta = s_int * np.pi / (2**num_counting_qubits) precision = int(num_counting_qubits / (np.log2(10))) + 2 a = round(np.sin(theta)**2, precision) return a ################ Benchmark Loop # Because circuit size grows significantly with num_qubits # limit the max_qubits here ... MAX_QUBITS=8 # Execute program with default parameters def run(min_qubits=4, max_qubits=8, skip_qubits=1, max_circuits=3, num_shots=100, #for dm-simulator min_qubits=4 because it requires to measure atleast 2 qubits num_state_qubits=1, # default, not exposed to users backend_id='dm_simulator', provider_backend=None, # hub="ibm-q", group="open", project="main", exec_options=None, context=None): print(f"{benchmark_name} Benchmark Program - QSim") # Clamp the maximum number of qubits if max_qubits > MAX_QUBITS: print(f"INFO: {benchmark_name} benchmark is limited to a maximum of {MAX_QUBITS} qubits.") max_qubits = MAX_QUBITS # validate parameters (smallest circuit is 3 qubits) num_state_qubits = max(1, num_state_qubits) if max_qubits < num_state_qubits + 2: print(f"ERROR: AE Benchmark needs at least {num_state_qubits + 2} qubits to run") return min_qubits = max(max(4, min_qubits), num_state_qubits + 2) # min_qubit=4 for AE using dm-simulator skip_qubits = max(1, skip_qubits) #print(f"min, max, state = {min_qubits} {max_qubits} {num_state_qubits}") # create context identifier if context is None: context = f"{benchmark_name} Benchmark" ########## # 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_counting_qubits = int(num_qubits) - num_state_qubits - 1 counts, fidelity = analyze_and_print_result(qc, result, num_counting_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, #hub=hub, group=group, project=project, exec_options=exec_options, context=context) ########## # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): # reset random seed np.random.seed(0) # as circuit width grows, the number of counting qubits is increased num_counting_qubits = num_qubits - num_state_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2 ** (num_counting_qubits), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") if verbose: print(f" with num_state_qubits = {num_state_qubits} num_counting_qubits = {num_counting_qubits}") # determine range of secret strings to loop over if 2**(num_counting_qubits) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(num_counting_qubits), num_circuits, False) # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() a_ = a_from_s_int(s_int, num_counting_qubits) qc = AmplitudeEstimation(num_state_qubits, num_counting_qubits, a_).reverse_bits() #applying reverse_bits() due to change in endianness metrics.store_metric(num_qubits, s_int, 'create_time', time.time() - ts) # collapse the 3 sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose().decompose().decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, s_int, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nControlled Quantum Operator 'cQ' ="); print(cQ_ if cQ_ != None else " ... too large!") print("\nQuantum Operator 'Q' ="); print(Q_ if Q_ != None else " ... too large!") print("\nAmplitude Generator 'A' ="); print(A_ if A_ != None else " ... too large!") print("\nInverse QFT Circuit ="); print(QFTI_ if QC_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim") # if main, execute method if __name__ == '__main__': ex.local_args() # calling local_args() needed while taking noise parameters through command line arguments (for individual benchmarks) run()
https://github.com/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 optimize-1q-gate pass""" import unittest import numpy as np from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Optimize1qGates, Unroller from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase from qiskit.circuit import Parameter from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, UGate, PhaseGate from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.target import Target class TestOptimize1qGates(QiskitTestCase): """Test for 1q gate optimizations.""" def test_dont_optimize_id(self): """Identity gates are like 'wait' commands. They should never be optimized (even without barriers). See: https://github.com/Qiskit/qiskit-terra/issues/2373 """ qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.i(qr) circuit.i(qr) dag = circuit_to_dag(circuit) pass_ = Optimize1qGates() after = pass_.run(dag) self.assertEqual(dag, after) def test_optimize_h_gates_pass_manager(self): """Transpile: qr:--[H]-[H]-[H]-- == qr:--[u2]--""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.h(qr[0]) expected = QuantumCircuit(qr) expected.append(U2Gate(0, np.pi), [qr[0]]) passmanager = PassManager() passmanager.append(Unroller(["u2"])) passmanager.append(Optimize1qGates()) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_1q_gates_collapse_identity_equivalent(self): """test optimize_1q_gates removes u1(2*pi) rotations. See: https://github.com/Qiskit/qiskit-terra/issues/159 """ # ┌───┐┌───┐┌────────┐┌───┐┌─────────┐┌───────┐┌─────────┐┌───┐ ┌─┐» # qr_0: ┤ H ├┤ X ├┤ U1(2π) ├┤ X ├┤ U1(π/2) ├┤ U1(π) ├┤ U1(π/2) ├┤ X ├─────────┤M├» # └───┘└─┬─┘└────────┘└─┬─┘└─────────┘└───────┘└─────────┘└─┬─┘┌───────┐└╥┘» # qr_1: ───────■──────────────■───────────────────────────────────■──┤ U1(π) ├─╫─» # └───────┘ ║ » # cr: 2/═══════════════════════════════════════════════════════════════════════╩═» # 0 » # « # «qr_0: ──────────── # « ┌───────┐┌─┐ # «qr_1: ┤ U1(π) ├┤M├ # « └───────┘└╥┘ # «cr: 2/══════════╩═ # « 1 qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[1], qr[0]) qc.append(U1Gate(2 * np.pi), [qr[0]]) qc.cx(qr[1], qr[0]) qc.append(U1Gate(np.pi / 2), [qr[0]]) # these three should combine qc.append(U1Gate(np.pi), [qr[0]]) # to identity then qc.append(U1Gate(np.pi / 2), [qr[0]]) # optimized away. qc.cx(qr[1], qr[0]) qc.append(U1Gate(np.pi), [qr[1]]) qc.append(U1Gate(np.pi), [qr[1]]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) dag = circuit_to_dag(qc) simplified_dag = Optimize1qGates().run(dag) num_u1_gates_remaining = len(simplified_dag.named_nodes("u1")) self.assertEqual(num_u1_gates_remaining, 0) def test_optimize_1q_gates_collapse_identity_equivalent_phase_gate(self): """test optimize_1q_gates removes u1(2*pi) rotations. See: https://github.com/Qiskit/qiskit-terra/issues/159 """ # ┌───┐┌───┐┌───────┐┌───┐┌────────┐┌──────┐┌────────┐┌───┐ ┌─┐» # qr_0: ┤ H ├┤ X ├┤ P(2π) ├┤ X ├┤ P(π/2) ├┤ P(π) ├┤ P(π/2) ├┤ X ├────────┤M├» # └───┘└─┬─┘└───────┘└─┬─┘└────────┘└──────┘└────────┘└─┬─┘┌──────┐└╥┘» # qr_1: ───────■─────────────■────────────────────────────────■──┤ P(π) ├─╫─» # └──────┘ ║ » # cr: 2/══════════════════════════════════════════════════════════════════╩═» # 0 » # « # «qr_0: ─────────── # « ┌──────┐┌─┐ # «qr_1: ┤ P(π) ├┤M├ # « └──────┘└╥┘ # «cr: 2/═════════╩═ # « 1 qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[1], qr[0]) qc.append(PhaseGate(2 * np.pi), [qr[0]]) qc.cx(qr[1], qr[0]) qc.append(PhaseGate(np.pi / 2), [qr[0]]) # these three should combine qc.append(PhaseGate(np.pi), [qr[0]]) # to identity then qc.append(PhaseGate(np.pi / 2), [qr[0]]) # optimized away. qc.cx(qr[1], qr[0]) qc.append(PhaseGate(np.pi), [qr[1]]) qc.append(PhaseGate(np.pi), [qr[1]]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) dag = circuit_to_dag(qc) simplified_dag = Optimize1qGates(["p", "u2", "u", "cx", "id"]).run(dag) num_u1_gates_remaining = len(simplified_dag.named_nodes("p")) self.assertEqual(num_u1_gates_remaining, 0) def test_ignores_conditional_rotations(self): """Conditional rotations should not be considered in the chain. qr0:--[U1]-[U1]-[U1]-[U1]- qr0:--[U1]-[U1]- || || || || cr0:===.================== == cr0:===.====.=== || || cr1:========.============= cr1:========.=== """ qr = QuantumRegister(1, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.append(U1Gate(0.1), [qr]).c_if(cr, 1) circuit.append(U1Gate(0.2), [qr]).c_if(cr, 3) circuit.append(U1Gate(0.3), [qr]) circuit.append(U1Gate(0.4), [qr]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.append(U1Gate(0.1), [qr]).c_if(cr, 1) expected.append(U1Gate(0.2), [qr]).c_if(cr, 3) expected.append(U1Gate(0.7), [qr]) pass_ = Optimize1qGates() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_ignores_conditional_rotations_phase_gates(self): """Conditional rotations should not be considered in the chain. qr0:--[U1]-[U1]-[U1]-[U1]- qr0:--[U1]-[U1]- || || || || cr0:===.================== == cr0:===.====.=== || || cr1:========.============= cr1:========.=== """ qr = QuantumRegister(1, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.append(PhaseGate(0.1), [qr]).c_if(cr, 1) circuit.append(PhaseGate(0.2), [qr]).c_if(cr, 3) circuit.append(PhaseGate(0.3), [qr]) circuit.append(PhaseGate(0.4), [qr]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.append(PhaseGate(0.1), [qr]).c_if(cr, 1) expected.append(PhaseGate(0.2), [qr]).c_if(cr, 3) expected.append(PhaseGate(0.7), [qr]) pass_ = Optimize1qGates(["p", "u2", "u", "cx", "id"]) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_in_the_back(self): """Optimizations can be in the back of the circuit. See https://github.com/Qiskit/qiskit-terra/issues/2004. qr0:--[U1]-[U1]-[H]-- qr0:--[U1]-[H]-- """ qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U1Gate(0.3), [qr]) circuit.append(U1Gate(0.4), [qr]) circuit.h(qr) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.append(U1Gate(0.7), [qr]) expected.h(qr) pass_ = Optimize1qGates() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_in_the_back_phase_gate(self): """Optimizations can be in the back of the circuit. See https://github.com/Qiskit/qiskit-terra/issues/2004. qr0:--[U1]-[U1]-[H]-- qr0:--[U1]-[H]-- """ qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(PhaseGate(0.3), [qr]) circuit.append(PhaseGate(0.4), [qr]) circuit.h(qr) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.append(PhaseGate(0.7), [qr]) expected.h(qr) pass_ = Optimize1qGates(["p", "u2", "u", "cx", "id"]) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_single_parameterized_circuit(self): """Parameters should be treated as opaque gates.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) theta = Parameter("theta") qc.append(U1Gate(0.3), [qr]) qc.append(U1Gate(0.4), [qr]) qc.append(U1Gate(theta), [qr]) qc.append(U1Gate(0.1), [qr]) qc.append(U1Gate(0.2), [qr]) dag = circuit_to_dag(qc) expected = QuantumCircuit(qr) expected.append(U1Gate(theta + 1.0), [qr]) after = Optimize1qGates().run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_parameterized_circuits(self): """Parameters should be treated as opaque gates.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) theta = Parameter("theta") qc.append(U1Gate(0.3), [qr]) qc.append(U1Gate(0.4), [qr]) qc.append(U1Gate(theta), [qr]) qc.append(U1Gate(0.1), [qr]) qc.append(U1Gate(0.2), [qr]) qc.append(U1Gate(theta), [qr]) qc.append(U1Gate(0.3), [qr]) qc.append(U1Gate(0.2), [qr]) dag = circuit_to_dag(qc) expected = QuantumCircuit(qr) expected.append(U1Gate(2 * theta + 1.5), [qr]) after = Optimize1qGates().run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_parameterized_expressions_in_circuits(self): """Expressions of Parameters should be treated as opaque gates.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) theta = Parameter("theta") phi = Parameter("phi") sum_ = theta + phi product_ = theta * phi qc.append(U1Gate(0.3), [qr]) qc.append(U1Gate(0.4), [qr]) qc.append(U1Gate(theta), [qr]) qc.append(U1Gate(phi), [qr]) qc.append(U1Gate(sum_), [qr]) qc.append(U1Gate(product_), [qr]) qc.append(U1Gate(0.3), [qr]) qc.append(U1Gate(0.2), [qr]) dag = circuit_to_dag(qc) expected = QuantumCircuit(qr) expected.append(U1Gate(2 * theta + 2 * phi + product_ + 1.2), [qr]) after = Optimize1qGates().run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_global_phase_u3_on_left(self): """Check proper phase accumulation with instruction with no definition.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) u1 = U1Gate(0.1) u1.definition.global_phase = np.pi / 2 qc.append(u1, [0]) qc.global_phase = np.pi / 3 qc.append(U3Gate(0.1, 0.2, 0.3), [0]) dag = circuit_to_dag(qc) after = Optimize1qGates().run(dag) self.assertAlmostEqual(after.global_phase, 5 * np.pi / 6, 8) def test_global_phase_u_on_left(self): """Check proper phase accumulation with instruction with no definition.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) u1 = U1Gate(0.1) u1.definition.global_phase = np.pi / 2 qc.append(u1, [0]) qc.global_phase = np.pi / 3 qc.append(UGate(0.1, 0.2, 0.3), [0]) dag = circuit_to_dag(qc) after = Optimize1qGates(["u1", "u2", "u", "cx"]).run(dag) self.assertAlmostEqual(after.global_phase, 5 * np.pi / 6, 8) class TestOptimize1qGatesParamReduction(QiskitTestCase): """Test for 1q gate optimizations parameter reduction, reduce n in Un""" def test_optimize_u3_to_u2(self): """U3(pi/2, pi/3, pi/4) -> U2(pi/3, pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(np.pi / 2, np.pi / 3, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U2Gate(np.pi / 3, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates()) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u3_to_u2_round(self): """U3(1.5707963267948961, 1.0471975511965971, 0.7853981633974489) -> U2(pi/3, pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(1.5707963267948961, 1.0471975511965971, 0.7853981633974489), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U2Gate(np.pi / 3, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates()) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u3_to_u1(self): """U3(0, 0, pi/4) -> U1(pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(0, 0, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U1Gate(np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates()) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u3_to_phase_gate(self): """U3(0, 0, pi/4) -> U1(pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(0, 0, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(PhaseGate(np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["p", "u2", "u", "cx", "id"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u3_to_u1_round(self): """U3(1e-16, 1e-16, pi/4) -> U1(pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(1e-16, 1e-16, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U1Gate(np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates()) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u3_to_phase_round(self): """U3(1e-16, 1e-16, pi/4) -> U1(pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(1e-16, 1e-16, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(PhaseGate(np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["p", "u2", "u", "cx", "id"])) result = passmanager.run(circuit) self.assertEqual(expected, result) class TestOptimize1qGatesBasis(QiskitTestCase): """Test for 1q gate optimizations parameter reduction with basis""" def test_optimize_u3_basis_u3(self): """U3(pi/2, pi/3, pi/4) (basis[u3]) -> U3(pi/2, pi/3, pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(np.pi / 2, np.pi / 3, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u3"])) result = passmanager.run(circuit) self.assertEqual(circuit, result) def test_optimize_u3_basis_u(self): """U3(pi/2, pi/3, pi/4) (basis[u3]) -> U(pi/2, pi/3, pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(np.pi / 2, np.pi / 3, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u"])) result = passmanager.run(circuit) expected = QuantumCircuit(qr) expected.append(UGate(np.pi / 2, np.pi / 3, np.pi / 4), [qr[0]]) self.assertEqual(expected, result) def test_optimize_u3_basis_u2(self): """U3(pi/2, 0, pi/4) -> U2(0, pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(np.pi / 2, 0, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U2Gate(0, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u2"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u3_basis_u2_with_target(self): """U3(pi/2, 0, pi/4) -> U2(0, pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(np.pi / 2, 0, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U2Gate(0, np.pi / 4), [qr[0]]) target = Target(num_qubits=1) target.add_instruction(U2Gate(Parameter("theta"), Parameter("phi"))) passmanager = PassManager() passmanager.append(Optimize1qGates(target=target)) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u_basis_u(self): """U(pi/2, pi/3, pi/4) (basis[u3]) -> U(pi/2, pi/3, pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(UGate(np.pi / 2, np.pi / 3, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u"])) result = passmanager.run(circuit) self.assertEqual(circuit, result) def test_optimize_u3_basis_u2_cx(self): """U3(pi/2, 0, pi/4) -> U2(0, pi/4). Basis [u2, cx].""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(np.pi / 2, 0, np.pi / 4), [qr[0]]) circuit.cx(qr[0], qr[1]) expected = QuantumCircuit(qr) expected.append(U2Gate(0, np.pi / 4), [qr[0]]) expected.cx(qr[0], qr[1]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u2", "cx"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u_basis_u2_cx(self): """U(pi/2, 0, pi/4) -> U2(0, pi/4). Basis [u2, cx].""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.append(UGate(np.pi / 2, 0, np.pi / 4), [qr[0]]) circuit.cx(qr[0], qr[1]) expected = QuantumCircuit(qr) expected.append(U2Gate(0, np.pi / 4), [qr[0]]) expected.cx(qr[0], qr[1]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u2", "cx"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u1_basis_u2_u3(self): """U1(pi/4) -> U3(0, 0, pi/4). Basis [u2, u3].""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U1Gate(np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U3Gate(0, 0, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u2", "u3"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u1_basis_u2_u(self): """U1(pi/4) -> U3(0, 0, pi/4). Basis [u2, u3].""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U1Gate(np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(UGate(0, 0, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u2", "u"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u1_basis_u2(self): """U1(pi/4) -> Raises. Basis [u2]""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U1Gate(np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U3Gate(0, 0, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u2"])) with self.assertRaises(TranspilerError): _ = passmanager.run(circuit) def test_optimize_u3_basis_u2_u1(self): """U3(pi/2, 0, pi/4) -> U2(0, pi/4). Basis [u2, u1].""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(np.pi / 2, 0, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U2Gate(0, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u2", "u1"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u3_basis_u2_phase_gate(self): """U3(pi/2, 0, pi/4) -> U2(0, pi/4). Basis [u2, p].""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(np.pi / 2, 0, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U2Gate(0, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u2", "p"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u3_basis_u1(self): """U3(0, 0, pi/4) -> U1(pi/4). Basis [u1].""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(0, 0, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U1Gate(np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u1"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u3_basis_phase_gate(self): """U3(0, 0, pi/4) -> p(pi/4). Basis [p].""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(0, 0, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(PhaseGate(np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["p"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u_basis_u1(self): """U(0, 0, pi/4) -> U1(pi/4). Basis [u1].""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.append(UGate(0, 0, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U1Gate(np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u1"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u_basis_phase_gate(self): """U(0, 0, pi/4) -> p(pi/4). Basis [p].""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.append(UGate(0, 0, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(PhaseGate(np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["p"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u3_with_parameters(self): """Test correct behavior for u3 gates.""" phi = Parameter("φ") alpha = Parameter("α") qr = QuantumRegister(1, "qr") qc = QuantumCircuit(qr) qc.ry(2 * phi, qr[0]) qc.ry(alpha, qr[0]) qc.ry(0.1, qr[0]) qc.ry(0.2, qr[0]) passmanager = PassManager([Unroller(["u3"]), Optimize1qGates()]) result = passmanager.run(qc) expected = QuantumCircuit(qr) expected.append(U3Gate(2 * phi, 0, 0), [qr[0]]) expected.append(U3Gate(alpha, 0, 0), [qr[0]]) expected.append(U3Gate(0.3, 0, 0), [qr[0]]) self.assertEqual(expected, result) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-jku-provider
qiskit-community
# -*- coding: utf-8 -*- # Copyright 2019, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. """Usage examples for the JKU Provider""" from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, execute from qiskit_jku_provider import JKUProvider JKU = JKUProvider() jku_backend = JKU.get_backend('qasm_simulator') print(jku_backend) # gets the name of the backend. print(jku_backend.name()) # gets the status of the backend. print(jku_backend.status()) # returns the provider of the backend print(jku_backend.provider()) # gets the configuration of the backend. print(jku_backend.configuration()) # gets the properties of the backend. print(jku_backend.properties()) # Demonstration of Job qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr, cr) job = execute(qc, backend=jku_backend) # gets the backend the job was run on backend = job.backend() print(backend) # returns the status of the job. Should be running print(job.status()) # returns the obj that was run qobj = job.qobj() print(qobj) # prints the job id print(job.job_id()) # cancels the job print(job.cancel()) # returns the status of the job. Should be canceled print(job.status()) # runs the qjob on the backend job2 = backend.run(qobj) # gets the result of the job. This is a blocker print(job2.result())
https://github.com/kerenavnery/qmail
kerenavnery
import Protocols ALICE_ADDR = 'localhost' OSCAR_ADDR = 'localhost' ALICE_PORT = 5008 OSCAR_PORT = 5009 def main(): # prepare message Protocols.multiparty_2grover_local( ALICE_PORT, OSCAR_PORT ) pass if __name__ == "__main__": main()
https://github.com/duartefrazao/Quantum-Finance-Algorithms
duartefrazao
from qiskit import QuantumCircuit from qiskit import transpiler from qiskit import Aer,BasicAer,execute,execute_function import time import math #circ.measure(1,1) backend = Aer.get_backend('aer_simulator') means = { "h":0, "cx":0, "x":0, "rx":0, "rz":0, "sdg":0 } iterations = 3 sleep_time = 0.2 #Hadamard times = 0 for i in range(iterations): circ = QuantumCircuit(1,1) circ.h(0) circ.measure(0,0) job = execute(circ, backend) times = times + job.result().time_taken time.sleep(sleep_time) means['h'] = 100*times/iterations #X times = 0 for i in range(iterations): circ = QuantumCircuit(1,1) circ.x(0) circ.measure(0,0) job = execute(circ, backend) times = times + job.result().time_taken time.sleep(sleep_time) means['x'] = 100*times/iterations #RZ times = 0 for i in range(iterations): circ = QuantumCircuit(1,1) circ.rz(math.pi/2,0) circ.measure(0,0) job = execute(circ, backend) times = times + job.result().time_taken time.sleep(sleep_time) means['rz'] = 100*times/iterations #RX times = 0 for i in range(iterations): circ = QuantumCircuit(1,1) circ.rx(math.pi/2,0) circ.measure(0,0) job = execute(circ, backend) times = times + job.result().time_taken time.sleep(sleep_time) means['rx'] = 100*times/iterations #CX times = 0 for i in range(iterations): circ = QuantumCircuit(2,2) circ.cx(0,1) circ.measure(0,0) circ.measure(1,1) job = execute(circ, backend) times = times + job.result().time_taken time.sleep(sleep_time) means['cx'] = 100*times/iterations #SDG times = 0 for i in range(iterations): circ = QuantumCircuit(1,1) circ.sdg(0) circ.measure(0,0) job = execute(circ, backend) times = times + job.result().time_taken time.sleep(sleep_time) means['sdg'] = 100*times/iterations f = open('gate_costs.txt', 'w') for gate in means: f.write(gate + ((4-len(gate))*" ") + "- " +str(means[gate]) + "\n") f.close() backend = BasicAer.get_backend('qasm_simulator') from time import time circ = QuantumCircuit(1,1) circ.h(0) job = execute(circ, backend) times = job.result().time_taken print(times)
https://github.com/devilkiller-ag/UnravelQuantum
devilkiller-ag
# ########## Import Initialization ############ from qiskit import QuantumCircuit, transpile from qiskit_aer import AerSimulator from qiskit.providers.basic_provider import BasicProvider from qiskit.visualization import plot_histogram, circuit_drawer from qiskit_ibm_provider.job import job_monitor from qiskit_ibm_provider import IBMProvider import streamlit as st import matplotlib.pyplot as plt from random import choice # ############################################# # ########## Deustch Josza Algorithm ########## def generate_bitstring(n): return "".join(choice("01") for _ in range(n)) def ConstantFunctionOracle(n, output): oracle = QuantumCircuit(n + 1) # n input qubits, 1 ancillia qubit for |-> if output == 0: return oracle elif output == 1: # Performing X on all qubits except one qubit(k) is computationally same as performing X only on one qubit(k) oracle.x(n) return oracle else: return "Error: Invalid function output" def BalancedFunctionOracle(n): xGatesString = cxGatesString = generate_bitstring(n) if len(xGatesString) != n: return "Error: Invalid length of X Gate String" if len(cxGatesString) != n: return "Error: Invalid length of CX Gate String" oracle = QuantumCircuit(n + 1) # n input qubits, 1 ancillia qubit for |-> # Place X-gates before implementing CX gates in the next loop for i in range(n): if xGatesString[i] == "1": oracle.x(i) # Place CX-gates to give phase at desired combinations for m in range(n): if cxGatesString[m] == "1": oracle.cx(m, n) # Place X-gates again to revert to original inputs on 0 to n-1 qubits for k in range(n): if xGatesString[k] == "1": oracle.x(k) return oracle def DeustchJoszaAlgo(n, FunctionOracle): dj_circuit = QuantumCircuit(n + 1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put ancillia qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.barrier() # Add Oracle dj_circuit = dj_circuit.compose(FunctionOracle) dj_circuit.barrier() # Repeat H-Gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) return dj_circuit def RunCircuit(circuit, provider, backend_name, shots=1024): backend = provider.get_backend(backend_name) job = transpile(circuit, backend=backend, shots=shots) results = job.result() counts = results.get_counts() job_monitor(job) job.status() return counts def run_on_simulator(circuit, provider, backend): answer = RunCircuit(circuit, provider, backend, shots=1024) st.subheader("Result Counts:") st.write(answer) # Display result counts as text st.subheader("Histogram:") fig, ax = plt.subplots() # Create a Matplotlib figure and axes plot_histogram(answer, ax=ax) # Pass the axes to the plot_histogram function st.pyplot(fig) # Display the Matplotlib figure using st.pyplot def run_on_real_backend(circuit, provider_api_key, backend): IBMProvider.save_account(provider_api_key, overwrite=True) provider = IBMProvider() # backend = 'ibm_perth' answer = RunCircuit(circuit, provider, backend, shots=1024) st.subheader("Result Counts:") st.write(answer) # Display result counts as text st.subheader("Histogram:") fig, ax = plt.subplots() # Create a Matplotlib figure and axes plot_histogram(answer, ax=ax) # Pass the axes to the plot_histogram function st.pyplot(fig) # Display the Matplotlib figure using st.pyplot # ########## Use the DJ Algorithm ########## # Page Config st.set_page_config(page_title='Deustch Josza Algorithm - Unravel Quantum', page_icon="⚔️", layout='wide') st.title("Deustch Josza Algorithm") n = st.slider("Select the number of qubits (n)", 1, 10, 3) st.write(f"Selected number of qubits: {n}") f0allx = ConstantFunctionOracle(n, 0) f1allx = ConstantFunctionOracle(n, 1) f01half = BalancedFunctionOracle(n) functions = {"Constant Function (f(x) = 0)": f0allx, "Constant Function (f(x) = 1)": f1allx, "Balanced Function": f01half} selected_function = st.selectbox("Select the type of function", list(functions.keys())) dj_circuit = DeustchJoszaAlgo(n, functions[selected_function]) st.write("**Circuit**") fig, ax = plt.subplots() circuit_drawer(dj_circuit, output='mpl', ax=ax) # Display the circuit using Matplotlib st.pyplot(fig) # Show the Matplotlib figure in Streamlit # providers = {"BasicAer": BasicProvider, "AerSimulator": AerSimulator} providers = {"BasicAer": BasicProvider} selected_provider = st.selectbox("Select Provider", list(providers.keys())) backends = providers[selected_provider]().backends() selected_backend = st.selectbox("Select Backend", list(backends)) if st.button("Run on Simulator") and selected_provider in providers: run_on_simulator(dj_circuit, providers[selected_provider], str(selected_backend)) # provider_api_key = st.text_input("Enter your IBM Quantum Experience API Key (for real backend)") # if st.button("Run on Real Backend") and provider_api_key: # backends = IBMProvider.backends() # selected_backend = st.selectbox("Select Backend", list(backends)) # run_on_real_backend(dj_circuit, provider_api_key, selected_backend) # ################################### Show the Implementation ######################################### dj_algo_code = ''' # Importing libraries from qiskit import QuantumCircuit, transpile from qiskit.providers.basic_provider import BasicProvider from qiskit_aer import AerSimulator from qiskit.visualization import plot_histogram, circuit_drawer from qiskit_ibm_provider.job import job_monitor from qiskit_ibm_provider import IBMProvider from random import choice def ConstantFunctionOracle(n, output): oracle = QuantumCircuit(n + 1) # n input qubits, 1 ancillia qubit for |-> if output == 0: return oracle elif output == 1: # Performing X on all qubits except one qubit(k) is computationally same as performing X only on one qubit(k) oracle.x(n) return oracle else: return "Error: Invalid function output" def BalancedFunctionOracle(n, xGatesString, cxGatesString): if len(xGatesString) != n: return "Error: Invalid length of X Gate String" if len(cxGatesString) != n: return "Error: Invalid length of CX Gate String" oracle = QuantumCircuit(n + 1) # n input qubits, 1 ancillia qubit for |-> # Place X-gates before implementing CX gates in the next loop for i in range(n): if xGatesString[i] == "1": oracle.x(i) # Place CX-gates to give phase at desired combinations for m in range(n): if cxGatesString[m] == "1": oracle.cx(m, n) # Place X-gates again to revert to original inputs on 0 to n-1 qubits for k in range(n): if xGatesString[k] == "1": oracle.x(k) return oracle def DeustchJoszaAlgo(n, FunctionOracle): dj_circuit = QuantumCircuit(n + 1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put ancillia qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.barrier() # Add Oracle dj_circuit = dj_circuit.compose(FunctionOracle) dj_circuit.barrier() # Repeat H-Gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) return dj_circuit def RunCircuit(circuit, provider, backend_name, shots=1024): backend = provider.get_backend(backend_name) transpiled_circuit = transpile(circuit, backend=backend) job = backend.run(transpiled_circuit, shots=shots) results = job.result() counts = results.get_counts() job_monitor(job) job.status() return counts def run_on_simulator(circuit, provider, backend, shots=1024): answer = RunCircuit(circuit, provider, backend, shots) plot_histogram(answer) return answer def run_on_real_backend(circuit, provider_api_key, backend, shots=1024): IBMProvider.save_account(provider_api_key, overwrite=True) provider = IBMProvider() answer = RunCircuit(circuit, provider, backend, shots) plot_histogram(answer) return answer # Create DJ Circuit f0allx = ConstantFunctionOracle(n, 0) f1allx = ConstantFunctionOracle(n, 1) f01half = BalancedFunctionOracle(n, "101", "101") dj_circuit = DeustchJoszaAlgo(n, f01half) dj_circuit.draw('mpl') # Run on the simulator provider = BasicProvider backend = 'qasm_simulator' run_on_simulator(dj_circuit, provider, backend, shots=1024) # Run on the real backend # provider_api_key = # your provider api key backend = 'ibm_perth' # run_on_real_backend(dj_circuit, provider_api_key, backend, shots=1024) ''' st.subheader("Implementation of Deustch Josza Algorithm") st.write(""" Reference: - [Deustch Josza Algorithm - Qiskit Textbook](https://learn.qiskit.org/course/ch-algorithms/deutsch-jozsa-algorithm) - [Deustch Josza Algorithm - Classiq](https://www.classiq.io/insights/the-deutsch-jozsa-algorithm-explained) """) st.code(dj_algo_code, language='python') # ################################### About the author ######################################### st.subheader("About the author: [Ashmit JaiSarita Gupta](https://jaisarita.vercel.app/)") st.write(""" [Ashmit JaiSarita Gupta](https://jaisarita.vercel.app/) is an engineering physics undergraduate passionate about Quantum Computing, Machine Learning, UI/UX, and Web Development. I am a student driven by the community and who shares what he has learned. I love to work on real world projects about the topics I learn which can be used by others. To accomplish this I frequently attend hackathons and collaborate with companies to work on real-world projects related to my domains. Feel free to contact me if your company is interested in working on awesome projects in these fields with me. I’m currently building most frequently with: JavaScript/Typescript, C++, and Python.Some of the main frameworks and libraries I frequently use are: React.js,Express.js, Tailwind CSS, ShadCN UI, Qiskit,and Pytorch. Explore the below links to explore more about him, his previous projects, blogs, and experience at various organizations. """) # ############ Socials ############ c1, c2, c3 = st.columns(3) with c1: st.info('**Portfolio: [Ashmit JaiSarita Gupta](https://jaisarita.vercel.app/)**', icon="🔥") with c2: st.info('**GitHub: [@devilkiller-ag](https://github.com/devilkiller-ag)**', icon="😸") with c3: st.info('**GitLab: [@devilkiller-ag](https://gitlab.com/devilkiller-ag)**', icon="🚀") c4, c5, c6 = st.columns(3) with c4: st.info('**LinkedIn: [jaisarita](https://www.linkedin.com/in/jaisarita/)**', icon="🌐") with c5: st.info('**Twitter: [@jaisarita](https://github.com/devilkiller-ag)**', icon="🐤") with c6: st.info('**Hashnode: [jaisarita](https://jaisarita.hashnode.dev/)**', icon="✍🏻")
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import numpy as np import qiskit from qiskit.opflow import X,Z,I from qiskit.opflow.state_fns import StateFn, CircuitStateFn from modules.utils import * import matplotlib.pyplot as plt from scipy import sparse import scipy.sparse.linalg.eigen.arpack as arp %matplotlib inline # first need a gate that is the exponential of ZZ, which shouldnt be too difficult since it can be done analytically L = 2 qreg = qiskit.QuantumRegister(L, 'q') creg = qiskit.ClassicalRegister(2, 'c') circ = qiskit.QuantumCircuit(qreg, creg) circ.rz() tau = qiskit.circuit.Parameter("tau") diaglist = [tau, -tau, -tau, tau] diaglist dt = 0.05 diaglist = [np.exp(dt), np.exp(-dt), np.exp(-dt), np.exp(dt)] qiskit.circuit.library.Diagonal(diaglist) import numpy as np from qiskit.opflow import I, X, Y, Z, H, CX, Zero, ListOp, PauliExpectation, PauliTrotterEvolution, CircuitSampler, MatrixEvolution, Suzuki from qiskit.circuit import Parameter from qiskit import BasicAer L=5 anti = -1 gx = 1e-2 gz = 1e-2 two_qubit_H2 = QHIsing(L,anti,np.float32(gx),np.float32(gz)) two_qubit_H2 = 1 * (X^X^X^Z^X + Z^Z^Z^Z^X) two_qubit_H2 evo_time = Parameter('θ') evolution_op = (evo_time * two_qubit_H2).exp_i() h2_measurement = StateFn(two_qubit_H2).adjoint() #print(h2_measurement) evo_and_meas = h2_measurement @ evolution_op @ Zero #print(evo_and_meas) trotterized_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=1)).convert(evo_and_meas) bound = trotterized_op.bind_parameters({evo_time: .5}) diagonalized_meas_op = PauliExpectation().convert(trotterized_op) evo_time_points = [1,2,3,4] h2_trotter_expectations = diagonalized_meas_op.bind_parameters({evo_time: evo_time_points}) h2_trotter_expectations.eval() # Ops H = QHIsing(L,anti,np.float32(gx),np.float32(gz)) H_meas = StateFn(H).adjoint() mag = QMag(L,anti) qiskit.opflow.One^5 qiskit.opflow.VectorStateFn(qiskit.opflow.One^5) asd = H_meas @ qiskit.opflow.One^5 asd.eval() evo_time = qiskit.circuit.Parameter('θ') # note that we will have to bind it laterevo_time = Parameter('θ') evolution_op = (evo_time * H).exp_i() #* 1j # expH = suzi.convert(H) evo_and_meas = H_meas @ evolution_op trotterized_op = qiskit.opflow.evolutions.PauliTrotterEvolution(trotter_mode=qiskit.opflow.evolutions.Suzuki(order=2, reps=1)).convert(evo_and_meas) bound = trotterized_op.bind_parameters({evo_time: .5}) bound.eval() diagonalized_meas_op = qiskit.opflow.PauliExpectation().convert(trotterized_op) h2_trotter_expectations = diagonalized_meas_op.bind_parameters({evo_time: 1}) h2_trotter_expectations.eval() H.__class__, evolution_op.__class__ def imaginary_time_evolution(tau, L, gx, gz, anti=-1): H = QHIsing(L,anti,np.float32(gx),np.float32(gz)) evo_time = qiskit.circuit.Parameter('tau') # note that we will have to bind it later evolution_op = (tau * 1j * H).exp_i() trotterized_op = qiskit.opflow.evolutions.PauliTrotterEvolution(trotter_mode=qiskit.opflow.evolutions.Suzuki(order=2, reps=1)).convert(H_meas @ evolution_op) return trotterized_op trott_op = imaginary_time_evolution(tau=1, L=5, gx=1e-2, gz=1e-2, anti=-1) trott_op.bind_param({evo_}) bound = trott_op.bind_parameters({evo_time: 1}) bound.to_circuit().draw() mag_res = ~StateFn(mag) @ StateFn(trott_op) mag_res.eval() bound.eval() bound = trotterized_op.bind_parameters({evo_time: tau}) # this is a dummy circuit for the sake of checking how I can combine the evolved state with a circuit later circ = qiskit.circuit.library.TwoLocal(5,"rx","cz", reps=1,entanglement="linear") circ.draw() circ_fn = CircuitStateFn(circ) print(circ_fn) evolved_processed = evolution_op @ circ_fn # first the imaginary time evolution, then the dummy processing print(evolved_processed ) trotterized_op = qiskit.opflow.evolutions.PauliTrotterEvolution(trotter_mode=qiskit.opflow.evolutions.Suzuki(order=2, reps=1)).convert(evolved_processed) print(trotterized_op) bound = trotterized_op.bind_parameters({evo_time: .5j}) bound.to_circuit().draw() # ED result Smag = Mag(L,anti) init_state, E, ham = ising_groundstate(L, anti, np.float(gx), np.float(gz)) Sen = E Smags = init_state.T.conj()@Smag@init_state #Magnetization with Numpy results
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.quantum_info import SparsePauliOp H2_op = SparsePauliOp.from_list( [ ("II", -1.052373245772859), ("IZ", 0.39793742484318045), ("ZI", -0.39793742484318045), ("ZZ", -0.01128010425623538), ("XX", 0.18093119978423156), ] ) from qiskit.primitives import Estimator estimator = Estimator() import numpy as np from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SLSQP from qiskit.circuit.library import TwoLocal from qiskit.utils import algorithm_globals # we will iterate over these different optimizers optimizers = [COBYLA(maxiter=80), L_BFGS_B(maxiter=60), SLSQP(maxiter=60)] converge_counts = np.empty([len(optimizers)], dtype=object) converge_vals = np.empty([len(optimizers)], dtype=object) for i, optimizer in enumerate(optimizers): print("\rOptimizer: {} ".format(type(optimizer).__name__), end="") algorithm_globals.random_seed = 50 ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) vqe = VQE(estimator, ansatz, optimizer, callback=store_intermediate_result) result = vqe.compute_minimum_eigenvalue(operator=H2_op) converge_counts[i] = np.asarray(counts) converge_vals[i] = np.asarray(values) print("\rOptimization complete "); import pylab pylab.rcParams["figure.figsize"] = (12, 8) for i, optimizer in enumerate(optimizers): pylab.plot(converge_counts[i], converge_vals[i], label=type(optimizer).__name__) pylab.xlabel("Eval count") pylab.ylabel("Energy") pylab.title("Energy convergence for various optimizers") pylab.legend(loc="upper right"); from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit.opflow import PauliSumOp numpy_solver = NumPyMinimumEigensolver() result = numpy_solver.compute_minimum_eigenvalue(operator=PauliSumOp(H2_op)) ref_value = result.eigenvalue.real print(f"Reference value: {ref_value:.5f}") pylab.rcParams["figure.figsize"] = (12, 8) for i, optimizer in enumerate(optimizers): pylab.plot( converge_counts[i], abs(ref_value - converge_vals[i]), label=type(optimizer).__name__, ) pylab.xlabel("Eval count") pylab.ylabel("Energy difference from solution reference value") pylab.title("Energy convergence for various optimizers") pylab.yscale("log") pylab.legend(loc="upper right"); from qiskit.algorithms.gradients import FiniteDiffEstimatorGradient estimator = Estimator() gradient = FiniteDiffEstimatorGradient(estimator, epsilon=0.01) algorithm_globals.random_seed = 50 ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") optimizer = SLSQP(maxiter=100) counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) vqe = VQE( estimator, ansatz, optimizer, callback=store_intermediate_result, gradient=gradient ) result = vqe.compute_minimum_eigenvalue(operator=H2_op) print(f"Value using Gradient: {result.eigenvalue.real:.5f}") pylab.rcParams["figure.figsize"] = (12, 8) pylab.plot(counts, values, label=type(optimizer).__name__) pylab.xlabel("Eval count") pylab.ylabel("Energy") pylab.title("Energy convergence using Gradient") pylab.legend(loc="upper right"); print(result) cost_function_evals = result.cost_function_evals initial_pt = result.optimal_point estimator1 = Estimator() gradient1 = FiniteDiffEstimatorGradient(estimator, epsilon=0.01) ansatz1 = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") optimizer1 = SLSQP(maxiter=1000) vqe1 = VQE( estimator1, ansatz1, optimizer1, gradient=gradient1, initial_point=initial_pt ) result1 = vqe1.compute_minimum_eigenvalue(operator=H2_op) print(result1) cost_function_evals1 = result1.cost_function_evals print() print( f"cost_function_evals is {cost_function_evals1} with initial point versus {cost_function_evals} without it." ) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Z-928/Bugs4Q
Z-928
# https://github.com/Z-726/Bugs-from-Users/edit/main/Program/1999.py import numpy as np from qiskit import * from qiskit.transpiler import transpile from qiskit.tools.qi.qi import random_unitary_matrix from qiskit.mapper import two_qubit_kak from qiskit.mapper import CouplingMap from qiskit.extensions.standard import SwapGate from qiskit.converters import circuit_to_dag def build_qv_circuit(seed, n, depth): """Create a quantum program containing model circuits. The model circuits consist of layers of Haar random elements of SU(4) applied between corresponding pairs of qubits in a random bipartition. name = leading name of circuits n = number of qubits depth = ideal depth of each model circuit (over SU(4)) """ np.random.seed(seed) q = QuantumRegister(n, "q") c = ClassicalRegister(n, "c") # Create measurement subcircuit qc = QuantumCircuit(q,c) # For each layer for j in range(depth): # Generate uniformly random permutation Pj of [0...n-1] perm = np.random.permutation(n) # For each pair p in Pj, generate Haar random SU(4) # Decompose each SU(4) into CNOT + SU(2) and add to Ci for k in range(int(np.floor(n/2))): qubits = [int(perm[2*k]), int(perm[2*k+1])] U = random_unitary_matrix(4) for gate in two_qubit_kak(U): i0 = qubits[gate["args"][0]] if gate["name"] == "cx": i1 = qubits[gate["args"][1]] qc.cx(q[i0], q[i1]) elif gate["name"] == "u1": qc.u1(gate["params"][2], q[i0]) elif gate["name"] == "u2": qc.u2(gate["params"][1], gate["params"][2], q[i0]) elif gate["name"] == "u3": qc.u3(gate["params"][0], gate["params"][1], gate["params"][2], q[i0]) elif gate["name"] == "id": pass # do nothing #qc.measure(q,c) return qc circuit = build_qv_circuit(1234, 20, 100) dag = circuit_to_dag(circuit) print(dag.num_tensor_factors())
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=too-many-function-args, unexpected-keyword-arg """THIS FILE IS DEPRECATED AND WILL BE REMOVED IN RELEASE 0.9. """ import warnings from qiskit.converters import dag_to_circuit, circuit_to_dag from qiskit.transpiler import CouplingMap from qiskit import compiler from qiskit.transpiler.preset_passmanagers import (default_pass_manager_simulator, default_pass_manager) def transpile(circuits, backend=None, basis_gates=None, coupling_map=None, initial_layout=None, seed_mapper=None, pass_manager=None): """transpile one or more circuits. Args: circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile backend (BaseBackend): a backend to compile for basis_gates (list[str]): list of basis gate names supported by the target. Default: ['u1','u2','u3','cx','id'] coupling_map (list): coupling map (perhaps custom) to target in mapping initial_layout (Layout or dict or list): Initial position of virtual qubits on physical qubits. The final layout is not guaranteed to be the same, as the transpiler may permute qubits through swaps or other means. seed_mapper (int): random seed for the swap_mapper pass_manager (PassManager): a pass_manager for the transpiler stages Returns: QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s). Raises: TranspilerError: in case of bad inputs to transpiler or errors in passes """ warnings.warn("qiskit.transpiler.transpile() has been deprecated and will be " "removed in the 0.9 release. Use qiskit.compiler.transpile() instead.", DeprecationWarning) return compiler.transpile(circuits=circuits, backend=backend, basis_gates=basis_gates, coupling_map=coupling_map, initial_layout=initial_layout, seed_transpiler=seed_mapper, pass_manager=pass_manager) def transpile_dag(dag, basis_gates=None, coupling_map=None, initial_layout=None, seed_mapper=None, pass_manager=None): """Deprecated - Use qiskit.compiler.transpile for transpiling from circuits to circuits. Transform a dag circuit into another dag circuit (transpile), through consecutive passes on the dag. Args: dag (DAGCircuit): dag circuit to transform via transpilation basis_gates (list[str]): list of basis gate names supported by the target. Default: ['u1','u2','u3','cx','id'] coupling_map (list): A graph of coupling:: [ [control0(int), target0(int)], [control1(int), target1(int)], ] eg. [[0, 2], [1, 2], [1, 3], [3, 4]} initial_layout (Layout or None): A layout object seed_mapper (int): random seed_mapper for the swap mapper pass_manager (PassManager): pass manager instance for the transpilation process If None, a default set of passes are run. Otherwise, the passes defined in it will run. If contains no passes in it, no dag transformations occur. Returns: DAGCircuit: transformed dag """ warnings.warn("transpile_dag has been deprecated and will be removed in the " "0.9 release. Circuits can be transpiled directly to other " "circuits with the transpile function.", DeprecationWarning) if basis_gates is None: basis_gates = ['u1', 'u2', 'u3', 'cx', 'id'] if pass_manager is None: # default set of passes # if a coupling map is given compile to the map if coupling_map: pass_manager = default_pass_manager(basis_gates, CouplingMap(coupling_map), initial_layout, seed_transpiler=seed_mapper) else: pass_manager = default_pass_manager_simulator(basis_gates) # run the passes specified by the pass manager # TODO return the property set too. See #1086 name = dag.name circuit = dag_to_circuit(dag) circuit = pass_manager.run(circuit) dag = circuit_to_dag(circuit) dag.name = name return dag
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
https://github.com/emad-boosari/QuEST_Group
emad-boosari
# Packeges you must load from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import transpile from qiskit.providers.aer import QasmSimulator # The packeges you should load )() from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_qsphere from qiskit.quantum_info import DensityMatrix # For using Density matrix from qiskit.visualization import plot_state_city from qiskit.visualization import plot_state_hinton from qiskit.visualization import plot_state_paulivec from qiskit.visualization import plot_bloch_multivector from qiskit.visualization import plot_histogram q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) qc.draw('mpl') ψ1 = Statevector(qc) ψ1.draw('latex') plot_state_qsphere(qc) Statevector(qc).draw('latex') ρ1 = DensityMatrix(qc) ρ1.draw('latex',prefix = '\\rho_1 = ') plot_state_city(qc) plot_state_hinton(qc) plot_state_paulivec(qc) plot_bloch_multivector(qc) qc.measure(q[0],c[0]) qc.draw('mpl') backend = QasmSimulator() result = backend.run(transpile(qc,backend),shots=1024).result() counts = result.get_counts() plot_histogram(counts) # It can be nice if you try the effect of different gates on a circuit with one qubit gate
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
from datetime import datetime import matplotlib.pyplot as plt from qiskit import QuantumCircuit, BasicAer, execute, IBMQ, transpile from qiskit.providers import BaseJob from qiskit.providers.ibmq import least_busy, IBMQJobManager from qiskit.providers.ibmq.managed import ManagedJobSet from qiskit.visualization import plot_histogram import constants from QCLG_lvl3.classical.bernstein_vazirani_classical import BersteinVaziraniClassical from QCLG_lvl3.classical.classical_xor import ClassicalXor from QCLG_lvl3.classical.random_binary import RandomBinary from QCLG_lvl3.quantum_algorithms.bernstein_vazirani import BernsteinVazirani from QCLG_lvl3.quantum_algorithms.deutsch_josza import DeutschJosza from credentials import account_details class Tools: @classmethod def calculate_elapsed_time(cls, first_step: datetime, last_step: datetime): difference = last_step - first_step return difference.total_seconds() @classmethod def run_on_simulator(cls, circuit: QuantumCircuit): # use local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1024 results = execute(circuit, backend=backend, shots=shots).result() answer = results.get_counts() max_value = 0 max_key = "" for key, value in answer.items(): if value > max_value: max_value = value max_key = key return max_key[::-1] @classmethod def run_on_real_device(cls, circuit: QuantumCircuit, least_busy_backend): from qiskit.tools.monitor import job_monitor shots = int(input("Number of shots (distinct executions to run this experiment: )")) job = execute(circuit, backend=least_busy_backend, shots=shots, optimization_level=3) job_monitor(job, interval=2) return job @classmethod def find_least_busy_backend_from_open(cls, n): if account_details.account_token_open is None: account_token = input("Insert your account token: ") else: account_token = account_details.account_token_open if IBMQ.active_account() is None: IBMQ.enable_account(account_token) provider = IBMQ.get_provider(hub='ibm-q') return least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n + 1) and not x.configuration().simulator and x.status().operational == True)) @classmethod def find_least_busy_backend_from_research(cls, n): if account_details.account_token_research is None \ or account_details.hub is None \ or account_details.group is None \ or account_details.project is None: account_token = input("Insert your account token: ") hub = input("Insert your hub: ") group = input("Insert your group: ") project = input("Insert your project: ") else: account_token = account_details.account_token_research hub = account_details.hub group = account_details.group project = account_details.project IBMQ.enable_account(account_token) provider = IBMQ.get_provider(hub=hub, group=group, project=project) print(provider) return least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n + 1) and not x.configuration().simulator and x.status().operational == True)) @classmethod def print_simul(cls, answer_of_simul, algorithm: str): print(constants.algorithms[int(algorithm)]) print("\nMeasurements: ", answer_of_simul) return @classmethod def print_real(cls, job: BaseJob, least_busy_backend, algorithm: str): results = job.result() answer = results.get_counts() print("\nTotal counts are:", answer) elapsed = results.time_taken print(f"The time it took for the experiment to complete after validation was {elapsed} seconds") plot_histogram(data=answer, title=f"{constants.algorithms[int(algorithm)]} on {least_busy_backend}") plt.show() return @classmethod def execute_classically(cls, algorithm): if algorithm == "0": return cls.execute_deutsch_josza_classically() elif algorithm == "1": return cls.execute_bernstein_vazirani_classically() @classmethod def execute_in_simulator(cls, algorithm): dj_circuit = None if algorithm == "0": bits = str(input("Enter a bit sequence for the quantum circuit:")) dj_circuit = DeutschJosza.deutsch_josza(bits, eval_mode=False) elif algorithm == "1": decimals = int(input("Give the upper limit of the random number: ")) random_binary = RandomBinary.generate_random_binary(decimals) dj_circuit = BernsteinVazirani.bernstein_vazirani(random_binary, eval_mode=False) return cls.run_on_simulator(dj_circuit) @classmethod def execute_in_real_device(cls, algorithm): if algorithm == "0": answer = cls.execute_dj_in_real_device() return answer elif algorithm == "1": decimals = int(input("Give the upper limit of the random number: ")) random_binary = RandomBinary.generate_random_binary(decimals) answer = cls.execute_bv_in_real_device(random_binary) return answer @classmethod def execute_dj_in_real_device(cls): bits = str(input("Enter a bit sequence for the quantum circuit:")) least_busy_backend = Tools.choose_from_provider(len(bits) + 1) dj_circuit = DeutschJosza.deutsch_josza(bits, eval_mode=False) answer_of_real = Tools.run_on_real_device(dj_circuit, least_busy_backend) print(f"least busy is {least_busy_backend}") return answer_of_real @classmethod def execute_bv_in_real_device(cls, random_binary: str): dj_circuit = BernsteinVazirani.bernstein_vazirani(random_binary, eval_mode=False) least_busy_backend = Tools.choose_from_provider(dj_circuit.qubits) answer_of_real = Tools.run_on_real_device(dj_circuit, least_busy_backend) print(f"least busy is {least_busy_backend}") return answer_of_real @classmethod def choose_from_provider(cls, size: int): least_busy_backend = None research = input("Do you want to run this experiment on the research backends? (Y/N)") while research != "Y" and research != "N": research = input("Do you want to run this experiment on the research backends? (Y/N)") if research == "N": least_busy_backend = Tools.find_least_busy_backend_from_open(size) elif research == "Y": least_busy_backend = Tools.find_least_busy_backend_from_research(size) return least_busy_backend @classmethod def execute_deutsch_josza_classically(cls): number_of_bits = int(input("Enter number of bits for a the classical solution:")) return ClassicalXor.execute_classical_xor(bits=number_of_bits) @classmethod def execute_bernstein_vazirani_classically(cls): decimals = int(input("Give the upper limit of the random number: ")) random_binary = RandomBinary.generate_random_binary(decimals) return BersteinVaziraniClassical.guess_number(random_binary) @classmethod def print_classical_answer(cls, classical_answer, algorithm): time_to_generate_worst_input = classical_answer[0] execution_time = classical_answer[1] bits = classical_answer[2] function_nature = classical_answer[3] print(f"Results of classical implementation for the {constants.algorithms[int(algorithm)]} Algorithm:") print(f"Function is {function_nature}") print(f"Time to generate worse input for {bits} bits took {time_to_generate_worst_input} seconds.") print(f"Determining if xor is balanced for {bits} bits took {execution_time} seconds.") print(classical_answer) @classmethod def execute_both(cls, algorithm): answer = [] if algorithm == "0": classical = cls.execute_deutsch_josza_classically() real = cls.execute_dj_in_real_device() answer.append(classical) answer.append(real) elif algorithm == " 1": classical = cls.execute_bernstein_vazirani_classically() real = cls.execute_bv_in_real_device(classical) answer.append(classical) answer.append(real) return answer # ################################################################################################################# # Evaluation methods @classmethod def prepare_dj(cls, bits: int): bit_sequence = "0" * bits dj_circuit = DeutschJosza.deutsch_josza(bit_sequence, eval_mode=True) return dj_circuit @classmethod def prepare_bv(cls, random_binary: str): bj_circuit = BernsteinVazirani.bernstein_vazirani(random_binary, eval_mode=True) return bj_circuit @classmethod def deutsch_josza_classical(cls, bits: int): return ClassicalXor.execute_classical_xor(bits=bits) @classmethod def bernstein_vazirani_classical(cls, bits: int): random_binary = RandomBinary.generate_random_binary_v2(bits) return BersteinVaziraniClassical.guess_number(random_binary) @classmethod def run_batch_job(cls, circuits: list, least_busy_backend) -> ManagedJobSet: transpiled_circuits = transpile(circuits, backend=least_busy_backend) # Use Job Manager to break the circuits into multiple jobs. job_manager = IBMQJobManager() job_set_eval = job_manager.run(transpiled_circuits, backend=least_busy_backend, name='eval', max_experiments_per_job=1) # max_experiments_per_job =1 very important to get # individual execution times return job_set_eval
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/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Unit tests for pulse instructions.""" import numpy as np from qiskit import pulse, circuit from qiskit.pulse import channels, configuration, instructions, library, exceptions from qiskit.pulse.transforms import inline_subroutines, target_qobj_transform from qiskit.test import QiskitTestCase class TestAcquire(QiskitTestCase): """Acquisition tests.""" def test_can_construct_valid_acquire_command(self): """Test if valid acquire command can be constructed.""" kernel_opts = {"start_window": 0, "stop_window": 10} kernel = configuration.Kernel(name="boxcar", **kernel_opts) discriminator_opts = { "neighborhoods": [{"qubits": 1, "channels": 1}], "cal": "coloring", "resample": False, } discriminator = configuration.Discriminator( name="linear_discriminator", **discriminator_opts ) acq = instructions.Acquire( 10, channels.AcquireChannel(0), channels.MemorySlot(0), kernel=kernel, discriminator=discriminator, name="acquire", ) self.assertEqual(acq.duration, 10) self.assertEqual(acq.discriminator.name, "linear_discriminator") self.assertEqual(acq.discriminator.params, discriminator_opts) self.assertEqual(acq.kernel.name, "boxcar") self.assertEqual(acq.kernel.params, kernel_opts) self.assertIsInstance(acq.id, int) self.assertEqual(acq.name, "acquire") self.assertEqual( acq.operands, ( 10, channels.AcquireChannel(0), channels.MemorySlot(0), None, kernel, discriminator, ), ) def test_instructions_hash(self): """Test hashing for acquire instruction.""" acq_1 = instructions.Acquire( 10, channels.AcquireChannel(0), channels.MemorySlot(0), name="acquire", ) acq_2 = instructions.Acquire( 10, channels.AcquireChannel(0), channels.MemorySlot(0), name="acquire", ) hash_1 = hash(acq_1) hash_2 = hash(acq_2) self.assertEqual(hash_1, hash_2) class TestDelay(QiskitTestCase): """Delay tests.""" def test_delay(self): """Test delay.""" delay = instructions.Delay(10, channels.DriveChannel(0), name="test_name") self.assertIsInstance(delay.id, int) self.assertEqual(delay.name, "test_name") self.assertEqual(delay.duration, 10) self.assertIsInstance(delay.duration, int) self.assertEqual(delay.operands, (10, channels.DriveChannel(0))) self.assertEqual(delay, instructions.Delay(10, channels.DriveChannel(0))) self.assertNotEqual(delay, instructions.Delay(11, channels.DriveChannel(1))) self.assertEqual(repr(delay), "Delay(10, DriveChannel(0), name='test_name')") # Test numpy int for duration delay = instructions.Delay(np.int32(10), channels.DriveChannel(0), name="test_name2") self.assertEqual(delay.duration, 10) self.assertIsInstance(delay.duration, np.integer) def test_operator_delay(self): """Test Operator(delay).""" from qiskit.circuit import QuantumCircuit from qiskit.quantum_info import Operator circ = QuantumCircuit(1) circ.delay(10) op_delay = Operator(circ) expected = QuantumCircuit(1) expected.i(0) op_identity = Operator(expected) self.assertEqual(op_delay, op_identity) class TestSetFrequency(QiskitTestCase): """Set frequency tests.""" def test_freq(self): """Test set frequency basic functionality.""" set_freq = instructions.SetFrequency(4.5e9, channels.DriveChannel(1), name="test") self.assertIsInstance(set_freq.id, int) self.assertEqual(set_freq.duration, 0) self.assertEqual(set_freq.frequency, 4.5e9) self.assertEqual(set_freq.operands, (4.5e9, channels.DriveChannel(1))) self.assertEqual( set_freq, instructions.SetFrequency(4.5e9, channels.DriveChannel(1), name="test") ) self.assertNotEqual( set_freq, instructions.SetFrequency(4.5e8, channels.DriveChannel(1), name="test") ) self.assertEqual(repr(set_freq), "SetFrequency(4500000000.0, DriveChannel(1), name='test')") def test_freq_non_pulse_channel(self): """Test set frequency constructor with illegal channel""" with self.assertRaises(exceptions.PulseError): instructions.SetFrequency(4.5e9, channels.RegisterSlot(1), name="test") def test_parameter_expression(self): """Test getting all parameters assigned by expression.""" p1 = circuit.Parameter("P1") p2 = circuit.Parameter("P2") expr = p1 + p2 instr = instructions.SetFrequency(expr, channel=channels.DriveChannel(0)) self.assertSetEqual(instr.parameters, {p1, p2}) class TestShiftFrequency(QiskitTestCase): """Shift frequency tests.""" def test_shift_freq(self): """Test shift frequency basic functionality.""" shift_freq = instructions.ShiftFrequency(4.5e9, channels.DriveChannel(1), name="test") self.assertIsInstance(shift_freq.id, int) self.assertEqual(shift_freq.duration, 0) self.assertEqual(shift_freq.frequency, 4.5e9) self.assertEqual(shift_freq.operands, (4.5e9, channels.DriveChannel(1))) self.assertEqual( shift_freq, instructions.ShiftFrequency(4.5e9, channels.DriveChannel(1), name="test") ) self.assertNotEqual( shift_freq, instructions.ShiftFrequency(4.5e8, channels.DriveChannel(1), name="test") ) self.assertEqual( repr(shift_freq), "ShiftFrequency(4500000000.0, DriveChannel(1), name='test')" ) def test_freq_non_pulse_channel(self): """Test shift frequency constructor with illegal channel""" with self.assertRaises(exceptions.PulseError): instructions.ShiftFrequency(4.5e9, channels.RegisterSlot(1), name="test") def test_parameter_expression(self): """Test getting all parameters assigned by expression.""" p1 = circuit.Parameter("P1") p2 = circuit.Parameter("P2") expr = p1 + p2 instr = instructions.ShiftFrequency(expr, channel=channels.DriveChannel(0)) self.assertSetEqual(instr.parameters, {p1, p2}) class TestSetPhase(QiskitTestCase): """Test the instruction construction.""" def test_default(self): """Test basic SetPhase.""" set_phase = instructions.SetPhase(1.57, channels.DriveChannel(0)) self.assertIsInstance(set_phase.id, int) self.assertEqual(set_phase.name, None) self.assertEqual(set_phase.duration, 0) self.assertEqual(set_phase.phase, 1.57) self.assertEqual(set_phase.operands, (1.57, channels.DriveChannel(0))) self.assertEqual( set_phase, instructions.SetPhase(1.57, channels.DriveChannel(0), name="test") ) self.assertNotEqual( set_phase, instructions.SetPhase(1.57j, channels.DriveChannel(0), name="test") ) self.assertEqual(repr(set_phase), "SetPhase(1.57, DriveChannel(0))") def test_set_phase_non_pulse_channel(self): """Test shift phase constructor with illegal channel""" with self.assertRaises(exceptions.PulseError): instructions.SetPhase(1.57, channels.RegisterSlot(1), name="test") def test_parameter_expression(self): """Test getting all parameters assigned by expression.""" p1 = circuit.Parameter("P1") p2 = circuit.Parameter("P2") expr = p1 + p2 instr = instructions.SetPhase(expr, channel=channels.DriveChannel(0)) self.assertSetEqual(instr.parameters, {p1, p2}) class TestShiftPhase(QiskitTestCase): """Test the instruction construction.""" def test_default(self): """Test basic ShiftPhase.""" shift_phase = instructions.ShiftPhase(1.57, channels.DriveChannel(0)) self.assertIsInstance(shift_phase.id, int) self.assertEqual(shift_phase.name, None) self.assertEqual(shift_phase.duration, 0) self.assertEqual(shift_phase.phase, 1.57) self.assertEqual(shift_phase.operands, (1.57, channels.DriveChannel(0))) self.assertEqual( shift_phase, instructions.ShiftPhase(1.57, channels.DriveChannel(0), name="test") ) self.assertNotEqual( shift_phase, instructions.ShiftPhase(1.57j, channels.DriveChannel(0), name="test") ) self.assertEqual(repr(shift_phase), "ShiftPhase(1.57, DriveChannel(0))") def test_shift_phase_non_pulse_channel(self): """Test shift phase constructor with illegal channel""" with self.assertRaises(exceptions.PulseError): instructions.ShiftPhase(1.57, channels.RegisterSlot(1), name="test") def test_parameter_expression(self): """Test getting all parameters assigned by expression.""" p1 = circuit.Parameter("P1") p2 = circuit.Parameter("P2") expr = p1 + p2 instr = instructions.ShiftPhase(expr, channel=channels.DriveChannel(0)) self.assertSetEqual(instr.parameters, {p1, p2}) class TestSnapshot(QiskitTestCase): """Snapshot tests.""" def test_default(self): """Test default snapshot.""" snapshot = instructions.Snapshot(label="test_name", snapshot_type="state") self.assertIsInstance(snapshot.id, int) self.assertEqual(snapshot.name, "test_name") self.assertEqual(snapshot.type, "state") self.assertEqual(snapshot.duration, 0) self.assertNotEqual(snapshot, instructions.Delay(10, channels.DriveChannel(0))) self.assertEqual(repr(snapshot), "Snapshot(test_name, state, name='test_name')") class TestPlay(QiskitTestCase): """Play tests.""" def setUp(self): """Setup play tests.""" super().setUp() self.duration = 4 self.pulse_op = library.Waveform([1.0] * self.duration, name="test") def test_play(self): """Test basic play instruction.""" play = instructions.Play(self.pulse_op, channels.DriveChannel(1)) self.assertIsInstance(play.id, int) self.assertEqual(play.name, self.pulse_op.name) self.assertEqual(play.duration, self.duration) self.assertEqual( repr(play), "Play(Waveform(array([1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j]), name='test')," " DriveChannel(1), name='test')", ) def test_play_non_pulse_ch_raises(self): """Test that play instruction on non-pulse channel raises a pulse error.""" with self.assertRaises(exceptions.PulseError): instructions.Play(self.pulse_op, channels.AcquireChannel(0)) class TestDirectives(QiskitTestCase): """Test pulse directives.""" def test_relative_barrier(self): """Test the relative barrier directive.""" a0 = channels.AcquireChannel(0) d0 = channels.DriveChannel(0) m0 = channels.MeasureChannel(0) u0 = channels.ControlChannel(0) mem0 = channels.MemorySlot(0) reg0 = channels.RegisterSlot(0) chans = (a0, d0, m0, u0, mem0, reg0) name = "barrier" barrier = instructions.RelativeBarrier(*chans, name=name) self.assertEqual(barrier.name, name) self.assertEqual(barrier.duration, 0) self.assertEqual(barrier.channels, chans) self.assertEqual(barrier.operands, chans) class TestCall(QiskitTestCase): """Test call instruction.""" def setUp(self): super().setUp() with pulse.build() as _subroutine: pulse.delay(10, pulse.DriveChannel(0)) self.subroutine = _subroutine self.param1 = circuit.Parameter("amp1") self.param2 = circuit.Parameter("amp2") with pulse.build() as _function: pulse.play(pulse.Gaussian(160, self.param1, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, self.param2, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, self.param1, 40), pulse.DriveChannel(0)) self.function = _function def test_call(self): """Test basic call instruction.""" with self.assertWarns(DeprecationWarning): call = instructions.Call(subroutine=self.subroutine) self.assertEqual(call.duration, 10) self.assertEqual(call.subroutine, self.subroutine) def test_parameterized_call(self): """Test call instruction with parameterized subroutine.""" with self.assertWarns(DeprecationWarning): call = instructions.Call(subroutine=self.function) self.assertTrue(call.is_parameterized()) self.assertEqual(len(call.parameters), 2) def test_assign_parameters_to_call(self): """Test create schedule by calling subroutine and assign parameters to it.""" init_dict = {self.param1: 0.1, self.param2: 0.5} with pulse.build() as test_sched: pulse.call(self.function) test_sched = test_sched.assign_parameters(value_dict=init_dict) test_sched = inline_subroutines(test_sched) with pulse.build() as ref_sched: pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, 0.5, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) self.assertEqual(target_qobj_transform(test_sched), target_qobj_transform(ref_sched)) def test_call_initialize_with_parameter(self): """Test call instruction with parameterized subroutine with initial dict.""" init_dict = {self.param1: 0.1, self.param2: 0.5} with self.assertWarns(DeprecationWarning): call = instructions.Call(subroutine=self.function, value_dict=init_dict) with pulse.build() as ref_sched: pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, 0.5, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) self.assertEqual( target_qobj_transform(call.assigned_subroutine()), target_qobj_transform(ref_sched) ) def test_call_subroutine_with_different_parameters(self): """Test call subroutines with different parameters in the same schedule.""" init_dict1 = {self.param1: 0.1, self.param2: 0.5} init_dict2 = {self.param1: 0.3, self.param2: 0.7} with pulse.build() as test_sched: pulse.call(self.function, value_dict=init_dict1) pulse.call(self.function, value_dict=init_dict2) with pulse.build() as ref_sched: pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, 0.5, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, 0.3, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, 0.7, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, 0.3, 40), pulse.DriveChannel(0)) self.assertEqual(target_qobj_transform(test_sched), target_qobj_transform(ref_sched))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(3, 'q') anc = QuantumRegister(1, 'ancilla') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qr, anc, cr) qc.x(anc[0]) qc.h(anc[0]) qc.h(qr[0:3]) qc.cx(qr[0:3], anc[0]) qc.h(qr[0:3]) qc.barrier(qr) qc.measure(qr, cr) qc.draw('mpl')
https://github.com/zapata-engineering/orquestra-qiskit
zapata-engineering
from typing import List, Optional, Sequence, Union from orquestra.quantum.api import BaseCircuitRunner from orquestra.quantum.circuits import ( Circuit, combine_bitstrings, expand_sample_sizes, split_into_batches, ) from orquestra.quantum.measurements import Measurements from qiskit import ClassicalRegister, QuantumCircuit, execute from qiskit.providers import BackendV1, BackendV2 from qiskit.transpiler import CouplingMap from qiskit_aer.noise import NoiseModel from orquestra.integrations.qiskit.conversions import export_to_qiskit AnyQiskitBackend = Union[BackendV1, BackendV2] def prepare_for_running_on_backend(circuit: Circuit) -> QuantumCircuit: qiskit_circuit = export_to_qiskit(circuit) qiskit_circuit.add_register(ClassicalRegister(size=qiskit_circuit.num_qubits)) qiskit_circuit.measure(qiskit_circuit.qubits, qiskit_circuit.clbits) return qiskit_circuit def _listify(counts): return counts if isinstance(counts, list) else [counts] class QiskitRunner(BaseCircuitRunner): def __init__( self, qiskit_backend: AnyQiskitBackend, noise_model: Optional[NoiseModel] = None, coupling_map: Optional[CouplingMap] = None, basis_gates: Optional[List[str]] = None, optimization_level: int = 0, seed: Optional[int] = None, discard_extra_measurements: bool = False, execute_function=execute, ): super().__init__() self.backend = qiskit_backend self.seed = seed self.backend = qiskit_backend self.noise_model = noise_model self.optimization_level = optimization_level self.basis_gates = ( noise_model.basis_gates if basis_gates is None and noise_model is not None else basis_gates ) self.coupling_map = coupling_map self._execute = execute_function self.discard_extra_measurements = discard_extra_measurements def _run_and_measure(self, circuit: Circuit, n_samples: int) -> Measurements: return self._run_batch_and_measure([circuit], [n_samples])[0] def _run_batch_and_measure( self, batch: Sequence[Circuit], samples_per_circuit: Sequence[int] ): circuits_to_execute = [ prepare_for_running_on_backend(circuit) for circuit in batch ] new_circuits, new_n_samples, multiplicities = expand_sample_sizes( circuits_to_execute, samples_per_circuit, self.backend.configuration().max_shots, ) batch_size = getattr( self.backend.configuration(), "max_experiments", len(circuits_to_execute) ) batches = split_into_batches(new_circuits, new_n_samples, batch_size) jobs = [ self._execute( list(circuits), backend=self.backend, shots=n_samples, noise_model=self.noise_model, coupling_map=self.coupling_map, basis_gates=self.basis_gates, optimization_level=self.optimization_level, seed_simulator=self.seed, seed_transpiler=self.seed, memory=True, ) for circuits, n_samples in batches ] # Qiskit runners return single dictionary with counts when there was # only one experiment. To simplify logic, we make sure to always have a # list of counts from a job. # One can use job.result().get_counts() to get all counts, but # job.result().get_memory() does require index of the experiment # This is why the below list comprehension looks so clumsy. all_bitstrings = [ job.result().get_memory(i) for job in jobs for i in range(len(job.result().results)) ] combined_bitstrings = combine_bitstrings(all_bitstrings, multiplicities) if self.discard_extra_measurements: combined_bitstrings = [ bitstrings[:n_samples] for bitstrings, n_samples in zip( combined_bitstrings, samples_per_circuit ) ] return [ Measurements([tuple(map(int, b[::-1])) for b in bitstrings]) for bitstrings in combined_bitstrings ]
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.circuit.random import random_circuit circuit = random_circuit(2, 2, seed=0).decompose(reps=1) display(circuit.draw("mpl")) from qiskit.quantum_info import SparsePauliOp observable = SparsePauliOp("XZ") print(f">>> Observable: {observable.paulis}") from qiskit.primitives import Estimator estimator = Estimator() job = estimator.run(circuit, observable) print(f">>> Job ID: {job.job_id()}") print(f">>> Job Status: {job.status()}") result = job.result() print(f">>> {result}") print(f" > Expectation value: {result.values[0]}") circuit = random_circuit(2, 2, seed=1).decompose(reps=1) observable = SparsePauliOp("IY") job = estimator.run(circuit, observable) result = job.result() display(circuit.draw("mpl")) print(f">>> Observable: {observable.paulis}") print(f">>> Expectation value: {result.values[0]}") circuits = ( random_circuit(2, 2, seed=0).decompose(reps=1), random_circuit(2, 2, seed=1).decompose(reps=1), ) observables = ( SparsePauliOp("XZ"), SparsePauliOp("IY"), ) job = estimator.run(circuits, observables) result = job.result() [display(cir.draw("mpl")) for cir in circuits] print(f">>> Observables: {[obs.paulis for obs in observables]}") print(f">>> Expectation values: {result.values.tolist()}") from qiskit.circuit.library import RealAmplitudes circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1) observable = SparsePauliOp("ZI") parameter_values = [0, 1, 2, 3, 4, 5] job = estimator.run(circuit, observable, parameter_values) result = job.result() display(circuit.draw("mpl")) print(f">>> Observable: {observable.paulis}") print(f">>> Parameter values: {parameter_values}") print(f">>> Expectation value: {result.values[0]}") from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService(channel="ibm_quantum") backend = service.backend("ibmq_qasm_simulator") from qiskit.circuit.random import random_circuit from qiskit.quantum_info import SparsePauliOp circuit = random_circuit(2, 2, seed=0).decompose(reps=1) display(circuit.draw("mpl")) observable = SparsePauliOp("XZ") print(f">>> Observable: {observable.paulis}") from qiskit_ibm_runtime import Estimator estimator = Estimator(session=backend) job = estimator.run(circuit, observable) print(f">>> Job ID: {job.job_id()}") print(f">>> Job Status: {job.status()}") result = job.result() print(f">>> {result}") print(f" > Expectation value: {result.values[0]}") print(f" > Metadata: {result.metadata[0]}") from qiskit_ibm_runtime import Options options = Options(optimization_level=3, environment={"log_level": "INFO"}) from qiskit_ibm_runtime import Options options = Options() options.resilience_level = 1 options.execution.shots = 2048 estimator = Estimator(session=backend, options=options) result = estimator.run(circuit, observable).result() print(f">>> Metadata: {result.metadata[0]}") estimator = Estimator(session=backend, options=options) result = estimator.run(circuit, observable, shots=1024).result() print(f">>> Metadata: {result.metadata[0]}") from qiskit_ibm_runtime import Options # optimization_level=3 adds dynamical decoupling # resilience_level=1 adds readout error mitigation options = Options(optimization_level=3, resilience_level=1) estimator = Estimator(session=backend, options=options) result = estimator.run(circuit, observable).result() print(f">>> Expectation value: {result.values[0]}") print(f">>> Metadata: {result.metadata[0]}") from qiskit_ibm_runtime import Session, Estimator with Session(backend=backend, max_time="1h"): estimator = Estimator() result = estimator.run(circuit, observable).result() print(f">>> Expectation value from the first run: {result.values[0]}") result = estimator.run(circuit, observable).result() print(f">>> Expectation value from the second run: {result.values[0]}") from qiskit.circuit.random import random_circuit sampler_circuit = random_circuit(2, 2, seed=0).decompose(reps=1) sampler_circuit.measure_all() display(circuit.draw("mpl")) from qiskit_ibm_runtime import Session, Sampler, Estimator with Session(backend=backend): sampler = Sampler() estimator = Estimator() result = sampler.run(sampler_circuit).result() print(f">>> Quasi Distribution from the sampler job: {result.quasi_dists[0]}") result = estimator.run(circuit, observable).result() print(f">>> Expectation value from the estimator job: {result.values[0]}") from qiskit_ibm_runtime import Session, Sampler, Estimator with Session(backend=backend): sampler = Sampler() estimator = Estimator() sampler_job = sampler.run(sampler_circuit) estimator_job = estimator.run(circuit, observable) print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}") print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}") from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Estimator, Options # 1. Initialize account service = QiskitRuntimeService(channel="ibm_quantum") # 2. Specify options, such as enabling error mitigation options = Options(resilience_level=1) # 3. Select a backend. backend = service.backend("ibmq_qasm_simulator") # 4. Create a session with Session(backend=backend): # 5. Create primitive instances sampler = Sampler(options=options) estimator = Estimator(options=options) # 6. Submit jobs sampler_job = sampler.run(sampler_circuit) estimator_job = estimator.run(circuit, observable) # 7. Get results print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}") print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}") import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() from qiskit.tools.jupyter import * %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate from qiskit.converters import dag_to_circuit q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) circuit = dag_to_circuit(dag) circuit.draw('mpl')
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test for the converter dag dependency to dag circuit and dag circuit to dag dependency.""" import unittest from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.converters.dag_to_dagdependency import dag_to_dagdependency from qiskit.converters.dagdependency_to_dag import dagdependency_to_dag from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.test import QiskitTestCase class TestCircuitToDagDependency(QiskitTestCase): """Test DAGCircuit to DAGDependency.""" def test_circuit_and_dag_dependency(self): """Check convert to dag dependency and back""" qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit_in = QuantumCircuit(qr, cr) circuit_in.h(qr[0]) circuit_in.h(qr[1]) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.x(qr[0]).c_if(cr, 0x3) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.measure(qr[2], cr[2]) dag_in = circuit_to_dag(circuit_in) dag_dependency = dag_to_dagdependency(dag_in) dag_out = dagdependency_to_dag(dag_dependency) self.assertEqual(dag_out, dag_in) def test_circuit_and_dag_dependency2(self): """Check convert to dag dependency and back also when the option ``create_preds_and_succs`` is False.""" qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit_in = QuantumCircuit(qr, cr) circuit_in.h(qr[0]) circuit_in.h(qr[1]) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.x(qr[0]).c_if(cr, 0x3) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.measure(qr[2], cr[2]) dag_in = circuit_to_dag(circuit_in) dag_dependency = dag_to_dagdependency(dag_in, create_preds_and_succs=False) dag_out = dagdependency_to_dag(dag_dependency) self.assertEqual(dag_out, dag_in) def test_metadata(self): """Test circuit metadata is preservered through conversion.""" meta_dict = {"experiment_id": "1234", "execution_number": 4} qr = QuantumRegister(2) circuit_in = QuantumCircuit(qr, metadata=meta_dict) circuit_in.h(qr[0]) circuit_in.cx(qr[0], qr[1]) circuit_in.measure_all() dag = circuit_to_dag(circuit_in) self.assertEqual(dag.metadata, meta_dict) dag_dependency = dag_to_dagdependency(dag) self.assertEqual(dag_dependency.metadata, meta_dict) dag_out = dagdependency_to_dag(dag_dependency) self.assertEqual(dag_out.metadata, meta_dict) if __name__ == "__main__": unittest.main(verbosity=2)