repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from random import randrange r = randrange(10,51) if r % 2 ==0: print(r,"is even") else: print(r,"is odd") from random import randrange for N in [100,1000,10000,100000]: first_half=second_half=0 for i in range(N): r = randrange(100) if r<50: first_half = first_half + 1 else: second_half=second_half + 1 print(N,"->",first_half/N,second_half/N)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) qc.draw('mpl')
https://github.com/Pitt-JonesLab/clonk_transpilation
Pitt-JonesLab
from qiskit import QuantumCircuit from qiskit.transpiler import PassManager import sys sys.path.append("..") from clonk.backend_utils.backend_analysis_pass import TopologyAnalysis qc = QuantumCircuit(1) from clonk.backend_utils.mock_backends.ibm import * backend_list = [PenguinV1(), PenguinV2(), PenguinV3(), PenguinV4(), FalconR4()] for backend in backend_list: print(backend.name) pm1 = PassManager(TopologyAnalysis(backend)) pm1.run(qc) # FIXME, just save the property_set dictionary directly for key, value in pm1.property_set.items(): print(key, value) print() # from clonk.utils.transpiler_passes import level_0_pass_manager # pm_lattice = level_0_pass_manager(PenguinV1(), basis_gate="CR") # qc = QuantumCircuit(2) # qc.cx(0,1) # transp = pm_lattice.run(qc) # transp.draw(output='mpl') import sys sys.path.append("..") from clonk.backend_utils.mock_backends import FakeHeavyHex from circuit_suite import circuits circuit_lambdas = [v.circuit_lambda(10) for k, v in circuits.items()] circuit_labels = [v.label for k, v in circuits.items()] backend_list = [ PenguinV1(), PenguinV2(), PenguinV3(), PenguinV4(), FakeHeavyHex(), ] # FalconR4()] import matplotlib.pyplot as plt import numpy as np labels = [backend.name for backend in backend_list] circuit_depth_list = [] for circuit in circuit_lambdas: circuit_depth_temp = [] for backend in backend_list: from clonk.utils.transpiler_passes import level_0_pass_manager pm = level_0_pass_manager(backend, basis_gate="CR") pm.run(circuit) circuit_depth_temp.append(pm.property_set["depth"]) circuit_depth_list.append(circuit_depth_temp) x = np.arange(len(labels)) # the label locations width = 0.5 / (len(labels) - 1) # the width of the bars fig, ax = plt.subplots() count = 0 for circuit_depth, label in zip(circuit_depth_list, circuit_labels): rects1 = ax.bar(x + width * count, circuit_depth, width, label=label) ax.bar_label(rects1, padding=3) count += 1 # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel("Depth") ax.set_title("IBM Topologies on Circuit Benchmark") ax.set_xticks(x, labels) ax.legend() fig.tight_layout() plt.show() from qiskit import QuantumCircuit import sys sys.path.append("..") qc = QuantumCircuit(2) qc.swap(0, 1) from clonk.utils.transpiler_passes import level_0_pass_manager from clonk.backend_utils.mock_backends import * pm = level_0_pass_manager(PenguinV1(), "CR", decompose_1q=False) transp = pm.run(qc) transp.draw(output="mpl") # from qiskit.quantum_info import Operator # Operator(transp).equiv(Operator(qc))
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
# This code is a Qiskit project. # (C) Copyright IBM 2024. # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for find_cuts module.""" import unittest import pytest import os import numpy as np from qiskit import QuantumCircuit from qiskit.circuit.library import EfficientSU2 from circuit_knitting.cutting.automated_cut_finding import ( find_cuts, OptimizationParameters, DeviceConstraints, ) class TestCuttingDecomposition(unittest.TestCase): def test_find_cuts(self): with self.subTest("simple circuit"): path_to_circuit = os.path.join( os.path.dirname(__file__), "..", "qasm_circuits", "circuit_find_cuts_test.qasm", ) circuit = QuantumCircuit.from_qasm_file(path_to_circuit) optimization = OptimizationParameters(seed=111) constraints = DeviceConstraints(qubits_per_subcircuit=4) _, metadata = find_cuts( circuit, optimization=optimization, constraints=constraints ) cut_types = {cut[0] for cut in metadata["cuts"]} assert len(metadata["cuts"]) == 2 assert {"Wire Cut", "Gate Cut"} == cut_types assert np.isclose(127.06026169, metadata["sampling_overhead"], atol=1e-8) assert metadata["minimum_reached"] is True with self.subTest("Cut both wires instance"): qc = EfficientSU2(4, entanglement="linear", reps=2).decompose() qc.assign_parameters([0.4] * len(qc.parameters), inplace=True) optimization = OptimizationParameters( seed=12345, gate_lo=False, wire_lo=True ) constraints = DeviceConstraints(qubits_per_subcircuit=2) _, metadata = find_cuts( qc, optimization=optimization, constraints=constraints ) cut_types = {cut[0] for cut in metadata["cuts"]} assert len(metadata["cuts"]) == 8 assert {"Wire Cut"} == cut_types assert np.isclose(65536.0**2, metadata["sampling_overhead"], atol=1e-8) with self.subTest("3-qubit gate"): circuit = QuantumCircuit(3) circuit.cswap(2, 1, 0) circuit.crx(3.57, 1, 0) circuit.z(2) with pytest.raises(ValueError) as e_info: _, metadata = find_cuts( circuit, optimization=optimization, constraints=constraints ) assert e_info.value.args[0] == ( "The input circuit must contain only single and two-qubits gates. " "Found 3-qubit gate: (cswap)." ) with self.subTest( "right-wire-cut" ): # tests resolution of https://github.com/Qiskit-Extensions/circuit-knitting-toolbox/issues/508 circuit = QuantumCircuit(5) circuit.cx(0, 3) circuit.cx(1, 3) circuit.cx(2, 3) circuit.h(4) circuit.cx(3, 4) constraints = DeviceConstraints(qubits_per_subcircuit=3) _, metadata = find_cuts( circuit, optimization=optimization, constraints=constraints ) cut_types = {cut[0] for cut in metadata["cuts"]} assert len(metadata["cuts"]) == 1 assert {"Wire Cut"} == cut_types assert metadata["sampling_overhead"] == 16 @pytest.mark.parametrize("qubits_per_subcircuit", [-1, 0]) def test_device_constraints(qubits_per_subcircuit: int): """Test device constraints for being valid data types.""" with pytest.raises(ValueError): _ = DeviceConstraints(qubits_per_subcircuit) @pytest.mark.parametrize("qubits_per_subcircuit", [2, 1]) def test_get_qpu_width(qubits_per_subcircuit: int): """Test that get_qpu_width returns number of qubits per qpu.""" assert ( DeviceConstraints(qubits_per_subcircuit).get_qpu_width() == qubits_per_subcircuit )
https://github.com/NesyaLab/qaoa
NesyaLab
import sys import os os.chdir("..") import pickle import networkx as nx import matplotlib.pyplot as plt from classes import Problems as P current_path = os.path.abspath(os.curdir) graphs_path = current_path + '/data/' problems_path = current_path + '/classes/' figures_path = current_path + '/figures/' for i in range(16): g = P.Problems(verbose=True) path = graphs_path + "graph_"+str(i)+".nx" with open(path, "wb") as fp: pickle.dump(g, fp) # Graphs graphs = [] for i in range(16): sys.path.append("classes/") path = "data/graph_"+str(i)+".nx" with open(path, 'rb') as f: g = pickle.load(f) graphs.append(g) graphs[0].get_draw() graphs[15].get_draw()
https://github.com/FMZennaro/QuantumGames
FMZennaro
import numpy as np import gym from IPython.display import display import qcircuit env = gym.make('qcircuit-v1') env.reset() display(env.render()) done = False while(not done): obs, _, done, info = env.step(env.action_space.sample()) display(info['circuit_img']) env.close() from stable_baselines.common.policies import MlpPolicy from stable_baselines.common.vec_env import DummyVecEnv from stable_baselines import PPO2 env = DummyVecEnv([lambda: env]) modelPPO2 = PPO2(MlpPolicy, env, verbose=1) modelPPO2.learn(total_timesteps=10000) obs = env.reset() display(env.render()) for _ in range(10): action, _states = modelPPO2.predict(obs) obs, _, done, info = env.step(action) display(info[0]['circuit_img']) env.close() from stable_baselines import A2C modelA2C = A2C(MlpPolicy, env, verbose=1) modelA2C.learn(total_timesteps=10000) obs = env.reset() display(env.render()) for _ in range(10): action, _states = modelA2C.predict(obs) obs, _, done, info = env.step(action) display(info[0]['circuit_img']) env.close() import evaluation n_episodes = 1000 PPO2_perf, _ = evaluation.evaluate_model(modelPPO2, env, num_steps=n_episodes) A2C_perf, _ = evaluation.evaluate_model(modelA2C, env, num_steps=n_episodes) env = gym.make('qcircuit-v1') rand_perf, _ = evaluation.evaluate_random(env, num_steps=n_episodes) print('Mean performance of random agent (out of {0} episodes): {1}'.format(n_episodes,rand_perf)) print('Mean performance of PPO2 agent (out of {0} episodes): {1}'.format(n_episodes,PPO2_perf)) print('Mean performance of A2C agent (out of {0} episodes): {1}'.format(n_episodes,A2C_perf))
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# here is a list holding all even numbers between 10 and 20 L = [10, 12, 14, 16, 18, 20] # let's print the list print(L) # let's print each element by using its index but in reverse order print(L[5],L[4],L[3],L[2],L[1],L[0]) # let's print the length (size) of list print(len(L)) # let's print each element and its index in the list # we use a for-loop, and the number of iteration is determined by the length of the list # everthing is automatical :-) L = [10, 12, 14, 16, 18, 20] for i in range(len(L)): print(L[i],"is the element in our list with the index",i) # let's replace each number in the above list with its double value # L = [10, 12, 14, 16, 18, 20] # let's print the list before doubling operation print("the list before doubling operation is",L) for i in range(len(L)): current_element=L[i] # get the value of the i-th element L[i] = 2 * current_element # update the value of the i-th element # let's shorten the code as #L[i] = 2 * L[i] # or #L[i] *= 2 # let's print the list after doubling operation print("the list after doubling operation is",L) # after each execution of this cell, the latest values will be doubled # so the values in the list will be exponentially increased # let's define two lists L1 = [1,2,3,4] L2 = [-5,-6,-7,-8] # two lists can be concatenated # the result is a new list print("the concatenation of L1 and L2 is",L1+L2) # the order of terms is important print("the concatenation of L2 and L1 is",L2+L1) # this is a different list than L1+L2 # we can add a new element to a list, which increases its length/size by 1 L = [10, 12, 14, 16, 18, 20] print(L,"the current length is",len(L)) # we add two values by showing two different methods # L.append(value) directly adds the value as a new element to the list L.append(-4) # we can also use concatenation operator + L = L + [-8] # here [-8] is a list having a single element print(L,"the new length is",len(L)) # a list can be multiplied with an integer L = [1,2] # we can consider the multiplication of L by an integer as a repeated summation (concatenation) of L by itself # L * 1 is the list itself # L * 2 is L + L (the concatenation of L with itself) # L * 3 is L + L + L (the concatenation of L with itself twice) # L * m is L + ... + L (the concatenation of L with itself m-1 times) # L * 0 is the empty list # L * i is the same as i * L # let's print the different cases for i in range(6): print(i,"* L is",i*L) # this operation can be useful when initializing a list with the same value(s) # let's create a list of prime numbers less than 100 # here is a function that determines whether a given number is prime or not def prime(number): if number < 2: return False if number == 2: return True if number % 2 == 0: return False for i in range(3,number,2): if number % i == 0: return False return True # end of a function # let's start with an empty list L=[] # what can the length of this list be? print("my initial length is",len(L)) for i in range(2,100): if prime(i): L.append(i) # alternative methods: #L = L + [i] #L += [i] # print the final list print(L) print("my final length is",len(L)) # let's define the list with S(0) L = [0] # let's iteratively define n and S # initial values n = 0 S = 0 # the number of iterations N = 20 while n <= N: # we iterate all values from 1 to 20 n = n + 1 S = S + n L.append(S) # print the final list print(L) # # your solution is here # F = [1,1] # the following list stores certain information about Asja # name, surname, age, profession, height, weight, partner(s) if any, kid(s) if any, the creation date of list ASJA = ['Asja','Sarkane',34,'musician',180,65.5,[],['Eleni','Fyodor'],"October 24, 2018"] print(ASJA) # Remark that an element of a list can be another list as well. # # your solution is here # # let's define a dictionary pairing a person with her/his age ages = { 'Asja':32, 'Balvis':28, 'Fyodor':43 } # let print all keys for person in ages: print(person) # let's print the values for person in ages: print(ages[person])
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeManilaV2 from qiskit import transpile from qiskit.tools.visualization import plot_histogram # Get a fake backend from the fake provider backend = FakeManilaV2() # Create a simple circuit circuit = QuantumCircuit(3) circuit.h(0) circuit.cx(0,1) circuit.cx(0,2) circuit.measure_all() circuit.draw('mpl') # Transpile the ideal circuit to a circuit that can be directly executed by the backend transpiled_circuit = transpile(circuit, backend) transpiled_circuit.draw('mpl') # Run the transpiled circuit using the simulated fake backend job = backend.run(transpiled_circuit) counts = job.result().get_counts() plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can make the bars more transparent to better see the ones that are behind # if they overlap. import numpy as np from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_city from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) state = Statevector(qc) plot_state_city(state, alpha=0.6)
https://github.com/apcarrik/qiskit-dev
apcarrik
import matplotlib.pyplot as plt import numpy as np from math import pi from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.tools.visualization import circuit_drawer from qiskit.quantum_info import state_fidelity from qiskit import BasicAer backend = BasicAer.get_backend('unitary_simulator') #### === Single Qubit Gates === q = QuantumRegister(1) ## general unitary gate qc = QuantumCircuit(q) theta = pi/2 phi = pi/2 lambd = pi/2 qc.u(theta,phi,lambd,q) # previously qc.u3 qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("u gate:", res) # u2 gate = u(pi/2, phi, lambda) is useful to create superpositions qc = QuantumCircuit(q) phi = pi/3 lambd = pi/4 qc.u(pi/2,phi,lambd,q) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("u2 gate:", res) # u1 gate = u3(0,0,lambda) is useful to apply a quantum phase qc = QuantumCircuit(q) lambd = pi/5 qc.p(lambd, q)# or, alternativley qc.u(0,0,lambd,q) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("u1 gate:", res) ## Identity gate qc = QuantumCircuit(q) qc.id(q) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("Identity gate:", res) ## Pauli gates # X (bit-flip) gate = u(pi,0,pi) qc = QuantumCircuit(q) qc.x(q) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("X gate:", res) # Y (bit- and phase-flip) gate = u(pi,pi/2,pi/2) qc = QuantumCircuit(q) qc.y(q) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("Y gate:", res) # Z (bit-flip) gate = u(pi,0,pi) qc = QuantumCircuit(q) qc.x(q) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("Z gate", res) ## Clifford Gates # Hadamard gate = u3(pi/2, 0, pi) qc = QuantumCircuit(q) qc.h(q) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("Hadamard gate", res) # S (sqrt(Z) phase) gate = u1(pi/2) qc = QuantumCircuit(q) qc.s(q) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("S gate", res) # S-dagger (conjugate of sqrt(Z) phase) gate = u3(-pi/2) qc = QuantumCircuit(q) qc.sdg(q) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("S-dagger gate", res) ## C3 Gates # T (sqrt(S)) gate = u1(pi/4) qc = QuantumCircuit(q) qc.t(q) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("T gate", res) # T-dagger (conjugate of sqrt(S)) gate = u1(-pi/4) qc = QuantumCircuit(q) qc.tdg(q) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("T-dagger gate", res) ## Standard Rotations # Rotation around X-axis = u3(theta, -pi/2, pi/2) qc = QuantumCircuit(q) theta=pi/2 qc.rx(theta, q) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("X-axis rotation gate", res) # Rotation around Y-axis = u3(theta, 0, 0) qc = QuantumCircuit(q) theta=pi/2 qc.ry(theta, q) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("Y-axis rotation gate", res) # Rotation around Z-axis = u1(phi) qc = QuantumCircuit(q) phi=pi/2 qc.rz(phi, q) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("Z-axis rotation gate", res) #### === Multi-Qubit Gates === ### Two-Qubit Gates q= QuantumRegister(2) ## Controlled Pauli Gates # Controled-X Gate qc = QuantumCircuit(q) qc.cx(q[0], q[1]) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("Controlled-X gate", res) # Controled-Y Gate qc = QuantumCircuit(q) qc.cy(q[0], q[1]) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("Controlled-Y gate", res) # Controled-Z Gate qc = QuantumCircuit(q) qc.cz(q[0], q[1]) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("Controlled-Z gate", res) ## Controled Hadamard Gate qc = QuantumCircuit(q) qc.ch(q[0], q[1]) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("Controlled Hadamard gate", res) ## Controlled Rotation Gates # Controled-Z Rotation Gate qc = QuantumCircuit(q) lambd = pi/2 qc.crz(lambd, q[0], q[1]) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("Controlled Rotation Around Z-axis gate", res) # Controled-Phase Rotation Gate qc = QuantumCircuit(q) lambd = pi/2 qc.cp(lambd, q[0], q[1]) # previously qc.cu1 qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("Controlled-Phase Roatation gate", res) # Controled-u Rotation Gate qc = QuantumCircuit(q) theta = pi/2 phi = pi/2 lambd = pi/2 qc.cu(theta,phi,lambd, 0, q[0], q[1]) # previously qc.cu3 qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("Controlled-u Rotation gate", res) # SWAP Gate qc = QuantumCircuit(q) qc.swap(q[0], q[1]) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("SWAP gate", res) ### Three-Qubit Gates q= QuantumRegister(3) ## Toffoli Gate qc = QuantumCircuit(q) qc.ccx(q[0], q[1], q[2]) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("Toffoli gate", res) ## Controlled Swap (Fredkin) Gate qc = QuantumCircuit(q) qc.cswap(q[0], q[1], q[2]) qc.draw('mpl') plt.show() job = execute(qc, backend) res = job.result().get_unitary(qc, decimals=3) print("Controlled Swap gate", res) #### === Non-Unitary Operations === q = QuantumRegister(1) c = ClassicalRegister(1) ### Measurements # qubit in state |0> only qc = QuantumCircuit(q,c) qc.measure(q,c) qc.draw('mpl') plt.show() backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1024) res = job.result().get_counts(qc) print("Measurement Results: ", res) # qubit in state |0> and |1> with equal probability qc = QuantumCircuit(q,c) qc.h(q) qc.measure(q,c) qc.draw('mpl') plt.show() backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1024) res = job.result().get_counts(qc) print("Measurement Results: ", res) ### Reset # Resets all qubits to |0> state qc = QuantumCircuit(q,c) qc.h(q) qc.reset(q[0]) qc.measure(q,c) qc.draw('mpl') plt.show() backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1024) res = job.result().get_counts(qc) print("Measurement Results: ", res) ### Conditional Operators # classical bit always takes value 0 so qubit state is always flipped qc = QuantumCircuit(q,c) qc.x(q[0]).c_if(c,0) qc.measure(q,c) qc.draw('mpl') plt.show() backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1024) res = job.result().get_counts(qc) print("Measurement Results: ", res) # classical bit by first measurement is random, but conditional operation results in qubit being # deterministically put to 1. qc = QuantumCircuit(q,c) qc.h(q) qc.measure(q,c) qc.x(q[0]).c_if(c,0) qc.measure(q,c) qc.draw('mpl') plt.show() backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1024) res = job.result().get_counts(qc) print("Measurement Results: ", res) ### Arbitrary Initialization # Initialize qubit register to arbitrary state: # |psi> = i/4|000> + 1/sqrt(8)|001> + (1+i)/4|010> + (1 + 2i)/sqrt(8)|101> + 1/4|110> import math desired_vector = [ 1 / math.sqrt(16) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(16) * complex(1, 1), 0, 0, 1 / math.sqrt(8) * complex(1, 2), 1 / math.sqrt(16) * complex(1, 0), 0 ] q = QuantumRegister(3) qc = QuantumCircuit(q) qc.initialize(desired_vector, [q[0],q[1],q[2]]) qc.draw('mpl') plt.show() backend = BasicAer.get_backend('statevector_simulator') job = execute(qc, backend) qc_state = job.result().get_statevector(qc) print("QC state:", qc_state) # you should check the Fidelity to ensure the state matches the desired vector fid = state_fidelity(desired_vector, qc_state) print("Fidelity: ", fid)
https://github.com/purvi1508/Quantum_Computing_Fundamentals
purvi1508
!pip install qiskit 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] #The Discrete Fourier Transform (DFT) is a mathematical algorithm used to compute the discrete Fourier transform of a sequence. #It takes a sequence of N complex numbers as input and produces another sequence of N complex numbers as output. #fourier checking would tell how correlated the fourier transforrmation of G is to F #P(f,g)>0.05-> then our function is correlated circ=FourierChecking(f=f,g=g) circ.draw(initial_state = True) zero=qi.Statevector.from_label('00') sv=zero.evolve(circ) probs= sv.probabilities_dict() plot_histogram(probs)
https://github.com/lynkos/grovers-algorithm
lynkos
my_list = [1, 3, 5, 2, 4, 9, 5, 8, 0, 7, 6] def the_oracle(my_input): winner = 7 return my_input == winner for index, trial_number in enumerate(my_list): if the_oracle(trial_number): print(f"Found the winner at index {index}!") print(f"{index+1} calls made") break from qiskit import * from qiskit.visualization import plot_histogram, array_to_latex from qiskit.providers.ibmq import least_busy import matplotlib.pyplot as plt import numpy as np grover_circuit = QuantumCircuit(2) def init_state(qc, qubits): for q in qubits: qc.h(q) return qc grover_circuit = init_state(grover_circuit, [0, 1]) grover_circuit.draw("mpl") #define the oracle circuit def oracle(qc, qubits): qc.cz(qubits[0], qubits[1]) qc = QuantumCircuit(2) oracle(qc, [0, 1]) qc.draw("mpl") usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() array_to_latex(unitary, prefix="\\text{One can see that only the state }\ket{11}\\text{ has been flipped: }\n") def diffusion(qc, qubits): qc.h([0, 1]) qc.z([0, 1]) qc.cz(0, 1) qc.h([0, 1]) grover_circuit.barrier() oracle(grover_circuit, [0, 1]) grover_circuit.barrier() diffusion(grover_circuit, [0, 1]) grover_circuit.measure_all() grover_circuit.draw("mpl") # Let's see if the final statevector matches our expectations sv_sim = Aer.get_backend('statevector_simulator') result = sv_sim.run(grover_circuit).result() statevec = result.get_statevector() statevec aer_sim = Aer.get_backend('aer_simulator') result = execute(grover_circuit, aer_sim, shots=1024).result() result.get_counts() # Load IBM Q account and get the least busy backend device # Run the following line with your API token to use IBM's own quantum computers #IBMQ.save_account('') provider = IBMQ.load_account() provider = IBMQ.get_provider("ibm-q") device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor transpiled_grover_circuit = transpile(grover_circuit, device, optimization_level=3) job = device.run(transpiled_grover_circuit) job_monitor(job, interval=2) # Get the results from the computation results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) grover_circuit = QuantumCircuit(3) grover_circuit = init_state(grover_circuit, [0, 1, 2]) grover_circuit.draw("mpl") oracle_qc = QuantumCircuit(3) oracle_qc.cz(0, 1) oracle_qc.cz(0, 2) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "U$_\omega$" def diffuser(nqubits): qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> -> |11..1> for qubit in range(nqubits): qc.h(qubit) qc.x(qubit) # When these are combined, they function as a multi-controlled Z gate # A negative phase is added to |11..1> to flip the state qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) # Apply transformation |11..1> -> |00..0> -> |s> for qubit in range(nqubits): qc.x(qubit) qc.h(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "U$_s$" return U_s num_qubits = 3 grover_circuit = QuantumCircuit(num_qubits) grover_circuit = init_state(grover_circuit, [0, 1, 2]) grover_circuit.barrier() grover_circuit.append(oracle_gate, [0, 1, 2]) grover_circuit.barrier() grover_circuit.append(diffuser(num_qubits), [0, 1, 2]) grover_circuit.measure_all() grover_circuit.draw("mpl") qasm_sim = Aer.get_backend('qasm_simulator') transpiled_grover_circuit = transpile(grover_circuit, qasm_sim) results = qasm_sim.run(transpiled_grover_circuit).result() counts = results.get_counts() plot_histogram(counts) backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor transpiled_grover_circuit = transpile(grover_circuit, device, optimization_level=3) job = device.run(transpiled_grover_circuit) job_monitor(job, interval=2) # Get the results from the computation results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Helper function for converting a circuit to a dag""" import copy from qiskit.dagcircuit.dagcircuit import DAGCircuit def circuit_to_dag(circuit, copy_operations=True, *, qubit_order=None, clbit_order=None): """Build a ``DAGCircuit`` object from a ``QuantumCircuit``. Args: circuit (QuantumCircuit): the input circuit. copy_operations (bool): Deep copy the operation objects in the :class:`~.QuantumCircuit` for the output :class:`~.DAGCircuit`. This should only be set to ``False`` if the input :class:`~.QuantumCircuit` will not be used anymore as the operations in the output :class:`~.DAGCircuit` will be shared instances and modifications to operations in the :class:`~.DAGCircuit` will be reflected in the :class:`~.QuantumCircuit` (and vice versa). qubit_order (Iterable[Qubit] or None): the order that the qubits should be indexed in the output DAG. Defaults to the same order as in the circuit. clbit_order (Iterable[Clbit] or None): the order that the clbits should be indexed in the output DAG. Defaults to the same order as in the circuit. Return: DAGCircuit: the DAG representing the input circuit. Raises: ValueError: if the ``qubit_order`` or ``clbit_order`` parameters do not match the bits in the circuit. Example: .. code-block:: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) """ dagcircuit = DAGCircuit() dagcircuit.name = circuit.name dagcircuit.global_phase = circuit.global_phase dagcircuit.calibrations = circuit.calibrations dagcircuit.metadata = circuit.metadata if qubit_order is None: qubits = circuit.qubits elif len(qubit_order) != circuit.num_qubits or set(qubit_order) != set(circuit.qubits): raise ValueError("'qubit_order' does not contain exactly the same qubits as the circuit") else: qubits = qubit_order if clbit_order is None: clbits = circuit.clbits elif len(clbit_order) != circuit.num_clbits or set(clbit_order) != set(circuit.clbits): raise ValueError("'clbit_order' does not contain exactly the same clbits as the circuit") else: clbits = clbit_order dagcircuit.add_qubits(qubits) dagcircuit.add_clbits(clbits) for register in circuit.qregs: dagcircuit.add_qreg(register) for register in circuit.cregs: dagcircuit.add_creg(register) for instruction in circuit.data: op = instruction.operation if copy_operations: op = copy.deepcopy(op) dagcircuit.apply_operation_back(op, instruction.qubits, instruction.clbits) dagcircuit.duration = circuit.duration dagcircuit.unit = circuit.unit return dagcircuit
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/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/henrik-dreyer/TASP-for-Qiskit
henrik-dreyer
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 2 17:07:01 2019 @author: henrikdreyer """ """TASP Ansatz described in https://journals.aps.org/pra/pdf/10.1103/PhysRevA.92.042303""" import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua.components.variational_forms import VariationalForm class TASP(VariationalForm): """Trotterized Adiabatic State Preparation. https://journals.aps.org/pra/pdf/10.1103/PhysRevA.92.042303""" CONFIGURATION = { 'name': 'TASP', 'description': 'TASP Variational Form', 'input_schema': { '$schema': 'http://json-schema.org/draft-07/schema#', 'id': 'tasp_schema', 'type': 'object', 'properties': { 'depth': { 'type': 'integer', 'default': 1, 'minimum': 1 }, }, 'additionalProperties': False }, 'depends': [ { 'pluggable_type': 'initial_state', 'default': { 'name': 'ZERO', } }, ], } def __init__(self, num_qubits, h_list, depth=1, initial_state=None): """Constructor. Args: num_qubits (int) : number of qubits depth (int) : number of TASP steps layers (corresponds to the variable S in equation 8 of the paper above) h_list (WeightedPauliOperator) : list of Hamiltonians with which to evolve, e.g. H_ex, H_hop, H_diag in the paper above. initial_state (InitialState): an initial state object """ self.validate(locals()) super().__init__() self._num_qubits = num_qubits self._h_list = h_list self._depth = depth self._initial_state = initial_state self._num_parameters=len(self._h_list)*depth self._bounds = [(-np.pi, np.pi)] * self._num_parameters def construct_circuit(self, parameters, q=None): """ Construct the variational form, given its parameters. Args: parameters (numpy.ndarray): circuit parameters q (QuantumRegister): Quantum Register for the circuit. Returns: QuantumCircuit: a quantum circuit with given `parameters` Raises: ValueError: the number of parameters is incorrect. """ if len(parameters) != self._num_parameters: raise ValueError('The number of parameters has to be {}'.format(self._num_parameters)) if q is None: q = QuantumRegister(self._num_qubits, name='q') if self._initial_state is not None: circuit = self._initial_state.construct_circuit('circuit', q) else: circuit = QuantumCircuit(q) for b in range(self._depth): for i in range(len(self._h_list)): if not self._h_list[i].is_empty(): circuit+=self._h_list[i].evolve(evo_time=parameters[i], quantum_registers=q) for i in range(len(self._h_list)-1,-1,-1): if not self._h_list[i].is_empty(): circuit+=self._h_list[i].evolve(evo_time=parameters[i], quantum_registers=q) return circuit
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl')
https://github.com/qiskit-community/prototype-zne
qiskit-community
# 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. """Noise amplification strategy via unitary/inverse repetition.""" from __future__ import annotations from warnings import warn from numpy.random import Generator, default_rng from qiskit import QuantumCircuit from qiskit.dagcircuit import DAGCircuit from ...utils.typing import isreal from ..noise_amplifier import NoiseAmplifier class FoldingAmplifier(NoiseAmplifier): """Interface for folding amplifier strategies.""" def __init__( # pylint: disable=super-init-not-called, duplicate-code, too-many-arguments self, sub_folding_option: str = "from_first", barriers: bool = True, random_seed: int | None = None, noise_factor_relative_tolerance: float = 1e-2, warn_user: bool = True, ) -> None: """ Args: sub_folding_option: Specifies which gates are used for sub folding when ``noise_factor`` is not an odd integer. Can either be "from_last", "from_first", or "random". barriers: If True applies barriers when folding (e.g. to avoid simplification). random_seed: Random seed used for performing random sub-gate-folding. noise_factor_relative_tolerance: Relative allowed tolerance interval between ``noise_factor`` input and actual noise factor that was used for the amplification. If the discrepancy exceeds the tolerance, a warning is displayed. warn_user: Specifies whether user warnings are displayed. """ self.warn_user: bool = warn_user self._set_sub_folding_option(sub_folding_option) self._set_barriers(barriers) self._prepare_rng(random_seed) self._set_noise_factor_relative_tolerance(noise_factor_relative_tolerance) ################################################################################ ## PROPERTIES ################################################################################ @property def options(self) -> dict: """Strategy options.""" options: dict = self._init_options options.pop("warn_user", None) return options @property def warn_user(self) -> bool: """Option whether warnings are displayed.""" return self._warn_user @warn_user.setter def warn_user(self, warn_user: bool) -> None: if not isinstance(warn_user, bool): raise TypeError(f"Expected boolean, received {type(warn_user)} instead.") self._warn_user: bool = warn_user @property def sub_folding_option(self) -> str: """Option for sub-gate-folding. Specifies which gates of the full circuit are used for sub folding when ``noise_factor`` is is not an odd integer. Can either be "from_last", "from_first", or "random". """ return self._sub_folding_option def _set_sub_folding_option(self, sub_folding_option: str) -> None: if sub_folding_option not in ["from_last", "from_first", "random"]: raise ValueError( f"Sub-folding option must be a string of either 'from_last', 'from_first, or " f"'random'. Received {sub_folding_option} instead." ) self._sub_folding_option: str = sub_folding_option @property def barriers(self) -> bool: """Option for whether to apply barriers when folding.""" return self._barriers def _set_barriers(self, barriers: bool) -> None: self._barriers = bool(barriers) def _prepare_rng(self, seed: int | None = None) -> None: """Sets random number generator with seed.""" if not isinstance(seed, (type(None), int)): raise TypeError("Random seed must be an integer or None.") self._rng: Generator = default_rng(seed) # TODO: add property getter def _set_noise_factor_relative_tolerance(self, tolerance: float) -> None: """Sets noise factor relative tolerance.""" if not isreal(tolerance): raise TypeError("Noise factor relative tolerance must be real valued.") self._noise_factor_relative_tolerance: float = tolerance ################################################################################ ## FOLDING METHODS ################################################################################ @staticmethod def folding_to_noise_factor(folding: float) -> float: """Converts number of foldings to noise factor. Args: folding: The number of foldings. Returns: The corresponding noise factor. """ return 2 * folding + 1 def warn(self, *args, **kwargs): """Throws user warning if enabled.""" if self.warn_user: warn(*args, **kwargs) def _validate_noise_factor(self, noise_factor): """Validates noise factor. Args: noise_factor: The noise amplification factor by which to amplify the circuit noise. Raises: ValueError: If the noise factor is smaller than 1. """ if noise_factor < 1: raise ValueError( f"{self.name} expects a positive float noise_factor >= 1." f"Received {noise_factor} instead." ) def _apply_barrier(self, circuit: QuantumCircuit, *registers) -> QuantumCircuit: """Apply barrier to specified registers if option is set.""" if self._barriers: circuit.barrier(*registers) return circuit def _compute_folding_nums(self, noise_factor: float, num_instructions: int) -> tuple[int, int]: """Returns required number of full foldings and sub foldings. Args: noise_factor: The noise amplification factor by which to fold the circuit. num_instructions: The number of instructions to fold. Returns: A tuple containing the number of full-and sub-foldings. """ if num_instructions == 0: self.warn("Noise amplification is not performed since none of the gates are folded.") return 0, 0 num_foldings = round(num_instructions * (noise_factor - 1) / 2.0) closest_noise_factor: float = self.folding_to_noise_factor(num_foldings / num_instructions) relative_error = abs(closest_noise_factor - noise_factor) / noise_factor if relative_error > self._noise_factor_relative_tolerance: warn( "Rounding of noise factor: Foldings are performed with noise factor " f"{closest_noise_factor:.2f} instead of specified noise factor " f"{noise_factor:.2f} which amounts to a relative error of " f"{relative_error * 100:.2f}%." ) num_full_foldings, num_sub_foldings = divmod(num_foldings, num_instructions) return num_full_foldings, num_sub_foldings ################################################################################ ## IMPLEMENTATION ################################################################################ # pylint: disable=useless-parent-delegation def amplify_dag_noise( self, dag: DAGCircuit, noise_factor: float ) -> DAGCircuit: # pragma: no cover return super().amplify_dag_noise(dag, noise_factor)
https://github.com/grossiM/Qiskit_workshop1019
grossiM
# initialization import matplotlib.pyplot as plt %matplotlib inline import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute # import basic plot tools from qiskit.tools.visualization import plot_histogram nQubits = 2 # number of physical qubits used to represent s s = 3 # the hidden integer # make sure that a can be represented with nqubits s = s % 2**(nQubits) # Creating registers # qubits for querying the oracle and finding the hidden integer qr = QuantumRegister(nQubits) # bits for recording the measurement on qr cr = ClassicalRegister(nQubits) bvCircuit = QuantumCircuit(qr, cr) barriers = True # Apply Hadamard gates before querying the oracle for i in range(nQubits): bvCircuit.h(qr[i]) # Apply barrier if barriers: bvCircuit.barrier() # Apply the inner-product oracle for i in range(nQubits): if (s & (1 << i)): bvCircuit.z(qr[i]) else: bvCircuit.iden(qr[i]) # Apply barrier if barriers: bvCircuit.barrier() #Apply Hadamard gates after querying the oracle for i in range(nQubits): bvCircuit.h(qr[i]) # Apply barrier if barriers: bvCircuit.barrier() # Measurement bvCircuit.measure(qr, cr) bvCircuit.draw(output='mpl') # use local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1024 results = execute(bvCircuit, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer) # Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor shots = 1024 job = execute(bvCircuit, backend=backend, shots=shots) job_monitor(job, interval = 2) # Get the results from the computation results = job.result() answer = results.get_counts() plot_histogram(answer) import qiskit qiskit.__qiskit_version__
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit.quantum_info import * from qiskit import QuantumCircuit qc=QuantumCircuit(2) sv=Statevector.from_label('01') sv_evolve=sv.evolve(qc) sv_evolve sv_evolve.data sv_evolve.draw(output="latex") sv_evolve.draw('qsphere') qc=QuantumCircuit(2) sv=Statevector.from_int(2,2**2) sv_evolve=sv.evolve(qc) sv_evolve sv_evolve.data sv_evolve.draw(output="latex") qc=QuantumCircuit(2) density_M=DensityMatrix.from_label('01') density_M=density_M.evolve(qc) density_M density_M.data density_M.draw(output="latex") density_M.to_operator() density_M.to_statevector() density_M.draw('city')
https://github.com/DEBARGHYA4469/quantum-compiler
DEBARGHYA4469
from qiskit import register, available_backends , get_backend # Establish connection with IBMQuantum Experience try : import sys sys.path.append('../') import Qconfig qx_config = { # configuration details 'APItoken' : Qconfig.APItoken , 'url' : Qconfig.config['url']} except Exception as e : print(e) print("Check your API token") register(qx_config['APItoken'],qx_config['url']) def lowest_pending_jobs(): # find the best backend available list_backends = available_backends({'local':False,'simulator':False}) device_status = [get_backend(backend).status for backend in list_backends] best = min([x for x in device_status if x['available'] is True],key = lambda x: x['pending_jobs']) return best['name'] def get_qc(): backend = lowest_pending_jobs() print("The best backend is",backend) return backend
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### removed cx gate ### return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) ### removed h gate ### return qc
https://github.com/abbarreto/qiskit4
abbarreto
https://github.com/Pitt-JonesLab/mirror-gates
Pitt-JonesLab
"""Noisy fidelity of a circuit.""" import numpy as np from qiskit import transpile from qiskit.circuit import Delay from qiskit.converters import circuit_to_dag from qiskit.quantum_info import state_fidelity from qiskit.transpiler import PassManager from qiskit.transpiler.passes import ASAPSchedule, Optimize1qGatesDecomposition from qiskit_aer import AerSimulator, QasmSimulator # Import from Qiskit Aer noise module from qiskit_aer.noise import ( NoiseModel, RelaxationNoisePass, depolarizing_error, thermal_relaxation_error, ) from mirror_gates.logging import transpile_benchy_logger from mirror_gates.sqiswap_decomposer import SiSwapDecomposePass # 80 microsec (in nanoseconds) T1 = 80e3 # 80 microsec T2 = 80e3 # Instruction times (in nanoseconds) time_u3 = 25 time_cx = 100 time_siswap = int(time_cx / 2.0) # divide by 2 again since # each sqrt(iSwap) is compiled to an RXX and RYY time_rxx = int(time_siswap / 2.0) p1 = 0.0 p2 = 0.00658 class NoiseModelBuilder: """A class to help build a custom NoiseModel from scratch. Many of the functions are based on examples from https://github.com/Qiskit/qiskit-presentations/blob/master/2019-02-26_QiskitCamp/QiskitCamp_Simulation.ipynb """ def __init__(self, basis_gates, coupling_map=None): """Initialize a NoiseModelBuilder.""" self.noise_model = NoiseModel(basis_gates=basis_gates) self.coupling_map = coupling_map def construct_basic_device_model(self, p_depol1, p_depol2, t1, t2): """Emulate qiskit.providers.aer.noise.device.models.basic_device_noise_model(). The noise model includes the following errors: * Single qubit readout errors on measurements. * Single-qubit gate errors consisting of a depolarizing error followed by a thermal relaxation error for the qubit the gate acts on. * Two-qubit gate errors consisting of a 2-qubit depolarizing error followed by single qubit thermal relaxation errors for all qubits participating in the gate. :param p_depol1: Probability of a depolarising error on single qubit gates :param p_depol2: Probability of a depolarising error on two qubit gates :param t1: Thermal relaxation time constant :param t2: Dephasing time constant """ if t2 > 2 * t1: raise ValueError("t2 cannot be greater than 2t1") # Thermal relaxation error # QuantumError objects error_thermal_u3 = thermal_relaxation_error(t1, t2, time_u3) error_thermal_cx = thermal_relaxation_error(t1, t2, time_cx).expand( thermal_relaxation_error(t1, t2, time_cx) ) error_thermal_rxx = thermal_relaxation_error(t1, t2, time_rxx).expand( thermal_relaxation_error(t1, t2, time_rxx) ) # Depolarizing error error_depol1 = depolarizing_error(p_depol1, 1) error_depol2 = depolarizing_error(p_depol2, 2) self.noise_model.add_all_qubit_quantum_error( error_depol1.compose(error_thermal_u3), "u" ) for pair in self.coupling_map: self.noise_model.add_quantum_error( error_depol2.compose(error_thermal_cx), "cx", pair ) self.noise_model.add_quantum_error( error_depol2.compose(error_thermal_rxx), ["rxx", "ryy"], pair ) def heuristic_fidelity(N, duration, T1=None, T2=None): """Get heuristic fidelity of a circuit.""" if T1 is None: T1 = 80e3 if T2 is None: T2 = 80e3 decay_factor = (1 / T1 + 1 / T2) * duration single_qubit_fidelity = np.exp(-decay_factor) total_fidelity = single_qubit_fidelity**N return total_fidelity def get_noisy_fidelity(qc, coupling_map, sqrt_iswap_basis=False): """Get noisy fidelity of a circuit. NOTE: if qc is too big, will use heuristic fidelity function. Args: qc (QuantumCircuit): circuit to run, assumes all gates are consolidated coupling_map (CouplingMap): coupling map of device Returns: fidelity (float): noisy fidelity of circuit duration (int): duration of circuit circ (QuantumCircuit): transpiled circuit expected_fidelity (float): expected fidelity of circuit """ N = coupling_map.size() num_active = len(list(circuit_to_dag(qc).idle_wires())) - qc.num_clbits basis_gates = ["cx", "u", "rxx", "ryy", "id"] # Step 0. Create Noise Model # 0A. Set up Instruction Durations # (inst, qubits, time) instruction_durations = [] for j in range(N): instruction_durations.append(("u", j, time_u3)) for j, k in coupling_map: instruction_durations.append(("cx", (j, k), time_cx)) instruction_durations.append(("rxx", (j, k), time_rxx)) instruction_durations.append(("ryy", (j, k), time_rxx)) instruction_durations.append(("save_density_matrix", list(range(N)), 0.0)) # 0B. If circuit is too big, use heuristic fidelity function # Use heuristic fidelity function circ = transpile( qc, basis_gates=basis_gates, instruction_durations=instruction_durations, scheduling_method="asap", coupling_map=coupling_map, ) duration = circ.duration expected_fidelity = heuristic_fidelity(num_active, duration) if N > 10: return 0, duration, circ, expected_fidelity else: transpile_benchy_logger.debug(f"Expected fidelity: {expected_fidelity:.4g}") # 0C. Build noise model builder = NoiseModelBuilder(basis_gates, coupling_map) builder.construct_basic_device_model(p_depol1=p1, p_depol2=p2, t1=T1, t2=T2) noise_model = builder.noise_model # 0D. Create noisy simulator noisy_simulator = AerSimulator(noise_model=noise_model) # Step 1. Given consolidated circuit, decompose into basis gates if sqrt_iswap_basis: decomposer = PassManager() decomposer.append(SiSwapDecomposePass()) decomposer.append(Optimize1qGatesDecomposition()) qc = decomposer.run(qc) # Step 2. Convert into simulator basis gates # simulator = Aer.get_backend("density_matrix_gpu") simulator = QasmSimulator(method="density_matrix") circ = transpile( qc, simulator, basis_gates=basis_gates, coupling_map=coupling_map, ) # Step 3. transpile with scheduling and durations circ = transpile( qc, noisy_simulator, basis_gates=basis_gates + ["save_density_matrix"], instruction_durations=instruction_durations, scheduling_method="asap", coupling_map=coupling_map, ) # Step 4. Relaxation noise for idle qubits pm = PassManager() pm.append(ASAPSchedule()) pm.append( RelaxationNoisePass( t1s=[T1] * N, t2s=[T2] * N, dt=1e-9, op_types=[Delay], ) ) circ = pm.run(circ) duration = circ.duration # Step 5. Run perfect and noisy simulation and compare circ.save_density_matrix(list(range(N))) perfect_result = simulator.run(circ).result().data()["density_matrix"] noisy_result = noisy_simulator.run(circ).result().data()["density_matrix"] fidelity = state_fidelity(perfect_result, noisy_result) return fidelity, duration, circ, expected_fidelity
https://github.com/abbarreto/qiskit4
abbarreto
https://github.com/JavaFXpert/qiskit-runtime-lab
JavaFXpert
!pip install qiskit-algorithms from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService(channel="ibm_quantum") backend = service.backend("ibmq_qasm_simulator") from qiskit.quantum_info import SparsePauliOp # Create an operator by summing together three Pauli operators choc_op = SparsePauliOp(['ZII', 'IZI', 'IIZ']) print(choc_op.to_matrix()) import numpy as np from qiskit_algorithms.optimizers import SPSA from qiskit.circuit.library import EfficientSU2 from qiskit_ibm_runtime import Session, Estimator ansatz = EfficientSU2(3) ansatz.decompose().draw('mpl') from qiskit_ibm_runtime import Options options = Options() options.resilience_level = 1 options.execution.shots = 1024 with Session(backend=backend, max_time="1h") as session: estimator = Estimator(options=options) # Define a callback to print values in each iteration of the optimizer callback = lambda nfev, params, fval, step, acc: print(f'Evaluation {nfev}: {fval}') optimizer = SPSA(callback=callback, maxiter=800) # Define a cost function, flipping the sign so that the optimizer maximizes the expectation value cost_func = lambda params: estimator.run(ansatz, choc_op, parameter_values=params).result().values[0] * -1 result = optimizer.minimize(cost_func, x0=np.zeros(ansatz.num_parameters)) print(result) import matplotlib.pyplot as plt jobs = service.jobs(session_id=session.session_id, limit=None) expectations = [job.result().values[0] for job in jobs if job.done()][::-1] plt.plot(range(len(expectations)), expectations, label='backend') plt.plot(range(len(expectations)), [3.0]*len(expectations), ls='--', label='exact') plt.xlabel('Iteration', fontsize=16) plt.ylabel('Expectation', fontsize=16) plt.legend(loc='lower right')
https://github.com/madmen2/QASM
madmen2
from qiskit import * import matplotlib from qiskit.tools.visualization import plot_histogram circuit = QuantumCircuit(6+1,6) circuit.draw(output='mpl') secret_number='1001010' circuit.h([0,1,2,3,4,5]) circuit.x(6) circuit.h(6) circuit.barrier() circuit.cx(5,6) circuit.cx(3,6) circuit.cx(0,6) circuit.barrier() circuit.h([0,1,2,3,4,5]) circuit.barrier() #algorithm circuit.measure([0,1,2,3,4,5],[0,1,2,3,4,5]) circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=simulator, shots=1).result() print(result.get_counts(circuit)) #general case secret_number1 ='10110100' circuit = QuantumCircuit(len(secret_number1)+1,len(secret_number1)) circuit.h(range(len(secret_number1))) circuit.x(len(secret_number1)) circuit.h(len(secret_number1)) circuit.barrier() for ii, yesno in enumerate(reversed(secret_number1)): if yesno == '1': circuit.cx(ii, len(secret_number1)) circuit.barrier() circuit.h(range(len(secret_number1))) circuit.barrier() #algorithm circuit.measure(range(len(secret_number1)),range(len(secret_number1))) circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend= simulator).result() counts=result.get_counts(circuit) print(counts )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for circuit templates.""" import unittest from test import combine from inspect import getmembers, isfunction from ddt import ddt import numpy as np from qiskit import QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.quantum_info.operators import Operator import qiskit.circuit.library.templates as templib @ddt class TestTemplates(QiskitTestCase): """Tests for the circuit templates.""" circuits = [o[1]() for o in getmembers(templib) if isfunction(o[1])] for circuit in circuits: if isinstance(circuit, QuantumCircuit): circuit.assign_parameters({param: 0.2 for param in circuit.parameters}, inplace=True) @combine(template_circuit=circuits) def test_template(self, template_circuit): """test to verify that all templates are equivalent to the identity""" target = Operator(template_circuit) value = Operator(np.eye(2**template_circuit.num_qubits)) self.assertTrue(target.equiv(value)) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) ghz.draw(output='mpl')
https://github.com/qiskit-community/qiskit-cold-atom
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A base class for circuit solvers of cold atomic quantum circuits.""" from abc import ABC, abstractmethod from typing import List, Optional, Dict, Any import warnings import numpy as np from scipy.sparse import csc_matrix, identity, SparseEfficiencyWarning from scipy.sparse.linalg import expm from qiskit import QuantumCircuit from qiskit.circuit import Gate from qiskit_nature.second_q.operators import SparseLabelOp from qiskit_cold_atom.exceptions import QiskitColdAtomError class BaseCircuitSolver(ABC): """An abstract class for circuit solvers of different cold atom types. By subclassing BaseCircuitSolver one can create circuit solvers for different types of cold atomic setups such as spin, fermionic, and bosonic setups. All these subclasses will simulate cold atom quantum circuits by exponentiating matrices. Therefore, subclasses of BaseCircuitSolver are not intended to solve large circuits. """ def __init__( self, shots: Optional[int] = None, seed: Optional[int] = None, max_dimension: int = 1e6, ignore_barriers: bool = True, ): """ Args: shots: amount of shots for the measurement simulation; if not None, measurements are performed, otherwise no measurements are done. seed: seed for the RNG for the measurement simulation max_dimension: The maximum Hilbert space dimension (limited to keep computation times reasonably short) ignore_barriers: If true, will ignore barrier instructions """ self.shots = shots self._seed = seed if self._seed is not None: np.random.seed(self._seed) self._max_dimension = max_dimension self._ignore_barriers = ignore_barriers self._dim = None @property def seed(self) -> int: """The seed for the random number generator of the measurement simulation.""" return self._seed @seed.setter def seed(self, value: int): """Set the seed for the random number generator. This will also update numpy's seed.""" np.random.seed(value) self._seed = value @property def max_dimension(self) -> int: """The maximal Hilbert space dimension of the simulation.""" return self._max_dimension @max_dimension.setter def max_dimension(self, value: int): self._max_dimension = value @property def ignore_barriers(self) -> bool: """Boolean flag that defines how barrier instructions in the circuit are handled.""" return self._ignore_barriers @property def dim(self) -> int: """Return the dimension set by the last quantum circuit on which the solver was called.""" return self._dim @ignore_barriers.setter def ignore_barriers(self, boolean): self._ignore_barriers = boolean def __call__(self, circuit: QuantumCircuit) -> Dict[str, Any]: """ Performs the simulation of the circuit: Each operator is converted into a sparse matrix over the basis and is then exponentiated to get the unitary of the gate. All these unitaries are multiplied to give the total unitary of the circuit. Applying this to the initial state yields the final state of the circuit, from which we sample a number `shots` of shots (if specified). Args: circuit: A quantum circuit with gates described by second quantized generators Returns: output: dict{'unitary' : np.array((dimension, dimension)), 'statevector': np.array((dimension, 1)), 'counts': dict{string: int}} Raises: QiskitColdAtomError: - If one of the generating Hamiltonians is not hermitian which would lead to non-unitary time evolution. - If the dimension of the Hilbert space is larger than the max. dimension. NotImplementedError: - If ignore_barriers is False. """ self.preprocess_circuit(circuit) if self._dim > self.max_dimension: raise QiskitColdAtomError( f"Hilbert space dimension of the simulation ({self._dim}) exceeds the " f"maximally supported value {self.max_dimension}." ) # initialize the circuit unitary as an identity matrix circuit_unitary = identity(self._dim, dtype=complex) for op in self.to_operators(circuit): operator_mat = self.operator_to_mat(op) # check that the operators are hermitian before exponentiating if (operator_mat.H - operator_mat).count_nonzero() != 0: raise QiskitColdAtomError("generator of unitary gate is not hermitian!") # with the next release of qiskit nature this can be replaced with # if not operator.is_hermitian(): # raise QiskitColdAtomError("generator of unitary gate is not hermitian!") with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=SparseEfficiencyWarning) gate_unitary = expm(-1j * operator_mat) circuit_unitary = gate_unitary @ circuit_unitary final_state = circuit_unitary @ self.get_initial_state(circuit) output = { "unitary": circuit_unitary.toarray(), "statevector": final_state.toarray().reshape(self._dim), } # If shots is specified, simulate measurements on the entire register! if self.shots is not None: meas_distr = np.abs(final_state.toarray().reshape(self._dim)) ** 2 if not np.isclose(sum(meas_distr), 1.0): raise QiskitColdAtomError("Final statevector is not normalized") meas_results = self.draw_shots(meas_distr) counts_dict = { outcome: list(meas_results).count(outcome) for outcome in set(meas_results) } output["memory"] = meas_results output["counts"] = counts_dict # return empty memory and counts dictionary if no shots are specified else: output["memory"] = [] output["counts"] = {} return output def to_operators(self, circuit: QuantumCircuit) -> List[SparseLabelOp]: """ Convert a circuit to a list of second quantized operators that describe the generators of the gates applied to the circuit. The SparseLabelOps generating the gates are embedded in the larger space corresponding to the entire circuit. Args: circuit: A quantum circuit with gates described by second quantized generators Returns: operators: a list of second-quantized operators, one for each applied gate, in the order of the gates in the circuit Raises: QiskitColdAtomError: - If a given gate can not be converted into a second-quantized operator - If a gate is applied after a measurement instruction - If a circuit instruction other than a Gate, measure, load or barrier is given NotImplementedError: If ignore_barriers is False """ operators = [] measured = [False] * circuit.num_qubits for inst in circuit.data: name = inst[0].name qargs = [circuit.qubits.index(qubit) for qubit in inst[1]] if name == "measure": for idx in qargs: measured[idx] = True elif name == "load": continue elif name == "barrier": if self.ignore_barriers: continue raise NotImplementedError elif isinstance(inst[0], Gate): try: second_quantized_op = inst[0].generator except AttributeError as attribute_error: raise QiskitColdAtomError( f"Gate {inst[0].name} has no defined generator" ) from attribute_error if not isinstance(second_quantized_op, SparseLabelOp): raise QiskitColdAtomError( "Gate generator needs to be initialized as qiskit_nature SparseLabelOp" ) for idx in qargs: if measured[idx]: raise QiskitColdAtomError( f"Simulator cannot handle gate {name} after previous measure instruction." ) if not second_quantized_op.register_length == len(qargs): raise QiskitColdAtomError( f"length of operator labels {second_quantized_op.register_length} must be " f"equal to length of wires {len(qargs)} the gate acts on" ) operators.append( self._embed_operator(second_quantized_op, circuit.num_qubits, qargs) ) else: raise QiskitColdAtomError(f"Unknown instruction {name} applied to circuit") return operators @abstractmethod def get_initial_state(self, circuit: QuantumCircuit) -> csc_matrix: """Returns the initial state of the quantum circuit as a sparse column vector.""" @abstractmethod def _embed_operator( self, operator: SparseLabelOp, num_wires: int, qargs: List[int] ) -> SparseLabelOp: """ Turning an operator that acts on the wires given in qargs into an operator that acts on the entire state space of a circuit. The implementation of the subclasses depends on whether the operators use sparse labels (SpinOp) or dense labels (FermionicOp). Args: operator: SparseLabelOp describing the generating Hamiltonian of a gate num_wires: number of wires of the space in which to embed the operator qargs: The wire indices the gate acts on Returns: A SparseLabelOp acting on the entire quantum register of the Circuit """ @abstractmethod def operator_to_mat(self, operator: SparseLabelOp) -> csc_matrix: """Turn a SparseLabelOp into a sparse matrix.""" @abstractmethod def preprocess_circuit(self, circuit: QuantumCircuit): """Pre-process the circuit, e.g. initialize the basis and validate. This needs to update ``dim``, i.e. the Hilbert space dimension of the solver.""" @abstractmethod def draw_shots(self, measurement_distribution: List[float]) -> List[str]: """ Simulates shots by drawing from a given distribution of measurement outcomes. Assigning the index of each outcome to the occupations of the modes can be non-trivial which is why this step needs to be implemented by the subclasses. Args: measurement_distribution: A list with the probabilities of the different measurement outcomes that has the length of the Hilbert space dimension. Returns: A list of strings encoding the outcome of the individual shots. """
https://github.com/mistryiam/IBM-Qiskit-Machine-Learning
mistryiam
import networkx as nx import numpy as np import plotly.graph_objects as go import matplotlib as mpl import pandas as pd from IPython.display import clear_output from plotly.subplots import make_subplots from matplotlib import pyplot as plt from qiskit import Aer from qiskit import QuantumCircuit from qiskit.visualization import plot_state_city from qiskit.algorithms.optimizers import COBYLA, SLSQP, ADAM from time import time from copy import copy from typing import List from qc_grader.graph_util import display_maxcut_widget, QAOA_widget, graphs mpl.rcParams['figure.dpi'] = 300 from qiskit.circuit import Parameter, ParameterVector #Parameters are initialized with a simple string identifier parameter_0 = Parameter('ΞΈ[0]') parameter_1 = Parameter('ΞΈ[1]') circuit = QuantumCircuit(1) #We can then pass the initialized parameters as the rotation angle argument to the Rx and Ry gates circuit.ry(theta = parameter_0, qubit = 0) circuit.rx(theta = parameter_1, qubit = 0) circuit.draw('mpl') parameter = Parameter('ΞΈ') circuit = QuantumCircuit(1) circuit.ry(theta = parameter, qubit = 0) circuit.rx(theta = parameter, qubit = 0) circuit.draw('mpl') #Set the number of layers and qubits n=3 num_layers = 2 #ParameterVectors are initialized with a string identifier and an integer specifying the vector length parameters = ParameterVector('ΞΈ', n*(num_layers+1)) circuit = QuantumCircuit(n, n) for layer in range(num_layers): #Appending the parameterized Ry gates using parameters from the vector constructed above for i in range(n): circuit.ry(parameters[n*layer+i], i) circuit.barrier() #Appending the entangling CNOT gates for i in range(n): for j in range(i): circuit.cx(j,i) circuit.barrier() #Appending one additional layer of parameterized Ry gates for i in range(n): circuit.ry(parameters[n*num_layers+i], i) circuit.barrier() circuit.draw('mpl') print(circuit.parameters) #Create parameter dictionary with random values to bind param_dict = {parameter: np.random.random() for parameter in parameters} print(param_dict) #Assign parameters using the assign_parameters method bound_circuit = circuit.assign_parameters(parameters = param_dict) bound_circuit.draw('mpl') new_parameters = ParameterVector('Ξ¨',9) new_circuit = circuit.assign_parameters(parameters = [k*new_parameters[i] for k in range(9)]) new_circuit.draw('mpl') #Run the circuit with assigned parameters on Aer's statevector simulator simulator = Aer.get_backend('statevector_simulator') result = simulator.run(bound_circuit).result() statevector = result.get_statevector(bound_circuit) plot_state_city(statevector) #The following line produces an error when run because 'circuit' still contains non-assigned parameters #result = simulator.run(circuit).result() for key in graphs.keys(): print(key) graph = nx.Graph() #Add nodes and edges graph.add_nodes_from(np.arange(0,6,1)) edges = [(0,1,2.0),(0,2,3.0),(0,3,2.0),(0,4,4.0),(0,5,1.0),(1,2,4.0),(1,3,1.0),(1,4,1.0),(1,5,3.0),(2,4,2.0),(2,5,3.0),(3,4,5.0),(3,5,1.0)] graph.add_weighted_edges_from(edges) graphs['custom'] = graph #Display widget display_maxcut_widget(graphs['custom']) def maxcut_cost_fn(graph: nx.Graph, bitstring: List[int]) -> float: """ Computes the maxcut cost function value for a given graph and cut represented by some bitstring Args: graph: The graph to compute cut values for bitstring: A list of integer values '0' or '1' specifying a cut of the graph Returns: The value of the cut """ #Get the weight matrix of the graph weight_matrix = nx.adjacency_matrix(graph).toarray() size = weight_matrix.shape[0] value = 0. #INSERT YOUR CODE TO COMPUTE THE CUT VALUE HERE for i in range(size): for j in range(size): value+= weight_matrix[i,j]*bitstring[i]*(1-bitstring[j]) return value def plot_maxcut_histogram(graph: nx.Graph) -> None: """ Plots a bar diagram with the values for all possible cuts of a given graph. Args: graph: The graph to compute cut values for """ num_vars = graph.number_of_nodes() #Create list of bitstrings and corresponding cut values bitstrings = ['{:b}'.format(i).rjust(num_vars, '0')[::-1] for i in range(2**num_vars)] values = [maxcut_cost_fn(graph = graph, bitstring = [int(x) for x in bitstring]) for bitstring in bitstrings] #Sort both lists by largest cut value values, bitstrings = zip(*sorted(zip(values, bitstrings))) #Plot bar diagram bar_plot = go.Bar(x = bitstrings, y = values, marker=dict(color=values, colorscale = 'plasma', colorbar=dict(title='Cut Value'))) fig = go.Figure(data=bar_plot, layout = dict(xaxis=dict(type = 'category'), width = 1500, height = 600)) fig.show() plot_maxcut_histogram(graph = graphs['custom']) from qc_grader import grade_lab2_ex1 bitstring = [1, 0, 1, 1, 0, 0] #DEFINE THE CORRECT MAXCUT BITSTRING HERE # Note that the grading function is expecting a list of integers '0' and '1' grade_lab2_ex1(bitstring) from qiskit_optimization import QuadraticProgram quadratic_program = QuadraticProgram('sample_problem') print(quadratic_program.export_as_lp_string()) quadratic_program.binary_var(name = 'x_0') quadratic_program.integer_var(name = 'x_1') quadratic_program.continuous_var(name = 'x_2', lowerbound = -2.5, upperbound = 1.8) quadratic = [[0,1,2],[3,4,5],[0,1,2]] linear = [10,20,30] quadratic_program.minimize(quadratic = quadratic, linear = linear, constant = -5) print(quadratic_program.export_as_lp_string()) def quadratic_program_from_graph(graph: nx.Graph) -> QuadraticProgram: """Constructs a quadratic program from a given graph for a MaxCut problem instance. Args: graph: Underlying graph of the problem. Returns: QuadraticProgram """ #Get weight matrix of graph weight_matrix = nx.adjacency_matrix(graph) shape = weight_matrix.shape size = shape[0] #Build qubo matrix Q from weight matrix W qubo_matrix = np.zeros((size, size)) qubo_vector = np.zeros(size) for i in range(size): for j in range(size): qubo_matrix[i, j] -= weight_matrix[i, j] for i in range(size): for j in range(size): qubo_vector[i] += weight_matrix[i,j] #INSERT YOUR CODE HERE quadratic_program=QuadraticProgram('sample_problem') for i in range(size): quadratic_program.binary_var(name='x_{}'.format(i)) quadratic_program.maximize(quadratic =qubo_matrix, linear = qubo_vector) return quadratic_program quadratic_program = quadratic_program_from_graph(graphs['custom']) print(quadratic_program.export_as_lp_string()) from qc_grader import grade_lab2_ex2 # Note that the grading function is expecting a quadratic program grade_lab2_ex2(quadratic_program) def qaoa_circuit(qubo: QuadraticProgram, p: int = 1): """ Given a QUBO instance and the number of layers p, constructs the corresponding parameterized QAOA circuit with p layers. Args: qubo: The quadratic program instance p: The number of layers in the QAOA circuit Returns: The parameterized QAOA circuit """ size = len(qubo.variables) qubo_matrix = qubo.objective.quadratic.to_array(symmetric=True) qubo_linearity = qubo.objective.linear.to_array() #Prepare the quantum and classical registers qaoa_circuit = QuantumCircuit(size,size) #Apply the initial layer of Hadamard gates to all qubits qaoa_circuit.h(range(size)) #Create the parameters to be used in the circuit gammas = ParameterVector('gamma', p) betas = ParameterVector('beta', p) #Outer loop to create each layer for i in range(p): #Apply R_Z rotational gates from cost layer #INSERT YOUR CODE HERE for j in range(size): qubo_matrix_sum_of_col = 0 for k in range(size): qubo_matrix_sum_of_col+= qubo_matrix[j][k] qaoa_circuit.rz(gammas[i]*(qubo_linearity[j]+qubo_matrix_sum_of_col),j) #Apply R_ZZ rotational gates for entangled qubit rotations from cost layer #INSERT YOUR CODE HERE for j in range(size): for k in range(size): if j!=k: qaoa_circuit.rzz(gammas[i]*qubo_matrix[j][k]*0.5,j,k) # Apply single qubit X - rotations with angle 2*beta_i to all qubits #INSERT YOUR CODE HERE for j in range(size): qaoa_circuit.rx(2*betas[i],j) return qaoa_circuit quadratic_program = quadratic_program_from_graph(graphs['custom']) custom_circuit = qaoa_circuit(qubo = quadratic_program) test = custom_circuit.assign_parameters(parameters=[1.0]*len(custom_circuit.parameters)) from qc_grader import grade_lab2_ex3 # Note that the grading function is expecting a quantum circuit grade_lab2_ex3(test) from qiskit.algorithms import QAOA from qiskit_optimization.algorithms import MinimumEigenOptimizer backend = Aer.get_backend('statevector_simulator') qaoa = QAOA(optimizer = ADAM(), quantum_instance = backend, reps=1, initial_point = [0.1,0.1]) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) quadratic_program = quadratic_program_from_graph(graphs['custom']) result = eigen_optimizer.solve(quadratic_program) print(result) def plot_samples(samples): """ Plots a bar diagram for the samples of a quantum algorithm Args: samples """ #Sort samples by probability samples = sorted(samples, key = lambda x: x.probability) #Get list of probabilities, function values and bitstrings probabilities = [sample.probability for sample in samples] values = [sample.fval for sample in samples] bitstrings = [''.join([str(int(i)) for i in sample.x]) for sample in samples] #Plot bar diagram sample_plot = go.Bar(x = bitstrings, y = probabilities, marker=dict(color=values, colorscale = 'plasma',colorbar=dict(title='Function Value'))) fig = go.Figure( data=sample_plot, layout = dict( xaxis=dict( type = 'category' ) ) ) fig.show() plot_samples(result.samples) graph_name = 'custom' quadratic_program = quadratic_program_from_graph(graph=graphs[graph_name]) trajectory={'beta_0':[], 'gamma_0':[], 'energy':[]} offset = 1/4*quadratic_program.objective.quadratic.to_array(symmetric = True).sum() + 1/2*quadratic_program.objective.linear.to_array().sum() def callback(eval_count, params, mean, std_dev): trajectory['beta_0'].append(params[1]) trajectory['gamma_0'].append(params[0]) trajectory['energy'].append(-mean + offset) optimizers = { 'cobyla': COBYLA(), 'slsqp': SLSQP(), 'adam': ADAM() } qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=1, initial_point = [6.2,1.8],callback = callback) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) result = eigen_optimizer.solve(quadratic_program) fig = QAOA_widget(landscape_file=f'./resources/energy_landscapes/{graph_name}.csv', trajectory = trajectory, samples = result.samples) fig.show() graph_name = 'custom' quadratic_program = quadratic_program_from_graph(graphs[graph_name]) #Create callback to record total number of evaluations max_evals = 0 def callback(eval_count, params, mean, std_dev): global max_evals max_evals = eval_count #Create empty lists to track values energies = [] runtimes = [] num_evals=[] #Run QAOA for different values of p for p in range(1,10): print(f'Evaluating for p = {p}...') qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=p, callback=callback) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) start = time() result = eigen_optimizer.solve(quadratic_program) runtimes.append(time()-start) num_evals.append(max_evals) #Calculate energy of final state from samples avg_value = 0. for sample in result.samples: avg_value += sample.probability*sample.fval energies.append(avg_value) #Create and display plots energy_plot = go.Scatter(x = list(range(1,10)), y =energies, marker=dict(color=energies, colorscale = 'plasma')) runtime_plot = go.Scatter(x = list(range(1,10)), y =runtimes, marker=dict(color=runtimes, colorscale = 'plasma')) num_evals_plot = go.Scatter(x = list(range(1,10)), y =num_evals, marker=dict(color=num_evals, colorscale = 'plasma')) fig = make_subplots(rows = 1, cols = 3, subplot_titles = ['Energy value', 'Runtime', 'Number of evaluations']) fig.update_layout(width=1800,height=600, showlegend=False) fig.add_trace(energy_plot, row=1, col=1) fig.add_trace(runtime_plot, row=1, col=2) fig.add_trace(num_evals_plot, row=1, col=3) clear_output() fig.show() def plot_qaoa_energy_landscape(graph: nx.Graph, cvar: float = None): num_shots = 1000 seed = 42 simulator = Aer.get_backend('qasm_simulator') simulator.set_options(seed_simulator = 42) #Generate circuit circuit = qaoa_circuit(qubo = quadratic_program_from_graph(graph), p=1) circuit.measure(range(graph.number_of_nodes()),range(graph.number_of_nodes())) #Create dictionary with precomputed cut values for all bitstrings cut_values = {} size = graph.number_of_nodes() for i in range(2**size): bitstr = '{:b}'.format(i).rjust(size, '0')[::-1] x = [int(bit) for bit in bitstr] cut_values[bitstr] = maxcut_cost_fn(graph, x) #Perform grid search over all parameters data_points = [] max_energy = None for beta in np.linspace(0,np.pi, 50): for gamma in np.linspace(0, 4*np.pi, 50): bound_circuit = circuit.assign_parameters([beta, gamma]) result = simulator.run(bound_circuit, shots = num_shots).result() statevector = result.get_counts(bound_circuit) energy = 0 measured_cuts = [] for bitstring, count in statevector.items(): measured_cuts = measured_cuts + [cut_values[bitstring]]*count if cvar is None: #Calculate the mean of all cut values energy = sum(measured_cuts)/num_shots else: #raise NotImplementedError() #INSERT YOUR CODE HERE measured_cuts = sorted(measured_cuts, reverse = True) for w in range(int(cvar*num_shots)): energy += measured_cuts[w]/int((cvar*num_shots)) #Update optimal parameters if max_energy is None or energy > max_energy: max_energy = energy optimum = {'beta': beta, 'gamma': gamma, 'energy': energy} #Update data data_points.append({'beta': beta, 'gamma': gamma, 'energy': energy}) #Create and display surface plot from data_points df = pd.DataFrame(data_points) df = df.pivot(index='beta', columns='gamma', values='energy') matrix = df.to_numpy() beta_values = df.index.tolist() gamma_values = df.columns.tolist() surface_plot = go.Surface( x=gamma_values, y=beta_values, z=matrix, coloraxis = 'coloraxis' ) fig = go.Figure(data = surface_plot) fig.show() #Return optimum return optimum graph = graphs['custom'] optimal_parameters = plot_qaoa_energy_landscape(graph = graph) print('Optimal parameters:') print(optimal_parameters) optimal_parameters = plot_qaoa_energy_landscape(graph = graph, cvar = 0.2) print(optimal_parameters) from qc_grader import grade_lab2_ex4 # Note that the grading function is expecting a python dictionary # with the entries 'beta', 'gamma' and 'energy' grade_lab2_ex4(optimal_parameters)
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
import unittest import numpy as np import hypothesis.strategies as st from hypothesis import given, settings from qiskit import QuantumCircuit, Aer ##################################################################################### ### Change the file to import from, in order to test a mutant version of the code ### ##################################################################################### ### e.g. from Add_mutant_1 import remove_garbage, generate_binary, encode_message, measure_message ##################################################################################### from Add_mutant_1 import remove_garbage, generate_binary, encode_message, measure_message ########################################################################### ## Define composite strategies to generate lists of ints in equal length ## ########################################################################### @st.composite def single_list(draw): arrayLengths = draw(st.integers(min_value=1, max_value=100)) fixed_length_list = st.lists(st.integers(min_value=0, max_value=1), min_size=arrayLengths, max_size=arrayLengths) return (draw(fixed_length_list)) @st.composite def pair_of_lists(draw): arrayLengths = draw(st.integers(min_value=1, max_value=100)) fixed_length_list = st.lists(st.integers(min_value=0, max_value=1), min_size=arrayLengths, max_size=arrayLengths) return (draw(fixed_length_list), draw(fixed_length_list)) @st.composite def trio_of_lists(draw): arrayLengths = draw(st.integers(min_value=1, max_value=100)) fixed_length_list = st.lists(st.integers(min_value=0, max_value=1), min_size=arrayLengths, max_size=arrayLengths) return (draw(fixed_length_list), draw(fixed_length_list), draw(fixed_length_list)) @st.composite def long_trio_of_lists(draw): arrayLengths = draw(st.integers(min_value=100, max_value=110)) fixed_length_list = st.lists(st.integers(min_value=0, max_value=1), min_size=arrayLengths, max_size=arrayLengths) return (draw(fixed_length_list), draw(fixed_length_list), draw(fixed_length_list)) ########################## ## test generate binary ## ########################## @given(testLength = st.integers(min_value=0, max_value=10000)) def test_created_message_is_binary(testLength): binArr = generate_binary(testLength) for i in binArr: assert (i == 1 or i == 0) @given(testLength = st.integers(min_value=1, max_value=10000)) def test_created_message_equal_length_to_int_passed_in(testLength): binArr = generate_binary(testLength) assert(len(binArr) == testLength) ############################ ## encoding message tests ## ############################ @given(pair_of_lists()) @settings(deadline=None) def test_encode_message_equal_length_to_base(lists): alice_bits, alice_bases = lists circuitArr = encode_message(alice_bits, alice_bases, len(alice_bits)) assert(len(circuitArr) == len(alice_bits)) ############################ ## decoding message tests ## ############################ @given(lists = trio_of_lists()) @settings(deadline=None) def test_decode_message_length_equals_base_length(lists): alice_bits, alice_bases, bob_base = lists encoded_message = encode_message(alice_bits, alice_bases, len(bob_base)) msmtArr = measure_message(encoded_message, bob_base, len(bob_base)) assert len(msmtArr) == len(bob_base) @given(lists = trio_of_lists()) @settings(deadline=None) def test_decode_message_is_binary(lists): alice_bits, alice_bases, bob_base = lists encoded_message = encode_message(alice_bits, alice_bases, len(bob_base)) msmtArr = measure_message(encoded_message, bob_base, len(bob_base)) for i in msmtArr: assert (i == 1 or i == 0) @given(lists = pair_of_lists()) @settings(deadline=None) def test_decode_with_same_base_returns_original_bits(lists): alice_bits, alice_bases = lists encoded_message = encode_message(alice_bits, alice_bases, len(alice_bits)) decodeWithSameBases = measure_message(encoded_message, alice_bases, len(alice_bases)) assert(np.array_equal(np.array(alice_bits), np.array(decodeWithSameBases))) @given(lists = pair_of_lists()) @settings(deadline=None) def test_decode_with_same_bases_return_same_array(lists): alice_bits, alice_bases = lists encoded_message = encode_message(alice_bits, alice_bases, len(alice_bits)) encoded_message2 = encode_message(alice_bits, alice_bases, len(alice_bits)) decodeWithSameBases = measure_message(encoded_message, alice_bases, len(alice_bases)) decodeWithSameBases2 = measure_message(encoded_message2, alice_bases, len(alice_bases)) assert(np.array_equal(np.array(decodeWithSameBases), np.array(decodeWithSameBases2))) @given(lists = long_trio_of_lists()) @settings(deadline=None) def test_decoding_runs_likely_different(lists): alice_bits, alice_bases, bob_bases = lists encoded_message = encode_message(alice_bits, alice_bases, len(bob_bases)) msmtArr = measure_message(encoded_message, alice_bases, len(alice_bases)) msmtArrRun2 = measure_message(encoded_message, bob_bases, len(bob_bases)) assert(not np.array_equal(np.array(msmtArr), np.array(msmtArrRun2))) ############################## ## remove garbage/key tests ## ############################## @given(lists = trio_of_lists()) @settings(deadline=None) def test_key_smaller_or_equal_len_to_original_bits(lists): alice_bits, alice_bases, bob_base = lists assert len(remove_garbage(alice_bits, alice_bases, bob_base, len(bob_base))) <= len(bob_base) @given(lists = trio_of_lists()) @settings(deadline=None) def test_check_keys_equal(lists): alice_bits, alice_bases, bob_bases = lists message = encode_message(alice_bits, alice_bases, len(bob_bases)) bob_results = measure_message(message, bob_bases, len(bob_bases)) alice_key = remove_garbage(alice_bases, bob_bases, alice_bits, len(bob_bases)) bob_key = remove_garbage(alice_bases, bob_bases, bob_results, len(bob_bases)) assert(np.array_equal(np.array(alice_key), np.array(bob_key))) @given(lists = trio_of_lists()) @settings(deadline=None) def test_key_is_binary(lists): alice_bits, alice_bases, bob_bases = lists alice_key = remove_garbage(alice_bases, bob_bases, alice_bits, len(bob_bases)) for i in alice_key: assert (i == 1 or i == 0) if __name__ == "__main__": test_created_message_is_binary() test_created_message_equal_length_to_int_passed_in() test_encode_message_equal_length_to_base() test_decode_message_length_equals_base_length() test_decode_message_is_binary() test_decode_with_same_base_returns_original_bits() test_decode_with_same_bases_return_same_array() ########### #test_decoding_runs_likely_different() ########### test_key_smaller_or_equal_len_to_original_bits() test_check_keys_equal() test_key_is_binary()
https://github.com/ansh25saini/Grover_Algorithm_Project
ansh25saini
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() from qiskit.circuit.library.standard_gates import XGate, HGate from operator import * n = 3 N = 8 #2**n index_colour_table = {} colour_hash_map = {} index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"} colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'} def database_oracle(index_colour_table, colour_hash_map): circ_database = QuantumCircuit(n + n) for i in range(N): circ_data = QuantumCircuit(n) idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) # qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0 # we therefore reverse the index string -> q0, ..., qn data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour) circ_database.append(data_gate, list(range(n+n))) return circ_database # drawing the database oracle circuit print("Database Encoding") database_oracle(index_colour_table, colour_hash_map).draw() circ_data = QuantumCircuit(n) m = 4 idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) print("Internal colour encoding for the colour green (as an example)"); circ_data.draw() def oracle_grover(database, data_entry): circ_grover = QuantumCircuit(n + n + 1) circ_grover.append(database, list(range(n+n))) target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target") # control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()' # The β€œmissing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class. circ_grover.append(target_reflection_gate, list(range(n, n+n+1))) circ_grover.append(database, list(range(n+n))) return circ_grover print("Grover Oracle (target example: orange)") oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw() def mcz_gate(num_qubits): num_controls = num_qubits - 1 mcz_gate = QuantumCircuit(num_qubits) target_mcz = QuantumCircuit(1) target_mcz.z(0) target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ") mcz_gate.append(target_mcz, list(range(num_qubits))) return mcz_gate.reverse_bits() print("Multi-controlled Z (MCZ) Gate") mcz_gate(n).decompose().draw() def diffusion_operator(num_qubits): circ_diffusion = QuantumCircuit(num_qubits) qubits_list = list(range(num_qubits)) # Layer of H^n gates circ_diffusion.h(qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of Multi-controlled Z (MCZ) Gate circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of H^n gates circ_diffusion.h(qubits_list) return circ_diffusion print("Diffusion Circuit") diffusion_operator(n).draw() # Putting it all together ... !!! item = "green" print("Searching for the index of the colour", item) circuit = QuantumCircuit(n + n + 1, n) circuit.x(n + n) circuit.barrier() circuit.h(list(range(n))) circuit.h(n+n) circuit.barrier() unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator") unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator") M = countOf(index_colour_table.values(), item) Q = int(np.pi * np.sqrt(N/M) / 4) for i in range(Q): circuit.append(unitary_oracle, list(range(n + n + 1))) circuit.append(unitary_diffuser, list(range(n))) circuit.barrier() circuit.measure(list(range(n)), list(range(n))) circuit.draw() backend_sim = Aer.get_backend('qasm_simulator') job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) if M==1: print("Index of the colour", item, "is the index with most probable outcome") else: print("Indices of the colour", item, "are the indices the most probable outcomes") from qiskit.visualization import plot_histogram plot_histogram(counts)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for uniformly controlled Rx,Ry and Rz gates""" import itertools import unittest import numpy as np from scipy.linalg import block_diag from qiskit import BasicAer, QuantumCircuit, QuantumRegister, execute from qiskit.test import QiskitTestCase from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.compiler import transpile angles_list = [ [0], [0.4], [0, 0], [0, 0.8], [0, 0, 1, 1], [0, 1, 0.5, 1], (2 * np.pi * np.random.rand(2**3)).tolist(), (2 * np.pi * np.random.rand(2**4)).tolist(), (2 * np.pi * np.random.rand(2**5)).tolist(), ] rot_axis_list = ["X", "Y", "Z"] class TestUCRXYZ(QiskitTestCase): """Qiskit tests for UCRXGate, UCRYGate and UCRZGate rotations gates.""" def test_ucy(self): """Test the decomposition of uniformly controlled rotations.""" for angles, rot_axis in itertools.product(angles_list, rot_axis_list): with self.subTest(angles=angles, rot_axis=rot_axis): num_contr = int(np.log2(len(angles))) q = QuantumRegister(num_contr + 1) qc = QuantumCircuit(q) if rot_axis == "X": qc.ucrx(angles, q[1 : num_contr + 1], q[0]) elif rot_axis == "Y": qc.ucry(angles, q[1 : num_contr + 1], q[0]) else: qc.ucrz(angles, q[1 : num_contr + 1], q[0]) # Decompose the gate qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"]) # Simulate the decomposed gate simulator = BasicAer.get_backend("unitary_simulator") result = execute(qc, simulator).result() unitary = result.get_unitary(qc) unitary_desired = _get_ucr_matrix(angles, rot_axis) self.assertTrue(matrix_equal(unitary_desired, unitary, ignore_phase=True)) def _get_ucr_matrix(angles, rot_axis): if rot_axis == "X": gates = [ np.array( [ [np.cos(angle / 2), -1j * np.sin(angle / 2)], [-1j * np.sin(angle / 2), np.cos(angle / 2)], ] ) for angle in angles ] elif rot_axis == "Y": gates = [ np.array( [[np.cos(angle / 2), -np.sin(angle / 2)], [np.sin(angle / 2), np.cos(angle / 2)]] ) for angle in angles ] else: gates = [ np.array([[np.exp(-1.0j * angle / 2), 0], [0, np.exp(1.0j * angle / 2)]]) for angle in angles ] return block_diag(*gates) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
p = 0.2 import numpy as np from qiskit.circuit import QuantumCircuit class BernoulliA(QuantumCircuit): """A circuit representing the Bernoulli A operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(theta_p, 0) class BernoulliQ(QuantumCircuit): """A circuit representing the Bernoulli Q operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit self._theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(2 * self._theta_p, 0) def power(self, k): # implement the efficient power of Q q_k = QuantumCircuit(1) q_k.ry(2 * k * self._theta_p, 0) return q_k A = BernoulliA(p) Q = BernoulliQ(p) from qiskit.algorithms import EstimationProblem problem = EstimationProblem( state_preparation=A, # A operator grover_operator=Q, # Q operator objective_qubits=[0], # the "good" state Psi1 is identified as measuring |1> in qubit 0 ) from qiskit.primitives import Sampler sampler = Sampler() from qiskit.algorithms import AmplitudeEstimation ae = AmplitudeEstimation( num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy sampler=sampler, ) ae_result = ae.estimate(problem) print(ae_result.estimation) import matplotlib.pyplot as plt # plot estimated values gridpoints = list(ae_result.samples.keys()) probabilities = list(ae_result.samples.values()) plt.bar(gridpoints, probabilities, width=0.5 / len(probabilities)) plt.axvline(p, color="r", ls="--") plt.xticks(size=15) plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15) plt.title("Estimated Values", size=15) plt.ylabel("Probability", size=15) plt.xlabel(r"Amplitude $a$", size=15) plt.ylim((0, 1)) plt.grid() plt.show() print("Interpolated MLE estimator:", ae_result.mle) ae_circuit = ae.construct_circuit(problem) ae_circuit.decompose().draw( "mpl", style="iqx" ) # decompose 1 level: exposes the Phase estimation circuit! from qiskit import transpile basis_gates = ["h", "ry", "cry", "cx", "ccx", "p", "cp", "x", "s", "sdg", "y", "t", "cz"] transpile(ae_circuit, basis_gates=basis_gates, optimization_level=2).draw("mpl", style="iqx") from qiskit.algorithms import IterativeAmplitudeEstimation iae = IterativeAmplitudeEstimation( epsilon_target=0.01, # target accuracy alpha=0.05, # width of the confidence interval sampler=sampler, ) iae_result = iae.estimate(problem) print("Estimate:", iae_result.estimation) iae_circuit = iae.construct_circuit(problem, k=3) iae_circuit.draw("mpl", style="iqx") from qiskit.algorithms import MaximumLikelihoodAmplitudeEstimation mlae = MaximumLikelihoodAmplitudeEstimation( evaluation_schedule=3, # log2 of the maximal Grover power sampler=sampler, ) mlae_result = mlae.estimate(problem) print("Estimate:", mlae_result.estimation) from qiskit.algorithms import FasterAmplitudeEstimation fae = FasterAmplitudeEstimation( delta=0.01, # target accuracy maxiter=3, # determines the maximal power of the Grover operator sampler=sampler, ) fae_result = fae.estimate(problem) print("Estimate:", fae_result.estimation) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse3Q # TODO: This example should use a real mock backend. backend = FakeOpenPulse3Q() d2 = pulse.DriveChannel(2) with pulse.build(backend) as bell_prep: pulse.u2(0, math.pi, 0) pulse.cx(0, 1) with pulse.build(backend) as decoupled_bell_prep_and_measure: # We call our bell state preparation schedule constructed above. with pulse.align_right(): pulse.call(bell_prep) pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2) pulse.barrier(0, 1, 2) registers = pulse.measure_all() decoupled_bell_prep_and_measure.draw()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver() problem = driver.run() print(problem) from qiskit_nature.second_q.problems import ElectronicBasis driver.run_pyscf() problem = driver.to_problem(basis=ElectronicBasis.MO, include_dipole=True) print(problem.basis) ao_problem = driver.to_problem(basis=ElectronicBasis.AO) print(ao_problem.basis) from qiskit_nature.second_q.formats.qcschema_translator import qcschema_to_problem qcschema = driver.to_qcschema() ao_problem = qcschema_to_problem(qcschema, basis=ElectronicBasis.AO) from qiskit_nature.second_q.formats.qcschema_translator import get_ao_to_mo_from_qcschema basis_transformer = get_ao_to_mo_from_qcschema(qcschema) mo_problem = basis_transformer.transform(ao_problem) print(mo_problem.basis) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for Stabilizerstate quantum state class.""" import unittest from test import combine import logging from ddt import ddt, data, unpack import numpy as np from qiskit.test import QiskitTestCase from qiskit import QuantumCircuit from qiskit.quantum_info.random import random_clifford, random_pauli from qiskit.quantum_info.states import StabilizerState, Statevector from qiskit.circuit.library import IGate, XGate, HGate from qiskit.quantum_info.operators import Clifford, Pauli, Operator logger = logging.getLogger(__name__) @ddt class TestStabilizerState(QiskitTestCase): """Tests for StabilizerState class.""" rng = np.random.default_rng(12345) samples = 10 shots = 1000 threshold = 0.1 * shots @combine(num_qubits=[2, 3, 4, 5]) def test_init_clifford(self, num_qubits): """Test initialization from Clifford.""" stab1 = StabilizerState(random_clifford(num_qubits, seed=self.rng)) stab2 = StabilizerState(stab1) self.assertEqual(stab1, stab2) @combine(num_qubits=[2, 3, 4, 5]) def test_init_circuit(self, num_qubits): """Test initialization from a Clifford circuit.""" cliff = random_clifford(num_qubits, seed=self.rng) stab1 = StabilizerState(cliff.to_circuit()) stab2 = StabilizerState(cliff) self.assertEqual(stab1, stab2) @combine(num_qubits=[2, 3, 4, 5]) def test_init_instruction(self, num_qubits): """Test initialization from a Clifford instruction.""" cliff = random_clifford(num_qubits, seed=self.rng) stab1 = StabilizerState(cliff.to_instruction()) stab2 = StabilizerState(cliff) self.assertEqual(stab1, stab2) @combine(num_qubits=[2, 3, 4, 5]) def test_init_pauli(self, num_qubits): """Test initialization from pauli.""" pauli = random_pauli(num_qubits, seed=self.rng) stab1 = StabilizerState(pauli) stab2 = StabilizerState(stab1) self.assertEqual(stab1, stab2) @combine(num_qubits=[2, 3, 4, 5]) def test_to_operator(self, num_qubits): """Test to_operator method for returning projector.""" for _ in range(self.samples): stab = StabilizerState(random_clifford(num_qubits, seed=self.rng)) target = Operator(stab) op = StabilizerState(stab).to_operator() self.assertEqual(op, target) @combine(num_qubits=[2, 3, 4]) def test_trace(self, num_qubits): """Test trace methods""" stab = StabilizerState(random_clifford(num_qubits, seed=self.rng)) trace = stab.trace() self.assertEqual(trace, 1.0) @combine(num_qubits=[2, 3, 4]) def test_purity(self, num_qubits): """Test purity methods""" stab = StabilizerState(random_clifford(num_qubits, seed=self.rng)) purity = stab.purity() self.assertEqual(purity, 1.0) @combine(num_qubits=[2, 3]) def test_conjugate(self, num_qubits): """Test conjugate method.""" for _ in range(self.samples): cliff = random_clifford(num_qubits, seed=self.rng) target = StabilizerState(cliff.conjugate()) state = StabilizerState(cliff).conjugate() self.assertEqual(state, target) def test_tensor(self): """Test tensor method.""" for _ in range(self.samples): cliff1 = random_clifford(2, seed=self.rng) cliff2 = random_clifford(3, seed=self.rng) stab1 = StabilizerState(cliff1) stab2 = StabilizerState(cliff2) target = StabilizerState(cliff1.tensor(cliff2)) state = stab1.tensor(stab2) self.assertEqual(state, target) def test_expand(self): """Test expand method.""" for _ in range(self.samples): cliff1 = random_clifford(2, seed=self.rng) cliff2 = random_clifford(3, seed=self.rng) stab1 = StabilizerState(cliff1) stab2 = StabilizerState(cliff2) target = StabilizerState(cliff1.expand(cliff2)) state = stab1.expand(stab2) self.assertEqual(state, target) @combine(num_qubits=[2, 3, 4]) def test_evolve(self, num_qubits): """Test evolve method.""" for _ in range(self.samples): cliff1 = random_clifford(num_qubits, seed=self.rng) cliff2 = random_clifford(num_qubits, seed=self.rng) stab1 = StabilizerState(cliff1) stab2 = StabilizerState(cliff2) target = StabilizerState(cliff1.compose(cliff2)) state = stab1.evolve(stab2) self.assertEqual(state, target) @combine(num_qubits_1=[4, 5, 6], num_qubits_2=[1, 2, 3]) def test_evolve_subsystem(self, num_qubits_1, num_qubits_2): """Test subsystem evolve method.""" for _ in range(self.samples): cliff1 = random_clifford(num_qubits_1, seed=self.rng) cliff2 = random_clifford(num_qubits_2, seed=self.rng) stab1 = StabilizerState(cliff1) stab2 = StabilizerState(cliff2) qargs = sorted(np.random.choice(range(num_qubits_1), num_qubits_2, replace=False)) target = StabilizerState(cliff1.compose(cliff2, qargs)) state = stab1.evolve(stab2, qargs) self.assertEqual(state, target) def test_measure_single_qubit(self): """Test a measurement of a single qubit""" for _ in range(self.samples): cliff = Clifford(XGate()) stab = StabilizerState(cliff) value = stab.measure()[0] self.assertEqual(value, "1") cliff = Clifford(IGate()) stab = StabilizerState(cliff) value = stab.measure()[0] self.assertEqual(value, "0") cliff = Clifford(HGate()) stab = StabilizerState(cliff) value = stab.measure()[0] self.assertIn(value, ["0", "1"]) def test_measure_qubits(self): """Test a measurement of a subsystem of qubits""" for _ in range(self.samples): num_qubits = 4 qc = QuantumCircuit(num_qubits) stab = StabilizerState(qc) value = stab.measure()[0] self.assertEqual(value, "0000") value = stab.measure([0, 2])[0] self.assertEqual(value, "00") value = stab.measure([1])[0] self.assertEqual(value, "0") for i in range(num_qubits): qc.x(i) stab = StabilizerState(qc) value = stab.measure()[0] self.assertEqual(value, "1111") value = stab.measure([2, 0])[0] self.assertEqual(value, "11") value = stab.measure([1])[0] self.assertEqual(value, "1") qc = QuantumCircuit(num_qubits) qc.h(0) stab = StabilizerState(qc) value = stab.measure()[0] self.assertIn(value, ["0000", "0001"]) value = stab.measure([0, 1])[0] self.assertIn(value, ["00", "01"]) value = stab.measure([2])[0] self.assertEqual(value, "0") qc = QuantumCircuit(num_qubits) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) stab = StabilizerState(qc) value = stab.measure()[0] self.assertIn(value, ["0000", "1111"]) value = stab.measure([3, 1])[0] self.assertIn(value, ["00", "11"]) value = stab.measure([2])[0] self.assertIn(value, ["0", "1"]) def test_reset_single_qubit(self): """Test reset method of a single qubit""" empty_qc = QuantumCircuit(1) for _ in range(self.samples): cliff = Clifford(XGate()) stab = StabilizerState(cliff) value = stab.reset([0]) target = StabilizerState(empty_qc) self.assertEqual(value, target) cliff = Clifford(HGate()) stab = StabilizerState(cliff) value = stab.reset([0]) target = StabilizerState(empty_qc) self.assertEqual(value, target) def test_reset_qubits(self): """Test reset method of a subsystem of qubits""" num_qubits = 3 qc = QuantumCircuit(num_qubits) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) for _ in range(self.samples): with self.subTest(msg="reset (None)"): stab = StabilizerState(qc) res = stab.reset() value = res.measure()[0] self.assertEqual(value, "000") for _ in range(self.samples): for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"reset (qargs={qargs})"): stab = StabilizerState(qc) res = stab.reset(qargs) value = res.measure()[0] self.assertEqual(value, "000") for _ in range(self.samples): with self.subTest(msg="reset ([0])"): stab = StabilizerState(qc) res = stab.reset([0]) value = res.measure()[0] self.assertIn(value, ["000", "110"]) for _ in range(self.samples): with self.subTest(msg="reset ([1])"): stab = StabilizerState(qc) res = stab.reset([1]) value = res.measure()[0] self.assertIn(value, ["000", "101"]) for _ in range(self.samples): with self.subTest(msg="reset ([2])"): stab = StabilizerState(qc) res = stab.reset([2]) value = res.measure()[0] self.assertIn(value, ["000", "011"]) for _ in range(self.samples): for qargs in [[0, 1], [1, 0]]: with self.subTest(msg=f"reset (qargs={qargs})"): stab = StabilizerState(qc) res = stab.reset(qargs) value = res.measure()[0] self.assertIn(value, ["000", "100"]) for _ in range(self.samples): for qargs in [[0, 2], [2, 0]]: with self.subTest(msg=f"reset (qargs={qargs})"): stab = StabilizerState(qc) res = stab.reset(qargs) value = res.measure()[0] self.assertIn(value, ["000", "010"]) for _ in range(self.samples): for qargs in [[1, 2], [2, 1]]: with self.subTest(msg=f"reset (qargs={qargs})"): stab = StabilizerState(qc) res = stab.reset(qargs) value = res.measure()[0] self.assertIn(value, ["000", "001"]) def test_probablities_dict_single_qubit(self): """Test probabilities and probabilities_dict methods of a single qubit""" num_qubits = 1 qc = QuantumCircuit(num_qubits) for _ in range(self.samples): with self.subTest(msg="P(id(0))"): stab = StabilizerState(qc) value = stab.probabilities_dict() target = {"0": 1} self.assertEqual(value, target) probs = stab.probabilities() target = np.array([1, 0]) self.assertTrue(np.allclose(probs, target)) qc.x(0) for _ in range(self.samples): with self.subTest(msg="P(x(0))"): stab = StabilizerState(qc) value = stab.probabilities_dict() target = {"1": 1} self.assertEqual(value, target) probs = stab.probabilities() target = np.array([0, 1]) self.assertTrue(np.allclose(probs, target)) qc = QuantumCircuit(num_qubits) qc.h(0) for _ in range(self.samples): with self.subTest(msg="P(h(0))"): stab = StabilizerState(qc) value = stab.probabilities_dict() target = {"0": 0.5, "1": 0.5} self.assertEqual(value, target) probs = stab.probabilities() target = np.array([0.5, 0.5]) self.assertTrue(np.allclose(probs, target)) def test_probablities_dict_two_qubits(self): """Test probabilities and probabilities_dict methods of two qubits""" num_qubits = 2 qc = QuantumCircuit(num_qubits) qc.h(0) stab = StabilizerState(qc) for _ in range(self.samples): with self.subTest(msg="P(None)"): value = stab.probabilities_dict() target = {"00": 0.5, "01": 0.5} self.assertEqual(value, target) probs = stab.probabilities() target = np.array([0.5, 0.5, 0, 0]) self.assertTrue(np.allclose(probs, target)) for _ in range(self.samples): with self.subTest(msg="P([0, 1])"): value = stab.probabilities_dict([0, 1]) target = {"00": 0.5, "01": 0.5} self.assertEqual(value, target) probs = stab.probabilities([0, 1]) target = np.array([0.5, 0.5, 0, 0]) self.assertTrue(np.allclose(probs, target)) for _ in range(self.samples): with self.subTest(msg="P([1, 0])"): value = stab.probabilities_dict([1, 0]) target = {"00": 0.5, "10": 0.5} self.assertEqual(value, target) probs = stab.probabilities([1, 0]) target = np.array([0.5, 0, 0.5, 0]) self.assertTrue(np.allclose(probs, target)) for _ in range(self.samples): with self.subTest(msg="P[0]"): value = stab.probabilities_dict([0]) target = {"0": 0.5, "1": 0.5} self.assertEqual(value, target) probs = stab.probabilities([0]) target = np.array([0.5, 0.5]) self.assertTrue(np.allclose(probs, target)) for _ in range(self.samples): with self.subTest(msg="P([1])"): value = stab.probabilities_dict([1]) target = {"0": 1.0} self.assertEqual(value, target) probs = stab.probabilities([1]) target = np.array([1, 0]) self.assertTrue(np.allclose(probs, target)) def test_probablities_dict_qubits(self): """Test probabilities and probabilities_dict methods of a subsystem of qubits""" num_qubits = 3 qc = QuantumCircuit(num_qubits) qc.h(0) qc.h(1) qc.h(2) stab = StabilizerState(qc) for _ in range(self.samples): with self.subTest(msg="P(None), decimals=1"): value = stab.probabilities_dict(decimals=1) target = { "000": 0.1, "001": 0.1, "010": 0.1, "011": 0.1, "100": 0.1, "101": 0.1, "110": 0.1, "111": 0.1, } self.assertEqual(value, target) probs = stab.probabilities(decimals=1) target = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) self.assertTrue(np.allclose(probs, target)) for _ in range(self.samples): with self.subTest(msg="P(None), decimals=2"): value = stab.probabilities_dict(decimals=2) target = { "000": 0.12, "001": 0.12, "010": 0.12, "011": 0.12, "100": 0.12, "101": 0.12, "110": 0.12, "111": 0.12, } self.assertEqual(value, target) probs = stab.probabilities(decimals=2) target = np.array([0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12]) self.assertTrue(np.allclose(probs, target)) for _ in range(self.samples): with self.subTest(msg="P(None), decimals=3"): value = stab.probabilities_dict(decimals=3) target = { "000": 0.125, "001": 0.125, "010": 0.125, "011": 0.125, "100": 0.125, "101": 0.125, "110": 0.125, "111": 0.125, } self.assertEqual(value, target) probs = stab.probabilities(decimals=3) target = np.array([0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125]) self.assertTrue(np.allclose(probs, target)) def test_probablities_dict_ghz(self): """Test probabilities and probabilities_dict method of a subsystem of qubits""" num_qubits = 3 qc = QuantumCircuit(num_qubits) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) with self.subTest(msg="P(None)"): stab = StabilizerState(qc) value = stab.probabilities_dict() target = {"000": 0.5, "111": 0.5} self.assertEqual(value, target) probs = stab.probabilities() target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5]) self.assertTrue(np.allclose(probs, target)) # 3-qubit qargs for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = stab.probabilities_dict(qargs) target = {"000": 0.5, "111": 0.5} self.assertDictAlmostEqual(probs, target) probs = stab.probabilities(qargs) target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5]) self.assertTrue(np.allclose(probs, target)) # 2-qubit qargs for qargs in [[0, 1], [2, 1], [1, 0], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = stab.probabilities_dict(qargs) target = {"00": 0.5, "11": 0.5} self.assertDictAlmostEqual(probs, target) probs = stab.probabilities(qargs) target = np.array([0.5, 0, 0, 0.5]) self.assertTrue(np.allclose(probs, target)) # 1-qubit qargs for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = stab.probabilities_dict(qargs) target = {"0": 0.5, "1": 0.5} self.assertDictAlmostEqual(probs, target) probs = stab.probabilities(qargs) target = np.array([0.5, 0.5]) self.assertTrue(np.allclose(probs, target)) @combine(num_qubits=[2, 3, 4]) def test_probs_random_subsystem(self, num_qubits): """Test probabilities and probabilities_dict methods of random cliffords for a subsystem of qubits""" for _ in range(self.samples): for subsystem_size in range(1, num_qubits): cliff = random_clifford(num_qubits, seed=self.rng) qargs = np.random.choice(num_qubits, size=subsystem_size, replace=False) qc = cliff.to_circuit() stab = StabilizerState(cliff) probs = stab.probabilities(qargs) probs_dict = stab.probabilities_dict(qargs) target = Statevector(qc).probabilities(qargs) target_dict = Statevector(qc).probabilities_dict(qargs) self.assertTrue(np.allclose(probs, target)) self.assertDictAlmostEqual(probs_dict, target_dict) @combine(num_qubits=[2, 3, 4, 5]) def test_expval_from_random_clifford(self, num_qubits): """Test that the expectation values for a random Clifford, where the Pauli operators are all its stabilizers, are equal to 1.""" for _ in range(self.samples): cliff = random_clifford(num_qubits, seed=self.rng) qc = cliff.to_circuit() stab = StabilizerState(qc) stab_gen = stab.clifford.to_dict()["stabilizer"] for i in range(num_qubits): op = Pauli(stab_gen[i]) exp_val = stab.expectation_value(op) self.assertEqual(exp_val, 1) def test_sample_counts_reset_bell(self): """Test sample_counts after reset for Bell state""" num_qubits = 2 qc = QuantumCircuit(num_qubits) qc.h(0) qc.cx(0, 1) stab = StabilizerState(qc) target = {"00": self.shots / 2, "10": self.shots / 2} counts = {"00": 0, "10": 0} for _ in range(self.shots): res = stab.reset([0]) value = res.measure()[0] counts[value] += 1 self.assertDictAlmostEqual(counts, target, self.threshold) target = {"00": self.shots / 2, "01": self.shots / 2} counts = {"00": 0, "01": 0} for _ in range(self.shots): res = stab.reset([1]) value = res.measure()[0] counts[value] += 1 self.assertDictAlmostEqual(counts, target, self.threshold) def test_sample_counts_memory_ghz(self): """Test sample_counts and sample_memory method for GHZ state""" num_qubits = 3 qc = QuantumCircuit(num_qubits) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) stab = StabilizerState(qc) # 3-qubit qargs target = {"000": self.shots / 2, "111": self.shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = stab.sample_counts(self.shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, self.threshold) with self.subTest(msg=f"memory (qargs={qargs})"): memory = stab.sample_memory(self.shots, qargs=qargs) self.assertEqual(len(memory), self.shots) self.assertEqual(set(memory), set(target)) # 2-qubit qargs target = {"00": self.shots / 2, "11": self.shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 0]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = stab.sample_counts(self.shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, self.threshold) with self.subTest(msg=f"memory (qargs={qargs})"): memory = stab.sample_memory(self.shots, qargs=qargs) self.assertEqual(len(memory), self.shots) self.assertEqual(set(memory), set(target)) # 1-qubit qargs target = {"0": self.shots / 2, "1": self.shots / 2} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = stab.sample_counts(self.shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, self.threshold) with self.subTest(msg=f"memory (qargs={qargs})"): memory = stab.sample_memory(self.shots, qargs=qargs) self.assertEqual(len(memory), self.shots) self.assertEqual(set(memory), set(target)) def test_sample_counts_memory_superposition(self): """Test sample_counts and sample_memory method of a 3-qubit superposition""" num_qubits = 3 qc = QuantumCircuit(num_qubits) qc.h(0) qc.h(1) qc.h(2) stab = StabilizerState(qc) # 3-qubit qargs target = { "000": self.shots / 8, "001": self.shots / 8, "010": self.shots / 8, "011": self.shots / 8, "100": self.shots / 8, "101": self.shots / 8, "110": self.shots / 8, "111": self.shots / 8, } for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = stab.sample_counts(self.shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, self.threshold) with self.subTest(msg=f"memory (qargs={qargs})"): memory = stab.sample_memory(self.shots, qargs=qargs) self.assertEqual(len(memory), self.shots) self.assertEqual(set(memory), set(target)) # 2-qubit qargs target = { "00": self.shots / 4, "01": self.shots / 4, "10": self.shots / 4, "11": self.shots / 4, } for qargs in [[0, 1], [2, 1], [1, 2], [1, 0]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = stab.sample_counts(self.shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, self.threshold) with self.subTest(msg=f"memory (qargs={qargs})"): memory = stab.sample_memory(self.shots, qargs=qargs) self.assertEqual(len(memory), self.shots) self.assertEqual(set(memory), set(target)) # 1-qubit qargs target = {"0": self.shots / 2, "1": self.shots / 2} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = stab.sample_counts(self.shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, self.threshold) with self.subTest(msg=f"memory (qargs={qargs})"): memory = stab.sample_memory(self.shots, qargs=qargs) self.assertEqual(len(memory), self.shots) self.assertEqual(set(memory), set(target)) @ddt class TestStabilizerStateExpectationValue(QiskitTestCase): """Tests for StabilizerState.expectation_value method.""" rng = np.random.default_rng(12345) samples = 10 shots = 1000 threshold = 0.1 * shots @data(("Z", 1), ("X", 0), ("Y", 0), ("I", 1), ("Z", 1), ("-Z", -1), ("iZ", 1j), ("-iZ", -1j)) @unpack def test_expval_single_qubit_0(self, label, target): """Test expectation_value method of a single qubit on |0>""" qc = QuantumCircuit(1) stab = StabilizerState(qc) op = Pauli(label) expval = stab.expectation_value(op) self.assertEqual(expval, target) @data(("Z", -1), ("X", 0), ("Y", 0), ("I", 1)) @unpack def test_expval_single_qubit_1(self, label, target): """Test expectation_value method of a single qubit on |1>""" qc = QuantumCircuit(1) qc.x(0) stab = StabilizerState(qc) op = Pauli(label) expval = stab.expectation_value(op) self.assertEqual(expval, target) @data(("Z", 0), ("X", 1), ("Y", 0), ("I", 1), ("X", 1), ("-X", -1), ("iX", 1j), ("-iX", -1j)) @unpack def test_expval_single_qubit_plus(self, label, target): """Test expectation_value method of a single qubit on |+>""" qc = QuantumCircuit(1) qc.h(0) stab = StabilizerState(qc) op = Pauli(label) expval = stab.expectation_value(op) self.assertEqual(expval, target) @data( ("II", 1), ("XX", 0), ("YY", 0), ("ZZ", 1), ("IX", 0), ("IY", 0), ("IZ", 1), ("XY", 0), ("XZ", 0), ("YZ", 0), ("-ZZ", -1), ("iZZ", 1j), ("-iZZ", -1j), ) @unpack def test_expval_two_qubits_00(self, label, target): """Test expectation_value method of two qubits in |00>""" num_qubits = 2 qc = QuantumCircuit(num_qubits) stab = StabilizerState(qc) op = Pauli(label) expval = stab.expectation_value(op) self.assertEqual(expval, target) @data( ("II", 1), ("XX", 0), ("YY", 0), ("ZZ", 1), ("IX", 0), ("IY", 0), ("IZ", -1), ("XY", 0), ("XZ", 0), ("YZ", 0), ) @unpack def test_expval_two_qubits_11(self, label, target): """Test expectation_value method of two qubits in |11>""" qc = QuantumCircuit(2) qc.x(0) qc.x(1) stab = StabilizerState(qc) op = Pauli(label) expval = stab.expectation_value(op) self.assertEqual(expval, target) @data( ("II", 1), ("XX", 1), ("YY", 0), ("ZZ", 0), ("IX", 1), ("IY", 0), ("IZ", 0), ("XY", 0), ("XZ", 0), ("YZ", 0), ("-XX", -1), ("iXX", 1j), ("-iXX", -1j), ) @unpack def test_expval_two_qubits_plusplus(self, label, target): """Test expectation_value method of two qubits in |++>""" qc = QuantumCircuit(2) qc.h(0) qc.h(1) stab = StabilizerState(qc) op = Pauli(label) expval = stab.expectation_value(op) self.assertEqual(expval, target) @data( ("II", 1), ("XX", 0), ("YY", 0), ("ZZ", 0), ("IX", 0), ("IY", 0), ("IZ", -1), ("XY", 0), ("XZ", -1), ("YZ", 0), ) @unpack def test_expval_two_qubits_plus1(self, label, target): """Test expectation_value method of two qubits in |+1>""" qc = QuantumCircuit(2) qc.x(0) qc.h(1) stab = StabilizerState(qc) op = Pauli(label) expval = stab.expectation_value(op) self.assertEqual(expval, target) @data( ("II", 1), ("XX", 1), ("YY", -1), ("ZZ", 1), ("IX", 0), ("IY", 0), ("IZ", 0), ("XY", 0), ("XZ", 0), ("YZ", 0), ("-YY", 1), ("iYY", -1j), ("-iYY", 1j), ) @unpack def test_expval_two_qubits_bell_phi_plus(self, label, target): """Test expectation_value method of two qubits in bell phi plus""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) stab = StabilizerState(qc) op = Pauli(label) expval = stab.expectation_value(op) self.assertEqual(expval, target) @data( ("II", 1), ("XX", 1), ("YY", 1), ("ZZ", -1), ("IX", 0), ("IY", 0), ("IZ", 0), ("XY", 0), ("XZ", 0), ("YZ", 0), ("-XX", -1), ("-YY", -1), ("iXX", 1j), ("iYY", 1j), ("-iXX", -1j), ("-iYY", -1j), ) @unpack def test_expval_two_qubits_bell_phi_minus(self, label, target): """Test expectation_value method of two qubits in bell phi minus""" qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.cx(0, 1) stab = StabilizerState(qc) op = Pauli(label) expval = stab.expectation_value(op) self.assertEqual(expval, target) @data( ("II", 1), ("XX", 1), ("YY", 1), ("ZZ", -1), ("IX", 0), ("IY", 0), ("IZ", 0), ("XY", 0), ("XZ", 0), ("YZ", 0), ("-XX", -1), ("-YY", -1), ("iXX", 1j), ("iYY", 1j), ("-iXX", -1j), ("-iYY", -1j), ) @unpack def test_expval_two_qubits_bell_sdg_h(self, label, target): """Test expectation_value method of two qubits in bell followed by sdg and h""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.sdg(0) qc.sdg(1) qc.h(0) qc.h(1) stab = StabilizerState(qc) op = Pauli(label) expval = stab.expectation_value(op) self.assertEqual(expval, target) @combine(num_qubits=[2, 3, 4, 5]) def test_expval_random(self, num_qubits): """Test expectation_value method of random Cliffords""" for _ in range(self.samples): cliff = random_clifford(num_qubits, seed=self.rng) op = random_pauli(num_qubits, group_phase=True, seed=self.rng) qc = cliff.to_circuit() stab = StabilizerState(cliff) exp_val = stab.expectation_value(op) target = Statevector(qc).expectation_value(op) self.assertAlmostEqual(exp_val, target) @combine(num_qubits=[2, 3, 4, 5]) def test_expval_random_subsystem(self, num_qubits): """Test expectation_value method of random Cliffords and a subsystem""" for _ in range(self.samples): cliff = random_clifford(num_qubits, seed=self.rng) op = random_pauli(2, group_phase=True, seed=self.rng) qargs = np.random.choice(num_qubits, size=2, replace=False) qc = cliff.to_circuit() stab = StabilizerState(cliff) exp_val = stab.expectation_value(op, qargs) target = Statevector(qc).expectation_value(op, qargs) self.assertAlmostEqual(exp_val, target) def test_stabilizer_bell_equiv(self): """Test that two circuits produce the same stabilizer group.""" qc1 = QuantumCircuit(2) qc1.h(0) qc1.x(1) qc1.cx(0, 1) qc2 = QuantumCircuit(2) qc2.h(0) qc2.cx(0, 1) qc2.sdg(0) qc2.sdg(1) qc2.h(0) qc2.h(1) qc3 = QuantumCircuit(2) qc3.h(0) qc3.cx(0, 1) qc4 = QuantumCircuit(2) qc4.h(0) qc4.cx(0, 1) qc4.s(0) qc4.sdg(1) qc4.h(0) qc4.h(1) cliff1 = StabilizerState(qc1) # ['+XX', '-ZZ'] cliff2 = StabilizerState(qc2) # ['+YY', '+XX'] cliff3 = StabilizerState(qc3) # ['+XX', '+ZZ'] cliff4 = StabilizerState(qc4) # ['-YY', '+XX'] # [XX, -ZZ] and [XX, YY] both generate the stabilizer group {II, XX, YY, -ZZ} self.assertTrue(cliff1.equiv(cliff2)) self.assertEqual(cliff1.probabilities_dict(), cliff2.probabilities_dict()) # [XX, ZZ] and [XX, -YY] both generate the stabilizer group {II, XX, -YY, ZZ} self.assertTrue(cliff3.equiv(cliff4)) self.assertEqual(cliff3.probabilities_dict(), cliff4.probabilities_dict()) self.assertFalse(cliff1.equiv(cliff3)) self.assertFalse(cliff2.equiv(cliff4)) if __name__ == "__main__": unittest.main()
https://github.com/tomtuamnuq/compare-qiskit-ocean
tomtuamnuq
import io import numpy as np from numpy import pi import pydot from PIL import Image import retworkx as rx from qiskit import IBMQ, QuantumRegister, ClassicalRegister, QuantumCircuit, transpile def create_qaoa_circuit() -> QuantumCircuit: """ taken from IBMQ Experience """ qreg_q = QuantumRegister(3, 'q') circuit = QuantumCircuit(qreg_q) circuit.h(qreg_q[0]) circuit.h(qreg_q[1]) circuit.cx(qreg_q[1], qreg_q[0]) circuit.rz(-0.06942544294642758, qreg_q[0]) circuit.cx(qreg_q[1], qreg_q[0]) circuit.rz(-0.20827632883928274, qreg_q[0]) circuit.rx(0.7530122052855767, qreg_q[0]) circuit.h(qreg_q[2]) circuit.cx(qreg_q[2], qreg_q[1]) circuit.rz(1.2496579730356965, qreg_q[1]) circuit.cx(qreg_q[2], qreg_q[1]) circuit.rz(-0.20827632883928274, qreg_q[1]) circuit.rx(0.7530122052855767, qreg_q[1]) circuit.rx(0.7530122052855767, qreg_q[2]) return circuit # transpile circuit for ibmq_belem IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') device = provider.get_backend("ibmq_belem") conf = device.configuration() print(conf.basis_gates) qc = create_qaoa_circuit() circuit_transpiled = transpile(qc, backend=device, optimization_level=3) circuit_transpiled.draw(output='mpl') graph = rx.PyGraph(multigraph=False) coupling_map = [tuple(edge) for edge in conf.coupling_map] graph.add_nodes_from([i for i in range(5)]) graph.add_edges_from_no_data(coupling_map) circuit_nodes = [0, 1, 2] neighbor_nodes = [3] def node_attr(node): kwargs = dict(style='filled', shape="circle", fontsize="14", fixedsize="true", width="0.4", height="0.4") if node in circuit_nodes: kwargs.update(fillcolor='green') elif node in neighbor_nodes: kwargs.update(fillcolor='lightblue', label="") else: kwargs.update(fillcolor='darkblue', label="") return kwargs dot_str = graph.to_dot(node_attr) dot = pydot.graph_from_dot_data(dot_str)[0] png = dot.create_png(prog='neato') Image.open(io.BytesIO(png))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 42 from qiskit.circuit import Parameter from qiskit import QuantumCircuit params1 = [Parameter("input1"), Parameter("weight1")] qc1 = QuantumCircuit(1) qc1.h(0) qc1.ry(params1[0], 0) qc1.rx(params1[1], 0) qc1.draw("mpl") from qiskit.quantum_info import SparsePauliOp observable1 = SparsePauliOp.from_list([("Y" * qc1.num_qubits, 1)]) from qiskit_machine_learning.neural_networks import EstimatorQNN estimator_qnn = EstimatorQNN( circuit=qc1, observables=observable1, input_params=[params1[0]], weight_params=[params1[1]] ) estimator_qnn from qiskit.circuit import ParameterVector inputs2 = ParameterVector("input", 2) weights2 = ParameterVector("weight", 4) print(f"input parameters: {[str(item) for item in inputs2.params]}") print(f"weight parameters: {[str(item) for item in weights2.params]}") qc2 = QuantumCircuit(2) qc2.ry(inputs2[0], 0) qc2.ry(inputs2[1], 1) qc2.cx(0, 1) qc2.ry(weights2[0], 0) qc2.ry(weights2[1], 1) qc2.cx(0, 1) qc2.ry(weights2[2], 0) qc2.ry(weights2[3], 1) qc2.draw(output="mpl") from qiskit_machine_learning.neural_networks import SamplerQNN sampler_qnn = SamplerQNN(circuit=qc2, input_params=inputs2, weight_params=weights2) sampler_qnn estimator_qnn_input = algorithm_globals.random.random(estimator_qnn.num_inputs) estimator_qnn_weights = algorithm_globals.random.random(estimator_qnn.num_weights) print( f"Number of input features for EstimatorQNN: {estimator_qnn.num_inputs} \nInput: {estimator_qnn_input}" ) print( f"Number of trainable weights for EstimatorQNN: {estimator_qnn.num_weights} \nWeights: {estimator_qnn_weights}" ) sampler_qnn_input = algorithm_globals.random.random(sampler_qnn.num_inputs) sampler_qnn_weights = algorithm_globals.random.random(sampler_qnn.num_weights) print( f"Number of input features for SamplerQNN: {sampler_qnn.num_inputs} \nInput: {sampler_qnn_input}" ) print( f"Number of trainable weights for SamplerQNN: {sampler_qnn.num_weights} \nWeights: {sampler_qnn_weights}" ) estimator_qnn_forward = estimator_qnn.forward(estimator_qnn_input, estimator_qnn_weights) print( f"Forward pass result for EstimatorQNN: {estimator_qnn_forward}. \nShape: {estimator_qnn_forward.shape}" ) sampler_qnn_forward = sampler_qnn.forward(sampler_qnn_input, sampler_qnn_weights) print( f"Forward pass result for SamplerQNN: {sampler_qnn_forward}. \nShape: {sampler_qnn_forward.shape}" ) estimator_qnn_forward_batched = estimator_qnn.forward( [estimator_qnn_input, estimator_qnn_input], estimator_qnn_weights ) print( f"Forward pass result for EstimatorQNN: {estimator_qnn_forward_batched}. \nShape: {estimator_qnn_forward_batched.shape}" ) sampler_qnn_forward_batched = sampler_qnn.forward( [sampler_qnn_input, sampler_qnn_input], sampler_qnn_weights ) print( f"Forward pass result for SamplerQNN: {sampler_qnn_forward_batched}. \nShape: {sampler_qnn_forward_batched.shape}" ) estimator_qnn_input_grad, estimator_qnn_weight_grad = estimator_qnn.backward( estimator_qnn_input, estimator_qnn_weights ) print( f"Input gradients for EstimatorQNN: {estimator_qnn_input_grad}. \nShape: {estimator_qnn_input_grad}" ) print( f"Weight gradients for EstimatorQNN: {estimator_qnn_weight_grad}. \nShape: {estimator_qnn_weight_grad.shape}" ) sampler_qnn_input_grad, sampler_qnn_weight_grad = sampler_qnn.backward( sampler_qnn_input, sampler_qnn_weights ) print( f"Input gradients for SamplerQNN: {sampler_qnn_input_grad}. \nShape: {sampler_qnn_input_grad}" ) print( f"Weight gradients for SamplerQNN: {sampler_qnn_weight_grad}. \nShape: {sampler_qnn_weight_grad.shape}" ) estimator_qnn.input_gradients = True sampler_qnn.input_gradients = True estimator_qnn_input_grad, estimator_qnn_weight_grad = estimator_qnn.backward( estimator_qnn_input, estimator_qnn_weights ) print( f"Input gradients for EstimatorQNN: {estimator_qnn_input_grad}. \nShape: {estimator_qnn_input_grad.shape}" ) print( f"Weight gradients for EstimatorQNN: {estimator_qnn_weight_grad}. \nShape: {estimator_qnn_weight_grad.shape}" ) sampler_qnn_input_grad, sampler_qnn_weight_grad = sampler_qnn.backward( sampler_qnn_input, sampler_qnn_weights ) print( f"Input gradients for SamplerQNN: {sampler_qnn_input_grad}. \nShape: {sampler_qnn_input_grad.shape}" ) print( f"Weight gradients for SamplerQNN: {sampler_qnn_weight_grad}. \nShape: {sampler_qnn_weight_grad.shape}" ) observable2 = SparsePauliOp.from_list([("Z" * qc1.num_qubits, 1)]) estimator_qnn2 = EstimatorQNN( circuit=qc1, observables=[observable1, observable2], input_params=[params1[0]], weight_params=[params1[1]], ) estimator_qnn_forward2 = estimator_qnn2.forward(estimator_qnn_input, estimator_qnn_weights) estimator_qnn_input_grad2, estimator_qnn_weight_grad2 = estimator_qnn2.backward( estimator_qnn_input, estimator_qnn_weights ) print(f"Forward output for EstimatorQNN1: {estimator_qnn_forward.shape}") print(f"Forward output for EstimatorQNN2: {estimator_qnn_forward2.shape}") print(f"Backward output for EstimatorQNN1: {estimator_qnn_weight_grad.shape}") print(f"Backward output for EstimatorQNN2: {estimator_qnn_weight_grad2.shape}") parity = lambda x: "{:b}".format(x).count("1") % 2 output_shape = 2 # parity = 0, 1 sampler_qnn2 = SamplerQNN( circuit=qc2, input_params=inputs2, weight_params=weights2, interpret=parity, output_shape=output_shape, ) sampler_qnn_forward2 = sampler_qnn2.forward(sampler_qnn_input, sampler_qnn_weights) sampler_qnn_input_grad2, sampler_qnn_weight_grad2 = sampler_qnn2.backward( sampler_qnn_input, sampler_qnn_weights ) print(f"Forward output for SamplerQNN1: {sampler_qnn_forward.shape}") print(f"Forward output for SamplerQNN2: {sampler_qnn_forward2.shape}") print(f"Backward output for SamplerQNN1: {sampler_qnn_weight_grad.shape}") print(f"Backward output for SamplerQNN2: {sampler_qnn_weight_grad2.shape}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/antontutoveanu/quantum-tic-tac-toe
antontutoveanu
from termcolor import colored, cprint import json from qiskit import * from qiskit.tools.monitor import job_monitor def resetBoard(): return {'1': [' ', 0] , '2': [' ', 0], '3': [' ', 0], '4': [' ', 0], '5': [' ', 0], '6': [' ', 0], '7': [' ', 0], '8': [' ', 0], '9': [' ', 0]} def printBoard(board): print() colour = 0 for i in range (1,10): if board[str(i)][1] == 0: cprint(board[str(i)][0], end='') else: if (colour == 0 or colour == 1): cprint(board[str(i)][0], 'red', end='') colour = colour + 1 elif (colour == 2 or colour == 3): cprint(board[str(i)][0], 'green', end='') colour = colour + 1 elif (colour == 4 or colour == 5): cprint(board[str(i)][0], 'blue', end='') colour = colour + 1 elif (colour == 6 or colour == 7): cprint(board[str(i)][0], 'yellow', end='') colour = colour + 1 if i % 3 == 0: print() if i != 9: print('-+-+-') else: cprint('|', end='') def make_classic_move(theBoard, turn, count, circuit): valid_move = 0 valid_moves = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] while (not valid_move): print() print("Which location? (1-9) ", end='') location = input() if location in valid_moves: if theBoard[location][0] == ' ': valid_move = 1 # set the location's marker theBoard[location][0] = turn # increment counter (total markers on board) *when this = 9, collapse the board, also called measurement count += 1 # set marker's state (classical or quantum) theBoard[location][1] = 0 # classical (not flashing on screen) # set qubit[location] to ON, 100% = 1 # one pauli X gate circuit.x(int(location)-1) print(circuit.draw()) else: print() print("That place is already filled.") else: print("Please select a square from 1-9") return theBoard, turn, count, circuit def make_quantum_move(theBoard, count, circuit, turn): valid_move = False valid_moves = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] while (not valid_move): print() print("Which location? (1-9) ") location1 = input() print("Which location? (1-9) ") location2 = input() if theBoard[location1][0] == ' ' and theBoard[location2][0] == ' ' and location1 != location2: # set the location's marker theBoard[location1][0] = turn theBoard[location2][0] = turn # increment counter (total markers on board) *when this = 9, collapse the board, also called measurement count += 2 # set marker's state (classical or quantum) theBoard[location1][1] = 1 # quantum (flashing on screen) theBoard[location2][1] = 1 # quantum (flashing on screen) # set qubit[location1], qubit[location2] to superposition/entangled # hadamard gates circuit.h(int(location1)-1) # x gate circuit.x(int(location2)-1) # cnot gate circuit.cx(int(location1)-1,int(location2)-1) print(circuit.draw()) valid_move = True else: print() print("You have selected an invalid position/s") return theBoard, count, circuit, turn def measure(circuit, theBoard, count): # trigger collapse printBoard(theBoard) print() print("Trigger collapse.") print() # Use Aer's qasm_simulator simulator = qiskit.Aer.get_backend('qasm_simulator') circuit.measure(0,0) circuit.measure(1,1) circuit.measure(2,2) circuit.measure(3,3) circuit.measure(4,4) circuit.measure(5,5) circuit.measure(6,6) circuit.measure(7,7) circuit.measure(8,8) print(circuit.draw()) # Execute the circuit on quantum simulator job = qiskit.execute(circuit, simulator, shots=1) # Grab results from the job result = job.result() out = json.dumps(result.get_counts()) #Converts the result.get_counts() into a string string = out[2:11] #Removes unnecessary data from string, leaving us with board # update board for i in range(9): if string[i] == '1': # cement value in the board theBoard[str(9-i)][1] = 0 else: # make square empty theBoard[str(9-i)][1] = 0 theBoard[str(9-i)][0] = ' ' # update count (total number of markers on the board) count = 0 for i in range(9): theBoard[str(i+1)][1] = 0 if theBoard[str(i+1)][0] != ' ': count += 1 # reset qubits circuit.reset(0) circuit.reset(1) circuit.reset(2) circuit.reset(3) circuit.reset(4) circuit.reset(5) circuit.reset(6) circuit.reset(7) circuit.reset(8) for i in range(9): if string[8-i] == '1': # add pauli x gate circuit.x(i) return circuit, string, theBoard, count def check_win(theBoard, turn): if theBoard['7'][0] == theBoard['8'][0] == theBoard['9'][0] != ' ': # across the top if theBoard['7'][1] == theBoard['8'][1] == theBoard['9'][1] == 0: # only cemented markers printBoard(theBoard) print("\nGame Over.\n") print(" **** ", end='') print(theBoard['8'][0], end='') print(" won ****") print() return True elif theBoard['4'][0] == theBoard['5'][0] == theBoard['6'][0] != ' ': # across the middle if theBoard['4'][1] == theBoard['5'][1] == theBoard['6'][1] == 0: # only cemented markers printBoard(theBoard) print("\nGame Over.\n") print(" **** ", end='') print(theBoard['5'][0], end='') print(" won ****") print() return True elif theBoard['1'][0] == theBoard['2'][0] == theBoard['3'][0] != ' ': # across the bottom if theBoard['1'][1] == theBoard['2'][1] == theBoard['3'][1] == 0: # only cemented markers printBoard(theBoard) print("\nGame Over.\n") print(" **** ", end='') print(theBoard['2'][0], end='') print(" won ****") print() return True elif theBoard['1'][0] == theBoard['4'][0] == theBoard['7'][0] != ' ': # down the left side if theBoard['1'][1] == theBoard['4'][1] == theBoard['7'][1] == 0: # only cemented markers printBoard(theBoard) print("\nGame Over.\n") print(" **** ", end='') print(theBoard['4'][0], end='') print(" won ****") print() return True elif theBoard['2'][0] == theBoard['5'][0] == theBoard['8'][0] != ' ': # down the middle if theBoard['2'][1] == theBoard['5'][1] == theBoard['8'][1] == 0: # only cemented markers printBoard(theBoard) print("\nGame Over.\n") print(" **** ", end='') print(theBoard['5'][0], end='') print(" won ****") print() return True elif theBoard['3'][0] == theBoard['6'][0] == theBoard['9'][0] != ' ': # down the right side if theBoard['3'][1] == theBoard['6'][1] == theBoard['9'][1] == 0: # only cemented markers printBoard(theBoard) print("\nGame Over.\n") print(" **** ", end='') print(theBoard['6'][0], end='') print(" won ****") print() return True elif theBoard['7'][0] == theBoard['5'][0] == theBoard['3'][0] != ' ': # diagonal if theBoard['7'][1] == theBoard['5'][1] == theBoard['3'][1] == 0: # only cemented markers printBoard(theBoard) print("\nGame Over.\n") print(" **** ", end='') print(theBoard['5'][0], end='') print(" won ****") print() return True elif theBoard['1'][0] == theBoard['5'][0] == theBoard['9'][0] != ' ': # diagonal if theBoard['1'][1] == theBoard['5'][1] == theBoard['9'][1] == 0: # only cemented markers printBoard(theBoard) print("\nGame Over.\n") print(" **** ", end='') print(theBoard['5'][0], end='') print(" won ****") print() return True #Implementation of Two Player Tic-Tac-Toe game in Python. # start game function # Now we'll write the main function which has all the gameplay functionality. def game(): turn = 'X' count = 0 win = False x_collapse = 1 y_collapse = 1 # initialise quantum circuit with 9 qubits (all on OFF = 0) circuit = qiskit.QuantumCircuit(9, 9) while (not win): # ============================= ROUND START ============================ global theBoard printBoard(theBoard) print() print("It's your turn " + turn + ". Do you want to make a (1) classical move, (2) quantum move, (3) collapse?, or (4) quit?") move = input() # ============================= CLASSIC MOVE =========================== if int(move) == 1: theBoard, turn, count, circuit = make_classic_move(theBoard, turn, count, circuit) madeMove = True # ============================= QUANTUM MOVE =========================== elif int(move) == 2 and count > 8: # cant do a quantum move if there's only 1 empty square left print() print("There aren't enough empty spaces for that!") elif int(move) == 2 and count < 8: theBoard, count, circuit, turn = make_quantum_move(theBoard, count, circuit, turn) madeMove = True # ============================= COLLAPSE/MEASURE ======================= elif int(move) == 3: if (turn == 'X' and x_collapse== 1 ): circuit, string, theBoard, count = measure(circuit, theBoard, count) x_collapse = 0 elif (turn == 'O' and y_collapse == 1): circuit, string, theBoard, count = measure(circuit, theBoard, count) y_collapse = 0 else: print("You have already used your collapse this game!") # ============================= QUIT =================================== elif int(move) == 4: break # ============================= CHECK FOR WIN ========================== # Now we will check if player X or O has won,for every move if count >= 5: win = check_win(theBoard, turn) if (win): break # If neither X nor O wins and the board is full, we'll declare the result as 'tie'. if count == 9: circuit, string, theBoard, count = measure(circuit, theBoard, count) win = check_win(theBoard, turn) if count == 9: print("\nGame Over.\n") print("It's a Tie !") print() win = True # Now we have to change the player after every move. if (madeMove): madeMove = False if turn =='X': turn = 'O' else: turn = 'X' # Now we will ask if player wants to restart the game or not. restart = input("Play Again?(y/n) ") if restart == "y" or restart == "Y": theBoard = resetBoard() game() def start_menu(): start_menu = """ Start Menu: 1. Start Game 2. How to Play 3. Quit """ print(""" ########################### ### Quantum Tic-Tac-Toe ### ########################### """) print(start_menu) choice = 0 while (choice != '1'): print("What would you like to do? ", end='') choice = input() if (choice == '2'): How_To = """ In Quantum Tic-Tac-Toe, each square starts empty and your goal is to create a line of three of your naughts/crosses. Playing a classical move will result in setting a square permanently as your piece. Playing a quantum move will create a superposition between two squares of your choosing. You may only complete a quantum move in two empty squares. The board will collapse when the board is full. At collapse, each superposition is viewed and only 1 piece of the superposition will remain. *Powerup* Each player can decide to collapse the board prematurely, they may do this once per round each. """ print(How_To) if (choice == '3'): print("Goodbye") break return choice #Reset the board at start theBoard = resetBoard() #Set no moves made yet if (start_menu() == '1'): madeMove = False game()
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit.quantum_info.operators import Operator, Pauli from qiskit.visualization import * from qiskit.extensions import XGate,HGate from qiskit import QuantumCircuit,BasicAer,execute X=Operator([[0,1],[1,0]]) X X.data array_to_latex(X.data) pauli_Xgate = Pauli(label='X') Operator(pauli_Xgate) array_to_latex(Operator(pauli_Xgate).data) Operator(pauli_Xgate).is_unitary() Operator(XGate()) array_to_latex(Operator(XGate()).data) qc = QuantumCircuit(1) qc.x(0) # Convert circuit to an operator by implicit unitary simulation Operator(qc) array_to_latex(Operator(qc).data) #Create an operator XX = Operator(Pauli(label='XX')) # Add to a circuit qc = QuantumCircuit(2) qc.append(XX, [0,1]) qc.measure_all() qc.draw('mpl') #Get the backend backend=BasicAer.get_backend('qasm_simulator') job=backend.run(qc) result=job.result() counts=result.get_counts() print(counts) # Add to a circuit qc = QuantumCircuit(2) qc.append(Pauli(label='XX'), [0,1]) qc.measure_all() qc.draw('mpl') #Get the backend backend=BasicAer.get_backend('qasm_simulator') job=execute(qc,backend) result=job.result() counts=result.get_counts() print(counts) array_to_latex(Operator(HGate()).data)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') result = backend.run(qc, shots = 8192).result()
https://github.com/bayesian-randomized-benchmarking/qiskit-advocates-bayes-RB
bayesian-randomized-benchmarking
import numpy as np import copy from qiskit_experiments.library import StandardRB, InterleavedRB from qiskit_experiments.framework import ParallelExperiment from qiskit_experiments.library.randomized_benchmarking import RBUtils import qiskit.circuit.library as circuits # for retrieving gate calibration from datetime import datetime import qiskit.providers.aer.noise.device as dv # import the bayesian packages import pymc3 as pm import arviz as az import unif_bayesian_fitter as bf simulation = True # make your choice here if simulation: from qiskit.providers.aer import AerSimulator from qiskit.test.mock import FakeParis backend = AerSimulator.from_backend(FakeParis()) else: from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_lima') # type here hardware backend # for WIP import importlib importlib.reload(bf) lengths = np.arange(1, 2500, 250) num_samples = 10 seed = 1010 qubits = [0] # Run an RB experiment on qubit 0 exp1 = StandardRB(qubits, lengths, num_samples=num_samples, seed=seed) expdata1 = exp1.run(backend).block_for_results() results1 = expdata1.analysis_results() # View result data display(expdata1.figure(0)) for result in results1: print(result) popt = expdata1.analysis_results()[0].value.value pcov = expdata1.analysis_results()[0].extra['covariance_mat'] epc_est_fm = expdata1.analysis_results()[2].value.value epc_est_fm_err = expdata1.analysis_results()[2].value.stderr EPG_dic = {} for i in range(3,6): EPG_key = expdata1.analysis_results()[i].name EPG_dic[EPG_key] = expdata1.analysis_results()[i].value.value nQ = len(qubits) scale = (2 ** nQ - 1) / 2 ** nQ interleaved_gate ='' # get count data Y = bf.get_GSP_counts(expdata1._data, len(lengths),range(num_samples)) expdata1._data[1] experiment_type = expdata1._data[0]['metadata']['experiment_type'] physical_qubits = expdata1._data[0]['metadata']['physical_qubits'] shots = expdata1._data[0]['shots'] #build model pooled_model = bf.build_bayesian_model(model_type="pooled",Y=Y, shots=shots,m_gates=lengths, popt = popt, pcov = pcov) pm.model_to_graphviz(pooled_model) trace_p = bf.get_trace(pooled_model, target_accept = 0.95) # backend's recorded EPG print(RBUtils.get_error_dict_from_backend(backend, qubits)) bf.RB_bayesian_results(pooled_model, trace_p, lengths, epc_est_fm, epc_est_fm_err, experiment_type, scale, num_samples, Y, shots, physical_qubits, interleaved_gate, backend, EPG_dic = EPG_dic, routine = 'build_bayesian_model') #build model hierarchical_model = bf.build_bayesian_model(model_type="h_sigma",Y=Y, shots=shots,m_gates=lengths, popt = popt, pcov = pcov, sigma_theta=0.001,sigma_theta_l=0.0005,sigma_theta_u=0.0015) pm.model_to_graphviz(hierarchical_model) trace_h = bf.get_trace(hierarchical_model, target_accept = 0.99) # backend's recorded EPG print(RBUtils.get_error_dict_from_backend(backend, qubits)) bf.RB_bayesian_results(hierarchical_model, trace_h, lengths, epc_est_fm, epc_est_fm_err, experiment_type, scale, num_samples, Y, shots, physical_qubits, interleaved_gate, backend, EPG_dic = EPG_dic, routine = 'build_bayesian_model') # describe RB experiment interleaved_gate ='' physical_qubits = qubits = (1,4) nQ = len(qubits) scale = (2 ** nQ - 1) / 2 ** nQ # defined for the 2-qubit run lengths = np.arange(1, 200, 30) lengths_1_qubit = np.arange(1, 2500, 250) num_samples = 10 seed = 1010 # Run a 1-qubit RB expriment on each qubit to determine the error-per-gate of 1-qubit gates expdata_1q = {} epg_1q = [] for qubit in qubits: exp = StandardRB([qubit], lengths_1_qubit, num_samples=num_samples, seed=seed) expdata = exp.run(backend).block_for_results() expdata_1q[qubit] = expdata epg_1q += expdata.analysis_results() # Run an RB experiment on qubits 1, 4 exp2 = StandardRB(qubits, lengths, num_samples=num_samples, seed=seed) # Use the EPG data of the 1-qubit runs to ensure correct 2-qubit EPG computation exp2.set_analysis_options(epg_1_qubit=epg_1q) # Run the 2-qubit experiment expdata2 = exp2.run(backend).block_for_results() # View result data results2 = expdata2.analysis_results() # View result data display(expdata2.figure(0)) for result in results2: print(result) # Compare the computed EPG of the cx gate with the backend's recorded cx gate error: expected_epg = RBUtils.get_error_dict_from_backend(backend, qubits)[(qubits, 'cx')] exp2_epg = expdata2.analysis_results("EPG_cx").value print("Backend's reported EPG of the cx gate:", expected_epg) print("Experiment computed EPG of the cx gate:", exp2_epg) popt = expdata2.analysis_results()[0].value.value pcov = expdata2.analysis_results()[0].extra['covariance_mat'] epc_est_fm = expdata2.analysis_results()[2].value.value epc_est_fm_err = expdata2.analysis_results()[2].value.stderr EPG_dic = {} EPG_key = 'cx' #expdata2.analysis_results()[3].name EPG_dic[EPG_key] = expdata2.analysis_results()[3].value.value nQ = len(qubits) scale = (2 ** nQ - 1) / 2 ** nQ desired_gate ='cx' t = None # enter t in datetime format if necessary e_list = dv.gate_error_values(backend.properties()) # use properties(datetime=t) if t is defined epc_calib = np.nan for tuple_e in e_list: if tuple_e[0] == 'cx' and tuple_e[1] == physical_qubits: epc_calib = tuple_e[2] print('EPC calibration: {0:.6f}'.format(epc_calib)) # get count data Y = bf.get_GSP_counts(expdata2._data, len(lengths),range(num_samples)) experiment_type = expdata2._data[0]['metadata']['experiment_type'] physical_qubits = expdata2._data[0]['metadata']['physical_qubits'] shots = expdata2._data[0]['shots'] #build model S2QBp_model = bf.build_bayesian_model(model_type="pooled",Y=Y, shots=shots,m_gates=lengths, popt = popt, pcov = pcov) pm.model_to_graphviz(S2QBp_model) trace_p2 = bf.get_trace(S2QBp_model, target_accept = 0.95) bf.RB_bayesian_results(S2QBp_model, trace_p2, lengths, epc_est_fm, epc_est_fm_err, experiment_type, scale, num_samples, Y, shots, physical_qubits, interleaved_gate, backend, EPG_dic = EPG_dic, routine = 'build_bayesian_model') #build model S2QBh_model = bf.build_bayesian_model(model_type="h_sigma",Y=Y,shots=shots,m_gates=lengths, popt = popt, pcov = pcov, sigma_theta=0.001,sigma_theta_l=0.0005,sigma_theta_u=0.0015) pm.model_to_graphviz(S2QBh_model) trace_h2 = bf.get_trace(S2QBh_model) bf.RB_bayesian_results(S2QBh_model, trace_h2, lengths, epc_est_fm, epc_est_fm_err, experiment_type, scale, num_samples, Y, shots, physical_qubits, interleaved_gate, backend, EPG_dic = EPG_dic, routine = 'build_bayesian_model') # describe RB experiment interleaved_gate = "x" qubits = [0] interleaved_circuit = circuits.XGate() lengths = np.arange(1, 2500, 250) num_samples = 10 seed = 1010 # Run an interleaved RB experiment int_exp1 = InterleavedRB(interleaved_circuit, qubits, lengths, num_samples=num_samples, seed=seed) # Run int_expdata1 = int_exp1.run(backend).block_for_results() int_results1 = int_expdata1.analysis_results() # View result data display(int_expdata1.figure(0)) for result in int_results1: print(result) popt = int_expdata1.analysis_results()[0].value.value pcov = int_expdata1.analysis_results()[0].extra['covariance_mat'] popt[2] = popt[1]/popt[2] # replace alpha_C by p_tilde # WIP rigorously the covariance matrix could be modified too if used epc_est_fm = int_expdata1.analysis_results()[3].value.value epc_est_fm_err = int_expdata1.analysis_results()[3].value.stderr nQ = len(qubits) scale = (2 ** nQ - 1) / 2 ** nQ interleaved_gate ='x' # get count data Y1 = bf.get_GSP_counts(int_expdata1._data, len(lengths), range(0,2*num_samples-1,2)) Y2 = bf.get_GSP_counts(int_expdata1._data, len(lengths), range(1,2*num_samples,2)) int_expdata1._data[1] experiment_type = int_expdata1._data[0]['metadata']['experiment_type'] physical_qubits = int_expdata1._data[0]['metadata']['physical_qubits'] shots = int_expdata1._data[0]['shots'] Y=np.vstack((Y1,Y2)) RvsI = np.vstack((np.ones_like(Y1),np.zeros_like(Y2))) IvsR = np.vstack((np.zeros_like(Y1),np.ones_like(Y2))) tilde1 = bf.build_bayesian_model("tilde",Y=Y,shots=shots, m_gates=lengths, popt = popt, pcov = pcov, RvsI=RvsI,IvsR=IvsR) pm.model_to_graphviz(tilde1) trace_t = bf.get_trace(tilde1) t = None # enter t in datetime format if necessary e_list = dv.gate_error_values(backend.properties()) # use properties(datetime=t) if t is defined epc_calib = np.nan for tuple_e in e_list: if tuple_e[0] == interleaved_gate and tuple_e[1] == qubits: epc_calib = np.nan = tuple_e[2] print('EPC calibration: {0:.6f}'.format(epc_calib)) # example of interpolated EPC_cal for hardware experiments # EPC0 + (t_exp - tO) * (EPC1 - EPC0) / (t1 - t0) # code here: # epc_calib = 2.307E-4 + (23.6-7)*(2.193E-4 - 2.307E-4)/24 bf.RB_bayesian_results(tilde1, trace_t, lengths, epc_est_fm, epc_est_fm_err, experiment_type, scale, num_samples, Y, shots, physical_qubits, interleaved_gate, backend, epc_calib = epc_calib, Y1 = Y1, Y2 = Y2, routine = 'build_bayesian_model') import importlib importlib.reload(bf) Y=np.hstack((Y1,Y2)) RvsI_h = np.ravel(np.vstack((np.ones_like(lengths),np.zeros_like(lengths)))) IvsR_h = np.ravel(np.vstack((np.zeros_like(lengths),np.ones_like(lengths)))) tilde2 = bf.build_bayesian_model("h_tilde",Y=Y,shots=shots, m_gates=lengths, popt = popt, pcov = pcov, RvsI = RvsI_h, IvsR = IvsR_h, sigma_theta=0.001,sigma_theta_l=0.0005,sigma_theta_u=0.0015) pm.model_to_graphviz(tilde2) trace_t3 = bf.get_trace(tilde2, target_accept = .95) bf.RB_bayesian_results(tilde2, trace_t3, lengths, epc_est_fm, epc_est_fm_err, experiment_type, scale, num_samples, Y, shots, physical_qubits, interleaved_gate, backend, epc_calib = epc_calib, Y1 = Y1, Y2 = Y2, routine = 'build_bayesian_model') # describe RB experiment interleaved_gate = "cx" physical_qubits = qubits = [1,4] interleaved_circuit = circuits.CXGate() lengths = np.arange(1, 200, 30) num_samples = 10 seed = 1010 t = None # enter t in datetime format if necessary e_list = dv.gate_error_values(backend.properties()) # use properties(datetime=t) if t is defined epc_calib = np.nan for tuple_e in e_list: if tuple_e[0] == interleaved_gate and tuple_e[1] == physical_qubits: epc_calib = np.nan = tuple_e[2] print('EPC calibration: {0:.6f}'.format(epc_calib)) # Run an interleaved RB experiment int_exp2 = InterleavedRB(interleaved_circuit, qubits, lengths, num_samples=num_samples, seed=seed) # Run int_expdata2 = int_exp2.run(backend).block_for_results() int_results2 = int_expdata2.analysis_results() # View result data display(int_expdata2.figure(0)) for result in int_results2: print(result) popt = int_expdata2.analysis_results()[0].value.value pcov = int_expdata2.analysis_results()[0].extra['covariance_mat'] popt[2] = popt[1]/popt[2] # replace alpha_C by p_tilde # WIP rigorously the covariance matrix could be modified too if used epc_est_fm = int_expdata2.analysis_results()[3].value.value epc_est_fm_err = int_expdata2.analysis_results()[3].value.stderr nQ = len(qubits) scale = (2 ** nQ - 1) / 2 ** nQ interleaved_gate ='cx' # get count data Y1 = bf.get_GSP_counts(int_expdata2._data, len(lengths), range(0,2*num_samples-1,2)) Y2 = bf.get_GSP_counts(int_expdata2._data, len(lengths), range(1,2*num_samples,2)) int_expdata2._data[1] experiment_type = int_expdata2._data[0]['metadata']['experiment_type'] physical_qubits = int_expdata2._data[0]['metadata']['physical_qubits'] shots = int_expdata2._data[0]['shots'] # example of interpolated EPC_cal for hardware experiments # EPC0 + (t_exp - tO) * (EPC1 - EPC0) / (t1 - t0) # code here: # epc_calib = 2.307E-4 + (23.6-7)*(2.193E-4 - 2.307E-4)/24 Y = np.vstack((Y1,Y2)) RvsI = np.vstack((np.ones_like(Y1),np.zeros_like(Y2))) IvsR = np.vstack((np.zeros_like(Y1),np.ones_like(Y2))) tilde3 = bf.build_bayesian_model("tilde",Y=Y,shots=shots, m_gates=lengths, popt = popt, pcov = pcov, RvsI=RvsI,IvsR=IvsR) pm.model_to_graphviz(tilde3) trace_t3 = bf.get_trace(tilde3) bf.RB_bayesian_results(tilde3, trace_t3, lengths, epc_est_fm, epc_est_fm_err, experiment_type, scale, num_samples, Y, shots, physical_qubits, interleaved_gate, backend, epc_calib = epc_calib, Y1 = Y1, Y2 = Y2, routine = 'build_bayesian_model') import importlib importlib.reload(bf) # use 2m length array RvsI_h = np.ravel(np.vstack((np.ones_like(lengths),np.zeros_like(lengths)))) IvsR_h = np.ravel(np.vstack((np.zeros_like(lengths),np.ones_like(lengths)))) tilde4 = bf.build_bayesian_model("h_tilde",Y=np.hstack((Y1,Y2)), shots=shots, m_gates=lengths, popt = popt, pcov = pcov, RvsI = RvsI_h, IvsR = IvsR_h, sigma_theta=0.005,sigma_theta_l=0.001,sigma_theta_u=0.05) pm.model_to_graphviz(tilde4) trace_t4 = bf.get_trace(tilde4, target_accept = .99) bf.RB_bayesian_results(tilde4, trace_t4, lengths, epc_est_fm, epc_est_fm_err, experiment_type, scale, num_samples, Y, shots, physical_qubits, interleaved_gate, backend, epc_calib = epc_calib, Y1 = Y1, Y2 = Y2, routine = 'build_bayesian_model')
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Ripple adder example based on Cuccaro et al., quant-ph/0410184. """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import BasicAer from qiskit import execute ############################################################### # Set the backend name and coupling map. ############################################################### backend = BasicAer.get_backend("qasm_simulator") coupling_map = [ [0, 1], [0, 8], [1, 2], [1, 9], [2, 3], [2, 10], [3, 4], [3, 11], [4, 5], [4, 12], [5, 6], [5, 13], [6, 7], [6, 14], [7, 15], [8, 9], [9, 10], [10, 11], [11, 12], [12, 13], [13, 14], [14, 15], ] ############################################################### # Make a quantum program for the n-bit ripple adder. ############################################################### n = 2 a = QuantumRegister(n, "a") b = QuantumRegister(n, "b") cin = QuantumRegister(1, "cin") cout = QuantumRegister(1, "cout") ans = ClassicalRegister(n + 1, "ans") qc = QuantumCircuit(a, b, cin, cout, ans, name="rippleadd") def majority(p, a, b, c): """Majority gate.""" p.cx(c, b) p.cx(c, a) p.ccx(a, b, c) def unmajority(p, a, b, c): """Unmajority gate.""" p.ccx(a, b, c) p.cx(c, a) p.cx(a, b) # Build a temporary subcircuit that adds a to b, # storing the result in b adder_subcircuit = QuantumCircuit(cin, a, b, cout) majority(adder_subcircuit, cin[0], b[0], a[0]) for j in range(n - 1): majority(adder_subcircuit, a[j], b[j + 1], a[j + 1]) adder_subcircuit.cx(a[n - 1], cout[0]) for j in reversed(range(n - 1)): unmajority(adder_subcircuit, a[j], b[j + 1], a[j + 1]) unmajority(adder_subcircuit, cin[0], b[0], a[0]) # Set the inputs to the adder qc.x(a[0]) # Set input a = 0...0001 qc.x(b) # Set input b = 1...1111 # Apply the adder qc &= adder_subcircuit # Measure the output register in the computational basis for j in range(n): qc.measure(b[j], ans[j]) qc.measure(cout[0], ans[n]) ############################################################### # execute the program. ############################################################### # First version: not mapped job = execute(qc, backend=backend, coupling_map=None, shots=1024) result = job.result() print(result.get_counts(qc)) # Second version: mapped to 2x8 array coupling graph job = execute(qc, backend=backend, coupling_map=coupling_map, shots=1024) result = job.result() print(result.get_counts(qc)) # Both versions should give the same distribution
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/JavaFXpert/quantum-circuit-pygame
JavaFXpert
#!/usr/bin/env python # # Copyright 2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pygame from qiskit import BasicAer, execute, ClassicalRegister from utils.colors import * from utils.fonts import ARIAL_30 from utils.states import comp_basis_states from copy import deepcopy #from utils.paddle import * class StatevectorGrid(pygame.sprite.Sprite): """Displays a statevector grid""" def __init__(self, circuit, qubit_num, num_shots): pygame.sprite.Sprite.__init__(self) self.image = None self.rect = None self.basis_states = comp_basis_states(circuit.width()) self.set_circuit(circuit, qubit_num, num_shots) # def update(self): # # Nothing yet # a = 1ot def set_circuit(self, circuit, qubit_num, shot_num): backend_sv_sim = BasicAer.get_backend('statevector_simulator') job_sim = execute(circuit, backend_sv_sim, shots=shot_num) result_sim = job_sim.result() quantum_state = result_sim.get_statevector(circuit, decimals=3) # This square represent the probability of state after measurement self.image = pygame.Surface([(circuit.width()+1) * 50, 500]) self.image.convert() self.image.fill(BLACK) self.rect = self.image.get_rect() block_size = int(round(500 / 2 ** qubit_num)) x_offset = 50 y_offset = 15 self.paddle = pygame.Surface([10, block_size]) self.paddle.convert() for y in range(len(quantum_state)): text_surface = ARIAL_30.render("|"+self.basis_states[y]+">", False, (255, 255, 255)) self.image.blit(text_surface,(120, y * block_size + y_offset)) if abs(quantum_state[y]) > 0: #pygame.draw.rect(self.image, WHITE, rect, 0) self.paddle.fill(WHITE) self.paddle.set_alpha(int(round(abs(quantum_state[y])*255))) self.image.blit(self.paddle,(80,y * block_size)) def set_circuit_measure(self, circuit, qubit_num, shot_num): backend_sv_sim = BasicAer.get_backend('qasm_simulator') cr = ClassicalRegister(qubit_num) circuit2 = deepcopy(circuit) circuit2.add_register(cr) circuit2.measure(circuit2.qregs[0],circuit2.cregs[0]) job_sim = execute(circuit2, backend_sv_sim, shots=shot_num) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) print(counts) #quantum_state = result_sim.get_statevector(circuit, decimals=3) # This square represent the probability of state after measurement self.image = pygame.Surface([(circuit.width()+1) * 50, 500]) self.image.convert() self.image.fill(BLACK) self.rect = self.image.get_rect() block_size = int(round(500 / 2 ** qubit_num)) x_offset = 50 y_offset = 15 self.paddle = pygame.Surface([10, block_size]) self.paddle.convert() self.paddle.fill(WHITE) #for y in range(len(quantum_state)): # text_surface = ARIAL_30.render(self.basis_states[y], False, (0, 0, 0)) # self.image.blit(text_surface,(120, y * block_size + y_offset)) # if abs(quantum_state[y]) > 0: #pygame.draw.rect(self.image, WHITE, rect, 0) #self.paddle.fill(WHITE) # self.paddle.set_alpha(int(round(abs(quantum_state[y])*255))) print(counts.keys()) print(int(list(counts.keys())[0],2)) self.image.blit(self.paddle,(80,int(list(counts.keys())[0],2) * block_size)) #pygame.time.wait(100) return int(list(counts.keys())[0],2)
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
def square_roots(a,b,c): # we iteratively calculate the expression with many square roots # we start with c and continue with b and a result = c**0.5 # square root of c result = 2 * result # 2*sqrt(c) result = result + b # b + 2*sqrt(c) result = result**0.5 # square root result = a**0.5 - result return result quantum_state =[ square_roots(3,5,6)**(-1), square_roots(3,7,12)**(-1), square_roots(5,13,40)**(-1), square_roots(7,15,56)**(-1), ] # this is our quantum state # print the quantum state print(quantum_state) print() print("The probability of observing the states 00, 01, 10, 11:") total_probability = 0 for i in range(len(quantum_state)): current_probability = quantum_state[i]**2 # square of the amplitude print(current_probability) total_probability = total_probability + current_probability print() print("total probability is",total_probability) # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # import randrange for random choices from random import randrange number_of_qubit = 5 # define a quantum register with 5 qubits qreg = QuantumRegister(number_of_qubit) # define a classical register with 5 bits creg = ClassicalRegister(number_of_qubit) # define our quantum circuit mycircuit = QuantumCircuit(qreg,creg) # apply h-gate to all qubits for i in range(number_of_qubit): mycircuit.h(qreg[i]) # apply z-gate to randomly picked qubits for i in range(number_of_qubit): if randrange(2) == 0: # the qubit with index i is picked to apply z-gate mycircuit.z(qreg[i]) # apply h-gate to all qubits for i in range(number_of_qubit): mycircuit.h(qreg[i]) # measure all qubits mycircuit.measure(qreg,creg) print("Everything looks fine, let's continue ...") # draw the circuit mycircuit.draw() # execute the circuit 1000 times in the local simulator job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1000) counts = job.result().get_counts(mycircuit) for outcome in counts: # print the reverse of the outcome reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print(reverse_outcome,"is observed",counts[outcome],"times")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeVigoV2 from qiskit.visualization import plot_circuit_layout from qiskit.tools.monitor import job_monitor from qiskit.providers.fake_provider import FakeVigoV2 import matplotlib.pyplot as plt ghz = QuantumCircuit(3, 3) ghz.h(0) for idx in range(1,3): ghz.cx(0,idx) ghz.measure(range(3), range(3)) backend = FakeVigoV2() new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend)
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/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. """Tests for the converters.""" import os import unittest from qiskit.converters import ast_to_dag, circuit_to_dag from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import qasm from qiskit.test import QiskitTestCase class TestAstToDag(QiskitTestCase): """Test AST to DAG.""" def setUp(self): super().setUp() qr = QuantumRegister(3) cr = ClassicalRegister(3) self.circuit = QuantumCircuit(qr, cr) self.circuit.ccx(qr[0], qr[1], qr[2]) self.circuit.measure(qr, cr) self.dag = circuit_to_dag(self.circuit) def test_from_ast_to_dag(self): """Test Unroller.execute()""" qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm") ast = qasm.Qasm(os.path.join(qasm_dir, "example.qasm")).parse() dag_circuit = ast_to_dag(ast) expected_result = """\ OPENQASM 2.0; include "qelib1.inc"; qreg q[3]; qreg r[3]; creg c[3]; creg d[3]; h q[0]; h q[1]; h q[2]; cx q[0],r[0]; cx q[1],r[1]; cx q[2],r[2]; barrier q[0],q[1],q[2]; measure q[0] -> c[0]; measure q[1] -> c[1]; measure q[2] -> c[2]; measure r[0] -> d[0]; measure r[1] -> d[1]; measure r[2] -> d[2]; """ expected_dag = circuit_to_dag(QuantumCircuit.from_qasm_str(expected_result)) self.assertEqual(dag_circuit, expected_dag) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# numpy, for random number generation import numpy as np # Qiskit, for transpiler-related functions, the IBMQ provider, and the Aer simulator from qiskit import IBMQ, Aer, QuantumRegister from qiskit.transpiler import transpile, transpile_dag, PassManager from qiskit.converters import circuit_to_dag, dag_to_circuit # pytket, for optimization import pytket from pytket.qiskit import TketPass # Qiskit Aqua, for chemistry from qiskit_chemistry.drivers import PySCFDriver, UnitsType from qiskit_chemistry import FermionicOperator from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock from qiskit_chemistry.aqua_extensions.components.variational_forms import UCCSD IBMQ.load_accounts() # Choose a particular bond length # NOTE: Units are in Angstroms bond_length = 0.7 # Set up molecule # base_molecule_str = 'Li .0 .0 .0; H .0 .0 {}' base_molecule_str = 'H .0 .0 .0; H .0 .0 {}' # Specify other molecular properties charge = 0 spin = 0 basis = 'sto3g' # Using driver to get fermionic Hamiltonian # PySCF example driver = PySCFDriver(atom=base_molecule_str.format(bond_length), unit=UnitsType.ANGSTROM, charge=charge, spin=spin, basis=basis) molecule = driver.run() print("Molecular repulsion energy: ", molecule.nuclear_repulsion_energy) n_qubits = molecule.one_body_integrals.shape[0] n_electrons = molecule.num_alpha + molecule.num_beta - molecule.molecular_charge # get fermionic operator and mapping to qubit operator ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) qubitOp = ferOp.mapping(map_type='JORDAN_WIGNER', threshold=0.00000001) qubitOp.chop(10**-10) # Instantiate the initial state as a Hartree-Fock state initial_hf = HartreeFock(num_qubits=n_qubits, num_orbitals=n_qubits, qubit_mapping='jordan_wigner', two_qubit_reduction=False, num_particles= n_electrons) # Create the variational form var_form = UCCSD(num_qubits=n_qubits, num_orbitals=n_qubits, num_particles=n_electrons, depth=1, initial_state=initial_hf, qubit_mapping='jordan_wigner') # How many qubits do we need? print('Number of qubits: {0}'.format(n_qubits)) # Query the variational form for the number of parameters, and the parameter bounds. var_form.num_parameters, var_form.parameter_bounds[0] # Instantiate a concrete instance of the VQE ansatz by setting all the parameters to the # arbitrarily-chosen value of 0. var_circ = var_form.construct_circuit(np.zeros(var_form.num_parameters)) # Use Terra to convert the circuit to its directed, acyclic graph (DAG) representation. var_circ_dag = circuit_to_dag(var_circ) # The .properties() method of the DAG to get circuit properties. var_circ_dag.properties() # Grab an Aer backend aer_backend = Aer.get_backend('qasm_simulator') # Choose a random set of parameters seed = 0 np.random.seed(seed) params = np.random.uniform(low=-3.1, high=3.1, size=var_form.num_parameters) # Construct a random instance of the variational circuit var_circuit = var_form.construct_circuit(params) # Turn the circuit into a DAG var_dag = circuit_to_dag(var_circuit) var_dag.properties() # Create a Terra PassManager object tk_pass_manager = PassManager() # Set up the TketPass tk_pass = TketPass(aer_backend) # Add the TketPass to the PassManager tk_pass_manager.append(tk_pass) var_dag_transpiled = transpile_dag(var_dag, pass_manager=tk_pass_manager) var_dag_transpiled.properties() # Grab only backends that have at least 12 qubits IBMQ.backends(filters=lambda x: x.configuration().n_qubits >= 12) real_backend = IBMQ.get_backend('ibmq_16_melbourne') # Create a Terra PassManager object tk_pass_manager = PassManager() # Set up the TketPass tk_pass = TketPass(real_backend) # Add the TketPass to the PassManager tk_pass_manager.append(tk_pass) blank_qubits = QuantumRegister(len(real_backend.properties().qubits) - var_dag.width()) var_dag.add_qreg(blank_qubits) var_dag_transpiled = transpile_dag(var_dag, pass_manager=tk_pass_manager) var_dag_transpiled.properties() transpile_dag(var_dag, coupling_map=real_backend.configuration().coupling_map).properties() # Code imports # From Aqua, we need from qiskit_aqua import QuantumInstance from qiskit_aqua.algorithms.adaptive import VQE from qiskit_aqua.components.optimizers import L_BFGS_B # From pytket, we need QSE functions from pytket.chemistry import QseMatrices, QSE backend = Aer.get_backend('statevector_simulator') pass_manager = PassManager() tk_pass = TketPass(backend) pass_manager.append(tk_pass) quantum_instance = QuantumInstance(backend, pass_manager=pass_manager) # Temporary code for Aer on Macbook import os os.environ['KMP_DUPLICATE_LIB_OK']='True' # Set initial values of parameters number_amplitudes = len(var_form._single_excitations)+ len(var_form._double_excitations) amplitudes_0 = [] for i in range(number_amplitudes): amplitudes_0.append(0.00001) optimizer = L_BFGS_B() optimizer.set_options(maxfun=1000, factr=10, iprint=10) # setup VQE with operator, variation form, and optimzer vqe_algorithm = VQE(operator=qubitOp, operator_mode='matrix', var_form=var_form, optimizer=optimizer, initial_point=amplitudes_0) results = vqe_algorithm.run(quantum_instance) eigval = results['eigvals'][0] gs_energy = eigval.real + molecule.nuclear_repulsion_energy print("GS Minimum value: {}".format(gs_energy)) print("GS Parameters: {}".format(results['opt_params'])) # store ground state amplitudes for subsequent steps opti_amplitudes = results['opt_params'] qubitOp = ferOp.mapping(map_type='JORDAN_WIGNER', threshold=0.00000001) n_qubits = qubitOp.num_qubits qubitOp.chop(10**-10) # Use matrix term helper class matrix_terms = QseMatrices(qubitOp, n_qubits) # Instantiate an instance of the QSE algorithm qse_algorithm = QSE(matrix_terms, 'matrix', var_form, opt_init_point=opti_amplitudes) # Run the algorithm energies = qse_algorithm.run(quantum_instance)['eigvals'] # The excited state energies are the energies from above, # plus the nuclear repulsion energy. print("Excited State Energies: ", energies+molecule.nuclear_repulsion_energy)
https://github.com/anpaschool/QC-School-Fall2020
anpaschool
import numpy as np from qiskit import( QuantumCircuit, execute, Aer) from qiskit.visualization import plot_histogram circuit = QuantumCircuit(2, 2) # Two Qubit and 2 Classical bit (q,c) circuit.h(0) circuit.cx(0, 1) #Controlled-NOT Gate circuit.measure([0,1], [0,1]) #([q,q],[c,c]) circuit.draw() simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=100) result = job.result() counts = result.get_counts(circuit) print("\nTotal count for 00 and 11 are:",counts) plot_histogram(counts)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for unitary simulator.""" import unittest import numpy as np from qiskit import execute from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.providers.basicaer import UnitarySimulatorPy from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.test import ReferenceCircuits from qiskit.test import providers from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info import process_fidelity, Operator class BasicAerUnitarySimulatorPyTest(providers.BackendTestCase): """Test BasicAer unitary simulator.""" backend_cls = UnitarySimulatorPy circuit = ReferenceCircuits.bell_no_measure() def test_basicaer_unitary_simulator_py(self): """Test unitary simulator.""" circuits = self._test_circuits() job = execute(circuits, backend=self.backend) sim_unitaries = [job.result().get_unitary(circ) for circ in circuits] reference_unitaries = self._reference_unitaries() for u_sim, u_ref in zip(sim_unitaries, reference_unitaries): self.assertTrue(matrix_equal(u_sim, u_ref, ignore_phase=True)) def _test_circuits(self): """Return test circuits for unitary simulator""" qr = QuantumRegister(3) cr = ClassicalRegister(3) qc1 = QuantumCircuit(qr, cr) qc2 = QuantumCircuit(qr, cr) qc3 = QuantumCircuit(qr, cr) qc4 = QuantumCircuit(qr, cr) qc5 = QuantumCircuit(qr, cr) # Test circuit 1: HxHxH qc1.h(qr) # Test circuit 2: IxCX qc2.cx(qr[0], qr[1]) # Test circuit 3: CXxY qc3.y(qr[0]) qc3.cx(qr[1], qr[2]) # Test circuit 4: (CX.I).(IxCX).(IxIxX) qc4.h(qr[0]) qc4.cx(qr[0], qr[1]) qc4.cx(qr[1], qr[2]) # Test circuit 5 (X.Z)x(Z.Y)x(Y.X) qc5.x(qr[0]) qc5.y(qr[0]) qc5.y(qr[1]) qc5.z(qr[1]) qc5.z(qr[2]) qc5.x(qr[2]) return [qc1, qc2, qc3, qc4, qc5] def _reference_unitaries(self): """Return reference unitaries for test circuits""" # Gate matrices gate_h = np.array([[1, 1], [1, -1]]) / np.sqrt(2) gate_x = np.array([[0, 1], [1, 0]]) gate_y = np.array([[0, -1j], [1j, 0]]) gate_z = np.array([[1, 0], [0, -1]]) gate_cx = np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0.0, 0, 1, 0], [0, 1, 0, 0]]) # Unitary matrices target_unitary1 = np.kron(np.kron(gate_h, gate_h), gate_h) target_unitary2 = np.kron(np.eye(2), gate_cx) target_unitary3 = np.kron(gate_cx, gate_y) target_unitary4 = np.dot( np.kron(gate_cx, np.eye(2)), np.dot(np.kron(np.eye(2), gate_cx), np.kron(np.eye(4), gate_h)), ) target_unitary5 = np.kron( np.kron(np.dot(gate_x, gate_z), np.dot(gate_z, gate_y)), np.dot(gate_y, gate_x) ) return [target_unitary1, target_unitary2, target_unitary3, target_unitary4, target_unitary5] def test_unitary(self): """Test unitary gate instruction""" num_trials = 10 max_qubits = 3 # Test 1 to max_qubits for random n-qubit unitary gate for i in range(max_qubits): num_qubits = i + 1 unitary_init = Operator(np.eye(2**num_qubits)) qr = QuantumRegister(num_qubits, "qr") for _ in range(num_trials): # Create random unitary unitary = random_unitary(2**num_qubits) # Compute expected output state unitary_target = unitary.dot(unitary_init) # Simulate output on circuit circuit = QuantumCircuit(qr) circuit.unitary(unitary, qr) job = execute(circuit, self.backend) result = job.result() unitary_out = Operator(result.get_unitary(0)) fidelity = process_fidelity(unitary_target, unitary_out) self.assertGreater(fidelity, 0.999) def test_global_phase(self): """Test global phase for XZH See https://github.com/Qiskit/qiskit-terra/issues/3083""" q = QuantumRegister(1) circuit = QuantumCircuit(q) circuit.h(q[0]) circuit.z(q[0]) circuit.x(q[0]) job = execute(circuit, self.backend) result = job.result() unitary_out = result.get_unitary(circuit) unitary_target = np.array( [[-1 / np.sqrt(2), 1 / np.sqrt(2)], [1 / np.sqrt(2), 1 / np.sqrt(2)]] ) self.assertTrue(np.allclose(unitary_out, unitary_target)) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Class for a Real McLachlan's Variational Principle.""" from __future__ import annotations import warnings from collections.abc import Sequence import numpy as np from numpy import real from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.primitives import Estimator from qiskit.quantum_info import SparsePauliOp from qiskit.quantum_info.operators.base_operator import BaseOperator from .real_variational_principle import RealVariationalPrinciple from ....exceptions import AlgorithmError from ....gradients import ( BaseEstimatorGradient, BaseQGT, DerivativeType, LinCombQGT, LinCombEstimatorGradient, ) class RealMcLachlanPrinciple(RealVariationalPrinciple): """Class for a Real McLachlan's Variational Principle. It aims to minimize the distance between both sides of the SchrΓΆdinger equation with a quantum state given as a parametrized trial state. The principle leads to a system of linear equations handled by a linear solver. The real variant means that we consider real time dynamics. """ def __init__( self, qgt: BaseQGT | None = None, gradient: BaseEstimatorGradient | None = None, ) -> None: """ Args: qgt: Instance of a the GQT class used to compute the QFI. If ``None`` provided, ``LinCombQGT`` is used. gradient: Instance of a class used to compute the state gradient. If ``None`` provided, ``LinCombEstimatorGradient`` is used. Raises: AlgorithmError: If the gradient instance does not contain an estimator. """ self._validate_grad_settings(gradient) if gradient is not None: try: estimator = gradient._estimator except Exception as exc: raise AlgorithmError( "The provided gradient instance does not contain an estimator primitive." ) from exc else: estimator = Estimator() gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) if qgt is None: qgt = LinCombQGT(estimator) super().__init__(qgt, gradient) def evolution_gradient( self, hamiltonian: BaseOperator, ansatz: QuantumCircuit, param_values: Sequence[float], gradient_params: Sequence[Parameter] | None = None, ) -> np.ndarray: """ Calculates an evolution gradient according to the rules of this variational principle. Args: hamiltonian: Operator used for Variational Quantum Time Evolution. ansatz: Quantum state in the form of a parametrized quantum circuit. param_values: Values of parameters to be bound. gradient_params: List of parameters with respect to which gradients should be computed. If ``None`` given, gradients w.r.t. all parameters will be computed. Returns: An evolution gradient. Raises: AlgorithmError: If a gradient job fails. """ try: estimator_job = self.gradient._estimator.run([ansatz], [hamiltonian], [param_values]) energy = estimator_job.result().values[0] except Exception as exc: raise AlgorithmError("The primitive job failed!") from exc modified_hamiltonian = self._construct_modified_hamiltonian(hamiltonian, real(energy)) try: evolution_grad = ( 0.5 * self.gradient.run( [ansatz], [modified_hamiltonian], parameters=[gradient_params], parameter_values=[param_values], ) .result() .gradients[0] ) except Exception as exc: raise AlgorithmError("The gradient primitive job failed!") from exc # The BaseEstimatorGradient class returns the gradient of the opposite sign than we expect # here (i.e. with a minus sign), hence the correction that cancels it to recover the # real McLachlan's principle equations that do not have a minus sign. evolution_grad = (-1) * evolution_grad return evolution_grad @staticmethod def _construct_modified_hamiltonian(hamiltonian: BaseOperator, energy: float) -> BaseOperator: """ Modifies a Hamiltonian according to the rules of this variational principle. Args: hamiltonian: Operator used for Variational Quantum Time Evolution. energy: The energy correction value. Returns: A modified Hamiltonian. """ energy_term = SparsePauliOp.from_list( hamiltonian.to_list() + [("I" * hamiltonian.num_qubits, -energy)] ) return energy_term @staticmethod def _validate_grad_settings(gradient): if gradient is not None: if not hasattr(gradient, "_derivative_type"): raise ValueError( "The gradient instance provided does not support calculating imaginary part. " "Please choose a different gradient class." ) if gradient._derivative_type != DerivativeType.IMAG: warnings.warn( "A gradient instance with a setting for calculating real part of the" "gradient was provided. This variational principle requires the" "imaginary part. The setting to imaginary was changed automatically." ) gradient._derivative_type = DerivativeType.IMAG
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. # pylint: disable=invalid-name """Randomized tests of transpiler circuit equivalence. This test can be optionally configured (e.g. by CI) via the following env vars: QISKIT_RANDOMIZED_TEST_LAYOUT_METHODS A space-delimited list of layout method names from which the randomizer should pick the layout method. Defaults to all available built-in methods if unspecified. QISKIT_RANDOMIZED_TEST_ROUTING_METHODS A space-delimited list of routing method names from which the randomizer should pick the routing method. Defaults to all available built-in methods if unspecified. QISKIT_RANDOMIZED_TEST_SCHEDULING_METHODS A space-delimited list of scheduling method names from which the randomizer should pick the scheduling method. Defaults to all available built-in methods if unspecified. QISKIT_RANDOMIZED_TEST_BACKEND_NEEDS_DURATIONS A boolean value (e.g. "true", "Y", etc.) which, when true, forces the randomizer to pick a backend which fully supports scheduling (i.e. has fully specified duration info). Defaults to False. QISKIT_RANDOMIZED_TEST_ALLOW_BARRIERS A boolean value (e.g. "true", "Y", etc.) which, when false, prevents the randomizer from emitting barrier instructions. Defaults to True. """ import os from math import pi from hypothesis import assume, settings, HealthCheck from hypothesis.stateful import multiple, rule, precondition, invariant from hypothesis.stateful import Bundle, RuleBasedStateMachine import hypothesis.strategies as st from qiskit import transpile, Aer from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit import Measure, Reset, Gate, Barrier from qiskit.providers.fake_provider import ( FakeProvider, FakeOpenPulse2Q, FakeOpenPulse3Q, FakeYorktown, FakeTenerife, FakeOurense, FakeVigo, FakeMelbourne, FakeRueschlikon, FakeTokyo, FakePoughkeepsie, FakeAlmaden, FakeSingapore, FakeJohannesburg, FakeBoeblingen, FakeRochester, FakeBurlington, FakeCambridge, FakeCambridgeAlternativeBasis, FakeEssex, FakeLondon, FakeQasmSimulator, FakeArmonk, FakeRome, FakeSantiago, FakeSydney, FakeToronto, FakeValencia, ) from qiskit.test.base import dicts_almost_equal # pylint: disable=wildcard-import,unused-wildcard-import from qiskit.circuit.library.standard_gates import * default_profile = "transpiler_equivalence" settings.register_profile( default_profile, report_multiple_bugs=False, max_examples=200, deadline=None, suppress_health_check=[HealthCheck.filter_too_much], ) settings.load_profile(os.getenv("HYPOTHESIS_PROFILE", default_profile)) BASE_INSTRUCTIONS = { # Key is (n_qubits, n_clbits, n_params). All gates here should be directly known by Aer so they # can be simulated without an initial transpile (whether that's via `execute` or not). (1, 0, 0): [HGate, IGate, SGate, SdgGate, TGate, TdgGate, XGate, YGate, ZGate, Reset], (2, 0, 0): [CXGate, CYGate, CZGate, SwapGate], (3, 0, 0): [CCXGate, CSwapGate], (1, 0, 1): [PhaseGate, RXGate, RYGate, RZGate], (1, 0, 3): [UGate], (2, 0, 1): [RZZGate, CPhaseGate], (2, 0, 4): [CUGate], (1, 1, 0): [Measure], } variadic_gates = [Barrier] def _strtobool(s): return s.lower() in ("y", "yes", "t", "true", "on", "1") if not _strtobool(os.getenv("QISKIT_RANDOMIZED_TEST_ALLOW_BARRIERS", "True")): variadic_gates.remove(Barrier) def _getenv_list(var_name): value = os.getenv(var_name) return None if value is None else value.split() # Note: a value of `None` for any of the following methods means that # the selected pass manager gets to choose. However, to avoid complexity, # its not possible to specify `None` when overriding these with environment # variables. Really, `None` is useful only for testing Terra's pass managers, # and if you're overriding these, your goal is probably to test a specific # pass or set of passes instead. layout_methods = _getenv_list("QISKIT_RANDOMIZED_TEST_LAYOUT_METHODS") or [ None, "trivial", "dense", "noise_adaptive", "sabre", ] routing_methods = _getenv_list("QISKIT_RANDOMIZED_TEST_ROUTING_METHODS") or [ None, "basic", "stochastic", "lookahead", "sabre", ] scheduling_methods = _getenv_list("QISKIT_RANDOMIZED_TEST_SCHEDULING_METHODS") or [ None, "alap", "asap", ] backend_needs_durations = _strtobool( os.getenv("QISKIT_RANDOMIZED_TEST_BACKEND_NEEDS_DURATIONS", "False") ) def _fully_supports_scheduling(backend): """Checks if backend is not in the set of backends known not to have specified gate durations.""" return not isinstance( backend, ( # no coupling map FakeArmonk, # no measure durations FakeAlmaden, FakeBurlington, FakeCambridge, FakeCambridgeAlternativeBasis, FakeEssex, FakeJohannesburg, FakeLondon, FakeOpenPulse2Q, FakeOpenPulse3Q, FakePoughkeepsie, FakeQasmSimulator, FakeRochester, FakeRueschlikon, FakeSingapore, FakeTenerife, FakeTokyo, # No reset duration FakeAlmaden, FakeArmonk, FakeBoeblingen, FakeBurlington, FakeCambridge, FakeCambridgeAlternativeBasis, FakeEssex, FakeJohannesburg, FakeLondon, FakeMelbourne, FakeOpenPulse2Q, FakeOpenPulse3Q, FakeOurense, FakePoughkeepsie, FakeQasmSimulator, FakeRochester, FakeRome, FakeRueschlikon, FakeSantiago, FakeSingapore, FakeSydney, FakeTenerife, FakeTokyo, FakeToronto, FakeValencia, FakeVigo, FakeYorktown, ), ) fake_provider = FakeProvider() mock_backends = fake_provider.backends() mock_backends_with_scheduling = [b for b in mock_backends if _fully_supports_scheduling(b)] @st.composite def transpiler_conf(draw): """Composite search strategy to pick a valid transpiler config.""" all_backends = st.one_of(st.none(), st.sampled_from(mock_backends)) scheduling_backends = st.sampled_from(mock_backends_with_scheduling) scheduling_method = draw(st.sampled_from(scheduling_methods)) backend = ( draw(scheduling_backends) if scheduling_method or backend_needs_durations else draw(all_backends) ) return { "backend": backend, "optimization_level": draw(st.integers(min_value=0, max_value=3)), "layout_method": draw(st.sampled_from(layout_methods)), "routing_method": draw(st.sampled_from(routing_methods)), "scheduling_method": scheduling_method, "seed_transpiler": draw(st.integers(min_value=0, max_value=1_000_000)), } class QCircuitMachine(RuleBasedStateMachine): """Build a Hypothesis rule based state machine for constructing, transpiling and simulating a series of random QuantumCircuits. Build circuits with up to QISKIT_RANDOM_QUBITS qubits, apply a random selection of gates from qiskit.circuit.library with randomly selected qargs, cargs, and parameters. At random intervals, transpile the circuit for a random backend with a random optimization level and simulate both the initial and the transpiled circuits to verify that their counts are the same. """ qubits = Bundle("qubits") clbits = Bundle("clbits") backend = Aer.get_backend("aer_simulator") max_qubits = int(backend.configuration().n_qubits / 2) # Limit reg generation for more interesting circuits max_qregs = 3 max_cregs = 3 def __init__(self): super().__init__() self.qc = QuantumCircuit() self.enable_variadic = bool(variadic_gates) @precondition(lambda self: len(self.qc.qubits) < self.max_qubits) @precondition(lambda self: len(self.qc.qregs) < self.max_qregs) @rule(target=qubits, n=st.integers(min_value=1, max_value=max_qubits)) def add_qreg(self, n): """Adds a new variable sized qreg to the circuit, up to max_qubits.""" n = min(n, self.max_qubits - len(self.qc.qubits)) qreg = QuantumRegister(n) self.qc.add_register(qreg) return multiple(*list(qreg)) @precondition(lambda self: len(self.qc.cregs) < self.max_cregs) @rule(target=clbits, n=st.integers(1, 5)) def add_creg(self, n): """Add a new variable sized creg to the circuit.""" creg = ClassicalRegister(n) self.qc.add_register(creg) return multiple(*list(creg)) # Gates of various shapes @precondition(lambda self: self.qc.num_qubits > 0 and self.qc.num_clbits > 0) @rule(n_arguments=st.sampled_from(sorted(BASE_INSTRUCTIONS.keys())), data=st.data()) def add_gate(self, n_arguments, data): """Append a random fixed gate to the circuit.""" n_qubits, n_clbits, n_params = n_arguments gate_class = data.draw(st.sampled_from(BASE_INSTRUCTIONS[n_qubits, n_clbits, n_params])) qubits = data.draw(st.lists(self.qubits, min_size=n_qubits, max_size=n_qubits, unique=True)) clbits = data.draw(st.lists(self.clbits, min_size=n_clbits, max_size=n_clbits, unique=True)) params = data.draw( st.lists( st.floats( allow_nan=False, allow_infinity=False, min_value=-10 * pi, max_value=10 * pi ), min_size=n_params, max_size=n_params, ) ) self.qc.append(gate_class(*params), qubits, clbits) @precondition(lambda self: self.enable_variadic) @rule(gate=st.sampled_from(variadic_gates), qargs=st.lists(qubits, min_size=1, unique=True)) def add_variQ_gate(self, gate, qargs): """Append a gate with a variable number of qargs.""" self.qc.append(gate(len(qargs)), qargs) @precondition(lambda self: len(self.qc.data) > 0) @rule(carg=clbits, data=st.data()) def add_c_if_last_gate(self, carg, data): """Modify the last gate to be conditional on a classical register.""" creg = self.qc.find_bit(carg).registers[0][0] val = data.draw(st.integers(min_value=0, max_value=2 ** len(creg) - 1)) last_gate = self.qc.data[-1] # Conditional instructions are not supported assume(isinstance(last_gate[0], Gate)) last_gate[0].c_if(creg, val) # Properties to check @invariant() def qasm(self): """After each circuit operation, it should be possible to build QASM.""" self.qc.qasm() @precondition(lambda self: any(isinstance(d[0], Measure) for d in self.qc.data)) @rule(kwargs=transpiler_conf()) def equivalent_transpile(self, kwargs): """Simulate, transpile and simulate the present circuit. Verify that the counts are not significantly different before and after transpilation. """ assume( kwargs["backend"] is None or kwargs["backend"].configuration().n_qubits >= len(self.qc.qubits) ) call = ( "transpile(qc, " + ", ".join(f"{key:s}={value!r}" for key, value in kwargs.items() if value is not None) + ")" ) print(f"Evaluating {call} for:\n{self.qc.qasm()}") shots = 4096 # Note that there's no transpilation here, which is why the gates are limited to only ones # that Aer supports natively. aer_counts = self.backend.run(self.qc, shots=shots).result().get_counts() try: xpiled_qc = transpile(self.qc, **kwargs) except Exception as e: failed_qasm = f"Exception caught during transpilation of circuit: \n{self.qc.qasm()}" raise RuntimeError(failed_qasm) from e xpiled_aer_counts = self.backend.run(xpiled_qc, shots=shots).result().get_counts() count_differences = dicts_almost_equal(aer_counts, xpiled_aer_counts, 0.05 * shots) assert ( count_differences == "" ), "Counts not equivalent: {}\nFailing QASM Input:\n{}\n\nFailing QASM Output:\n{}".format( count_differences, self.qc.qasm(), xpiled_qc.qasm() ) TestQuantumCircuit = QCircuitMachine.TestCase
https://github.com/arnavdas88/QuGlassyIsing
arnavdas88
!pip install qiskit !pip install qiskit-aer-gpu from qiskit.providers.aer import QasmSimulator from qiskit.providers.aer import AerSimulator from qiskit.circuit.library import TwoLocal from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import EfficientSU2 from qiskit.aqua import set_qiskit_aqua_logging, QuantumInstance from qiskit.providers.aer import AerError # opflow is Qiskit's module for creating operators like yours from qiskit import * from qiskit.opflow import OperatorBase from qiskit.opflow import Z, X, I # Pauli Z, X matrices and identity import pylab import matplotlib.pyplot as plt import numpy as np # The config to be referenced by the rest of the notebook # Change here to change the params lattice_length = 3 no_of_terms_in_hamiltonian = 3 ** 2 B_x = 1. B_z = 1. J = 1. def get_interaction(element_1, element_2, matrix_dimension): output = [] (tR, tC) = matrix_dimension (R1, C1) = element_1 (R2, C2) = element_2 if (-1 in element_1) or (-1 in element_2) or (tR in [R1, R2]) or (tC in [C1, C2]): # Return empty, for outside bounds in edge cases return "" ''' element_1 : [1, 0] element_2 : [2, 0] matrix_dimension : 3, 3 output : III ZII ZII III ZII ZII ''' for _ in range(tR): R = [] for _ in range(tC): R += [ "I" ] output += [R] R,C = element_1 output[R][C] = "Z" R,C = element_2 output[R][C] = "Z" output = "^".join([ "^".join([ R for R in C ]) for C in output ]) return f"({output})" # print(get_interaction((0, 1), (1, 1), (3,3))) def HamiltonianInteraction(matrix_dimension = None): if not matrix_dimension: matrix_dimension = (lattice_length , lattice_length) (tR, tC) = matrix_dimension output = "" for R in range(tR): for C in range(tC): Oi = (R, C) Li = (R-1, C) Ri = (R+1, C) Ti = (R, C-1) Bi = (R, C+1) I = [] I += [get_interaction(Li, Oi, matrix_dimension)] I += [get_interaction(Ri, Oi, matrix_dimension)] I += [get_interaction(Ti, Oi, matrix_dimension)] I += [get_interaction(Bi, Oi, matrix_dimension)] I = "+".join(I) # print(I) output += I + "+" return output.replace("++", "+").replace("++", "+").strip('+') from pprint import pprint print( HamiltonianInteraction( (5,5) ) ) H = J * ((Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z) ) - B_x * ( ( X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ) ) - B_z * (( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ) ) counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) def run(B_X = 1, J_z = 1, B_Z = 1): master_counts = [] master_values = [] # for h in range (1,5,1): # h=+h # Initialization B_x = B_X J = J_z B_z = B_Z # or whatever value you have for h #H = - B_X * ((X ^ I ^ I ^ I) + (I ^ X ^ I ^ I) + (I ^ I ^ X ^ I) + (I ^ I ^ I ^ X)) + J_z * ((Z ^ Z ^ I ^ I ) + (I ^ Z ^ Z ^ I) + (I ^ I ^ Z ^ Z) + (Z ^ I ^ I ^ Z)) - B_Z * ((Z ^ I ^ I ^ I) + (I ^ Z ^ I ^ I) + (I ^ I ^ Z ^ I ) + (I ^ I ^ I ^ Z)) # for 25 qubits H = J * ((Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z) ) - B_x * ( ( X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ) ) - B_z * (( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ) ) # you can swap this for a real quantum device and keep the rest of the code the same! backend = AerSimulator(device="GPU") # COBYLA usually works well for small problems like this one optimizer = COBYLA() # EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library #ansatz = EfficientSU2(4, reps=1) # for 25 qubits # ansatz = EfficientSU2(25, reps=1) ansatz = TwoLocal(num_qubits=25, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True) # set the algorithm vqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result) # run it with the Hamiltonian we defined above result = vqe.compute_minimum_eigenvalue(H) # print the result (it contains lot's of information) return result %%time print(run())
https://github.com/bayesian-randomized-benchmarking/qiskit-advocates-bayes-RB
bayesian-randomized-benchmarking
#Import general libraries (needed for functions) import numpy as np import matplotlib.pyplot as plt from IPython import display #Import Qiskit classes import qiskit from qiskit.tools.monitor import job_monitor from qiskit import Aer from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors.standard_errors import depolarizing_error, thermal_relaxation_error from qiskit import QuantumRegister, QuantumCircuit #Import the RB Functions import qiskit.ignis.verification.randomized_benchmarking as rb import copy import time # import the bayesian packages import pymc3 as pm import arviz as az from scipy.optimize import curve_fit def obtain_priors_and_data_from_fitter(rbfit, nCliffs, shots, printout = True): m_gates = copy.deepcopy(nCliffs) # We choose the count matrix corresponding to 2 Qubit RB Y = (np.array(rbfit._raw_data[0])*shots).astype(int) # alpha prior and bounds alpha_ref = rbfit._fit[0]['params'][1] #alpha_lower = alpha_ref - 6*rbfit._fit[0]['params_err'][1] #alpha_upper = alpha_ref + 6*rbfit._fit[0]['params_err'][1] alpha_lower = .95*alpha_ref alpha_upper = min(1.05*alpha_ref,1.0) # priors for A anbd B mu_AB = np.delete(rbfit._fit[0]['params'],1) cov_AB=np.delete(rbfit._fit[0]['params_err'],1)**2 # prior for sigma theta: sigma_theta = 0.004 # WIP if printout: print("priors:\nalpha_ref",alpha_ref) print("alpha_lower", alpha_lower, "alpha_upper", alpha_upper) print("A,B", mu_AB, "\ncov A,B", cov_AB) print("sigma_theta", sigma_theta) return m_gates, Y, alpha_ref, alpha_lower, alpha_upper, mu_AB, cov_AB, sigma_theta # modified for accelerated BM with EPCest as extra parameter def get_bayesian_model(model_type,Y,shots,m_gates,mu_AB,cov_AB, alpha_ref, alpha_lower=0.5,alpha_upper=0.999,alpha_testval=0.9, p_lower=0.9,p_upper=0.999,p_testval=0.95, RvsI=None,IvsR=None,sigma_theta=0.001, sigma_theta_l=0.0005,sigma_theta_u=0.0015): # Bayesian model # from https://iopscience.iop.org/arti=RvsI, cle/1sigma_theta=0.004,0.1088/1367-2630/17/1/013042/pdf # see https://docs.pymc.io/api/model.html RB_model = pm.Model() with RB_model: total_shots = np.full(Y.shape, shots) #Priors for unknown model parameters alpha = pm.Uniform("alpha",lower=alpha_lower, upper=alpha_upper, testval = alpha_ref) BoundedMvNormal = pm.Bound(pm.MvNormal, lower=0.0) AB = BoundedMvNormal("AB", mu=mu_AB,testval = mu_AB, cov= np.diag(cov_AB), shape = (2)) if model_type == "hierarchical": GSP = AB[0]*alpha**m_gates + AB[1] theta = pm.Beta("GSP", mu=GSP, sigma = sigma_theta, shape = Y.shape[1]) # Likelihood (sampling distribution) of observations p = pm.Binomial("Counts_h", p=theta, observed=Y, n = total_shots) elif model_type == "h_sigma": sigma_t = pm.Uniform("sigma_t", testval = sigma_theta, upper = sigma_theta_u, lower = sigma_theta_l) GSP = AB[0]*alpha**m_gates + AB[1] theta = pm.Beta("GSP", mu=GSP, sigma = sigma_t, shape = Y.shape[1]) # Likelihood (sampling distribution) of observations p = pm.Binomial("Counts_h", p=theta, observed=Y, n = total_shots) elif model_type == "tilde": p_tilde = pm.Uniform("p_tilde",lower=p_lower, upper=p_upper, testval = p_testval) GSP = AB[0]*(RvsI*alpha**m_gates + IvsR*(alpha*p_tilde)**m_gates) + AB[1] # Likelihood (sampling distribution) of observations p = pm.Binomial("Counts_t", p=GSP, observed=Y, n = total_shots) else: # defaul model "pooled" GSP = AB[0]*alpha**m_gates + AB[1] # Likelihood (sampling distribution) of observations p = pm.Binomial("Counts_p", p=GSP, observed=Y, n = total_shots) return RB_model def get_bayesian_model_hierarchical(model_type,Y): # modified for accelerated BM with EPCest as extra parameter # Bayesian model # from https://iopscience.iop.org/article/10.1088/1367-2630/17/1/013042/pdf # see https://docs.pymc.io/api/model.html RBH_model = pm.Model() with RBH_model: #Priors for unknown model parameters alpha = pm.Uniform("alpha",lower=alpha_lower, upper=alpha_upper, testval = alpha_ref) BoundedMvNormal = pm.Bound(pm.MvNormal, lower=0.0) AB = BoundedMvNormal("AB", mu=mu_AB,testval = mu_AB, cov= np.diag(cov_AB), shape = (2)) # Expected value of outcome GSP = AB[0]*alpha**m_gates + AB[1] total_shots = np.full(Y.shape, shots) theta = pm.Beta("GSP", mu=GSP, sigma = sigma_theta, shape = Y.shape[1]) # Likelihood (sampling distribution) of observations p = pm.Binomial("Counts", p=theta, observed=Y, n = total_shots) return RBH_model def get_trace(RB_model, draws = 2000, tune= 10000, target_accept=0.95, return_inferencedata=True): # Gradient-based sampling methods # see also: https://docs.pymc.io/notebooks/sampler-stats.html # and https://docs.pymc.io/notebooks/api_quickstart.html with RB_model: trace= pm.sample(draws = draws, tune= tune, target_accept=target_accept, return_inferencedata=return_inferencedata) with RB_model: az.plot_trace(trace); return trace def get_summary(RB_model, trace, round_to=6, hdi_prob=.94, kind='stats'): with RB_model: # (hdi_prob=.94 is default) az_summary = az.summary(trace, round_to=round_to, hdi_prob=hdi_prob, kind=kind ) return az_summary # obtain EPC from alpha (used by plot_posterior) # deprecated, should use scale #def alpha_to_EPC(alpha): #return 3*(1-alpha)/4 def get_EPC_and_legends(rbfit,azs): EPC_Bayes = alpha_to_EPC(azs['mean']['alpha']) EPC_Bayes_err = EPC_Bayes - alpha_to_EPC(azs['mean']['alpha']+azs['sd']['alpha']) Bayes_legend ="EPC Bayes {0:.5f} ({1:.5f})".format(EPC_Bayes, EPC_Bayes_err) Fitter_legend ="EPC Fitter {0:.5f} ({1:.5f})".format(rbfit.fit[0]['epc']\ ,rbfit._fit[0]['epc_err']) if pred_epc > 0.0: pred_epc_legend = "EPC predicted {0:.5f}".format(pred_epc) else: pred_epc_legend = '' return EPC_Bayes, EPC_Bayes_err, Bayes_legend,Fitter_legend, pred_epc_legend def EPC_compare_fitter_to_bayes(RB_model, azs, trace,m_name,rbfit): EPC_Bayes, EPC_Bayes_err, Bayes_legend,Fitter_legend, pred_epc_legend = get_EPC_and_legends(rbfit,azs) with RB_model: az.plot_posterior(trace, var_names=['alpha'], round_to=4, transform = alpha_to_EPC, point_estimate=None) plt.title("Error per Clifford "+RB_process+" device: "+hardware +' backend: '+backend.name()+' model:'+m_name, fontsize=12) plt.axvline(x=alpha_to_EPC(alpha_ref),color='red') if pred_epc > 0.0: plt.axvline(x=pred_epc,color='green') plt.legend((Bayes_legend, "Higher density interval",Fitter_legend, pred_epc_legend), fontsize=10) else: plt.legend((Bayes_legend, "Higher density interval",Fitter_legend), fontsize=10 ) plt.show() def GSP_compare_fitter_to_bayes(RB_model, azs,m_name,rbfit): EPC_Bayes, EPC_Bayes_err, Bayes_legend,Fitter_legend,_ = get_EPC_and_legends(rbfit,azs) # plot ground state population ~ Clifford length fig, axes = plt.subplots(1, 1, sharex=True, figsize=(10, 6)) axes.set_ylabel("Ground State Population") axes.set_xlabel("Clifford Length") axes.plot(m_gates, np.mean(Y/shots,axis=0), 'r.') axes.plot(m_gates,azs['mean']['AB[0]']*azs['mean']['alpha']**m_gates+azs['mean']['AB[1]'],'--') #axes.plot(m_gates,azs['mean']['GSP'],'--') # WIP #axes.errorbar(m_gates, azs['mean']['GSP'], azs['sd']['GSP'], linestyle='None', marker='^') # WIP axes.plot(m_gates,mu_AB[0]*np.power(alpha_ref,m_gates)+mu_AB[1],':') for i_seed in range(nseeds): plt.scatter(m_gates-0.25, Y[i_seed,:]/shots, label = "data", marker="x") axes.legend(["Mean Observed Frequencies", "Bayesian Model\n"+Bayes_legend, "Fitter Model\n"+Fitter_legend],fontsize=12) axes.set_title(RB_process+" device: "+hardware+' backend: '+backend.name()+' model:'+m_name, fontsize=14) # WIP def get_predicted_EPC(error_source): #Count the number of single and 2Q gates in the 2Q Cliffords gates_per_cliff = rb.rb_utils.gates_per_clifford(transpile_list,xdata[0],basis_gates,rb_opts['rb_pattern'][0]) for basis_gate in basis_gates: print("Number of %s gates per Clifford: %f "%(basis_gate , np.mean([gates_per_cliff[rb_pattern[0][0]][basis_gate], gates_per_cliff[rb_pattern[0][1]][basis_gate]]))) # Calculate the predicted epc # from the known depolarizing errors on the simulation if error_source == "depolarization": # Error per gate from noise model epgs_1q = {'u1': 0, 'u2': p1Q/2, 'u3': 2*p1Q/2} epg_2q = p2Q*3/4 pred_epc = rb.rb_utils.calculate_2q_epc( gate_per_cliff=gates_per_cliff, epg_2q=epg_2q, qubit_pair=[0, 2], list_epgs_1q=[epgs_1q, epgs_1q]) # using the predicted primitive gate errors from the coherence limit if error_source == "from_T1_T2": # Predicted primitive gate errors from the coherence limit u2_error = rb.rb_utils.coherence_limit(1,[t1],[t2],gate1Q) u3_error = rb.rb_utils.coherence_limit(1,[t1],[t2],2*gate1Q) epg_2q = rb.rb_utils.coherence_limit(2,[t1,t1],[t2,t2],gate2Q) epgs_1q = {'u1': 0, 'u2': u2_error, 'u3': u3_error} pred_epc = rb.rb_utils.calculate_2q_epc( gate_per_cliff=gates_per_cliff, epg_2q=epg_2q, qubit_pair=[0, 1], list_epgs_1q=[epgs_1q, epgs_1q]) return pred_epc def get_and_run_seeds(rb_circs, shots, backend, coupling_map, basis_gates, noise_model, retrieve_list=[]): #basis_gates = ['u1','u2','u3','cx'] # use U,CX for now result_list = [] transpile_list = [] for rb_seed,rb_circ_seed in enumerate(rb_circs): print('Compiling seed %d'%rb_seed) rb_circ_transpile = qiskit.transpile(rb_circ_seed, optimization_level=0, basis_gates=basis_gates) print('Runing seed %d'%rb_seed) if retrieve_list == []: if noise_model == None: # this indicates harware run job = qiskit.execute(rb_circ_transpile, shots=shots, backend=backend, coupling_map=coupling_map, basis_gates=basis_gates) else: job = qiskit.execute(rb_circ_transpile, shots=shots, backend=backend, coupling_map=coupling_map, noise_model=noise_model, basis_gates=basis_gates) job_monitor(job) else: job = backend.retrieve_job(retrieve_list[rb_seed]) result_list.append(job.result()) transpile_list.append(rb_circ_transpile) print("Finished Jobs") return result_list, transpile_list def get_count_data(result_list, nCliffs): ### another way to obtain the observed counts #corrected for accomodation pooled data from 1Q, 2Q and 3Q interleave processes list_bitstring = ['0','00', '000', '100'] # all valid bistrings Y_list = [] for rbseed, result in enumerate(result_list): row_list = [] for c_index, c_value in enumerate(nCliffs) : total_counts = 0 for key,val in result.get_counts()[c_index].items(): if key in list_bitstring: total_counts += val #print(key,val,total_counts) row_list.append(total_counts) Y_list.append(row_list) return np.array(Y_list) # This section for the LS fit in this model pooling # data from 2Q and 3Q interleave processes def func(x, a, b, c): return a * b ** x + c def epc_fitter_when_mixed_2Q_3Q_RB(X,Y1,Y2,shots,check_plot=False): xdata = np.array(list(X)*Y1.shape[0]) # must be something simpler ydata1 = np.ravel(Y1)/shots popt, pcov = curve_fit(func, xdata, ydata1) perr= np.sqrt(np.diag(pcov)) ydata2 = np.ravel(Y2)/shots popt2, pcov2 = curve_fit(func, xdata, ydata2) perr2= np.sqrt(np.diag(pcov2)) if check_plot: import matplotlib.pyplot as plt plt.plot(xdata, ydata1, 'bx', label='Reference') plt.plot(xdata, ydata2, 'r+', label='Interleave') plt.plot(X, np.mean(Y1,axis=0)/shots, 'b-', label=None) plt.plot(X, np.mean(Y2,axis=0)/shots, 'r-', label=None) plt.ylabel('Population of |00>') plt.xlabel('Number of Cliffords') plt.legend() plt.show() print(popt[1]) print(perr[1]) print(popt2[1]) print(perr2[1]) epc_est_fitter = 3*(1 - popt2[1]/popt[1])/4 epc_est_fitter_err = 3*(popt2[1]/popt[1])/4 * (np.sqrt(perr[1]**2 + perr2[1]**2)) return epc_est_fitter, epc_est_fitter_err # This section for the demo with qiskit experiment def retrieve_from_lsf(exp): perr_fm = np.sqrt(np.diag(exp._analysis_results[0]['pcov'])) popt_fm = exp._analysis_results[0]['popt'] epc_est_fm = exp._analysis_results[0]['EPC'] epc_est_fm_err = exp._analysis_results[0]['EPC_err'] experiment_type = exp._data[0]['metadata']['experiment_type'] return perr_fm, popt_fm, epc_est_fm, epc_est_fm_err, experiment_type def get_GSP_counts(data, x_length, data_range): #obtain the observed counts used in the bayesian model #corrected for accomodation pooled data from 1Q, 2Q and 3Q interleave processes list_bitstring = ['0','00', '000', '100'] # all valid bistrings Y_list = [] for i_samples in data_range: row_list = [] for c_index in range(x_length) : total_counts = 0 i_data = i_samples*x_length + c_index for key,val in data[i_data]['counts'].items(): if key in list_bitstring: total_counts += val row_list.append(total_counts) Y_list.append(row_list) return np.array(Y_list) def RB_bayesian_results(resmodel, trace, lengths, epc_est_fm, epc_est_fm_err, experiment_type, scale, num_samples, Y, shots, physical_qubits, interleaved_gate, backend, EPG_dic = None, epc_calib = np.nan, Y1 = None, Y2= None, show_plot = True): # obtain EPC from alpha (used by az.plot_posterior) def alpha_to_EPC(alpha): return scale*(1-alpha) azt_summary = get_summary(resmodel, trace, kind = 'stats') print(azt_summary,'\n') if experiment_type == "StandardRB": p = 'alpha' epc_est_a = scale*(1 - azt_summary['mean'][p]) epc_est_a_err = scale* (azt_summary['sd'][p]) # compare LSF and SMC print("Model: Frequentist Bayesian") print("_______________________________________") print("EPC {0:1.3e} {1:1.3e} " .format(epc_est_fm,epc_est_a)) print("Β± sigma Β± {0:1.3e} Β± {1:1.3e} " .format(epc_est_fm_err, epc_est_a_err)) for i, (gate,EPG) in enumerate(EPG_dic.items()): print("{0:<12}{1:1.3e} {2:1.3e}" .format("EPG "+gate,EPG,EPG*epc_est_a/epc_est_fm)) if show_plot == False: return import matplotlib.pyplot as plt # seems we need to reimport for replot WIP fig, plt = plt.subplots(1, 1) plt.set_ylabel("P(0)") plt.set_xlabel("Cliffords Length") plt.plot(lengths,azt_summary['mean']['AB[0]']*azt_summary['mean']['alpha']**lengths+\ azt_summary['mean']['AB[1]'],'-',color="r") for i_seed in range(num_samples): plt.scatter(lengths, Y[i_seed,:]/shots, label = "data", marker="x",color="grey") plt.set_title(experiment_type +', ' + "qubit: " + str(physical_qubits)\ +', backend: '+backend.name(), fontsize=14); elif experiment_type == "InterleavedRB": p = 'p_tilde' epc_est_a = scale*(1 - azt_summary['mean'][p]) epc_est_a_err = scale* (azt_summary['sd'][p]) # compare LSF and SMC print("Model: Frequentist Bayesian Calibration") print("__________________________________________________________") print("EPC {0:1.3e} {1:1.3e} {2:1.3e}" .format(epc_est_fm,epc_est_a,epc_calib )) print("Β± sigma Β± {0:1.3e} Β± {1:1.3e} " .format(epc_est_fm_err, epc_est_a_err)) if show_plot ==False: return import matplotlib.pyplot as plt # seems we need to reimport for replot WIP fig, plt = plt.subplots(1, 1) plt.set_ylabel("P(0)") plt.set_xlabel("Cliffords Length") for i_seed in range(num_samples): plt.scatter(lengths, Y1[i_seed,:]/shots, label = "data", marker="x",color="r") plt.scatter(lengths, Y2[i_seed,:]/shots, label = "data", marker="+",color="orange") plt.plot(lengths,azt_summary['mean']['AB[0]']*azt_summary['mean']['alpha']**lengths+\ azt_summary['mean']['AB[1]'],'--',color="r") plt.plot(lengths,azt_summary['mean']['AB[0]']*(azt_summary['mean']['alpha']*azt_summary['mean']['p_tilde'])**\ lengths+azt_summary['mean']['AB[1]'],'--',color="orange") plt.legend(("Standard, SMC model", "Interleaved, SMC model")) plt.set_title(experiment_type +', ' + interleaved_gate + str(physical_qubits)\ +', backend: '+backend.name(), fontsize=14); import matplotlib.pyplot as plt # if not yet imported #plt.rcParams["figure.figsize"] = plt.rcParamsDefault["figure.figsize"] # to reset to default plt.rcParams["figure.figsize"] = (8,5) with resmodel: ax = az.plot_posterior(trace, var_names=[p], round_to=4, point_estimate=None, transform = alpha_to_EPC) ax.set_xlim(epc_est_a - 6*epc_est_a_err, epc_est_a + 6*epc_est_a_err) plt.axvline(x=epc_est_fm,color='cyan',ls="-") if epc_calib != np.nan: plt.axvline(x=epc_calib,color='r',ls=":") plt.axvline(x=epc_est_a,color='blue',ls=":") plt.title(experiment_type +', ' + interleaved_gate + " qubit(s):" + str(physical_qubits)\ +', backend: '+backend.name(), fontsize=14) Bayes_legend = "EPC SMC: {0:1.3e} Β± {1:1.3e}".format(epc_est_a, epc_est_a_err) LSF_legend = "EPC LSF: {0:1.3e} Β± {1:1.3e}".format(epc_est_fm, epc_est_fm_err) Cal_legend = "EPC Calibration: {0:1.3e}".format(epc_calib) if epc_calib > 0.0: plt.legend((Bayes_legend, "$Highest\; density\; interval$ HDI", LSF_legend, Cal_legend), fontsize=12 ) else: plt.legend((Bayes_legend, "$Highest\; density\; interval$ HDI", LSF_legend), fontsize=12 ) # obtain EPC from alpha and scale(used by az.plot_posterior) def alpha_to_EPC_from_scale(alpha, scale): return scale*(1-alpha) # guess number of shots def guess_shots(Y): shot_exp = 1 test_shot = np.max(Y) while test_shot > 2**shot_exp: shot_exp += 1 return 2**shot_exp def bayesian_standard_RB_model(): # construct model RB_model = get_bayesian_model(model_type="pooled",Y=Y,shots=shots,m_gates=lengths, mu_AB=[popt_fm[0],popt_fm[2]],cov_AB=[perr_fm[0],perr_fm[2]], alpha_ref=popt_fm[1], alpha_lower=popt_fm[1]-6*perr_fm[1], alpha_upper=min(1.-1.E-6,popt_fm[1]+6*perr_fm[1]), RvsI=None,IvsR=None) return RB_model def bayesian_interleaved_RB_model(): # construct model RB_model = get_bayesian_model("tilde",Y=Y,shots=shots, m_gates=lengths, alpha_ref=popt_fm[1], p_testval= popt_fm[2], alpha_lower=popt_fm[1]-6*perr_fm[1], alpha_upper=min(1.-1.E-6,popt_fm[1]+6*perr_fm[1]), p_lower=popt_fm[2]-6*perr_fm[2], p_upper=min(1.-1.E-6,popt_fm[2]+6*perr_fm[2]), mu_AB=[popt_fm[0],popt_fm[3]],cov_AB=[perr_fm[0],perr_fm[3]], RvsI=RvsI,IvsR=IvsR) return RB_model
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2 pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits) pw_approximation._build() qc = QuantumCircuit(pw_approximation.num_qubits) qc.h(list(range(num_state_qubits))) qc.append(pw_approximation.to_instruction(), qc.qubits) qc.draw(output='mpl')
https://github.com/abbarreto/qiskit4
abbarreto
https://github.com/qiskit-community/community.qiskit.org
qiskit-community
import numpy as np from qiskit import BasicAer from qiskit.tools.visualization import plot_histogram from qiskit.aqua import QuantumInstance, run_algorithm from qiskit.aqua.algorithms import Grover from qiskit.aqua.components.oracles import LogicalExpressionOracle, TruthTableOracle input_3sat = ''' 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 ''' oracle = LogicalExpressionOracle(input_3sat) grover = Grover(oracle) backend = BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1024) result = grover.run(quantum_instance) print(result['result']) plot_histogram(result['measurement']) # Load our saved IBMQ accounts and get the ibmq_16_melbourne backend from qiskit import IBMQ IBMQ.load_account() IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_16_melbourne') from qiskit.compiler import transpile # transpile the circuit for ibmq_16_melbourne grover_compiled = transpile(result['circuit'], backend=backend, optimization_level=3) print('gates = ', grover_compiled.count_ops()) print('depth = ', grover_compiled.depth()) import qiskit qiskit.__qiskit_version__
https://github.com/sebasmos/QuantumVE
sebasmos
import sys sys.path.insert(0,'../') from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.optim.lr_scheduler import StepLR from torch.utils.data import random_split from torch.utils.data import Subset, DataLoader, random_split from torchvision import datasets, transforms import torch.optim as optim from torch.optim.lr_scheduler import StepLR import matplotlib.pyplot as plt import os import numpy as np from sklearn.metrics import confusion_matrix, classification_report import pandas as pd # from MAE code from util.datasets import build_dataset import argparse import util.misc as misc import argparse import datetime import json import numpy as np import os import time from pathlib import Path import torch import torch.backends.cudnn as cudnn from torch.utils.tensorboard import SummaryWriter import timm assert timm.__version__ == "0.3.2" # version check from timm.models.layers import trunc_normal_ from timm.data.mixup import Mixup from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy import util.lr_decay as lrd import util.misc as misc from util.datasets import build_dataset from util.pos_embed import interpolate_pos_embed from util.misc import NativeScalerWithGradNormCount as NativeScaler import models_vit import sys import os import torch import numpy as np import matplotlib.pyplot as plt from PIL import Image import models_mae import torch; print(f'numpy version: {np.__version__}\nCUDA version: {torch.version.cuda} - Torch versteion: {torch.__version__} - device count: {torch.cuda.device_count()}') from engine_finetune import train_one_epoch, evaluate from timm.data import Mixup from timm.utils import accuracy from sklearn.metrics import confusion_matrix, classification_report import seaborn as sns from sklearn.preprocessing import LabelBinarizer from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt from itertools import cycle import numpy as np from sklearn.metrics import precision_score, recall_score, f1_score import torch.optim as optim imagenet_mean = np.array([0.485, 0.456, 0.406]) imagenet_std = np.array([0.229, 0.224, 0.225]) def show_image(image, title=''): # image is [H, W, 3] assert image.shape[2] == 3 plt.imshow(torch.clip((image * imagenet_std + imagenet_mean) * 255, 0, 255).int()) plt.title(title, fontsize=16) plt.axis('off') return def prepare_model(chkpt_dir, arch='mae_vit_large_patch16'): # build model model = getattr(models_mae, arch)() # load model checkpoint = torch.load(chkpt_dir, map_location='cpu') msg = model.load_state_dict(checkpoint['model'], strict=False) print(msg) return model def run_one_image(img, model): x = torch.tensor(img) # make it a batch-like x = x.unsqueeze(dim=0) x = torch.einsum('nhwc->nchw', x) # run MAE loss, y, mask = model(x.float(), mask_ratio=0.75) y = model.unpatchify(y) y = torch.einsum('nchw->nhwc', y).detach().cpu() # visualize the mask mask = mask.detach() mask = mask.unsqueeze(-1).repeat(1, 1, model.patch_embed.patch_size[0]**2 *3) # (N, H*W, p*p*3) mask = model.unpatchify(mask) # 1 is removing, 0 is keeping mask = torch.einsum('nchw->nhwc', mask).detach().cpu() x = torch.einsum('nchw->nhwc', x) # masked image im_masked = x * (1 - mask) # MAE reconstruction pasted with visible patches im_paste = x * (1 - mask) + y * mask # make the plt figure larger plt.rcParams['figure.figsize'] = [24, 24] plt.subplot(1, 4, 1) show_image(x[0], "original") plt.subplot(1, 4, 2) show_image(im_masked[0], "masked") plt.subplot(1, 4, 3) show_image(y[0], "reconstruction") plt.subplot(1, 4, 4) show_image(im_paste[0], "reconstruction + visible") plt.show() # Set the seed for PyTorch torch.manual_seed(42) parser = argparse.ArgumentParser('MAE fine-tuning for image classification', add_help=False) parser.add_argument('--batch_size', default=256, type=int, help='Batch size per GPU (effective batch size is batch_size * accum_iter * # gpus') parser.add_argument('--epochs', default=50, type=int) parser.add_argument('--accum_iter', default=4, type=int, help='Accumulate gradient iterations (for increasing the effective batch size under memory constraints)') # Model parameters parser.add_argument('--model', default='mobilenet_v3', type=str, metavar='MODEL', help='Name of model to train') parser.add_argument('--input_size', default=224, type=int, help='images input size') parser.add_argument('--drop_path', type=float, default=0.1, metavar='PCT', help='Drop path rate (default: 0.1)') # Optimizer parameters parser.add_argument('--clip_grad', type=float, default=None, metavar='NORM', help='Clip gradient norm (default: None, no clipping)') parser.add_argument('--weight_decay', type=float, default=0.05, help='weight decay (default: 0.05)') parser.add_argument('--lr', type=float, default=None, metavar='LR', help='learning rate (absolute lr)') parser.add_argument('--blr', type=float, default=5e-4, metavar='LR', help='base learning rate: absolute_lr = base_lr * total_batch_size / 256') parser.add_argument('--layer_decay', type=float, default=0.65, help='layer-wise lr decay from ELECTRA/BEiT') parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR', help='lower lr bound for cyclic schedulers that hit 0') parser.add_argument('--warmup_epochs', type=int, default=5, metavar='N', help='epochs to warmup LR') # Augmentation parameters parser.add_argument('--color_jitter', type=float, default=None, metavar='PCT', help='Color jitter factor (enabled only when not using Auto/RandAug)') parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME', help='Use AutoAugment policy. "v0" or "original". " + "(default: rand-m9-mstd0.5-inc1)'), parser.add_argument('--smoothing', type=float, default=0.1, help='Label smoothing (default: 0.1)') # * Random Erase params parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT', help='Random erase prob (default: 0.25)') parser.add_argument('--remode', type=str, default='pixel', help='Random erase mode (default: "pixel")') parser.add_argument('--recount', type=int, default=1, help='Random erase count (default: 1)') parser.add_argument('--resplit', action='store_true', default=False, help='Do not random erase first (clean) augmentation split') # * Mixup params parser.add_argument('--mixup', type=float, default=0.8, help='mixup alpha, mixup enabled if > 0.') parser.add_argument('--cutmix', type=float, default=1.0, help='cutmix alpha, cutmix enabled if > 0.') parser.add_argument('--cutmix_minmax', type=float, nargs='+', default=None, help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)') parser.add_argument('--mixup_prob', type=float, default=1.0, help='Probability of performing mixup or cutmix when either/both is enabled') parser.add_argument('--mixup_switch_prob', type=float, default=0.5, help='Probability of switching to cutmix when both mixup and cutmix enabled') parser.add_argument('--mixup_mode', type=str, default='batch', help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"') # * Finetuning params parser.add_argument('--finetune', default='mae_pretrain_vit_base.pth', help='finetune from checkpoint') parser.add_argument('--global_pool', action='store_true') parser.set_defaults(global_pool=True) parser.add_argument('--cls_token', action='store_false', dest='global_pool', help='Use class token instead of global pool for classification') # Dataset parameters parser.add_argument('--data_path', default='/media/enc/vera1/sebastian/data/ABGQI_mel_spectrograms', type=str, help='dataset path') parser.add_argument('--nb_classes', default=5, type=int, help='number of the classification types') parser.add_argument('--output_dir', default='quinn_5_classes', help='path where to save, empty for no saving') parser.add_argument('--log_dir', default='/media/enc/vera1/sebastian/codes/classifiers/mae/MobileNet/output_dir', help='path where to tensorboard log') parser.add_argument('--device', default='cuda', help='device to use for training / testing') parser.add_argument('--seed', default=0, type=int) parser.add_argument('--resume', default="/media/enc/vera1/sebastian/codes/classifiers/mae/MobileNet/quinn_5_classes/checkpoint-49.pth", help='resume from checkpoint') parser.add_argument('--start_epoch', default=0, type=int, metavar='N', help='start epoch') parser.add_argument('--eval',default=True, action='store_true', help='Perform evaluation only') parser.add_argument('--dist_eval', action='store_true', default=False, help='Enabling distributed evaluation (recommended during training for faster monitor') parser.add_argument('--num_workers', default=10, type=int) parser.add_argument('--pin_mem', action='store_true', help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem') parser.set_defaults(pin_mem=True) # distributed training parameters parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes') parser.add_argument('--local_rank', default=-1, type=int) parser.add_argument('--dist_on_itp', action='store_true') parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training') args, unknown = parser.parse_known_args() misc.init_distributed_mode(args) print("{}".format(args).replace(', ', ',\n')) os.makedirs(args.output_dir, exist_ok=True) device = torch.device(args.device) import torchvision.models as models import torch.nn as nn import torch def count_parameters(model, message=""): trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad) total_params = sum(p.numel() for p in model.parameters()) print(f"{message} Trainable params: {trainable_params} of {total_params}") # Load pre-trained MobileNetV3 model frozen_model = models.mobilenet_v3_large(pretrained=True, progress=True) # Freeze all layers except the classifier for param in frozen_model.parameters(): param.requires_grad = False count_parameters(frozen_model, "BEFORE") # Modify the classifier to fit the new number of classes num_classes = args.nb_classes in_features = frozen_model.classifier[-1].in_features frozen_model.classifier[-1] = nn.Linear(in_features, num_classes) num_layers_unfreeze = 50 # Unfreeze the last layer for fine-tuning for param in frozen_model.classifier[-num_layers_unfreeze:].parameters(): # if not isinstance(param, nn.BatchNorm2d):# not working anyway.. param.requires_grad = True import copy stage_1_model = copy.deepcopy(frozen_model) count_parameters(stage_1_model, "AFTER") # # Create random input data # batch_size = 1 # channels = 3 # height = 224 # width = 224 # random_input = torch.randn(batch_size, channels, height, width) # # Forward pass through the model # output = stage_1_model(random_input) # print("Output shape:", output.shape) misc.init_distributed_mode(args) # print('job dir: {}'.format(os.path.dirname(os.path.realpath(__file__)))) print("{}".format(args).replace(', ', ',\n')) device = torch.device(args.device) seed = args.seed + misc.get_rank() torch.manual_seed(seed) np.random.seed(seed) cudnn.benchmark = True dataset_train = build_dataset(is_train=True, args=args) dataset_val = build_dataset(is_train=False, args=args) if True: # args.distributed: num_tasks = misc.get_world_size() global_rank = misc.get_rank() sampler_train = torch.utils.data.DistributedSampler( dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True ) print("Sampler_train = %s" % str(sampler_train)) if args.dist_eval: if len(dataset_val) % num_tasks != 0: print('Warning: Enabling distributed evaluation with an eval dataset not divisible by process number. ' 'This will slightly alter validation results as extra duplicate entries are added to achieve ' 'equal num of samples per-process.') sampler_val = torch.utils.data.DistributedSampler( dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=True) # shuffle=True to reduce monitor bias else: sampler_val = torch.utils.data.SequentialSampler(dataset_val) else: sampler_train = torch.utils.data.RandomSampler(dataset_train) sampler_val = torch.utils.data.SequentialSampler(dataset_val) if global_rank == 0 and args.log_dir is not None and not args.eval: os.makedirs(args.log_dir, exist_ok=True) log_writer = SummaryWriter(log_dir=args.log_dir) else: log_writer = None data_loader_train = torch.utils.data.DataLoader( dataset_train, sampler=sampler_train, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True, ) data_loader_val = torch.utils.data.DataLoader( dataset_val, sampler=sampler_val, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False ) mixup_fn = None mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None if mixup_active: print("Mixup is activated!") mixup_fn = Mixup( mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax, prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode, label_smoothing=args.smoothing, num_classes=args.nb_classes) # model = models_vit.__dict__[args.model]( # num_classes=args.nb_classes, # drop_path_rate=args.drop_path, # global_pool=args.global_pool, # ) model = stage_1_model if args.finetune and not args.eval: print("args.finetune and not args.eval") checkpoint = torch.load(args.finetune, map_location='cpu') print("Load pre-trained checkpoint from: %s" % args.finetune) checkpoint_model = checkpoint['model'] state_dict = model.state_dict() for k in ['head.weight', 'head.bias']: if k in checkpoint_model and checkpoint_model[k].shape != state_dict[k].shape: print(f"Removing key {k} from pretrained checkpoint") del checkpoint_model[k] # interpolate position embedding interpolate_pos_embed(model, checkpoint_model) # load pre-trained model msg = model.load_state_dict(checkpoint_model, strict=False) print(msg) if args.global_pool: assert set(msg.missing_keys) == {'head.weight', 'head.bias', 'fc_norm.weight', 'fc_norm.bias'} else: assert set(msg.missing_keys) == {'head.weight', 'head.bias'} # manually initialize fc layer trunc_normal_(model.head.weight, std=2e-5) model.to(device) model_without_ddp = model n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) print("Model = %s" % str(model_without_ddp)) print('number of params (M): %.2f' % (n_parameters / 1.e6)) eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size() if args.lr is None: # only base_lr is specified args.lr = args.blr * eff_batch_size / 256 print("base lr: %.2e" % (args.lr * 256 / eff_batch_size)) print("actual lr: %.2e" % args.lr) print("accumulate grad iterations: %d" % args.accum_iter) print("effective batch size: %d" % eff_batch_size) if args.distributed: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu]) model_without_ddp = model.module optimizer = optim.Adam(model.parameters(), lr=args.lr)#SEB # optimizer = torch.optim.AdamW(param_groups, lr=args.lr) loss_scaler = NativeScaler() if mixup_fn is not None: # smoothing is handled with mixup label transform criterion = SoftTargetCrossEntropy() elif args.smoothing > 0.: criterion = LabelSmoothingCrossEntropy(smoothing=args.smoothing) else: criterion = torch.nn.CrossEntropyLoss() print("criterion = %s" % str(criterion)) misc.load_model(args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler) if args.eval: test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") # exit(0) train = False if train: print(f"Start training for {args.epochs} epochs with batch size of {args.batch_size}") start_time = time.time() max_accuracy = 0.0 for epoch in range(args.start_epoch, args.epochs): if args.distributed: data_loader_train.sampler.set_epoch(epoch) train_stats = train_one_epoch( model, criterion, data_loader_train, optimizer, device, epoch, loss_scaler, args.clip_grad, mixup_fn, log_writer=log_writer, args=args ) if args.output_dir: misc.save_model( args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler, epoch=epoch) test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") max_accuracy = max(max_accuracy, test_stats["acc1"]) print(f'Max accuracy: {max_accuracy:.2f}%') if log_writer is not None: log_writer.add_scalar('perf/test_acc1', test_stats['acc1'], epoch) log_writer.add_scalar('perf/test_acc5', test_stats['acc5'], epoch) log_writer.add_scalar('perf/test_loss', test_stats['loss'], epoch) log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, **{f'test_{k}': v for k, v in test_stats.items()}, 'epoch': epoch, 'n_parameters': n_parameters} if args.output_dir and misc.is_main_process(): if log_writer is not None: log_writer.flush() with open(os.path.join(args.output_dir, "log.txt"), mode="a", encoding="utf-8") as f: f.write(json.dumps(log_stats) + "\n") total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) print('Training time {}'.format(total_time_str)) EXPERIMENT_NAME = "mobileNet" saving_model = f"{EXPERIMENT_NAME}/models" os.makedirs(saving_model, exist_ok = True) os.makedirs(EXPERIMENT_NAME, exist_ok=True) if args.eval: test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") @torch.no_grad() def evaluate_test(data_loader, model, device): criterion = torch.nn.CrossEntropyLoss() metric_logger = misc.MetricLogger(delimiter=" ") header = 'Test:' # switch to evaluation mode model.eval() all_predictions = [] all_labels = [] for batch in metric_logger.log_every(data_loader, 10, header): images = batch[0] target = batch[-1] images = images.to(device, non_blocking=True) target = target.to(device, non_blocking=True) # compute output with torch.cuda.amp.autocast(): output = model(images) loss = criterion(output, target)# pred = output.argmax(dim=1) all_predictions.append(pred.cpu().numpy())# ADDED all_labels.append(target.cpu().numpy())# ADDED acc1, acc5 = accuracy(output, target, topk=(1, 5)) batch_size = images.shape[0] metric_logger.update(loss=loss.item()) metric_logger.meters['acc1'].update(acc1.item(), n=batch_size) metric_logger.meters['acc5'].update(acc5.item(), n=batch_size) # import pdb;pdb.set_trace() all_predictions = np.array(all_predictions)#.squeeze(0) all_labels = np.array(all_labels)#.squeeze(0) # gather the stats from all processes metric_logger.synchronize_between_processes() print('* Acc@1 {top1.global_avg:.3f} Acc@5 {top5.global_avg:.3f} loss {losses.global_avg:.3f}' .format(top1=metric_logger.acc1, top5=metric_logger.acc5, losses=metric_logger.loss)) # return return {k: meter.global_avg for k, meter in metric_logger.meters.items()}, np.concatenate(all_predictions, axis=0), np.concatenate(all_labels, axis=0) metrics, all_predictions, all_labels = evaluate_test(data_loader_val, model, device) # print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") all_predictions metrics all_predictions unique_classes = np.unique(np.concatenate((all_labels, all_predictions))) unique_classes confusion_mat = confusion_matrix(all_labels, all_predictions, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) conf_matrix unique_classes = np.unique(np.concatenate((all_labels, all_predictions))) confusion_mat = confusion_matrix(all_labels, all_predictions, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) # Plot the confusion matrix using seaborn plt.figure(figsize=(5, 4)) ax = sns.heatmap(conf_matrix, annot=True, fmt='.1f', cmap=sns.cubehelix_palette(as_cmap=True), linewidths=0.1, cbar=True) # Set labels and ticks ax.set_xlabel('Predicted Labels') ax.set_ylabel('True Labels') # Set x and y ticks using the unique classes ax.set_xticks(range(len(unique_classes))) ax.set_yticks(range(len(unique_classes))) # Set x and y ticks at the center of the cells ax.set_xticks([i + 0.5 for i in range(len(unique_classes))]) ax.set_yticks([i + 0.5 for i in range(len(unique_classes))]) plt.show() def plot_multiclass_roc_curve(all_labels, all_predictions, EXPERIMENT_NAME="."): # Step 1: Label Binarization label_binarizer = LabelBinarizer() y_onehot = label_binarizer.fit_transform(all_labels) all_predictions_hot = label_binarizer.transform(all_predictions) # Step 2: Calculate ROC curves fpr = dict() tpr = dict() roc_auc = dict() unique_classes = range(y_onehot.shape[1]) for i in unique_classes: fpr[i], tpr[i], _ = roc_curve(y_onehot[:, i], all_predictions_hot[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Step 3: Plot ROC curves fig, ax = plt.subplots(figsize=(8, 8)) # Micro-average ROC curve fpr_micro, tpr_micro, _ = roc_curve(y_onehot.ravel(), all_predictions_hot.ravel()) roc_auc_micro = auc(fpr_micro, tpr_micro) plt.plot( fpr_micro, tpr_micro, label=f"micro-average ROC curve (AUC = {roc_auc_micro:.2f})", color="deeppink", linestyle=":", linewidth=4, ) # Macro-average ROC curve all_fpr = np.unique(np.concatenate([fpr[i] for i in unique_classes])) mean_tpr = np.zeros_like(all_fpr) for i in unique_classes: mean_tpr += np.interp(all_fpr, fpr[i], tpr[i]) mean_tpr /= len(unique_classes) fpr_macro = all_fpr tpr_macro = mean_tpr roc_auc_macro = auc(fpr_macro, tpr_macro) plt.plot( fpr_macro, tpr_macro, label=f"macro-average ROC curve (AUC = {roc_auc_macro:.2f})", color="navy", linestyle=":", linewidth=4, ) # Individual class ROC curves with unique colors colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_classes))) for class_id, color in zip(unique_classes, colors): plt.plot( fpr[class_id], tpr[class_id], color=color, label=f"ROC curve for Class {class_id} (AUC = {roc_auc[class_id]:.2f})", linewidth=2, ) plt.plot([0, 1], [0, 1], color='gray', linestyle='--', linewidth=2) # Add diagonal line for reference plt.axis("equal") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("Extension of Receiver Operating Characteristic\n to One-vs-Rest multiclass") plt.legend() plt.savefig(f'{EXPERIMENT_NAME}/roc_curve.png') plt.show() # Example usage: plot_multiclass_roc_curve(all_labels, all_predictions, EXPERIMENT_NAME) # def visualize_predictions(model, val_loader, device, type_label=None, dataset_type=1, unique_classes=np.array([0, 1, 2, 3, 4, 5, 6])): # criterion = torch.nn.CrossEntropyLoss() # metric_logger = misc.MetricLogger(delimiter=" ") # header = 'Test:' # # switch to evaluation mode # model.eval() # all_predictions = [] # all_labels = [] # for batch in metric_logger.log_every(val_loader, 10, header): # images = batch[0] # target = batch[-1] # images = images.to(device, non_blocking=True) # target = target.to(device, non_blocking=True) # # compute output # with torch.cuda.amp.autocast(): # output = model(images) # loss = criterion(output, target)# # pred = output.argmax(dim=1) # all_predictions.append(pred.cpu().numpy())# ADDED # all_labels.append(target.cpu().numpy())# ADDED # acc1, acc5 = accuracy(output, target, topk=(1, 5)) # batch_size = images.shape[0] # metric_logger.update(loss=loss.item()) # metric_logger.meters['acc1'].update(acc1.item(), n=batch_size) # metric_logger.meters['acc5'].update(acc5.item(), n=batch_size) # all_predictions = np.array(all_predictions)#.squeeze(0) # all_labels = np.array(all_labels)#.squeeze(0) # if type_label is None: # type_label = unique_classes # # Create a 4x4 grid for visualization # num_rows = 4 # num_cols = 4 # plt.figure(figsize=(12, 12)) # for i in range(num_rows * num_cols): # plt.subplot(num_rows, num_cols, i + 1) # idx = np.random.randint(len(all_labels)) # import pdb;pdb.set_trace() # plt.imshow(images[idx].cpu().numpy().squeeze(), cmap='gray') # # Use the class names instead of numeric labels for Fashion MNIST # if dataset_type == 1: # class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] # predicted_class = class_names[all_predictions[idx]] # actual_class = class_names[all_labels[idx]] # else: # predicted_class = all_predictions[idx] # actual_class = all_labels[idx] # plt.title(f'Pred: {predicted_class}\nActual: {actual_class}') # plt.axis('off') # plt.tight_layout() # plt.show() # visualize_predictions(model, data_loader_val, device, dataset_type=2, unique_classes=unique_classes) unique_classes report = classification_report(all_labels, all_predictions, target_names=unique_classes,output_dict=True)# Mostrar el informe de df = pd.DataFrame(report).transpose() df.to_csv(os.path.join(EXPERIMENT_NAME, "confusion_matrix.csv")) print(df) df # Calculate precision, recall, and specificity (micro-averaged) precision = precision_score(all_labels, all_predictions, average='micro') recall = recall_score(all_labels, all_predictions, average='micro') # Calculate true negatives, false positives, and specificity (micro-averaged) tn = np.sum((all_labels != 1) & (all_predictions != 1)) fp = np.sum((all_labels != 1) & (all_predictions == 1)) specificity = tn / (tn + fp) # Calculate F1 score (weighted average) f1 = f1_score(all_labels, all_predictions, average='weighted') evaluation_metrics = { "Acc1": metrics['acc1'], # Add acc1 metric "Acc5": metrics['acc5'], # Add acc5 metric "loss": metrics['loss'], # Add acc5 metric "F1 Score": [f1], "Precision": [precision], "Recall": [recall], "Specificity": [specificity] } evaluation_metrics # Create a DataFrame from the dictionary df = pd.DataFrame(evaluation_metrics) # Save the DataFrame to a CSV file df.to_csv(f'{EXPERIMENT_NAME}/evaluation_metrics_for_table.csv', index=False) df
https://github.com/sintefmath/QuantumPoker
sintefmath
import sys IN_COLAB = 'google.colab' in sys.modules if IN_COLAB: from google.colab import output output.enable_custom_widget_manager() !pip install qiskit !pip install ipympl !rm -rf /content/QuantumPoker/ !git clone https://github.com/sintefmath/QuantumPoker sys.path.append('/content/QuantumPoker/Python') sys.path.append('/content/QuantumPoker') get_ipython().magic('matplotlib ipympl') else: get_ipython().magic('matplotlib notebook') from os.path import dirname, abspath import sys sys.path.append(dirname(abspath(''))) from PokerGame import PokerGame import matplotlib.pyplot as plt from numpy import array, count_nonzero dealer = 0 nPlayers = 3 gameHasRun = False deckOfGates = {"H": nPlayers, "X": nPlayers, "ZH": nPlayers, "CX": nPlayers} money = array([100 for i in range(nPlayers)]) names = ["James", "Lilly", "Harry"] if not count_nonzero(money==0) == (nPlayers-1): if gameHasRun: dealer = (dealer + 1) % nPlayers if 0 in money: toDelete=nonzero(money==0)[0] for i in flip(toDelete): if i < dealer: dealer -= 1 names = delete(names, nonzero(money==0)[0]) money = delete(money, nonzero(money==0)[0]) nPlayers = money.shape[0] gameHasRun = True pokerGame = PokerGame(deckOfGates, nPlayers, money, names = names, smallBlind=5, smallBlindPlayer=dealer, enableEntanglement=True)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Determines a commutation library over the unparameterizable standard gates, i.e. a dictionary for each pair of parameterizable standard gates and all qubit overlaps that maps to either True or False, depending on the present commutation relation. """ import itertools from functools import lru_cache from typing import List from qiskit.circuit.commutation_checker import _get_relative_placement, _order_operations from qiskit.circuit import Gate, CommutationChecker import qiskit.circuit.library.standard_gates as stdg from qiskit.dagcircuit import DAGOpNode @lru_cache(None) def _get_unparameterizable_gates() -> List[Gate]: """Retrieve a list of non-parmaterized gates with up to 3 qubits, using the python inspection module Return: A list of non-parameterized gates to be considered in the commutation library """ # These two gates may require a large runtime in later processing steps # blocked_types = [C3SXGate, C4XGate] gates = list(stdg.get_standard_gate_name_mapping().values()) return [g for g in gates if len(g.params) == 0] def _generate_commutation_dict(considered_gates: List[Gate] = None) -> dict: """Compute the commutation relation of considered gates Args: considered_gates List[Gate]: a list of gates between which the commutation should be determined Return: A dictionary that includes the commutation relation for each considered pair of operations and each relative placement """ commutations = {} cc = CommutationChecker() for gate0 in considered_gates: node0 = DAGOpNode(op=gate0, qargs=list(range(gate0.num_qubits)), cargs=[]) for gate1 in considered_gates: # only consider canonical entries ( ( first_gate, _, _, ), (second_gate, _, _), ) = _order_operations(gate0, None, None, gate1, None, None) if (first_gate, second_gate) != (gate0, gate1) and gate0.name != gate1.name: continue # enumerate all relative gate placements with overlap between gate qubits gate_placements = itertools.permutations( range(gate0.num_qubits + gate1.num_qubits - 1), gate0.num_qubits ) gate_pair_commutation = {} for permutation in gate_placements: permutation_list = list(permutation) gate1_qargs = [] # use idx_non_overlapping qubits to represent qubits on g1 that are not connected to g0 next_non_overlapping_qubit_idx = gate0.num_qubits for i in range(gate1.num_qubits): if i in permutation_list: gate1_qargs.append(permutation_list.index(i)) else: gate1_qargs.append(next_non_overlapping_qubit_idx) next_non_overlapping_qubit_idx += 1 node1 = DAGOpNode(op=gate1, qargs=gate1_qargs, cargs=[]) # replace non-overlapping qubits with None to act as a key in the commutation library relative_placement = _get_relative_placement(node0.qargs, node1.qargs) if not gate0.is_parameterized() and not gate1.is_parameterized(): # if no gate includes parameters, compute commutation relation using # matrix multiplication op1 = node0.op qargs1 = node0.qargs cargs1 = node0.cargs op2 = node1.op qargs2 = node1.qargs cargs2 = node1.cargs commutation_relation = cc.commute( op1, qargs1, cargs1, op2, qargs2, cargs2, max_num_qubits=4 ) else: pass # TODO gate_pair_commutation[relative_placement] = commutation_relation commutations[gate0.name, gate1.name] = gate_pair_commutation return commutations def _simplify_commuting_dict(commuting_dict: dict) -> dict: """Compress some of the commutation library entries Args: commuting_dict (dict): A commutation dictionary Return: commuting_dict (dict): A commutation dictionary with simplified entries """ # Remove relative placement key if commutation is independent of relative placement for ops in commuting_dict.keys(): gates_commutations = set(commuting_dict[ops].values()) if len(gates_commutations) == 1: commuting_dict[ops] = next(iter(gates_commutations)) return commuting_dict def _dump_commuting_dict_as_python( commutations: dict, file_name: str = "../_standard_gates_commutations.py" ): """Write commutation dictionary as python object to ./qiskit/circuit/_standard_gates_commutations.py. Args: commutations (dict): a dictionary that includes the commutation relation for each considered pair of operations """ with open(file_name, "w") as fp: dir_str = "standard_gates_commutations = {\n" for k, v in commutations.items(): if not isinstance(v, dict): dir_str += ' ("{}", "{}"): {},\n'.format(*k, v) else: dir_str += ' ("{}", "{}"): {{\n'.format(*k) for entry_key, entry_val in v.items(): dir_str += " {}: {},\n".format(entry_key, entry_val) dir_str += " },\n" dir_str += "}\n" fp.write(dir_str.replace("'", "")) if __name__ == "__main__": cgates = [ g for g in _get_unparameterizable_gates() if g.name not in ["reset", "measure", "delay"] ] commutation_dict = _generate_commutation_dict(considered_gates=cgates) commutation_dict = _simplify_commuting_dict(commutation_dict) _dump_commuting_dict_as_python(commutation_dict)
https://github.com/primaryobjects/oracle
primaryobjects
from qiskit import QuantumCircuit from qiskit.circuit.classicalfunction.classicalfunction import ClassicalFunction def oracle(logic, n): ''' Returns a quantum circuit that implementes the logic for n qubits. Parameters: logic: a Python function using the format below. def oracle_func(x1: Int1, x2: Int1, x3: Int1) -> Int1:\n return (x1 and not x2 and not x3) n: the number of qubits in the circuit. ''' # Convert the logic to a quantum circuit. formula = ClassicalFunction(logic) fc = formula.synth() # Convert the quantum circuit to a quantum program. qc = QuantumCircuit(n+1) qc.compose(fc, inplace=True) print(qc.draw()) # Convert the oracle to a gate. gate = qc.to_gate() gate.name = "oracle" return gate
https://github.com/pedroripper/qiskit_tutoriais
pedroripper
from qiskit import * %matplotlib inline import numpy as np qc = QuantumCircuit(2,2) qc.rx(np.pi/2,0) qc.z(0) qc.draw(output='mpl') qc2 = QuantumCircuit(2,2) qc2.z(0) qc2.rx(-np.pi/2,0) qc2.draw(output='mpl')
https://github.com/AasthaShayla/Qiskit-Teleportation
AasthaShayla
from qiskit import* # Loading your IBM Quantum account(s) provider = IBMQ.load_account() qc=QuantumCircuit(1,1) from qiskit.tools.visualization import plot_bloch_multivector qc.x(0) sim=Aer.get_backend('statevector_simulator') result=execute(qc,backend=sim).result() sv=result.get_statevector() print(sv) qc.draw() plot_bloch_multivector(sv) qc.measure(range(1),range(1)) backend=Aer.get_backend('qasm_simulator') result=execute(qc,backend=backend).result() count=result.get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(count) s=Aer.get_backend('unitary_simulator') result=execute(qc,backend=s).result() unitary=result.get_unitary() print(unitary)
https://github.com/JessicaJohnBritto/Quantum-Computing-and-Information
JessicaJohnBritto
# Do the necessary imports import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ from qiskit.visualization import plot_histogram, plot_bloch_multivector ### Creating 3 qubit and 2 classical bits in each separate register qr = QuantumRegister(3) crz = ClassicalRegister(1) crx = ClassicalRegister(1) teleportation_circuit = QuantumCircuit(qr, crz, crx) ### A third party eve helps to create an entangled state def create_bell_pair(qc, a, b): qc.h(a) qc.cx(a, b) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.draw() def alice_gates(qc, a, b): qc.cx(a, b) qc.h(a) teleportation_circuit.barrier() alice_gates(teleportation_circuit, 0, 1) teleportation_circuit.draw() def measure_and_send(qc, a, b): qc.barrier() qc.measure(a,0) qc.measure(b,1) teleportation_circuit.barrier() measure_and_send(teleportation_circuit, 0, 1) teleportation_circuit.draw() def bob_gates(qc, qubit, crz, crx): qc.x(qubit).c_if(crx, 1) qc.z(qubit).c_if(crz, 1) teleportation_circuit.barrier() bob_gates(teleportation_circuit, 2, crz, crx) teleportation_circuit.draw() from qiskit.extensions import Initialize import math qc = QuantumCircuit(1) initial_state = [0,1] init_gate = Initialize(initial_state) # qc.append(initialize_qubit, [0]) qr = QuantumRegister(3) # Protocol uses 3 qubits crz = ClassicalRegister(1) # and 2 classical registers crx = ClassicalRegister(1) qc = QuantumCircuit(qr, crz, crx) # First, let's initialise Alice's q0 qc.append(init_gate, [0]) qc.barrier() # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) # Alice then sends her classical bits to Bob measure_and_send(qc, 0, 1) # Bob decodes qubits bob_gates(qc, 2, crz, crx) qc.draw() backend = BasicAer.get_backend('statevector_simulator') out_vector = execute(qc, backend).result().get_statevector() plot_bloch_multivector(out_vector) inverse_init_gate = init_gate.gates_to_uncompute() qc.append(inverse_init_gate, [2]) qc.draw() cr_result = ClassicalRegister(1) qc.add_register(cr_result) qc.measure(2,2) qc.draw() backend = BasicAer.get_backend('qasm_simulator') counts = execute(qc, backend, shots=1024).result().get_counts() plot_histogram(counts) def bob_gates(qc, a, b, c): qc.cz(a, c) qc.cx(b, c) qc = QuantumCircuit(3,1) # First, let's initialise Alice's q0 qc.append(init_gate, [0]) qc.barrier() # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) qc.barrier() # Alice sends classical bits to Bob bob_gates(qc, 0, 1, 2) # We undo the initialisation process qc.append(inverse_init_gate, [2]) # See the results, we only care about the state of qubit 2 qc.measure(2,0) # View the results: qc.draw() from qiskit import IBMQ IBMQ.save_account('### IMB TOKEN ') IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() from qiskit.providers.ibmq import least_busy backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and not b.configuration().simulator and b.status().operational==True)) job_exp = execute(qc, backend=backend, shots=8192) exp_result = job_exp.result() exp_measurement_result = exp_result.get_counts(qc) print(exp_measurement_result) plot_histogram(exp_measurement_result) error_rate_percent = sum([exp_measurement_result[result] for result in exp_measurement_result.keys() if result[0]=='1']) \ * 100./ sum(list(exp_measurement_result.values())) print("The experimental error rate : ", error_rate_percent, "%")
https://github.com/MonitSharma/qiskit-projects
MonitSharma
from functions import BinPacking, BinPackingNewApproach, new_eq_optimal, get_figure, interpret, eval_constrains from functions import mapping_cost, cost_func, qaoa_circuit, check_best_sol from qiskit.algorithms import QAOA, NumPyMinimumEigensolver from qiskit_optimization.algorithms import CplexOptimizer, MinimumEigenOptimizer from qiskit.algorithms.optimizers import COBYLA import numpy as np from qiskit_optimization.problems.constraint import ConstraintSense import matplotlib.pyplot as plt from scipy.optimize import minimize from qiskit import Aer backend = Aer.get_backend("qasm_simulator") #np.random.seed(1) num_items = 4 # number of items num_bins = num_items # maximum number of bins max_weight = 15 # max weight of a bin cases = 1 solutions_new = {} optimal_new = [] ratio_new = []; new =[] result_classical = []; result_qaoa_new = [] check_const = [] weights=[] qaoa = MinimumEigenOptimizer(QAOA(optimizer=COBYLA(maxiter=100), reps=1, quantum_instance=backend)) for i in range(cases): # Testing 5 different randomly selected configurations of the problem print(f"----------- Case {i+1} -------------") weights.append(np.random.randint(1, max_weight, num_items)) # Randomly picking the item weight qubo_new = BinPackingNewApproach(num_items, num_bins, weights[-1], max_weight, alpha=1, simplification=True) qubo_classical, qp = BinPacking(num_items, num_bins, weights[-1], max_weight, simplification=True) result_classical.append(CplexOptimizer().solve(qubo_classical)) optimal_new.append(new_eq_optimal(qubo_new, qubo_classical)) result_qaoa_new.append(qaoa.solve(qubo_new)) solutions_new = result_qaoa_new[-1].fval new.append(solutions_new) check_const.append(eval_constrains(qp, result_qaoa_new[-1].x, max_weight)) print(check_const[-1]) print(f" The percetage of positive cases is {100*np.sum(check_const)/cases} %") for i in range(len(result_classical)): fig = get_figure(interpret(result_classical[i].x, weights[i], max_weight, num_items, num_bins, simplify=True), weights[i], max_weight, title=f"-------Case {i+1}-----") fig = get_figure(interpret(result_qaoa_new[i].x, weights[i], max_weight, num_items, num_bins, simplify=True), weights[i], max_weight, title="New") n = 50 alpha = np.linspace(0, 2*np.pi, n) beta = np.linspace(0, np.pi, n) map_cost_10 = mapping_cost(alpha, beta, qubo_new, n = 10) map_cost_20 = mapping_cost(alpha, beta, qubo_new, n = 20) fig, ax = plt.subplots(1,2, figsize=(10,10)) ax[0].imshow(np.log(map_cost_10)) ax[1].imshow(np.log(map_cost_20)) for i in range(2): # ax[i].set_xticks([0,9,19], ["0", r"$\pi/2$", r"$\pi$"]) # ax[i].set_yticks([0,9,19], ["0", r"$\pi$", r"2$\pi$"]) ax[i].set_xlabel(r"$\beta$", fontsize=22) ax[i].set_ylabel(r"$\alpha$", fontsize=22) p = 4 x0 = np.random.rand(p*2) circuit = qaoa_circuit(qubo_new, p=p) objective = qubo_new.objective num_evals = 20 fmin = minimize(cost_func, x0, args = (circuit, objective, num_evals), method="COBYLA") best_sol = check_best_sol(fmin.x, circuit, qp, max_weight, n=10) print(f" minimum my cost_fun {best_sol}, minimum with cplex {result_qaoa_new[-1].x}") fig = get_figure(interpret(np.array(best_sol), weights[-1], max_weight, num_items, num_bins, simplify=True), weights[-1], max_weight, title=f"-------Case {i+1}-----") best_sol
https://github.com/quantum-kittens/quantum-computing-basics
quantum-kittens
!pip install qiskit from IPython.display import clear_output clear_output() from qiskit import * import math import numpy as np import random import itertools teas = ['black', 'green'] mild_spices = ['cardamom (elaichi)', 'fennel seeds (saunf)', 'star anise', 'bay leaves', 'cloves (laung)', 'cinnamon', 'nutmeg', 'saffron (kesar)', 'vanilla bean/extract', 'holy basil (tulsi)'] zesty_spices = [ 'ginger (adrak)', 'black peppercorns', 'white peppercorns', 'cumin seeds (zeera)', 'allspice', 'carom seeds (ajwain)', 'turmeric (haldi)', 'paprika (lal mirch)'] herbs = ['peppermint', 'lemongrass', 'licorice root', 'chamomile', 'spearmint', 'coriander', 'lavender' ] misc_flavors = ['orange peel', 'rose petals', 'lemon', 'almond shavings/extract', 'cocoa', 'coconut butter', 'jasmine'] def which_tea(): # creates the Bell state (|01> + |10>)/sqrt(2) to choose between black and green tea circ = QuantumCircuit(2,2) # create a quantum circuit with 2 qubits and 2 classical bits circ.h(0) # Hadamard gate on qubit 0 circ.cx(0,1) # controlled x with qubit 0 as control and qubit 1 as target circ.x(0) # x on qubit 0 circ.measure([0,1],[0,1]) # each qubit is measured, and the total outcome is either 01 or 10 job = qiskit.execute(circ, qiskit.BasicAer.get_backend('qasm_simulator') ) # run on qasm_simulator result = job.result().get_counts() # result is a dict, with key = classical bit outcomes, value = number of counts max_res = max(result, key=result.get) # find the result with the highest count return teas[int(max_res,2)-1] #convert to decimal def run_QuantumCirc(n): # creates and runs a quantum circuit with a Hadamard operating on each qubit qr = qiskit.QuantumRegister(n) # create quantum register with n qubits cr = qiskit.ClassicalRegister(n) # create classical register with n bits circ = qiskit.QuantumCircuit(qr, cr) # create circuit with the two registers circ.h(qr) # perform Hadamard on each qubit circ.measure(qr,cr) # each qubit is measured, and the outcome for one qubit is either 0 or 1 job = qiskit.execute(circ, qiskit.BasicAer.get_backend('qasm_simulator') ) result = job.result().get_counts() return result def select_ingredients(category): # runs a quantum circuit to select the number of ingredients in a category num_choices = len(category) if math.log(num_choices,2)%int(math.log(num_choices,2)) == 0: # checks whether log(num_choices) to the base 2 is a whole number n = int(math.log(num_choices,2)) # n = number of qubits result = run_QuantumCirc(n) max_res = max(result, key=result.get) else: n = int(math.log(num_choices,2))+1 # adds 1 to log(N) to the base 2 to get total number of qubits needed result = run_QuantumCirc(n) max_res = max(result, key=result.get) while(int(max_res,2) > num_choices-1): # find max that is less than num_choices result.pop(str(max_res)) max_res = max(result, key=result.get) selections = [] random.shuffle(category) # randomly shuffles the category list for i in range(int(max_res,2)+1): # int(max_res,2)+1 is in decimal; it's the number of ingredients in the category that you will be using selections.append(category[i]) # returns the first int(max_res,2)+1 entries in the shuffled list return selections def ingredient_compatibilities(final_ingredients): # removes what I feel are flavor incomptibilities. This is solely my opinion. comment out any you don't agree with! if tea == 'green' and 'cocoa' in final_ingredients: final_ingredients.remove('cocoa') if tea == 'black' and 'chamomile' in final_ingredients: final_ingredients.remove('chamomile') if tea == 'black' and 'jasmine' in final_ingredients: final_ingredients.remove('jasmine') if 'paprika' and 'jasmine' in final_ingredients: final_ingredients.remove('jasmine') return final_ingredients def choose_categories(tea): # chooses which ingredient categories your ingredients will come from, we use simple qubit superposition state |0>+|1> n = 4 #There are 4 ingredient categories categories_dict = {'0': select_ingredients(mild_spices), '1': select_ingredients(herbs), '2': select_ingredients(misc_flavors), '3': select_ingredients(zesty_spices)} max_res = '0000' final_ingredients = [] while len(final_ingredients) == 0: # to make sure we don't return an empty list while max_res == '0000': # run it until we get SOME ingredients! No one wants 0 ingredients. That'd be utterly boring. result = run_QuantumCirc(n) max_res = max(result, key=result.get) for ind in range(n): if max_res[ind] == '1': final_ingredients.append(categories_dict[str(ind)]) final_ingredients = list(itertools.chain.from_iterable(final_ingredients)) final_ingredients = ingredient_compatibilities(final_ingredients) return final_ingredients tea = which_tea() print(f""" Your quantum chai is {tea} tea with the following ingredients: {choose_categories(tea)} Happy drinking!""")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_right(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=80 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog.draw()
https://github.com/epelaaez/QuantumLibrary
epelaaez
# Import helper module from local folder import sys import os sys.path.append(os.getcwd()) from resources import helper # Numerical and plotting tools import numpy as np import matplotlib.pyplot as plt # Import SI unit conversion factors from resources.helper import GHz, MHz, kHz, us, ns # Importing standard Qiskit libraries from qiskit import IBMQ from qiskit.tools.jupyter import * # Loading your IBM Quantum account IBMQ.load_account() IBMQ.providers() # see a list of providers you have access to # Get the special provider assigned to you using information from the output above hub_name = 'iqc2021-1' # e.g. 'iqc2021-1' group_name = 'challenge-26' # e.g. 'challenge-1' project_name = 'ex4' # Your project name should be 'ex4' provider = IBMQ.get_provider(hub=hub_name, group=group_name, project=project_name) # Get `ibmq_jakarta` backend from the provider backend_name = 'ibmq_jakarta' backend = provider.get_backend(backend_name) backend # See details of the `ibmq_jakarta` quantum system from qiskit import pulse from qiskit.pulse import Play, Schedule, DriveChannel # Please use qubit 0 throughout the notebook qubit = 0 backend_config = backend.configuration() exc_chans = helper.get_exc_chans(globals()) dt = backend_config.dt print(f"Sampling time: {dt*1e9} ns") backend_defaults = backend.defaults() center_frequency = backend_defaults.qubit_freq_est inst_sched_map = backend_defaults.instruction_schedule_map inst_sched_map.instructions # Retrieve calibrated measurement pulse from backend meas = inst_sched_map.get('measure', qubits=[qubit]) meas.exclude(channels=exc_chans).draw(time_range=[0,1000]) from qiskit.pulse import DriveChannel, Gaussian # The same spec pulse for both 01 and 12 spec drive_amp = 0.25 drive_duration = inst_sched_map.get('x', qubits=[qubit]).duration # Calibrated backend pulse use advanced DRAG pulse to reduce leakage to the |2> state. # Here we will use simple Gaussian pulse drive_sigma = drive_duration // 4 # DRAG pulses typically 4*sigma long. spec_pulse = Gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma, name=f"Spec drive amplitude = {drive_amp}") # Construct an np array of the frequencies for our experiment spec_freqs_GHz = helper.get_spec01_freqs(center_frequency, qubit) # Create the base schedule # Start with drive pulse acting on the drive channel spec01_scheds = [] for freq in spec_freqs_GHz: with pulse.build(name="Spec Pulse at %.3f GHz" % freq) as spec01_sched: with pulse.align_sequential(): # Pay close attention to this part to solve the problem at the end pulse.set_frequency(freq*GHz, DriveChannel(qubit)) pulse.play(spec_pulse, DriveChannel(qubit)) pulse.call(meas) spec01_scheds.append(spec01_sched) # Draw spec01 schedule spec01_scheds[-1].exclude(channels=exc_chans).draw(time_range=[0,1000]) from qiskit.tools.monitor import job_monitor # Run the job on a real backend spec01_job = backend.run(spec01_scheds, job_name="Spec 01", **helper.job_params) print(spec01_job.job_id()) job_monitor(spec01_job) # If the queuing time is too long, you can save the job id # And retrieve the job after it's done # Replace 'JOB_ID' with your job id and uncomment to line below #spec01_job = backend.retrieve_job('JOB_ID') from resources.helper import SpecFitter amp_guess = 5e6 f01_guess = 5 B = 1 C = 0 fit_guess = [amp_guess, f01_guess, B, C] fit = SpecFitter(spec01_job.result(), spec_freqs_GHz, qubits=[qubit], fit_p0=fit_guess) fit.plot(0, series='z') f01 = fit.spec_freq(0, series='z') print("Spec01 frequency is %.6f GHz" % f01) # Retrieve qubit frequency from backend properties f01_calibrated = backend.properties().frequency(qubit) / GHz f01_error = abs(f01-f01_calibrated) * 1000 # error in MHz print("Qubit frequency error is %.6f MHz" % f01_error) max_rabi_amp = 0.75 rabi_amps = helper.get_rabi_amps(max_rabi_amp) rabi_scheds = [] for ridx, amp in enumerate(rabi_amps): with pulse.build(name="rabisched_%d_0" % ridx) as sched: # '0' corresponds to Rabi with pulse.align_sequential(): pulse.set_frequency(f01*GHz, DriveChannel(qubit)) rabi_pulse = Gaussian(duration=drive_duration, amp=amp, \ sigma=drive_sigma, name=f"Rabi drive amplitude = {amp}") pulse.play(rabi_pulse, DriveChannel(qubit)) pulse.call(meas) rabi_scheds.append(sched) # Draw rabi schedule rabi_scheds[-1].exclude(channels=exc_chans).draw(time_range=[0,1000]) # Run the job on a real device rabi_job = backend.run(rabi_scheds, job_name="Rabi", **helper.job_params) print(rabi_job.job_id()) job_monitor(rabi_job) # If the queuing time is too long, you can save the job id # And retrieve the job after it's done # Replace 'JOB_ID' with the the your job id and uncomment to line below #rabi_job = backend.retrieve_job('JOB_ID') from qiskit.ignis.characterization.calibrations.fitters import RabiFitter amp_guess = 5e7 fRabi_guess = 2 phi_guess = 0.5 c_guess = 0 fit_guess = [amp_guess, fRabi_guess, phi_guess, c_guess] fit = RabiFitter(rabi_job.result(), rabi_amps, qubits=[qubit], fit_p0=fit_guess) fit.plot(qind=0, series='0') x180_amp = fit.pi_amplitude() print("Pi amplitude is %.3f" % x180_amp) # Define pi pulse x_pulse = Gaussian(duration=drive_duration, amp=x180_amp, sigma=drive_sigma, name='x_pulse') def build_spec12_pulse_schedule(freq, anharm_guess_GHz): with pulse.build(name="Spec Pulse at %.3f GHz" % (freq+anharm_guess_GHz)) as spec12_schedule: with pulse.align_sequential(): # WRITE YOUR CODE BETWEEN THESE LINES - START pulse.play(x_pulse, DriveChannel(qubit)) pulse.set_frequency((freq+anharm_guess_GHz)*GHz, DriveChannel(qubit)) pulse.play(spec_pulse, DriveChannel(qubit)) pulse.call(meas) # WRITE YOUR CODE BETWEEN THESE LINES - END return spec12_schedule anharmonicity_guess_GHz = -0.3 # your anharmonicity guess freqs_GHz = helper.get_spec12_freqs(f01, qubit) # Now vary the sideband frequency for each spec pulse spec12_scheds = [] for freq in freqs_GHz: spec12_scheds.append(build_spec12_pulse_schedule(freq, anharmonicity_guess_GHz)) # Draw spec12 schedule spec12_scheds[-1].exclude(channels=exc_chans).draw(time_range=[0,1000]) # Run the job on a real device spec12_job = backend.run(spec12_scheds, job_name="Spec 12", **helper.job_params) print(spec12_job.job_id()) job_monitor(spec12_job) # If the queuing time is too long, you can save the job id # And retrieve the job after it's done # Replace 'JOB_ID' with the the your job id and uncomment to line below #spec12_job = backend.retrieve_job('JOB_ID') amp_guess = 2e7 f12_guess = f01 - 0.3 B = .1 C = 0 fit_guess = [amp_guess, f12_guess, B, C] fit = SpecFitter(spec12_job.result(), freqs_GHz+anharmonicity_guess_GHz, qubits=[qubit], fit_p0=fit_guess) fit.plot(0, series='z') f12 = fit.spec_freq(0, series='z') print("Spec12 frequency is %.6f GHz" % f12) # Check your answer using following code from qc_grader import grade_ex4 grade_ex4(f12,qubit,backend_name) # Submit your answer. You can re-submit at any time. from qc_grader import submit_ex4 submit_ex4(f12,qubit,backend_name) Ec = f01 - f12 Ej = (2*f01-f12)**2/(8*(f01-f12)) print(f"Ej/Ec: {Ej/Ec:.2f}") # This value is typically ~ 30
https://github.com/qiskit-community/prototype-qrao
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for MagicRounding.""" import itertools import unittest import pytest import numpy as np from docplex.mp.model import Model from qiskit import QuantumCircuit from qiskit.utils import QuantumInstance from qiskit.opflow import ( StateFn, X, Y, Z, ) from qiskit_aer import Aer, noise from qiskit_optimization.translators import from_docplex_mp from qrao import ( QuantumRandomAccessEncoding, RoundingContext, MagicRounding, ) from qrao.encoding import qrac_state_prep_1q, q2vars_from_var2op # pylint: disable=protected-access class TestMagicRounding(unittest.TestCase): """Test MagicRounding Class""" def setUp(self): # load problem, define encoding etc # instantiate MagicRounding # things here don't change (often) super().setUp() self.gate_circ = QuantumCircuit(2) self.gate_circ.h(0) self.gate_circ.h(1) self.gate_circ.z(1) self.gate_circ.cx(0, 1) self.gate_circ.s(0) self.gate_circ.save_statevector() self.deterministic_trace_vals = [ [1, 1, 1], [1, -1, -1], [1, -1, 1], [1, 1, -1], ] elist = [(0, 1), (0, 4), (0, 3), (1, 2), (1, 5), (2, 3), (2, 4), (4, 5), (5, 3)] num_nodes = 6 mod = Model("maxcut") nodes = list(range(num_nodes)) var = [mod.binary_var(name="x" + str(i)) for i in nodes] mod.maximize(mod.sum((var[i] + var[j] - 2 * var[i] * var[j]) for i, j in elist)) self.problem = from_docplex_mp(mod) self.rounding_qi = QuantumInstance( backend=Aer.get_backend("aer_simulator"), shots=10 ) # Start test cases in order of increasing complexity # toy problems # harder problems w/ minimal inputs # harder problems w/ more inputs # negative test cases def test_round_on_gate_and_sv_circs(self): """Test MagicRounding""" ops = [X, Y, Z] var2op = {i: (i // 3, ops[i % 3]) for i in range(3)} qi = QuantumInstance(backend=Aer.get_backend("aer_simulator"), shots=1000) magic = MagicRounding( quantum_instance=qi, basis_sampling="weighted", ) # subtest for gate based and sv based etc with self.subTest("Gate Based Magic Uniform Rounding"): for m in itertools.product((0, 1), repeat=3): qrac_gate_circ = qrac_state_prep_1q(*m).to_circuit() magic_basis = 2 * (m[1] ^ m[2]) + (m[0] ^ m[2]) tv = self.deterministic_trace_vals[magic_basis] rounding_context = RoundingContext( trace_values=tv, circuit=qrac_gate_circ, var2op=var2op, _vars_per_qubit=3, ) rounding_res = magic.round(rounding_context) self.assertEqual(rounding_res.samples[0].x.tolist(), list(m)) self.assertEqual(rounding_res.samples[0].probability, 1) with self.subTest("SV Based Magic Uniform Rounding"): for m in itertools.product((0, 1), repeat=3): qrac_gate_circ = qrac_state_prep_1q(*m).to_circuit() sv = StateFn(qrac_gate_circ).eval().primitive qrac_sv_circ = QuantumCircuit(1) qrac_sv_circ.initialize(sv) magic_basis = 2 * (m[1] ^ m[2]) + (m[0] ^ m[2]) tv = self.deterministic_trace_vals[magic_basis] rounding_context = RoundingContext( trace_values=tv, circuit=qrac_sv_circ, var2op=var2op, _vars_per_qubit=3, ) rounding_res = magic.round(rounding_context) self.assertEqual(rounding_res.samples[0].x.tolist(), list(m)) self.assertEqual(rounding_res.samples[0].probability, 1) def test_evaluate_magic_bases(self): qi = QuantumInstance(backend=Aer.get_backend("aer_simulator"), shots=1000) magic = MagicRounding( quantum_instance=qi, basis_sampling="weighted", ) for m in itertools.product((0, 1), repeat=3): qrac_state = qrac_state_prep_1q(*m).to_circuit() bases = [[2 * (m[1] ^ m[2]) + (m[0] ^ m[2])]] basis_counts = magic._evaluate_magic_bases( qrac_state, bases=bases, basis_shots=[10], vars_per_qubit=3 ) self.assertEqual(len(basis_counts), 1) self.assertEqual(int(list(basis_counts[0].keys())[0]), m[0] ^ m[1] ^ m[2]) def test_dv_counts(self): """ Checks that the dv_counts method unpacks these measurement outcomes properly. This also effectively tests `unpack_measurement_outcome`. """ ops = [X, Y, Z] var2op = {i: (i // 3, ops[i % 3]) for i in range(6)} magic = MagicRounding(self.rounding_qi) compute_dv_counts = magic._compute_dv_counts solns = [] for b0 in range(4): for b1 in range(4): for outcome in range(4): bases = [[b0, b1]] basis_counts = [{f"{outcome:02b}": 1}] dv_counts = compute_dv_counts(basis_counts, bases, var2op, 3) solns.append(list(dv_counts.keys())[0]) ref = [ "000000", "000111", "111000", "111111", "000011", "000100", "111011", "111100", "000101", "000010", "111101", "111010", "000110", "000001", "111110", "111001", "011000", "011111", "100000", "100111", "011011", "011100", "100011", "100100", "011101", "011010", "100101", "100010", "011110", "011001", "100110", "100001", "101000", "101111", "010000", "010111", "101011", "101100", "010011", "010100", "101101", "101010", "010101", "010010", "101110", "101001", "010110", "010001", "110000", "110111", "001000", "001111", "110011", "110100", "001011", "001100", "110101", "110010", "001101", "001010", "110110", "110001", "001110", "001001", ] self.assertTrue(np.all(np.array(ref) == np.array(solns))) def test_sample_bases_weighted(self): # pylint: disable=too-many-locals """ There are a few settings of the trace values which cause the magic basis sampling probabilities to be deterministic. I pass these through (for a 2 qubit, 6 var example) and verify that the outputs are correctly shaped and are deterministic. Note that these input trace values are non-physical """ shots = 10 num_nodes = 6 num_qubits = 2 rounding_qi = QuantumInstance( backend=Aer.get_backend("aer_simulator"), shots=shots ) ops = [X, Y, Z] var2op = {i: (i // 3, ops[i % 3]) for i in range(num_nodes)} q2vars = q2vars_from_var2op(var2op) magic = MagicRounding(quantum_instance=rounding_qi, basis_sampling="weighted") sample_bases_weighted = magic._sample_bases_weighted for b0, tv0 in enumerate(self.deterministic_trace_vals): for b1, tv1 in enumerate(self.deterministic_trace_vals): tv = tv0 + tv1 bases, basis_shots = sample_bases_weighted(q2vars, tv, 3) self.assertTrue(np.all(np.array([b0, b1]) == bases)) self.assertEqual(basis_shots, (shots,)) self.assertEqual(bases.shape, (1, num_qubits)) # 1 == deterministic # Both trace values and a circuit must be provided with self.assertRaises(NotImplementedError): magic.round( RoundingContext(trace_values=[1.0], var2op=var2op, _vars_per_qubit=3) ) with self.assertRaises(NotImplementedError): magic.round( RoundingContext( circuit=self.gate_circ, var2op=var2op, _vars_per_qubit=3 ) ) def test_sample_bases_uniform(self): """ Verify that the outputs of uniform sampling are correctly shaped. """ num_nodes = 3 num_qubits = 1 ops = [X, Y, Z] var2op = {i: (i // 3, ops[i % 3]) for i in range(num_nodes)} q2vars = q2vars_from_var2op(var2op) shots = 1000 # set high enough to "always" have four distinct results qi = QuantumInstance(backend=Aer.get_backend("aer_simulator"), shots=shots) magic = MagicRounding( quantum_instance=qi, basis_sampling="uniform", ) bases, basis_shots = magic._sample_bases_uniform(q2vars, 3) self.assertEqual(basis_shots.shape, (4,)) self.assertEqual(np.sum(basis_shots), shots) self.assertEqual(bases.shape, (4, num_qubits)) # A circuit must be provided, but trace values need not be circuit = QuantumCircuit(1) circuit.h(0) magic.round(RoundingContext(circuit=circuit, var2op=var2op, _vars_per_qubit=3)) with self.assertRaises(NotImplementedError): magic.round(RoundingContext(var2op=var2op, _vars_per_qubit=3)) def test_unsupported_backend(): qi = QuantumInstance(Aer.get_backend("aer_simulator_unitary"), shots=100) with pytest.raises(ValueError): MagicRounding(quantum_instance=qi) def test_unsupported_basis_sampling_method(): qi = QuantumInstance(Aer.get_backend("aer_simulator"), shots=100) with pytest.raises(ValueError): MagicRounding(quantum_instance=qi, basis_sampling="foo") @pytest.mark.filterwarnings("ignore::PendingDeprecationWarning") def test_magic_rounding_statevector_simulator(): """Test magic rounding on the statevector simulator ... which behaves unlike the others, as the "counts" are probabilities, not integers, and so special care is required. """ qi = QuantumInstance(Aer.get_backend("statevector_simulator"), shots=10) ops = [X, Y, Z] var2op = {i: (i // 3, ops[i % 3]) for i in range(3)} with pytest.warns(UserWarning): magic = MagicRounding( quantum_instance=qi, basis_sampling="weighted", ) circ = QuantumCircuit(2) circ.h(0) circ.h(1) circ.cx(0, 1) ctx = RoundingContext( circuit=circ, trace_values=[1, 1, 1], var2op=var2op, _vars_per_qubit=3 ) res = magic.round(ctx) assert sum(s.probability for s in res.samples) == pytest.approx(1) def test_noisy_quantuminstance(): """Smoke test using a QuantumInstance with noise""" noise_model = noise.NoiseModel() # 1-qubit gates noise_model.add_all_qubit_quantum_error( noise.depolarizing_error(0.001, 1), ["rz", "sx", "x"] ) # 2-qubit gate noise_model.add_all_qubit_quantum_error(noise.depolarizing_error(0.01, 2), ["cx"]) backend = Aer.get_backend("aer_simulator") qi = QuantumInstance(backend=backend, noise_model=noise_model, shots=100) magic = MagicRounding(quantum_instance=qi) ops = [X, Y, Z] var2op = {i: (i // 3, ops[i % 3]) for i in range(3)} circuit = qrac_state_prep_1q(0, 1, 0).to_circuit() magic.round( RoundingContext( trace_values=[1, 1, 1], var2op=var2op, circuit=circuit, _vars_per_qubit=3 ) ) def test_magic_rounding_statistical(): """Statistical test for magic rounding to make sure each deterministic case rounds consistently """ shots = 1024 mr = MagicRounding( QuantumInstance(backend=Aer.get_backend("aer_simulator"), shots=shots) ) test_cases = ( # 3 variables encoded as a (3,1,p) QRAC ((0, 0, 0), 0, 0), ((1, 1, 1), 0, 1), ((0, 1, 1), 1, 0), ((1, 0, 0), 1, 1), ((1, 0, 1), 2, 0), ((0, 1, 0), 2, 1), ((1, 1, 0), 3, 0), ((0, 0, 1), 3, 1), # 2 variables encoded as a (2,1,p) QRAC ((0, 0), 0, 0), ((1, 1), 0, 1), ((0, 1), 1, 0), ((1, 0), 1, 1), # 1 variable encoded as a (1,1,1) QRAC ((0,), 0, 0), ((1,), 0, 1), ) for (m, basis, expected) in test_cases: encoding = QuantumRandomAccessEncoding(len(m)) encoding._add_variables(list(range(len(m)))) circuit = encoding.state_prep(m).to_circuit() result = mr.round(RoundingContext(encoding=encoding, circuit=circuit)) deterministic_dict = result.basis_counts[basis] assert set(deterministic_dict) == set([str(expected)]) if __name__ == "__main__": import sys sys.exit(pytest.main([__file__]))
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import itertools import numpy as np import qiskit from qiskit import * from qiskit.quantum_info import Statevector from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.opflow import CircuitSampler from qiskit.ignis.mitigation.measurement import CompleteMeasFitter # you will need to pip install qiskit-ignis from qiskit.ignis.mitigation.measurement import complete_meas_cal import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib.colors import BoundaryNorm cmap = plt.get_cmap("plasma") #'viridis' from modules.utils import * from qae import * import datetime print(qiskit.__version__, np.__version__) IBMQ.load_account() # this then automatically loads your saved account provider = IBMQ.get_provider(hub='ibm-q-research') device = provider.backend.ibmq_jakarta # 6 bogota ; 4 rome ### Real device execution: backend_device = device ### Simulation with noise profile from real device backend_sim = qiskit.providers.aer.AerSimulator.from_backend(device) ### Simulation without noise #backend = qiskit.providers.aer.AerSimulator() ### Preliminaries L = 5 num_trash = 2 anti = -1 # 1 for ferromagnetic Ising model, -1 for antiferromagnet run_VQE = True # whether or not you want to compute the VQE values; or load them execute = True real_device = True # want to execute on real device # dataset to be loaded (optimal VQE parameters) # if execute_VQE is True this will overwrite the file filename = f'data/jakarta_execute' # Give a _unique_ name to this notebook execution, the results will be stored in the appropriate files with that name name = "jakarta_execute" # uncomment in case you want to toy around with the ansatz circuit rotation_blocks = "ry" entanglement_blocks = "cz" # cx entanglement = "sca" #"sca" reps = 1 ansatz_config = dict(rotation_blocks = rotation_blocks, entanglement_blocks = entanglement_blocks, reps = reps, entanglement = entanglement) ansatz = qiskit.circuit.library.TwoLocal(L, **ansatz_config) ansatz.draw("mpl") tansatz = qiskit.transpile(ansatz, backend_sim) tansatz.draw("mpl") coupling_map = device.configuration().coupling_map noise_model = qiskit.providers.aer.noise.NoiseModel.from_backend(device) basis_gates = noise_model.basis_gates qi_device = qiskit.utils.QuantumInstance(backend=backend_device, # , seed_simulator=seed, seed_transpiler=seed shots = 1000, coupling_map=coupling_map, #noise_model=noise_model, # comment out on real device execution measurement_error_mitigation_cls= CompleteMeasFitter, cals_matrix_refresh_period=30 #How often to refresh the calibration matrix in measurement mitigation. in minutes ) qi_sim = qiskit.utils.QuantumInstance(backend=backend_sim, # , seed_simulator=seed, seed_transpiler=seed shots = 1000, coupling_map=coupling_map, noise_model=noise_model, # comment out on real device execution measurement_error_mitigation_cls= CompleteMeasFitter, cals_matrix_refresh_period=30 #How often to refresh the calibration matrix in measurement mitigation. in minutes ) if not real_device: backend_device = backend_sim qi_device = qi_sim if run_VQE: maxiter = [200,200,200,200,200, 200,200,200,150,150, 150,150,100,100,100, 60,30,30,30,30 ] maxiter = maxiter[::2] maxiter = [150] + [50] * 9 logspace_size = len(maxiter) gx_vals = np.logspace(-2,2,logspace_size) #gz_vals = [0.] # np.logspace(-2,2,logspace_size) counts = [] values = [] params = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) params.append(parameters) opt_params = [] gx_list = [] gz_list = [] countss, valuess, paramss = [], [], [] Qmag_sim, QZ_sim, Qen_sim= [],[], [] Smag, Sen = [], [] #maxiter = [200,200,200,200, 150, 60, 60, 60, 60, 60] for j,gx in enumerate(gx_vals): gz = 0 t0 = datetime.datetime.now() counts = [] values = [] params = [] optimizer = SPSA(maxiter=maxiter[j], blocking=True) # ,learning_rate=0.05, perturbation=0.05,; setting that speeds things up sometimes vqe = qiskit.algorithms.VQE(ansatz=ansatz, initial_point = opt_params[j-1] if j != 0 else None, optimizer=optimizer, callback=store_intermediate_result, # comment out on real device quantum_instance=qi_sim ) H = QHIsing(L,anti,np.float32(gx),np.float32(gz)) result = vqe.compute_minimum_eigenvalue(H, aux_operators = [QNKron(L,Z,I,i) for i in range(L)]) #ED with Qiskit VQE Qen_sim.append(result.eigenvalue) QZ_sim.append(result.aux_operator_eigenvalues[:,0]) # real-space resolved Z expectation value Qmag_sim.append(np.mean(anti**np.arange(L) * result.aux_operator_eigenvalues[:,0])) countss.append(counts) valuess.append(values) paramss.append(params) # uncomment if you want to recompute ED results (typically provided with guess parameters) ED_state, ED_E, ham = ising_groundstate(L, anti, np.float32(gx), np.float32(gz)) Sen.append(ED_E) Smag.append(ED_state.T.conj()@Mag(L,anti)@ED_state) print(f"ED energy: {Sen[j]} ;; VQE energy: {Qen_sim[j]} ;; diff {Qen_sim[j] - Sen[j]}") print(f"ED mag: {Smag[j]} ;; VQE mag: {Qmag_sim[j]} ;; diff {Qmag_sim[j] - Smag[j]}") gx_list.append(gx) gz_list.append(gz) opt_params.append(sort_params(result.optimal_parameters)) print(f"{j+1} / {len(gx_vals)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {(datetime.datetime.now() - t0)}") fig, axs = plt.subplots(ncols=2,figsize=(6,3)) axs[0].plot(countss[j],valuess[j]) axs[1].plot(result.aux_operator_eigenvalues[:,0]) plt.show() np.savez(filename, gx_list=gx_list, gz_list=gz_list, opt_params=opt_params, Qmag_sim=Qmag_sim, Qen_sim=Qen_sim, QZ_sim = QZ_sim, Sen=Sen, Smag=Smag, ansatz_config=ansatz_config, paramss = paramss, valuess = valuess, countss = countss ) temp = np.load(filename + ".npz",allow_pickle=True) gx_list = temp["gx_list"] gz = 0 gz_list = [0] Qmag_sim = temp["Qmag_sim"] QZ_sim = temp["QZ_sim"] Qen_sim = temp["Qen_sim"] Sen = temp["Sen"] Smag = temp["Smag"] opt_params = temp["opt_params"] paramss = temp["paramss"]; valuess = temp["valuess"]; countss = temp["countss"] # This just recomputes the magnetization with the parameters provided by guess_params if execute: QZ_executed=np.zeros((len(opt_params),L), dtype="complex") Qmag_executed=np.zeros((len(opt_params),), dtype="complex") for j in range(len(opt_params)): t0 = datetime.datetime.now() gx = gx_list[j] #H = QHIsing(L, anti, np.float32(gx), np.float32(gz)) # build Hamiltonian Op state = ansatz.assign_parameters(opt_params[j]) for i in range(L): meas_outcome = ~StateFn(QNKron(L,Z,I,i)) @ StateFn(state) QZ_executed[j,i] = CircuitSampler(qi_device).convert(meas_outcome).eval() #https://quantumcomputing.stackexchange.com/questions/12080/evaluating-expectation-values-of-operators-in-qiskit Qmag_executed[j] = np.mean(anti**np.arange(L) * QZ_executed[j]) #e_outcome = ~StateFn(H) @ StateFn(state) #Qen_executed[j] = CircuitSampler(qi).convert(e_outcome).eval() print(f"{j+1} / {len(opt_params)}, QZ: {Qmag_executed[j]}, gx = {gx:.2f}, gz = {gz:.2f}, time : {(datetime.datetime.now() - t0)}") fig, ax = plt.subplots(ncols=1,figsize=(4,3)) ax.plot(QZ_sim[j].real) ax.plot(QZ_executed[j].real,"x--") ax.set_title("S exec = {:.3f}, S sim = {:.3f}".format(Qmag_executed[j].real, Qmag_sim[j].real)) plt.show() np.savez(filename + f"_executed_-real-device-{real_device}", gx_list=gx_list, gz_list=gz_list, opt_params=opt_params, Qmag_sim=Qmag_sim, Qen_sim=Qen_sim, QZ_sim = QZ_sim, Sen=Sen, Smag=Smag, Qmag_device= Qmag_executed, QZ_device = QZ_executed, ansatz_config=ansatz_config, paramss = paramss, valuess = valuess, countss = countss ) fig, axs = plt.subplots(ncols=2, figsize=(10,5)) ax = axs[0] ax.plot(gx_list, np.abs(Smag),"x--", label="ED") ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="VQE sim") ax.plot(gx_list, np.abs(Qmag_executed),"x--", label="VQE ibmq_rome") ax.set_xscale("log") ax.legend() ax = axs[1] ax.plot(gx_list, Smag,"x--", label="ED") ax.plot(gx_list, Qmag_sim,"x--", label="VQE sim") ax.plot(gx_list, Qmag_executed,"x--", label="VQE ibmq_rome") ax.set_xscale("log") ax.legend() ############################################################################## ### II - Anomaly Detection ################################################## ############################################################################## trash_qubits_idxs = [1,3] # Using our QAEAnsatz class (described in qae.py) circ = QAEAnsatz(num_qubits = L, num_trash_qubits= num_trash, trash_qubits_idxs = trash_qubits_idxs, measure_trash=True) circ.draw("mpl") # an example with assigned parameters circ = circ.assign_parameters(np.arange(L*2+2)) circ.draw("mpl") def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True): QAE_circ = QAEAnsatz(num_qubits = L, num_trash_qubits= num_trash, trash_qubits_idxs = trash_qubits_idxs, measure_trash=measurement).assign_parameters(thetas) if vqe: VQE_circ = ansatz.assign_parameters(init_state) fullcirc = VQE_circ + QAE_circ else: fullcirc = QAE_circ.initialize(init_state, qreg) return fullcirc # example of the full circuit with random parameters assigned fullcirc = prepare_circuit(np.random.rand(L*2+2),L,num_trash, vqe=True, init_state=opt_params[0]) fullcirc.draw("mpl") backend = backend_device def calibrate_circuit(L, nums_trash=trash_qubits_idxs,shots=1000): # outputs a CompleteMeasFitter object for alter use num_trash = len(nums_trash) qreg = QuantumRegister(L, 'q') # obtain calibration matrix qubit_list = [i for i in nums_trash] # only need to calibrate the trash qubits circlabel = f'mcal_{datetime.datetime.now()}' meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qreg, circlabel=circlabel) cal_job = backend.run(meas_calibs, shots=shots) #, noise_model=noise_model) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel=circlabel) print(circlabel, meas_fitter.cal_matrix) return meas_fitter def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100, meas_fitter = None): circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) tcirc = qiskit.transpile(circ, backend) # Execute the circuit job_sim = backend.run(tcirc, shots=shots) # , seed_simulator=123, seed_transpiler=234 fix seed to make it reproducible result = job_sim.result() # Results without mitigation counts = result.get_counts() if meas_fitter != None: # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(result) counts = mitigated_results.get_counts(0) return counts phis = opt_params # the parameters for the VQE initialization def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ if vqe: init_state = phis[p] else: J, gx, gz = p init_state, _ = ising_groundstate(L, J, gx, gz) if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots, meas_fitter=meas_fitter) cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0) return cost/shots def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ cost = 0. n_samples = len(ising_params) for i, p in enumerate(ising_params): if param_encoding: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i], meas_fitter=meas_fitter) else: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, meas_fitter=meas_fitter) return cost/n_samples def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None, meas_fitter=None, callback=True): if thetas is None: n_params = (2*L+2)*2 if param_encoding else (2*L+2) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, blocking=True, callback=store_intermediate_result if callback else None, learning_rate=0.1, perturbation=0.1 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x, meas_fitter=meas_fitter)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted backend = backend_sim #calibration meas_fitter = calibrate_circuit(L, nums_trash=trash_qubits_idxs) # Training phys_params = [0] thetas_opt, loss, accepted = optimize(phys_params, max_iter=90, L=5, meas_fitter=meas_fitter) #, pick_optimizer="adam") plt.plot(loss) np.savez(filename + "run1_thetas_opt_sim", thetas_opt=thetas_opt, loss=loss, accepted=accepted) # Inference; note that on the real device each inference points takes about ~30 seconds cost = np.zeros((len(gx_vals))) thetas_opt = np.load(filename + "run1_thetas_opt_sim.npz",allow_pickle=True)["thetas_opt"] shots = 1000 for i,p in enumerate(list(gx_list)): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas_opt, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something print(f"{i} / {len(gx_list)} - execution time {datetime.datetime.now()-t0}") np.savez(filename + "run1_sim",cost=cost, thetas_opt=thetas_opt, loss=loss, accepted = accepted) # Training phys_params = [0] thetas_opt, loss, accepted = optimize(phys_params, max_iter=90, L=5, meas_fitter=meas_fitter) #, pick_optimizer="adam") plt.plot(loss) np.savez(filename + "run1_thetas_opt_sim2", thetas_opt=thetas_opt, loss=loss, accepted=accepted) # Inference; note that on the real device each inference points takes about ~30 seconds cost = np.zeros((len(gx_vals))) thetas_opt = np.load(filename + "run1_thetas_opt_sim2.npz",allow_pickle=True)["thetas_opt"] shots = 1000 for i,p in enumerate(list(gx_list)): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas_opt, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something print(f"{i} / {len(gx_list)} - execution time {datetime.datetime.now()-t0}") np.savez(filename + "run1_sim2",cost=cost, thetas_opt=thetas_opt, loss=loss, accepted = accepted) fig, axs = plt.subplots(ncols=2, figsize=(10,5)) temp0 = np.load(filename + "run1_sim2.npz",allow_pickle=True) cost = temp0["cost"] ; ax = axs[0] ax.plot(gx_list, cost,"X--", label="cost") ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="VQE res") ax.plot(gx_list, np.abs(Qmag_executed),"x--", label="VQE resample") ax.set_xscale("log") ax.legend() ax = axs[1] ax.plot(gx_list, cost,"X--", label="cost") ax.plot(gx_list, Qmag_sim,"x--", label="VQE res") ax.plot(gx_list, Qmag_executed,"x--", label="VQE resample") ax.set_xscale("log") ax.legend() # Training phys_params = [-1] thetas_opt, loss, accepted = optimize(phys_params, max_iter=40, L=5, meas_fitter=meas_fitter) #, pick_optimizer="adam") plt.plot(loss) np.savez(filename + "run2_thetas_opt_sim2", thetas_opt=thetas_opt, loss=loss, accepted=accepted) # Inference; note that on the real device each inference points takes about ~30 seconds cost = np.zeros((len(gx_vals))) thetas_opt = np.load(filename + "run2_thetas_opt_sim2.npz",allow_pickle=True)["thetas_opt"] shots = 1000 for i,p in enumerate(list(gx_list)): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas_opt, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something print(f"{i} / {len(gx_list)} - execution time {datetime.datetime.now()-t0}") np.savez(filename + "run2_sim2",cost=cost, thetas_opt=thetas_opt, loss=loss, accepted = accepted) fig, axs = plt.subplots(ncols=2, figsize=(10,5)) temp0 = np.load(filename + "run2_sim2.npz",allow_pickle=True) cost = temp0["cost"] ; ax = axs[0] ax.plot(gx_list, cost,"X--", label="cost") ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="VQE res") ax.plot(gx_list, np.abs(Qmag_executed),"x--", label="VQE resample") ax.set_xscale("log") ax.legend() ax = axs[1] ax.plot(gx_list, cost,"X--", label="cost") ax.plot(gx_list, Qmag_sim,"x--", label="VQE res") ax.plot(gx_list, Qmag_executed,"x--", label="VQE resample") ax.set_xscale("log") ax.legend() backend = backend_device meas_fitter = calibrate_circuit(L, nums_trash=trash_qubits_idxs) # Training phys_params = [0] thetas_guess = np.load(filename + "run1_thetas_opt_sim.npz",allow_pickle=True)["thetas_opt"] thetas_opt, loss, accepted = optimize(phys_params, thetas= thetas_guess, callback=False, max_iter=15, L=5, meas_fitter=meas_fitter) #, pick_optimizer="adam") plt.plot(loss) np.savez(filename + "run1_thetas_opt_device", thetas_opt=thetas_opt, loss=loss, accepted=accepted) # Inference; note that on the real device each inference points takes about ~30 seconds cost = np.zeros((len(gx_vals))) thetas_opt = np.load(filename + "run1_thetas_opt_device.npz",allow_pickle=True)["thetas_opt"] shots = 1000 for i,p in enumerate(list(gx_list)): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas_opt, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something print(f"{i} / {len(gx_list)} - execution time {datetime.datetime.now()-t0}") np.savez(filename + "run1_device",cost=cost, thetas_opt=thetas_opt, loss=loss, accepted = accepted) fig, axs = plt.subplots(ncols=2, figsize=(10,5)) cost_device = np.load(filename + "run1_device.npz",allow_pickle=True)["cost"] cost_sim = np.load(filename + "run1_sim.npz",allow_pickle=True)["cost"] ax = axs[0] ax.plot(gx_list, cost_sim,"X--", label="cost sim.") ax.plot(gx_list, cost_device,"X--", label="cost ibmq_jakarta") ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="$\hat{S}$ sim") ax.plot(gx_list, np.abs(Qmag_executed),"x--", label="$\hat{S}$ ibmq_jakarta") ax.set_xscale("log") ax.legend() ax = axs[1] ax.plot(gx_list, cost_sim,"X--", label="cost sim.") ax.plot(gx_list, cost_device,"X--", label="cost ibmq_jakarta") ax.plot(gx_list, Qmag_sim,"x--", label="$\hat{S}$ sim") ax.plot(gx_list, Qmag_executed,"x--", label="$\hat{S}$ ibmq_jakarta") ax.set_xscale("log") ax.legend() # Training phys_params = [0] thetas_guess = np.load(filename + "run1_thetas_opt_sim2.npz",allow_pickle=True)["thetas_opt"] thetas_opt, loss, accepted = optimize(phys_params, thetas= thetas_guess, callback=False, max_iter=25, L=5, meas_fitter=meas_fitter) #, pick_optimizer="adam") plt.plot(loss) np.savez(filename + "run1_thetas_opt_device2", thetas_opt=thetas_opt, loss=loss, accepted=accepted) # Inference; note that on the real device each inference points takes about ~30 seconds cost = np.zeros((len(gx_vals))) thetas_opt = np.load(filename + "run1_thetas_opt_device2.npz",allow_pickle=True)["thetas_opt"] shots = 1000 for i,p in enumerate(list(gx_list)): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas_opt, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something print(f"{i} / {len(gx_list)} - execution time {datetime.datetime.now()-t0}") np.savez(filename + "run1_device2",cost=cost, thetas_opt=thetas_opt, loss=loss, accepted = accepted) filename fig, axs = plt.subplots(ncols=2, figsize=(10,5)) cost_device = np.load(filename + "run1_device2.npz",allow_pickle=True)["cost"] cost_sim = np.load(filename + "run1_sim2.npz",allow_pickle=True)["cost"] ax = axs[0] ax.plot(gx_list, cost_sim,"X--", label="cost sim.") ax.plot(gx_list, cost_device,"X--", label="cost ibmq_jakarta") ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="$\hat{S}$ sim") ax.plot(gx_list, np.abs(Qmag_executed),"x--", label="$\hat{S}$ ibmq_jakarta") ax.set_xscale("log") ax.legend() ax = axs[1] ax.plot(gx_list, cost_sim,"X--", label="cost sim.") ax.plot(gx_list, cost_device,"X--", label="cost ibmq_jakarta") ax.plot(gx_list, Qmag_sim,"x--", label="$\hat{S}$ sim") ax.plot(gx_list, Qmag_executed,"x--", label="$\hat{S}$ ibmq_jakarta") ax.set_xscale("log") ax.legend() meas_fitter = calibrate_circuit(L, nums_trash=trash_qubits_idxs) # Inference; note that on the real device each inference points takes about ~30 seconds cost = np.zeros((len(gx_vals))) thetas_opt = np.load(filename + "run2_thetas_opt_sim.npz",allow_pickle=True)["thetas_opt"] shots = 1000 for i,p in enumerate(list(gx_list)): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas_opt, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something print(f"{i} / {len(gx_list)} - execution time {datetime.datetime.now()-t0}") filename np.savez(filename + "run2_device",cost=cost, thetas_opt=thetas_opt, loss=loss, accepted = accepted) fig, axs = plt.subplots(ncols=2, figsize=(10,5)) cost_device = np.load(filename + "run2_device.npz",allow_pickle=True)["cost"] cost_sim = np.load(filename + "run2_sim.npz",allow_pickle=True)["cost"] ax = axs[0] ax.plot(gx_list, cost_sim,"X--", label="cost sim.") ax.plot(gx_list, cost_device,"X--", label="cost ibmq_jakarta") ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="$\hat{S}$ sim") ax.plot(gx_list, np.abs(Qmag_executed),"x--", label="$\hat{S}$ ibmq_jakarta") ax.set_xscale("log") ax.legend() ax = axs[1] ax.plot(gx_list, cost_sim,"X--", label="cost sim.") ax.plot(gx_list, cost_device,"X--", label="cost ibmq_jakarta") ax.plot(gx_list, Qmag_sim,"x--", label="$\hat{S}$ sim") ax.plot(gx_list, Qmag_executed,"x--", label="$\hat{S}$ ibmq_jakarta") ax.set_xscale("log") ax.legend() meas_fitter = calibrate_circuit(L, nums_trash=trash_qubits_idxs) # Training phys_params = [-1] thetas_guess = np.load(filename + "run2_thetas_opt_sim.npz",allow_pickle=True)["thetas_opt"] thetas_opt, loss, accepted = optimize(phys_params, thetas= thetas_guess, callback=False, max_iter=25, L=5, meas_fitter=meas_fitter) #, pick_optimizer="adam") plt.plot(loss) np.savez(filename + "run2_thetas_opt_device_overnight", thetas_opt=thetas_opt, loss=loss, accepted=accepted) # Inference; note that on the real device each inference points takes about ~30 seconds cost = np.zeros((len(gx_vals))) thetas_opt = np.load(filename + "run2_thetas_opt_device_overnight.npz",allow_pickle=True)["thetas_opt"] shots = 1000 for i,p in enumerate(list(gx_list)): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas_opt, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something print(f"{i} / {len(gx_list)} - execution time {datetime.datetime.now()-t0}") np.savez(filename + "run2_device_overnight",cost=cost, thetas_opt=thetas_opt, loss=loss, accepted = accepted) fig, axs = plt.subplots(ncols=2, figsize=(10,5)) cost_device = np.load(filename + "run2_device_overnight.npz",allow_pickle=True)["cost"] cost_sim = np.load(filename + "run2_sim2.npz",allow_pickle=True)["cost"] ax = axs[0] ax.plot(gx_list, cost_sim,"X--", label="cost sim.") ax.plot(gx_list, cost_device,"X--", label="cost ibmq_jakarta") ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="$\hat{S}$ sim") ax.plot(gx_list, np.abs(Qmag_executed),"x--", label="$\hat{S}$ ibmq_jakarta") ax.set_xscale("log") ax.legend() ax = axs[1] ax.plot(gx_list, cost_sim,"X--", label="cost sim.") ax.plot(gx_list, cost_device,"X--", label="cost ibmq_jakarta") ax.plot(gx_list, Qmag_sim,"x--", label="$\hat{S}$ sim") ax.plot(gx_list, Qmag_executed,"x--", label="$\hat{S}$ ibmq_jakarta") ax.set_xscale("log") ax.legend()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# load necessary Runtime libraries from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session backend = "ibmq_qasm_simulator" # use the simulator from qiskit.circuit import Parameter from qiskit.opflow import I, X, Z mu = Parameter('$\\mu$') ham_pauli = mu * X cc = Parameter('$c$') ww = Parameter('$\\omega$') ham_res = -(1/2)*ww*(I^Z) + cc*(X^X) + (ham_pauli^I) tt = Parameter('$t$') U_ham = (tt*ham_res).exp_i() from qiskit import transpile from qiskit.circuit import ClassicalRegister from qiskit.opflow import PauliTrotterEvolution, Suzuki import numpy as np num_trot_steps = 5 total_time = 10 cr = ClassicalRegister(1, 'c') spec_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=num_trot_steps)).convert(U_ham) spec_circ = spec_op.to_circuit() spec_circ_t = transpile(spec_circ, basis_gates=['sx', 'rz', 'cx']) spec_circ_t.add_register(cr) spec_circ_t.measure(0, cr[0]) spec_circ_t.draw('mpl') # fixed Parameters fixed_params = { cc: 0.3, mu: 0.7, tt: total_time } # Parameter value for single circuit param_keys = list(spec_circ_t.parameters) # run through all the ww values to create a List of Lists of Parameter value num_pts = 101 wvals = np.linspace(-2, 2, num_pts) param_vals = [] for wval in wvals: all_params = {**fixed_params, **{ww: wval}} param_vals.append([all_params[key] for key in param_keys]) with Session(backend=backend): sampler = Sampler() job = sampler.run( circuits=[spec_circ_t]*num_pts, parameter_values=param_vals, shots=1e5 ) result = job.result() Zexps = [] for dist in result.quasi_dists: if 1 in dist: Zexps.append(1 - 2*dist[1]) else: Zexps.append(1) from qiskit.opflow import PauliExpectation, Zero param_bind = { cc: 0.3, mu: 0.7, tt: total_time } init_state = Zero^2 obsv = I^Z Zexp_exact = (U_ham @ init_state).adjoint() @ obsv @ (U_ham @ init_state) diag_meas_op = PauliExpectation().convert(Zexp_exact) Zexact_values = [] for w_set in wvals: param_bind[ww] = w_set Zexact_values.append(np.real(diag_meas_op.bind_parameters(param_bind).eval())) import matplotlib.pyplot as plt plt.style.use('dark_background') fig, ax = plt.subplots(dpi=100) ax.plot([-param_bind[mu], -param_bind[mu]], [0, 1], ls='--', color='purple') ax.plot([param_bind[mu], param_bind[mu]], [0, 1], ls='--', color='purple') ax.plot(wvals, Zexact_values, label='Exact') ax.plot(wvals, Zexps, label=f"{backend}") ax.set_xlabel(r'$\omega$ (arb)') ax.set_ylabel(r'$\langle Z \rangle$ Expectation') ax.legend() import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() from qiskit.tools.jupyter import * %qiskit_version_table
https://github.com/DRA-chaos/Solutions-to-the-Lab-Exercises---IBM-Qiskit-Summer-School-2021
DRA-chaos
import networkx as nx import numpy as np import plotly.graph_objects as go import matplotlib as mpl import pandas as pd from IPython.display import clear_output from plotly.subplots import make_subplots from matplotlib import pyplot as plt from qiskit import Aer from qiskit import QuantumCircuit from qiskit.visualization import plot_state_city from qiskit.algorithms.optimizers import COBYLA, SLSQP, ADAM from time import time from copy import copy from typing import List from qc_grader.graph_util import display_maxcut_widget, QAOA_widget, graphs mpl.rcParams['figure.dpi'] = 300 from qiskit.circuit import Parameter, ParameterVector #Parameters are initialized with a simple string identifier parameter_0 = Parameter('ΞΈ[0]') parameter_1 = Parameter('ΞΈ[1]') circuit = QuantumCircuit(1) #We can then pass the initialized parameters as the rotation angle argument to the Rx and Ry gates circuit.ry(theta = parameter_0, qubit = 0) circuit.rx(theta = parameter_1, qubit = 0) circuit.draw('mpl') parameter = Parameter('ΞΈ') circuit = QuantumCircuit(1) circuit.ry(theta = parameter, qubit = 0) circuit.rx(theta = parameter, qubit = 0) circuit.draw('mpl') #Set the number of layers and qubits n=3 num_layers = 2 #ParameterVectors are initialized with a string identifier and an integer specifying the vector length parameters = ParameterVector('ΞΈ', n*(num_layers+1)) circuit = QuantumCircuit(n, n) for layer in range(num_layers): #Appending the parameterized Ry gates using parameters from the vector constructed above for i in range(n): circuit.ry(parameters[n*layer+i], i) circuit.barrier() #Appending the entangling CNOT gates for i in range(n): for j in range(i): circuit.cx(j,i) circuit.barrier() #Appending one additional layer of parameterized Ry gates for i in range(n): circuit.ry(parameters[n*num_layers+i], i) circuit.barrier() circuit.draw('mpl') print(circuit.parameters) #Create parameter dictionary with random values to bind param_dict = {parameter: np.random.random() for parameter in parameters} print(param_dict) #Assign parameters using the assign_parameters method bound_circuit = circuit.assign_parameters(parameters = param_dict) bound_circuit.draw('mpl') new_parameters = ParameterVector('Ξ¨',9) new_circuit = circuit.assign_parameters(parameters = [k*new_parameters[i] for k in range(9)]) new_circuit.draw('mpl') #Run the circuit with assigned parameters on Aer's statevector simulator simulator = Aer.get_backend('statevector_simulator') result = simulator.run(bound_circuit).result() statevector = result.get_statevector(bound_circuit) plot_state_city(statevector) #The following line produces an error when run because 'circuit' still contains non-assigned parameters #result = simulator.run(circuit).result() for key in graphs.keys(): print(key) graph = nx.Graph() #Add nodes and edges graph.add_nodes_from(np.arange(0,6,1)) edges = [(0,1,2.0),(0,2,3.0),(0,3,2.0),(0,4,4.0),(0,5,1.0),(1,2,4.0),(1,3,1.0),(1,4,1.0),(1,5,3.0),(2,4,2.0),(2,5,3.0),(3,4,5.0),(3,5,1.0)] graph.add_weighted_edges_from(edges) graphs['custom'] = graph #Display widget display_maxcut_widget(graphs['custom']) def maxcut_cost_fn(graph: nx.Graph, bitstring: List[int]) -> float: """ Computes the maxcut cost function value for a given graph and cut represented by some bitstring Args: graph: The graph to compute cut values for bitstring: A list of integer values '0' or '1' specifying a cut of the graph Returns: The value of the cut """ #Get the weight matrix of the graph weight_matrix = nx.adjacency_matrix(graph).toarray() size = weight_matrix.shape[0] value = 0. #INSERT YOUR CODE TO COMPUTE THE CUT VALUE HERE for i in range(size): for j in range(size): value+= weight_matrix[i,j]*bitstring[i]*(1-bitstring[j]) return value def plot_maxcut_histogram(graph: nx.Graph) -> None: """ Plots a bar diagram with the values for all possible cuts of a given graph. Args: graph: The graph to compute cut values for """ num_vars = graph.number_of_nodes() #Create list of bitstrings and corresponding cut values bitstrings = ['{:b}'.format(i).rjust(num_vars, '0')[::-1] for i in range(2**num_vars)] values = [maxcut_cost_fn(graph = graph, bitstring = [int(x) for x in bitstring]) for bitstring in bitstrings] #Sort both lists by largest cut value values, bitstrings = zip(*sorted(zip(values, bitstrings))) #Plot bar diagram bar_plot = go.Bar(x = bitstrings, y = values, marker=dict(color=values, colorscale = 'plasma', colorbar=dict(title='Cut Value'))) fig = go.Figure(data=bar_plot, layout = dict(xaxis=dict(type = 'category'), width = 1500, height = 600)) fig.show() plot_maxcut_histogram(graph = graphs['custom']) from qc_grader import grade_lab2_ex1 bitstring = [1, 0, 1, 1, 0, 0] #DEFINE THE CORRECT MAXCUT BITSTRING HERE # Note that the grading function is expecting a list of integers '0' and '1' grade_lab2_ex1(bitstring) from qiskit_optimization import QuadraticProgram quadratic_program = QuadraticProgram('sample_problem') print(quadratic_program.export_as_lp_string()) quadratic_program.binary_var(name = 'x_0') quadratic_program.integer_var(name = 'x_1') quadratic_program.continuous_var(name = 'x_2', lowerbound = -2.5, upperbound = 1.8) quadratic = [[0,1,2],[3,4,5],[0,1,2]] linear = [10,20,30] quadratic_program.minimize(quadratic = quadratic, linear = linear, constant = -5) print(quadratic_program.export_as_lp_string()) def quadratic_program_from_graph(graph: nx.Graph) -> QuadraticProgram: """Constructs a quadratic program from a given graph for a MaxCut problem instance. Args: graph: Underlying graph of the problem. Returns: QuadraticProgram """ #Get weight matrix of graph weight_matrix = nx.adjacency_matrix(graph) shape = weight_matrix.shape size = shape[0] #Build qubo matrix Q from weight matrix W qubo_matrix = np.zeros((size, size)) qubo_vector = np.zeros(size) for i in range(size): for j in range(size): qubo_matrix[i, j] -= weight_matrix[i, j] for i in range(size): for j in range(size): qubo_vector[i] += weight_matrix[i,j] #INSERT YOUR CODE HERE quadratic_program=QuadraticProgram('sample_problem') for i in range(size): quadratic_program.binary_var(name='x_{}'.format(i)) quadratic_program.maximize(quadratic =qubo_matrix, linear = qubo_vector) return quadratic_program quadratic_program = quadratic_program_from_graph(graphs['custom']) print(quadratic_program.export_as_lp_string()) from qc_grader import grade_lab2_ex2 # Note that the grading function is expecting a quadratic program grade_lab2_ex2(quadratic_program) def qaoa_circuit(qubo: QuadraticProgram, p: int = 1): """ Given a QUBO instance and the number of layers p, constructs the corresponding parameterized QAOA circuit with p layers. Args: qubo: The quadratic program instance p: The number of layers in the QAOA circuit Returns: The parameterized QAOA circuit """ size = len(qubo.variables) qubo_matrix = qubo.objective.quadratic.to_array(symmetric=True) qubo_linearity = qubo.objective.linear.to_array() #Prepare the quantum and classical registers qaoa_circuit = QuantumCircuit(size,size) #Apply the initial layer of Hadamard gates to all qubits qaoa_circuit.h(range(size)) #Create the parameters to be used in the circuit gammas = ParameterVector('gamma', p) betas = ParameterVector('beta', p) #Outer loop to create each layer for i in range(p): #Apply R_Z rotational gates from cost layer #INSERT YOUR CODE HERE for j in range(size): qubo_matrix_sum_of_col = 0 for k in range(size): qubo_matrix_sum_of_col+= qubo_matrix[j][k] qaoa_circuit.rz(gammas[i]*(qubo_linearity[j]+qubo_matrix_sum_of_col),j) #Apply R_ZZ rotational gates for entangled qubit rotations from cost layer #INSERT YOUR CODE HERE for j in range(size): for k in range(size): if j!=k: qaoa_circuit.rzz(gammas[i]*qubo_matrix[j][k]*0.5,j,k) # Apply single qubit X - rotations with angle 2*beta_i to all qubits #INSERT YOUR CODE HERE for j in range(size): qaoa_circuit.rx(2*betas[i],j) return qaoa_circuit quadratic_program = quadratic_program_from_graph(graphs['custom']) custom_circuit = qaoa_circuit(qubo = quadratic_program) test = custom_circuit.assign_parameters(parameters=[1.0]*len(custom_circuit.parameters)) from qc_grader import grade_lab2_ex3 # Note that the grading function is expecting a quantum circuit grade_lab2_ex3(test) from qiskit.algorithms import QAOA from qiskit_optimization.algorithms import MinimumEigenOptimizer backend = Aer.get_backend('statevector_simulator') qaoa = QAOA(optimizer = ADAM(), quantum_instance = backend, reps=1, initial_point = [0.1,0.1]) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) quadratic_program = quadratic_program_from_graph(graphs['custom']) result = eigen_optimizer.solve(quadratic_program) print(result) def plot_samples(samples): """ Plots a bar diagram for the samples of a quantum algorithm Args: samples """ #Sort samples by probability samples = sorted(samples, key = lambda x: x.probability) #Get list of probabilities, function values and bitstrings probabilities = [sample.probability for sample in samples] values = [sample.fval for sample in samples] bitstrings = [''.join([str(int(i)) for i in sample.x]) for sample in samples] #Plot bar diagram sample_plot = go.Bar(x = bitstrings, y = probabilities, marker=dict(color=values, colorscale = 'plasma',colorbar=dict(title='Function Value'))) fig = go.Figure( data=sample_plot, layout = dict( xaxis=dict( type = 'category' ) ) ) fig.show() plot_samples(result.samples) graph_name = 'custom' quadratic_program = quadratic_program_from_graph(graph=graphs[graph_name]) trajectory={'beta_0':[], 'gamma_0':[], 'energy':[]} offset = 1/4*quadratic_program.objective.quadratic.to_array(symmetric = True).sum() + 1/2*quadratic_program.objective.linear.to_array().sum() def callback(eval_count, params, mean, std_dev): trajectory['beta_0'].append(params[1]) trajectory['gamma_0'].append(params[0]) trajectory['energy'].append(-mean + offset) optimizers = { 'cobyla': COBYLA(), 'slsqp': SLSQP(), 'adam': ADAM() } qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=1, initial_point = [6.2,1.8],callback = callback) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) result = eigen_optimizer.solve(quadratic_program) fig = QAOA_widget(landscape_file=f'./resources/energy_landscapes/{graph_name}.csv', trajectory = trajectory, samples = result.samples) fig.show() graph_name = 'custom' quadratic_program = quadratic_program_from_graph(graphs[graph_name]) #Create callback to record total number of evaluations max_evals = 0 def callback(eval_count, params, mean, std_dev): global max_evals max_evals = eval_count #Create empty lists to track values energies = [] runtimes = [] num_evals=[] #Run QAOA for different values of p for p in range(1,10): print(f'Evaluating for p = {p}...') qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=p, callback=callback) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) start = time() result = eigen_optimizer.solve(quadratic_program) runtimes.append(time()-start) num_evals.append(max_evals) #Calculate energy of final state from samples avg_value = 0. for sample in result.samples: avg_value += sample.probability*sample.fval energies.append(avg_value) #Create and display plots energy_plot = go.Scatter(x = list(range(1,10)), y =energies, marker=dict(color=energies, colorscale = 'plasma')) runtime_plot = go.Scatter(x = list(range(1,10)), y =runtimes, marker=dict(color=runtimes, colorscale = 'plasma')) num_evals_plot = go.Scatter(x = list(range(1,10)), y =num_evals, marker=dict(color=num_evals, colorscale = 'plasma')) fig = make_subplots(rows = 1, cols = 3, subplot_titles = ['Energy value', 'Runtime', 'Number of evaluations']) fig.update_layout(width=1800,height=600, showlegend=False) fig.add_trace(energy_plot, row=1, col=1) fig.add_trace(runtime_plot, row=1, col=2) fig.add_trace(num_evals_plot, row=1, col=3) clear_output() fig.show() def plot_qaoa_energy_landscape(graph: nx.Graph, cvar: float = None): num_shots = 1000 seed = 42 simulator = Aer.get_backend('qasm_simulator') simulator.set_options(seed_simulator = 42) #Generate circuit circuit = qaoa_circuit(qubo = quadratic_program_from_graph(graph), p=1) circuit.measure(range(graph.number_of_nodes()),range(graph.number_of_nodes())) #Create dictionary with precomputed cut values for all bitstrings cut_values = {} size = graph.number_of_nodes() for i in range(2**size): bitstr = '{:b}'.format(i).rjust(size, '0')[::-1] x = [int(bit) for bit in bitstr] cut_values[bitstr] = maxcut_cost_fn(graph, x) #Perform grid search over all parameters data_points = [] max_energy = None for beta in np.linspace(0,np.pi, 50): for gamma in np.linspace(0, 4*np.pi, 50): bound_circuit = circuit.assign_parameters([beta, gamma]) result = simulator.run(bound_circuit, shots = num_shots).result() statevector = result.get_counts(bound_circuit) energy = 0 measured_cuts = [] for bitstring, count in statevector.items(): measured_cuts = measured_cuts + [cut_values[bitstring]]*count if cvar is None: #Calculate the mean of all cut values energy = sum(measured_cuts)/num_shots else: #raise NotImplementedError() #INSERT YOUR CODE HERE measured_cuts = sorted(measured_cuts, reverse = True) for w in range(int(cvar*num_shots)): energy += measured_cuts[w]/int((cvar*num_shots)) #Update optimal parameters if max_energy is None or energy > max_energy: max_energy = energy optimum = {'beta': beta, 'gamma': gamma, 'energy': energy} #Update data data_points.append({'beta': beta, 'gamma': gamma, 'energy': energy}) #Create and display surface plot from data_points df = pd.DataFrame(data_points) df = df.pivot(index='beta', columns='gamma', values='energy') matrix = df.to_numpy() beta_values = df.index.tolist() gamma_values = df.columns.tolist() surface_plot = go.Surface( x=gamma_values, y=beta_values, z=matrix, coloraxis = 'coloraxis' ) fig = go.Figure(data = surface_plot) fig.show() #Return optimum return optimum graph = graphs['custom'] optimal_parameters = plot_qaoa_energy_landscape(graph = graph) print('Optimal parameters:') print(optimal_parameters) optimal_parameters = plot_qaoa_energy_landscape(graph = graph, cvar = 0.2) print(optimal_parameters) from qc_grader import grade_lab2_ex4 # Note that the grading function is expecting a python dictionary # with the entries 'beta', 'gamma' and 'energy' grade_lab2_ex4(optimal_parameters)
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/qiskit-community/qiskit-translations-staging
qiskit-community
import torch from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123456 _ = torch.manual_seed(123456) # suppress output import numpy as np num_dim = 2 num_discrete_values = 8 num_qubits = num_dim * int(np.log2(num_discrete_values)) from scipy.stats import multivariate_normal coords = np.linspace(-2, 2, num_discrete_values) rv = multivariate_normal(mean=[0.0, 0.0], cov=[[1, 0], [0, 1]], seed=algorithm_globals.random_seed) grid_elements = np.transpose([np.tile(coords, len(coords)), np.repeat(coords, len(coords))]) prob_data = rv.pdf(grid_elements) prob_data = prob_data / np.sum(prob_data) import matplotlib.pyplot as plt from matplotlib import cm mesh_x, mesh_y = np.meshgrid(coords, coords) grid_shape = (num_discrete_values, num_discrete_values) fig, ax = plt.subplots(figsize=(9, 9), subplot_kw={"projection": "3d"}) prob_grid = np.reshape(prob_data, grid_shape) surf = ax.plot_surface(mesh_x, mesh_y, prob_grid, cmap=cm.coolwarm, linewidth=0, antialiased=False) fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() from qiskit import QuantumCircuit from qiskit.circuit.library import EfficientSU2 qc = QuantumCircuit(num_qubits) qc.h(qc.qubits) ansatz = EfficientSU2(num_qubits, reps=6) qc.compose(ansatz, inplace=True) qc.decompose().draw("mpl") qc.num_parameters from qiskit.primitives import Sampler shots = 10000 sampler = Sampler(options={"shots": shots, "seed": algorithm_globals.random_seed}) from qiskit_machine_learning.connectors import TorchConnector from qiskit_machine_learning.neural_networks import SamplerQNN def create_generator() -> TorchConnector: qnn = SamplerQNN( circuit=qc, sampler=sampler, input_params=[], weight_params=qc.parameters, sparse=False, ) initial_weights = algorithm_globals.random.random(qc.num_parameters) return TorchConnector(qnn, initial_weights) from torch import nn class Discriminator(nn.Module): def __init__(self, input_size): super(Discriminator, self).__init__() self.linear_input = nn.Linear(input_size, 20) self.leaky_relu = nn.LeakyReLU(0.2) self.linear20 = nn.Linear(20, 1) self.sigmoid = nn.Sigmoid() def forward(self, input: torch.Tensor) -> torch.Tensor: x = self.linear_input(input) x = self.leaky_relu(x) x = self.linear20(x) x = self.sigmoid(x) return x generator = create_generator() discriminator = Discriminator(num_dim) def adversarial_loss(input, target, w): bce_loss = target * torch.log(input) + (1 - target) * torch.log(1 - input) weighted_loss = w * bce_loss total_loss = -torch.sum(weighted_loss) return total_loss from torch.optim import Adam lr = 0.01 # learning rate b1 = 0.7 # first momentum parameter b2 = 0.999 # second momentum parameter generator_optimizer = Adam(generator.parameters(), lr=lr, betas=(b1, b2), weight_decay=0.005) discriminator_optimizer = Adam( discriminator.parameters(), lr=lr, betas=(b1, b2), weight_decay=0.005 ) from IPython.display import clear_output def plot_training_progress(): # we don't plot if we don't have enough data if len(generator_loss_values) < 2: return clear_output(wait=True) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 9)) # Generator Loss ax1.set_title("Loss") ax1.plot(generator_loss_values, label="generator loss", color="royalblue") ax1.plot(discriminator_loss_values, label="discriminator loss", color="magenta") ax1.legend(loc="best") ax1.set_xlabel("Iteration") ax1.set_ylabel("Loss") ax1.grid() # Relative Entropy ax2.set_title("Relative entropy") ax2.plot(entropy_values) ax2.set_xlabel("Iteration") ax2.set_ylabel("Relative entropy") ax2.grid() plt.show() import time from scipy.stats import multivariate_normal, entropy n_epochs = 50 num_qnn_outputs = num_discrete_values**num_dim generator_loss_values = [] discriminator_loss_values = [] entropy_values = [] start = time.time() for epoch in range(n_epochs): valid = torch.ones(num_qnn_outputs, 1, dtype=torch.float) fake = torch.zeros(num_qnn_outputs, 1, dtype=torch.float) # Configure input real_dist = torch.tensor(prob_data, dtype=torch.float).reshape(-1, 1) # Configure samples samples = torch.tensor(grid_elements, dtype=torch.float) disc_value = discriminator(samples) # Generate data gen_dist = generator(torch.tensor([])).reshape(-1, 1) # Train generator generator_optimizer.zero_grad() generator_loss = adversarial_loss(disc_value, valid, gen_dist) # store for plotting generator_loss_values.append(generator_loss.detach().item()) generator_loss.backward(retain_graph=True) generator_optimizer.step() # Train Discriminator discriminator_optimizer.zero_grad() real_loss = adversarial_loss(disc_value, valid, real_dist) fake_loss = adversarial_loss(disc_value, fake, gen_dist.detach()) discriminator_loss = (real_loss + fake_loss) / 2 # Store for plotting discriminator_loss_values.append(discriminator_loss.detach().item()) discriminator_loss.backward() discriminator_optimizer.step() entropy_value = entropy(gen_dist.detach().squeeze().numpy(), prob_data) entropy_values.append(entropy_value) plot_training_progress() elapsed = time.time() - start print(f"Fit in {elapsed:0.2f} sec") with torch.no_grad(): generated_probabilities = generator().numpy() fig = plt.figure(figsize=(18, 9)) # Generated CDF gen_prob_grid = np.reshape(np.cumsum(generated_probabilities), grid_shape) ax1 = fig.add_subplot(1, 3, 1, projection="3d") ax1.set_title("Generated CDF") ax1.plot_surface(mesh_x, mesh_y, gen_prob_grid, linewidth=0, antialiased=False, cmap=cm.coolwarm) ax1.set_zlim(-0.05, 1.05) # Real CDF real_prob_grid = np.reshape(np.cumsum(prob_data), grid_shape) ax2 = fig.add_subplot(1, 3, 2, projection="3d") ax2.set_title("True CDF") ax2.plot_surface(mesh_x, mesh_y, real_prob_grid, linewidth=0, antialiased=False, cmap=cm.coolwarm) ax2.set_zlim(-0.05, 1.05) # Difference ax3 = fig.add_subplot(1, 3, 3, projection="3d") ax3.set_title("Difference between CDFs") ax3.plot_surface( mesh_x, mesh_y, real_prob_grid - gen_prob_grid, linewidth=2, antialiased=False, cmap=cm.coolwarm ) ax3.set_zlim(-0.05, 0.1) plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/AmirhoseynpowAsghari/Qiskit-Tutorials
AmirhoseynpowAsghari
import numpy as np import matplotlib.pyplot as plt # Define parameters^M frequency = 100 # Hz (cycles per second)^M sampling_rate = 10000 # Samples per second^M duration = 1 # Seconds^M time = np.linspace(0, duration, sampling_rate) # Generate signal^M signal = np.sin(2 * np.pi * frequency * time) # Calculate average^M average = np.mean(signal) # Print average^M print("Average of the signal:", average) # Plot signal^M plt.plot(time, signal) plt.xlabel("Time (s)") plt.ylabel("Signal") plt.title("Fast-Oscillating Signal (Average: {:.4f})".format(average)) plt.grid(True) plt.show() import numpy as np import matplotlib.pyplot as plt w_0 = 1e-1 w = np.linspace(0, 1e3, 1000) func = np.exp(1j*(w_0 - 1*w)) plt.figure(figsize=(10,4)) plt.plot(w, func) plt.grid() from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram # Create a Quantum Circuit with 3 qubits qc = QuantumCircuit(3, 3) # Create the Bell state qc.h(1) qc.cx(1, 2) # Prepare the state to be teleported qc.x(0) # Example: teleporting |1> # Entangle the qubit to be teleported with the first qubit of the Bell pair qc.cx(0, 1) qc.h(0) # Measure the qubits qc.measure([0, 1], [0, 1]) # Apply conditional operations based on the measurement results qc.cx(1, 2) qc.cz(0, 2) # Measure the teleported qubit qc.measure(2, 2) # Simulate the circuit simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend=simulator, shots=1024).result() # Get the counts of the measurement results counts = result.get_counts() # Plot the results plot_histogram(counts, title="Standard Quantum Teleportation") qc.draw(output='mpl') from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from qiskit.providers.aer import noise # Create a Quantum Circuit with 3 qubits qc_mixed = QuantumCircuit(3, 3) # Create the Bell state qc_mixed.h(1) qc_mixed.cx(1, 2) # Prepare the state to be teleported qc_mixed.x(0) # Example: teleporting |1> # Entangle the qubit to be teleported with the first qubit of the noisy Bell pair qc_mixed.cx(0, 1) qc_mixed.h(0) # Measure the qubits qc_mixed.measure([0, 1], [0, 1]) # Apply conditional operations based on the measurement results qc_mixed.cx(1, 2) qc_mixed.cz(0, 2) # Measure the teleported qubit qc_mixed.measure(2, 2) # Define a noise model with bit-flip noise bit_flip_prob = 0.2 bit_flip_noise = noise.pauli_error([('X', bit_flip_prob), ('I', 1 - bit_flip_prob)]) # Create a noise model noise_model = noise.NoiseModel() noise_model.add_all_qubit_quantum_error(bit_flip_noise, ['x', 'h']) # Add single-qubit noise to the circuit to simulate the mixed state qc_noisy = qc_mixed.copy() qc_noisy.append(bit_flip_noise.to_instruction(), [1]) qc_noisy.append(bit_flip_noise.to_instruction(), [2]) # Simulate the circuit with noise simulator = Aer.get_backend('qasm_simulator') result_mixed = execute(qc_noisy, backend=simulator, shots=1024, noise_model=noise_model).result() # Get the counts of the measurement results counts_mixed = result_mixed.get_counts() # Plot the results plot_histogram(counts_mixed, title="Teleportation with Mixed State Resource") import numpy as np import matplotlib.pyplot as plt # Define parameters omega_0 = 1.0 # Resonant frequency of the two-level atom gamma = 0.1 # Width of the Lorentzian peak for resonant interaction gamma_off = 0.3 # Width of the off-resonant interaction omega_off = 1.5 # Center frequency for off-resonant interaction # Frequency range omega = np.linspace(0, 2, 1000) # Lorentzian spectral density function for resonant interaction def J_resonant(omega, omega_0, gamma): return gamma**2 / ((omega - omega_0)**2 + gamma**2) # Lorentzian spectral density function for off-resonant interaction def J_off_resonant(omega, omega_off, gamma_off): return gamma_off**2 / ((omega - omega_off)**2 + gamma_off**2) # Total spectral density def J_total(omega, omega_0, gamma, omega_off, gamma_off): return J_resonant(omega, omega_0, gamma) + J_off_resonant(omega, omega_off, gamma_off) # Compute spectral densities J_omega_resonant = J_resonant(omega, omega_0, gamma) J_omega_off_resonant = J_off_resonant(omega, omega_off, gamma_off) J_omega_total = J_total(omega, omega_0, gamma, omega_off, gamma_off) # Plot the spectral densities plt.figure(figsize=(10, 6)) plt.plot(omega, J_omega_resonant, label='Resonant Interaction $J_{\\text{res}}(\\omega)$') plt.plot(omega, J_omega_off_resonant, label='Off-Resonant Interaction $J_{\\text{off-res}}(\\omega)$') plt.plot(omega, J_omega_total, label='Total Spectral Density $J_{\\text{total}}(\\omega)$', linestyle='--') plt.axvline(x=omega_0, color='r', linestyle='--', label='$\\omega_0$ (Resonant Frequency)') plt.axvline(x=omega_off, color='g', linestyle='--', label='$\\omega_{\\text{off}}$ (Off-Resonant Frequency)') plt.xlabel('$\\omega$ (Frequency)') plt.ylabel('$J(\\omega)$ (Spectral Density)') plt.title('Spectral Density for Two-Level Atom with Resonant and Off-Resonant Interactions') plt.legend() plt.grid(True) plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.tools.visualization import circuit_drawer q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) circuit_drawer(qc, output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/IvanIsCoding/Quantum
IvanIsCoding
from math import gcd, log from random import randint def is_prime(N): """Returns if N is prime or not. Notice that this is not optimal, there is faster primality testing algorithms e.g. Miller-Rabin """ if N == 2: return True # only even prime if N % 2 == 0 or N <= 1: return False # even numbers and 1 are not prime for i in range(3, N, 2): # only try odd candidates if i*i > N: break # we only need to check up to sqrt(N) if N % i == 0: return False # found a factor return True def find_power_k(N): """Returns the smallest k > 1 such that N**(1/k) is an integer, or 1 if there is no such k. """ upper_bound = int(log(N)/log(3)) for k in range(2, upper_bound + 1): p = int(N**(1/k)) if p**k == N: return k return 1 def order_finding(a, N): """Returns the smallest r such that a^r = 1 mod N Notice that this is a naive classic implementation and is exponentially slower than the quantum version invented by Peter Shor. """ i = 1 a_i = a % N while a_i != 1: i += 1 a_i = (a_i * a) % N return i order_finding(2, 15) def shor_algorithm(N): """Returns a pair of integers (P, Q) such that PQ = N for integer N""" if N % 2 == 0: # even case return (N//2, 2) if is_prime(N): # prime case return (N, 1) # N is primes, factors cannot be found if find_power_k(N) > 1: # prime power case P = int(N**(1/find_power_k(N))) # we find a k such that N**(1/k) is an integer Q = N//P return (P, Q) # Now we can assume that the criteria for Shor's algorithm is met while True: # Non-deterministic, we will try multiple values for a a = randint(2, N-1) # pick random a if gcd(a, N) != 1: # Lucky case: a and N are not coprime! P = gcd(a, N) # gcd yields a non-trivial factor Q = N//P return (P, Q) r = order_finding(a, N) # quantum subroutine of the code if r % 2 == 0: continue P = gcd(a**(r//2) - 1, N) if P != 1: Q = N//P # gcd yielded non trivial factor return (P, Q) N = 10013 P, Q = shor_algorithm(N) print( "Shor's algorithm found {} = {} x {} which is {}!".format(N, P, Q, ["incorrect", "correct"][P*Q==N]) ) S, T = shor_algorithm(Q) print( "Shor's algorithm found {} = {} x {} which is {} again!".format(Q, S, T, ["incorrect", "correct"][S*T==Q]) )
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") # from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open(filename, "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) filename = "job_ids_ibmq_jakarta_100step_20220413_030821_.pkl" # change here with open(filename, "rb") as f: job_ids_dict = pickle.load(f) job_ids = job_ids_dict["job_ids"] cal_job_id = job_ids_dict["cal_job_id"] retrieved_jobs = [] for job_id in job_ids: retrieved_jobs.append(backend.retrieve_job(job_id)) retrieved_cal_job = backend.retrieve_job(cal_job_id) cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/erikberter/qiskit-quantum-artificial-life
erikberter
from qiskit import * from qiskit.aqua.circuits.gates import cry from qiskit.visualization import plot_histogram import numpy as np import random import sys import matplotlib.pyplot as plt theta = 2*np.pi/3 thetaR = np.pi/4 fileNum = 30 sim = Aer.get_backend('qasm_simulator') # Devuelve el valor esperado de un circuito con un solo bit de registro def getExpectedValue(qc, shots=8192): job = execute(qc, sim, shots=shots) count = job.result().get_counts() a,b = [count[a]/shots if a in count else 0 for a in ['0','1']] return a-b def printHistogram(qc, shots=8192): job = execute(qc, sim, shots=shots) return plot_histogram(job.result().get_counts()) # Devuelve la Gate time_Lapse que aplica una iteraciΓ³n de paso de tiempo # # Changed : Float que representa el valor en radianes del gate CRY def getDecoherence(changed): decoherenceG = QuantumCircuit(2,1, name='decoherence') decoherenceG.ry(changed,1) decoherenceG.cx(0,1) decoherenceG.ry(-changed,1) decoherenceG.cx(0,1) decoherenceG.cx(1,0) decoherenceG.measure([1],[0]) decoherenceG.reset(1) return decoherenceG # Crea un circuito general de una Artificial Life de poblaciΓ³n 1 # # time : Integer representando la cantidad de iteraciones # initial : Float que representa los radiones de la gate U3 inicial # changed : Float que representa los radianes de la gate CRY # pop : Integer representando la cantidad de poblacion que tendra el algoritmo def getCircuit(pop=1,time=3, initial=theta, changed=theta, measure = True): decoherenceG = getDecoherence(changed).to_instruction() qc = QuantumCircuit(3*pop,pop) for i in range(pop): qc.u3(initial,0,0,i*3) qc.cx(i*3,i*3+1) qc.barrier() for i in range(0,time): #cry for j in range(pop): qc.append(decoherenceG, [j*3+1,j*3+2],[j]) qc.barrier() if(measure): qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) return qc # Aumenta el la cantidad de capas de tiempo del circuito. def addTimeLapse(qc,time,measure=False, changed = theta): decoherenceG = getDecoherence(changed).to_instruction() qBits = int(len(qc.qubits)/3) for i in range(0,time): #cry for j in range(qBits): qc.append(decoherenceG, [j*3+1,j*3+2],[j]) qc.barrier() if(measure): qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) # Crea un escenario general de clonaciΓ³n de poblaciΓ³n asexual mediante clonaciΓ³n exponencial # # time : Integer representando la cantidad de iteraciones # pop : Integer representando la cantidad de poblacion que tendra el algoritmo # initial : Float que representa los radiones de la gate U3 inicial # changed : Float que representa los radianes de la gate CRY # mutationRate : Float que representa el ratio de mutaciΓ³n def getCircuitG(time=3, pop=2, initial=theta, changed=theta, mutationRate = 0, mutation=False): decoherenceG = getDecoherence(changed).to_instruction() qc = QuantumCircuit(3*pop,pop) qc.u3(initial,0,0,0) qc.cx(0,1) actPop = 1 qc.barrier() for i in range(0,time): # Adding the Time_Lapse gates for j in range(0,actPop): qc.append(decoherenceG, [3*j+1,3*j+2],[j]) qc.barrier() # Adding the new population actPopi = actPop for z in range(0,min(actPop, pop-actPop)): qc.cx(3*z, 3*actPopi) if mutation: x = np.random.normal(loc=0, scale=mutationRate) qc.rx(x, 3*actPopi) y = np.random.normal(loc=0, scale=mutationRate) qc.ry(y, 3*actPopi) qc.cx(3*actPopi, 3*actPopi+1) qc.barrier() actPopi+=1 actPop = actPopi qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) return qc getCircuitG(pop=2, time=2).draw(output='mpl') getCircuit(pop=2, time=2).draw(output='mpl') color = ["b","g","r"] def checkPopulationParameters(shot = 50, timeSet = [0,1,2], parameter = "changed"): global fileNum for j in range(0,len(timeSet)): x = [] y = [] for i in range(int(shot)): if(i%10==0): sys.stdout.write(f"Work progress: Iteration {j} - {100*float(i)/(shot)}% \r" ) sys.stdout.flush() rand = random.uniform(0, 1) x+= [rand] timeT = timeSet[j] if (parameter=="changed"): qc = getCircuit(time = timeT, changed=rand*np.pi) elif(parameter=="initial"): qc = getCircuit(time = timeT, initial=rand*np.pi) y += [getExpectedValue(qc)] plt.scatter(x, y,c=color[j], label=f"Time {timeSet[j]}") plt.legend(loc="lower left") plt.savefig(f"file_RA{fileNum}_N{shot}.png") fileNum+=1 checkPopulationParameters(parameter="initial") qc = getCircuitG(time=3,pop=3, initial=np.pi, changed = np.pi/5) printHistogram(qc, shots=1000) qc = getCircuitG(pop=2, time=2,mutation=True, mutationRate=0.5) #addTimeLapse(qc, time=3) qc.draw(output='mpl') #CreaciΓ³n del circuito cuantico q=QuantumRegister(10) c=ClassicalRegister(10) qc=QuantumCircuit(q,c) #AsignaciΓ³n aleatoria de sexos a cada individuo qc.h(q[0]) qc.cx(q[0],q[2]) qc.h(q[3]) qc.cx(q[3],q[5]) qc.barrier() #ComprobaciΓ³n de la posibilidad de la reproducciΓ³n qc.cx(q[2],q[6]) qc.cx(q[5],q[6]) qc.barrier() #DeterminaciΓ³n del fenotipo qc.u3(np.pi/4,0,0,q[0]) qc.cx(q[0],q[1]) qc.u3(3*np.pi/4,0,0,q[3]) qc.cx(q[3],q[4]) qc.barrier() #CreaciΓ³n del hijo qc.h(q[8]) qc.cu3(5*np.pi/2,0,0,q[0],q[8]) qc.cu3(5*np.pi/2,0,0,q[3],q[8]) qc.cx(q[8],q[7]) qc.barrier() #Supervivencia del hijo qc.x(q[6]) qc.ccx(q[6],q[7],q[8]) qc.x(q[6]) qc.barrier() qc.cx(q[8],q[9]) #Medida qc.measure(q[6],c[6]) qc.measure(q[8],c[8]) backend=Aer.get_backend('qasm_simulator') result=execute(qc,backend).result().get_counts() qc.draw(output='mpl') plot_histogram(result) # Crea un circuito general de una Artificial Life de poblaciΓ³n 1 con un background customizado # # time : Integer representando la cantidad de iteraciones # initial : Float que representa los radiones de la gate U3 inicial # changed : Float que representa los radianes de la gate CRY # pop : Integer representando la cantidad de poblaciΓ³n que tendrΓ‘ el algoritmo def getCircuitCB(pop=1,time=3, initial=theta, changed=theta, measure = True, background_change=[np.pi/4,np.pi/8,np.pi/4], background_sign = [0,1,0]): qc = QuantumCircuit(3*pop,pop) for i in range(pop): qc.u3(initial,0,0,i*3) qc.cx(i*3,i*3+1) qc.barrier() for i in range(0,time): #cry for j in range(pop): decoherenceG = getDecoherence(background_change[i]).to_instruction() if(background_sign[i]==1): qc.x(j*3+1) qc.append(decoherenceG, [j*3+1,j*3+2],[j]) if(background_sign[i]==1): qc.x(j*3+1) qc.barrier() if(measure): qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) return qc getCircuitCB(pop=1, time=3).draw(output='mpl')
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
!pip install --upgrade pyscf 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, ) es_problem = driver.run() #!pip install qiskit_algorithms from qiskit_algorithms.optimizers import SPSA # simultaneous perturbation stochastic approximation from qiskit.circuit.library import EfficientSU2 # ansatz para o circuito variacional ansatz = EfficientSU2(2) ansatz.decompose().draw('mpl') from qiskit.primitives import Estimator estimator = Estimator() callback = lambda nfev, params, fval, step, acc: print(f'Evaluation {nfev}: {fval}') optimizer = SPSA(callback=callback, maxiter=1000) cost_func = lambda params: estimator.run(ansatz, H2_op, parameter_values=params).result().values[0] result = optimizer.minimize(cost_func, x0=np.zeros(ansatz.num_parameters))
https://github.com/Rishwi/Beyond-Classical-a-quantum-computing-crash-course-using-qiskit
Rishwi
pip install qiskit from qiskit import * qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr , cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.measure(qr,cr) circuit.draw(output='mpl') from qiskit.visualization import plot_histogram backend=Aer.get_backend('qasm_simulator') counts = execute(circuit, backend= backend, shots= 1024).result().get_counts() plot_histogram(counts) IBMQ.save_account('copy your token here') IBMQ.load_account() from qiskit.visualization import plot_histogram from qiskit.tools.monitor import job_monitor #used to monitor the job process provider = IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmq_16_melbourne') job=execute(circuit, backend=qcomp) job_monitor(job) rishwi=job.result() plot_histogram(rishwi.get_counts(circuit))
https://github.com/108mk/Quantum_Algorithms_and_Qiskit
108mk
# initialization import numpy as np # importing Qiskit from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, assemble, transpile # import basic plot tools from qiskit.visualization import plot_histogram import matplotlib as mpl # set the length of the n-bit input string. n = 2 #----------This was the original case considered by David Duetzch-----------# # set the length of the n-bit input string. const_oracle = QuantumCircuit(n+1) output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw("mpl") balanced_oracle = QuantumCircuit(n+1) #------input a 2-bit string as of your choice!!!!!!!! b_str = "11" balanced_oracle = QuantumCircuit(n+1) # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw("mpl") # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() balanced_oracle.draw("mpl") # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw("mpl") dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.draw("mpl") # Add oracle dj_circuit = QuantumCircuit.compose(dj_circuit,balanced_oracle) dj_circuit.draw("mpl") # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) # Display circuit dj_circuit.draw("mpl") # use local simulator aer_sim = Aer.get_backend('aer_simulator') qobj = assemble(dj_circuit, aer_sim) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) #---------CONCLUDING REMARKS---------------- ###--------THE ABOVE ALGORITHM CAN BE EXTENDED TO N-VARAIBLE CASE. IT IS CALLED DUETZCH-JOZSA ALGORITHM-----
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, assemble, Aer from qiskit.tools.visualization import plot_histogram from math import pi import matplotlib.pyplot as plt q = QuantumRegister(1,'q') c = ClassicalRegister(1,'c') qc = QuantumCircuit(q, c) qc.h(0) qc.measure(0,0) qc.x(0).c_if(c, 0) qc.draw(output='mpl') q = QuantumRegister(3,'q') c = ClassicalRegister(3,'c') qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.barrier() qc.measure(q,c) qc.draw('mpl') print(bin(3)) print(bin(7)) q = QuantumRegister(3,'q') c = ClassicalRegister(3,'c') qc = QuantumCircuit(q, c) qc.h(0) qc.h(1) qc.h(2) qc.barrier() qc.measure(q,c) qc.x(2).c_if(c, 3) # for the 011 case qc.x(2).c_if(c, 7) # for the 111 case qc.draw(output='mpl') nq = 2 m = 2 q = QuantumRegister(nq,'q') c = ClassicalRegister(m,'c') qc_S = QuantumCircuit(q,c) qc_S.h(0) qc_S.x(1) qc_S.draw('mpl') cu_circ = QuantumCircuit(2) cu_circ.cp(pi/2,0,1) cu_circ.draw('mpl') for _ in range(2**(m-1)): qc_S.cp(pi/2,0,1) qc_S.draw('mpl') def x_measurement(qc, qubit, cbit): """Measure 'qubit' in the X-basis, and store the result in 'cbit'""" qc.h(qubit) qc.measure(qubit, cbit) x_measurement(qc_S, q[0], c[0]) qc_S.draw('mpl') qc_S.reset(0) qc_S.h(0) qc_S.draw('mpl') qc_S.p(-pi/2,0).c_if(c,1) qc_S.draw('mpl') ## 2^t c-U operations (with t=m-2) for _ in range(2**(m-2)): qc_S.cp(pi/2,0,1) x_measurement(qc_S, q[0], c[1]) qc_S.draw('mpl') sim = Aer.get_backend('qasm_simulator') count0 = execute(qc_S, sim).result().get_counts() key_new = [str(int(key,2)/2**m) for key in list(count0.keys())] count1 = dict(zip(key_new, count0.values())) fig, ax = plt.subplots(1,2) plot_histogram(count0, ax=ax[0]) plot_histogram(count1, ax=ax[1]) plt.tight_layout() nq = 3 # number of qubits m = 3 # number of classical bits q = QuantumRegister(nq,'q') c = ClassicalRegister(m,'c') qc = QuantumCircuit(q,c) qc.h(0) qc.x([1,2]) qc.draw('mpl') cu_circ = QuantumCircuit(nq) cu_circ.mcp(pi/4,[0,1],2) cu_circ.draw('mpl') for _ in range(2**(m-1)): qc.mcp(pi/4,[0,1],2) qc.draw('mpl') x_measurement(qc, q[0], c[0]) qc.draw('mpl') qc.reset(0) qc.h(0) qc.draw('mpl') qc.p(-pi/2,0).c_if(c,1) qc.draw('mpl') for _ in range(2**(m-2)): qc.mcp(pi/4,[0,1],2) x_measurement(qc, q[0], c[1]) qc.draw('mpl') # initialization of qubit q0 qc.reset(0) qc.h(0) # phase correction qc.p(-pi/4,0).c_if(c,1) qc.p(-pi/2,0).c_if(c,2) qc.p(-3*pi/4,0).c_if(c,3) # c-U operations for _ in range(2**(m-3)): qc.mcp(pi/4,[0,1],2) # X measurement qc.h(0) qc.measure(0,2) qc.draw('mpl') count0 = execute(qc, sim).result().get_counts() key_new = [str(int(key,2)/2**m) for key in list(count0.keys())] count1 = dict(zip(key_new, count0.values())) fig, ax = plt.subplots(1,2) plot_histogram(count0, ax=ax[0]) plot_histogram(count1, ax=ax[1]) fig.tight_layout() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
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)) new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0) plot_circuit_layout(new_circ_lv0, backend)
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
# -*- 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/Fergus-Hayes/qiskit_tools
Fergus-Hayes
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ from qiskit.circuit.library import PhaseGate from qiskit.extensions import HamiltonianGate from qiskit.quantum_info import random_hermitian import qiskit_tools as qt import numpy as np import matplotlib.pyplot as plt import matplotlib matplotlib.rcParams['mathtext.fontset'] = 'stix' matplotlib.rcParams['font.family'] = 'STIXGeneral' width=0.75 color='black' fontsize=28 ticksize=22 figsize=(10,8) nx = 1 A = random_hermitian(2**nx).to_matrix() print(A) p_suc = 0.95 phase = True n = nx + int(np.ceil(np.log2(2. + 1./(2.*(1-p_suc))))) print('The number of output qubits is set to',n) lambda_min = np.real(np.min(np.linalg.eigvals(A))) lambda_max = np.real(np.max(np.linalg.eigvals(A))) kappa = np.abs(lambda_max/lambda_min) print('Minimum eigenvalue, maximum eigenvalue and conditional number of A:', lambda_min, lambda_max, kappa) # Calculate the new scale of the relative magnitudes of maximum and minimum eigenvalues rescale = int((2**(n-phase)-1)/kappa) # Make sure this scaling is not vanishingly small if rescale < 1.e-7: rescale = 1 # determine the number of integer qubits required nint = qt.get_nint(rescale) # Assert that the number of integer qubits is equal to or greater than the number of ancillary qubits assigned if nint < n - phase: nint = n - phase t0 = qt.bin_to_dec(qt.my_binary_repr(rescale, nint=nint, n=nint, phase=False), nint=0, phase=False) / (lambda_min * (2**phase)) t = 2 * np.pi * t0 qreg = QuantumRegister(nx, 'x') qout = QuantumRegister(n, 'out') circ = QuantumCircuit(qreg, qout) A_gate = HamiltonianGate(A, t) circ.h(qreg[0]); circ = qt.PhaseEst(circ, qreg, qout, A_gate) circ.draw('latex') backend = Aer.get_backend('statevector_simulator') job = execute(circ, backend) result = job.result() state_vector = np.asarray(result.get_statevector()) state_v = np.asarray(state_vector).reshape((2**n,2**nx)).T state_v = np.sum(state_v, axis=0) state_v = state_v/np.sqrt(np.sum(np.abs(state_v)**2)) xs = np.fft.fftfreq(2**n,2.**(-n))/(t0*2**(n)) fig = plt.figure(figsize=np.array(figsize)*[1,2]) ax = fig.add_subplot(211) plt.scatter(xs, state_v.real, marker='.', color='black') plt.scatter(xs, state_v.imag, marker='.', color='grey') ax.set_ylabel('Amplitude', fontsize=fontsize); ax.tick_params(axis='both', labelsize=ticksize); ax.axvline(lambda_min, ls='--', color='black') ax.axvline(lambda_max, ls=':', color='black') ax = fig.add_subplot(212) plt.scatter(xs, np.abs(state_v)**2, marker='.', color='black') ax.set_xlabel(r'$\theta$', fontsize=fontsize); ax.set_ylabel('Probability', fontsize=fontsize); ax.tick_params(axis='both', labelsize=ticksize); ax.axvline(lambda_min, ls='--', color='black') ax.axvline(lambda_max, ls=':', color='black') plt.show()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
import numpy as np def grovers_dist(num_qubits, marked_item, n_iterations): dist = {} for i in range(2**num_qubits): key = bin(i)[2:].zfill(num_qubits) theta = np.arcsin(1/np.sqrt(2 ** num_qubits)) if i == marked_item: dist[key] = np.sin((2*n_iterations+1)*theta)**2 else: dist[key] = (np.cos((2*n_iterations+1)*theta)/(np.sqrt(2 ** num_qubits - 1)))**2 return dist num_qubits = 4 marked_item = 6 n_iterations = int(np.pi * np.sqrt(2 ** num_qubits) / 4) grovers_dist(num_qubits, marked_item, n_iterations)
https://github.com/xtophe388/QISKIT
xtophe388
# Checking the version of PYTHON; we only support 3 at the moment import sys if sys.version_info < (3,0): raise Exception('Please use Python version 3 or greater.') # useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np import time from pprint import pprint # importing the QISKit from qiskit import QuantumCircuit, QuantumProgram #import Qconfig # import basic plot tools from qiskit.tools.visualization import plot_histogram QPS_SPECS = { 'circuits': [{ 'name': 'W_states', 'quantum_registers': [{ 'name':'q', 'size':5 }], 'classical_registers': [{ 'name':'c', 'size':5 }]}], } "Choice of the backend" # The flag_qx2 must be "True" for using the ibmqx2. # "True" is also better when using the simulator #backend = 'ibmqx2' # not advisable if other pending jobs! #backend = 'ibmqx4' # not advisable if other pending jobs! backend = 'local_qasm_simulator' #OK #backend = 'ibmqx_hpc_qasm_simulator' #OK flag_qx2 = True if backend == 'ibmqx4': flag_qx2 = False print("Your choice for the backend is: ", backend, "flag_qx2 is: ", flag_qx2) # Here, two useful routine # Define a F_gate def F_gate(circ,q,i,j,n,k) : theta = np.arccos(np.sqrt(1/(n-k+1))) circ.ry(-theta,q[j]) circ.cz(q[i],q[j]) circ.ry(theta,q[j]) circ.barrier(q[i]) # Define the cxrv gate which uses reverse CNOT instead of CNOT def cxrv(circ,q,i,j) : circ.h(q[i]) circ.h(q[j]) circ.cx(q[j],q[i]) circ.h(q[i]) circ.h(q[j]) circ.barrier(q[i],q[j]) # 3-qubit W state Q_program = QuantumProgram(specs=QPS_SPECS) #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) W_states = Q_program.get_circuit('W_states') q = Q_program.get_quantum_register('q') c = Q_program.get_classical_register('c') W_states.x(q[2]) #start is |100> F_gate(W_states,q,2,1,3,1) # Applying F12 F_gate(W_states,q,1,0,3,2) # Applying F23 if flag_qx2 : # option ibmqx2 W_states.cx(q[1],q[2]) # cNOT 21 W_states.cx(q[0],q[1]) # cNOT 32 else : # option ibmqx4 cxrv(W_states,q,1,2) cxrv(W_states,q,0,1) # Coin tossing W_states.h(q[3]) W_states.h(q[4]) for i in range(5) : W_states.measure(q[i] , c[i]) circuits = ['W_states'] "Dotted alphabet" top_bottom = "β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ" blank = "β–ˆ β–ˆ" chosen = [] chosen = chosen + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] chosen = chosen + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ"] chosen = chosen + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ"] chosen = chosen + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ"] chosen = chosen + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] chosen = chosen + ["β–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] chosen = chosen + ["β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] chosen = chosen + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] chosen = chosen + ["β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] chosen = chosen + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_left = [] here_left = here_left + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_left = here_left + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_left = here_left + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_left = here_left + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_left = here_left + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_left = here_left + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_left = here_left + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_left = here_left + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ"] here_left = here_left + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_left = here_left + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_center = [] here_center = here_center + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_center = here_center + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_center = here_center + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ"] here_center = here_center + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_center = here_center + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_center = here_center + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_center = here_center + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_center = here_center + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ"] here_center = here_center + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_center = here_center + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_right = [] here_right = here_right + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_right = here_right + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_right = here_right + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_right = here_right + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ"] here_right = here_right + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ"] here_right = here_right + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_right = here_right + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ"] here_right = here_right + ["β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ"] here_right = here_right + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] here_right = here_right + ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] goa=["β–ˆ β–ˆ","β–ˆ ( ) β–ˆ","β–ˆ ( ) β–ˆ","β–ˆ / O O \ β–ˆ","β–ˆ )|( β–ˆ","β–ˆ @ β–ˆ","β–ˆ = β–ˆ","β–ˆ Y β–ˆ","β–ˆ β–ˆ"] car=["β–ˆ β–ˆ","β–ˆ _______ β–ˆ","β–ˆ / \ β–ˆ","β–ˆ Β° _______ Β° β–ˆ","β–ˆ / \ β–ˆ","β–ˆ (O) ### (O) β–ˆ","β–ˆ =+=====+= β–ˆ","β–ˆ || || β–ˆ","β–ˆ β–ˆ"] "(RE)INITIATES STATISTICS" nb_randomnb = 0 nb_left = 0 nb_center = 0 nb_right = 0 nb_switches = 0 nb_stays = 0 nb_won_switching = 0 nb_won_sticking = 0 nb_games = 0 n_won = 0 "HERE START THE GAME" "Hiding the car and the two goats behind the three doors" Label = ["left", "central", "right"] shots = 1 repeat = "Y" while repeat == "Y": nb_of_cars = 4 while nb_of_cars != 1: result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=5, timeout=600) c5str = str(result.get_counts('W_states')) nb_of_cars = int(c5str[4]) + int(c5str[5]) + int(c5str[6]) #this is for checking results from the real computer: if nb_of_cars == 0: print("They managed to hide three goats and no car behind the doors! Restarting the hiding process...") if nb_of_cars >= 2: print("They managed to hide", nb_of_cars, "cars behind the doors! Restarting the hiding process...") print(top_bottom," ",top_bottom," ",top_bottom) for i in range(9): print(here_left[i]," ",here_center[i]," ",here_right[i]) print(top_bottom," ",top_bottom," ",top_bottom,"\n") door = input("Game master: Your choice? letter l: left door, c: central door, r: right door + enter\n").upper() picl = here_left picc = here_center picr = here_right if (door == "L"): Doorchosen = 1 nb_left = nb_left + 1 picl = chosen else: if (door == "C"): Doorchosen = 2 nb_center = nb_center + 1 picc=chosen else: Doorchosen = 3 nb_right = nb_right + 1 picr = chosen print('Game master: Your choice was the',Label[Doorchosen-1], "door") "AN OPPORTUNITY TO CHANGE YOUR MIND" c5str = str(result.get_counts('W_states')) randomnb = (int(c5str[2]) + int(c5str[3])) %2 if c5str[4] == "1": #car behind left door Doorwinning = 1 if Doorchosen == 1: Dooropen = 2 + randomnb Doorswitch = 3 - randomnb if Doorchosen == 2: Dooropen = 3 Doorswitch = 1 if Doorchosen == 3: Dooropen = 2 Doorswitch = 1 if c5str[5] == "1": #car behind central door Doorwinning = 2 if Doorchosen == 2: Dooropen = 1 + 2*randomnb Doorswitch = 3 - 2*randomnb if Doorchosen == 1: Dooropen = 3 Doorswitch = 2 if Doorchosen == 3: Dooropen = 1 Doorswitch = 2 if c5str[6] == "1": #car behind right door Doorwinning = 3 if Doorchosen == 3: Dooropen = randomnb + 1 Doorswitch = 2 - randomnb if Doorchosen == 1: Dooropen = 2 Doorswitch = 3 if Doorchosen == 2: Dooropen = 1 Doorswitch = 3 if Dooropen == 1: picl = goa if Dooropen == 2: picc = goa if Dooropen == 3: picr = goa print(top_bottom," ",top_bottom," ",top_bottom) for i in range(9): print(picl[i]," ",picc[i]," ",picr[i]) print(top_bottom," ",top_bottom," ",top_bottom,"\n") print('I opened the', Label[Dooropen-1], 'door and you see a goat') print('You get now an opportunity to change your choice!') print("Do you want to switch for the ",Label[Doorswitch-1], " door?") I_switch = input(" Answer by (y/n) + enter\n").upper() if (I_switch == "Y"): Doorfinal = Doorswitch else: Doorfinal = Doorchosen "FINAL ANNOUNCE" if Doorfinal == Doorwinning: if Doorfinal == 1: picl = car if Doorfinal == 2: picc = car if Doorfinal == 3: picr = car endmessage = 'won the car! Congratulations!' else: if Doorfinal == 1: picl = goa if Doorfinal == 2: picc = goa if Doorfinal == 3: picr = goa endmessage = 'won a goat! Sorry!' print(top_bottom," ",top_bottom," ",top_bottom) for i in range(9): print(picl[i]," ",picc[i]," ",picr[i]) print(top_bottom," ",top_bottom," ",top_bottom,"\n") print('Game master: You opened the',Label[Doorfinal-1],'door and', endmessage) "STATISTICS" nb_games = nb_games + 1 nb_randomnb = nb_randomnb + randomnb if Doorfinal == Doorswitch: nb_switches = nb_switches +1 if c5str[Doorfinal+3] == "1": nb_won_switching = nb_won_switching + 1 else: nb_stays = nb_stays+1 if c5str[Doorfinal+3] == "1": nb_won_sticking = nb_won_sticking + 1 n_won = nb_won_switching + nb_won_sticking print() print("YOUR STATS") print("nb of games: ", nb_games," total nb won:", n_won, " first choice: left",nb_left," center", nb_center,"right", nb_right) print("nb sticking: ",nb_stays," nb won when sticking: ",nb_won_sticking,"nb switching:",nb_switches," nb won when switching:",nb_won_switching) repeat = input("Another game? Answer by (y/n) + enter\n").upper() print("Game over") %run "../version.ipynb"
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
PacktPublishing
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created Nov 2020 @author: hassi """ from qiskit import QuantumCircuit, Aer, execute from qiskit.tools.visualization import plot_histogram from IPython.core.display import display print("Ch 4: Quantum double coin toss") print("------------------------------") qc = QuantumCircuit(2, 2) qc.h([0,1]) qc.measure([0,1],[0,1]) display(qc.draw('mpl')) backend = Aer.get_backend('qasm_simulator') counts = execute(qc, backend, shots=1).result().get_counts(qc) display(plot_histogram(counts))
https://github.com/DRA-chaos/Quantum-Classical-Hyrid-Neural-Network-for-binary-image-classification-using-PyTorch-Qiskit-pipeline
DRA-chaos
!pip install qiskit import numpy as np import matplotlib.pyplot as plt import torch from torch.autograd import Function from torchvision import datasets, transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import qiskit from qiskit import transpile, assemble from qiskit.visualization import * def to_numbers(tensor_list): num_list = [] for tensor in tensor_list: num_list += [tensor.item()] return num_list class QiskitCircuit(): # Specify initial parameters and the quantum circuit def __init__(self,shots): self.theta = Parameter('Theta') self.shots = shots def create_circuit(): qr = QuantumRegister(1,'q') cr = ClassicalRegister(1,'c') ckt = QuantumCircuit(qr,cr) ckt.h(qr[0]) ckt.barrier() ckt.ry(self.theta,qr[0]) ckt.barrier() ckt.measure(qr,cr) return ckt self.circuit = create_circuit() def N_qubit_expectation_Z(self,counts, shots, nr_qubits): expects = np.zeros(nr_qubits) for key in counts.keys(): perc = counts[key]/shots check = np.array([(float(key[i])-1/2)*2*perc for i in range(nr_qubits)]) expects += check return expects def bind(self, parameters): [self.theta] = to_numbers(parameters) self.circuit.data[2][0]._params = to_numbers(parameters) def run(self, i): self.bind(i) backend = Aer.get_backend('qasm_simulator') job_sim = execute(self.circuit,backend,shots=self.shots) result_sim = job_sim.result() counts = result_sim.get_counts(self.circuit) return self.N_qubit_expectation_Z(counts,self.shots,1) class TorchCircuit(Function): @staticmethod def forward(ctx, i): if not hasattr(ctx, 'QiskitCirc'): ctx.QiskitCirc = QiskitCircuit(shots=100) exp_value = ctx.QiskitCirc.run(i[0]) result = torch.tensor([exp_value]) # store the result as a torch tensor ctx.save_for_backward(result, i) return result @staticmethod def backward(ctx, grad_output): s = np.pi/2 forward_tensor, i = ctx.saved_tensors # Obtain paramaters input_numbers = to_numbers(i[0]) gradient = [] for k in range(len(input_numbers)): input_plus_s = input_numbers input_plus_s[k] = input_numbers[k] + s # Shift up by s exp_value_plus = ctx.QiskitCirc.run(torch.tensor(input_plus_s))[0] result_plus_s = torch.tensor([exp_value_plus]) input_minus_s = input_numbers input_minus_s[k] = input_numbers[k] - s # Shift down by s exp_value_minus = ctx.QiskitCirc.run(torch.tensor(input_minus_s))[0] result_minus_s = torch.tensor([exp_value_minus]) gradient_result = (result_plus_s - result_minus_s) gradient.append(gradient_result) result = torch.tensor([gradient]) return result.float() * grad_output.float() #import torchvision #transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors #cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform) #labels = cifar_trainset.targets # get the labels for the data #labels = labels.numpy() #idx1 = np.where(labels == 0) # filter on aeroplanes #idx2 = np.where(labels == 1) # filter on automobiles # Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set) #n=100 # concatenate the data indices #idx = np.concatenate((idx1[0][0:n],idx2[0][0:n])) # create the filtered dataset for our training set #cifar_trainset.targets = labels[idx] #cifar_trainset.data = cifar_trainset.data[idx] #train_loader = torch.utils.data.DataLoader(cifar_trainset, batch_size=1, shuffle=True) import tensorflow import torchvision def to_numbers(tensor_list): num_list = [] for tensor in tensor_list: num_list += [tensor.item()] return num_list import torchvision transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform) labels = cifar_trainset.targets # get the labels for the data labels = np.array(labels) idx1 = np.where(labels == 0) # filter on aeroplanes idx2 = np.where(labels == 1) # filter on automobiles # Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set) n=100 # concatenate the data indices idx = np.concatenate((idx1[0][0:n],idx2[0][0:n])) # create the filtered dataset for our training set cifar_trainset.targets = labels[idx] cifar_trainset.data = cifar_trainset.data[idx] train_loader = torch.utils.data.DataLoader(cifar_trainset, batch_size=1, shuffle=True) qc = TorchCircuit.apply class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.h1 = nn.Linear(500, 500) self.h2 = nn.Linear(500, 1) def forward(self,x): x = F.relu(F.max_pool2d(self.conv1(x), 2)) x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) x = x.view(-1, 500) x = F.relu(self.h1(x)) x = F.dropout(x, training=self.training) x = self.h2(x) x = qc(x) x = (x+1)/2 # Normalise the inputs to 1 or 0 x = torch.cat((x, 1-x), -1) return x network = Net() #input = input.permute(1,0,2,3) optimizer = optim.Adam(network.parameters(), lr=0.001) epochs = 10 loss_list = [] for epoch in range(epochs): total_loss = [] target_list = [] for batch_idx, (data, target) in enumerate(train_loader): target_list.append(target.item()) optimizer.zero_grad() output = network(data) loss = F.nll_loss(output, target) loss.backward() optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print(loss_list[-1]) # Normalise the loss between 0 and 1 for i in range(len(loss_list)): loss_list[i] += 1 # Plot the loss per epoch plt.plot(loss_list) import numpy as np import torch from torch.autograd import Function import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import torchvision from torchvision import datasets, transforms from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, execute from qiskit.circuit import Parameter from qiskit import Aer from tqdm import tqdm from matplotlib import pyplot as plt %matplotlib inline
https://github.com/AbdulahAmer/PHYS-31415-Summer-2021
AbdulahAmer
# Fyi in a code cell use a hash symbol or more coloquially known as a # 'hashtag' to make a line comment, comments do not get interpreted # by the editor and are great for leaving notes and things # and mostly are used to express clarity so other programmers like me # and yur classmates can read what you did and why you did it """ You can make block comments that spam multiple lines using triple quotes above and below your block. Please use these, take notes when you copy examples and are writing your own code I will try to do my best to leave these for your guys when I write code """ print('I love Quantum Computing') # when I run this cell it doesnt read the rest, only prints # At the top of every Notebook we use for this course we need to import # all the Qiskit functionality, this is done using Import from qiskit import * # this means that from the qiskit package # import ALL functionality(*) # we also want to see our results in insightful ways through graphs! from qiskit.visualization import * # bloch sphere graphs, bar graphs for measurements # We also need to import the simulators that we will use to make measurements S_simulator=Aer.backends(name='statevector_simulator')[0] # allows you to simulate statevectors M_simulator=Aer.backends(name='qasm_simulator')[0] # allows you to simulate measurements # You should be able to run this import with NO ERRORS, if you do get an # error please contact me so we can trouble shoot this together # In qiskit we can make a quantum circut by using the QuantumCircuit # class, and specifying our number of Quantum bits and Classical bits # example make a Quantum Circuit with 1 qubit and 1 classical bit our_first_quantum_circuit = QuantumCircuit(1,1) # Note that you can call the circuit whatever you want, most of the time # you want to be as specific as possible #NOTE: Unless programmed otherwise ALL qubits start in the |0> state. # qiskit makes it really easy to use gates, we just need to know which # gate and which qubit(s) we want to use it on #use the hadammard gate on the first qubit in our circuit our_first_quantum_circuit.h(0) # Lets explain what we did! # I used the name of my circuit, then a '.' followed by the gate # h for hadammard, and the in paranthesis I will specify the qubit I am # using the gate on, Python counts starting at 0, so the first qubit # will always be coded as the zeroth! # Now we made a circuit, and used a gate, how do we know if it worked? # we Measure it! our_first_quantum_circuit.measure(0,0) # this measures our first qubit # Notice how I have two inputs for measurement, the first input # is the qubit we want to measure and the second is the classical bit # we want to store the measurement in # execute our measurement 1000 times job=execute(our_first_quantum_circuit, M_simulator, shots=1000) #get the results counts=job.result().get_counts() #plot them in a pretty histogram plot_histogram(counts) # we can also measure the statevector using the S_simulator! # lets make a new ciruit and try it out to get the state vector #make a new circuit state_circuit= QuantumCircuit(1,1) state_circuit.h(0) #NOTE: to find out state in a superposition of state we do NOT measure! # execute our measurement of the statevector job=execute(state_circuit, S_simulator) #get the results state_vector=job.result().get_statevector() #plot them in a pretty histogram print('This should be the |+> state: ', state_vector) our_first_quantum_circuit.draw() # the draw method draws your circuit # if you use pip install matplotlib in command line you use # the matplotlib drawer to get really pretty circuits our_first_quantum_circuit.draw(output='mpl')
https://github.com/microsoft/qiskit-qir
microsoft
## # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. ## from qiskit_qir.translate import to_qir_module from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister import test_utils def test_single_array(): circuit = QuantumCircuit(3, 3) circuit.name = "test_single_array" circuit.h(1) circuit.s(2) circuit.t(0) circuit.measure([0, 1, 2], [2, 0, 1]) generated_qir = str(to_qir_module(circuit)[0]).splitlines() test_utils.check_attributes(generated_qir, 3, 3) func = test_utils.get_entry_point_body(generated_qir) assert func[0] == test_utils.initialize_call_string() assert func[1] == test_utils.single_op_call_string("h", 1) assert func[2] == test_utils.single_op_call_string("s", 2) assert func[3] == test_utils.single_op_call_string("t", 0) assert func[4] == test_utils.measure_call_string("mz", 2, 0) assert func[5] == test_utils.measure_call_string("mz", 0, 1) assert func[6] == test_utils.measure_call_string("mz", 1, 2) assert func[7] == test_utils.array_record_output_string(3) assert func[8] == test_utils.result_record_output_string(2) assert func[9] == test_utils.result_record_output_string(1) assert func[10] == test_utils.result_record_output_string(0) assert func[11] == test_utils.return_string() assert len(func) == 12 def test_no_measure_with_no_registers(): circuit = QuantumCircuit(1, 0) circuit.name = "test_no_measure_with_no_registers" circuit.h(0) generated_qir = str(to_qir_module(circuit)[0]).splitlines() test_utils.check_attributes(generated_qir, 1, 0) func = test_utils.get_entry_point_body(generated_qir) assert func[0] == test_utils.initialize_call_string() assert func[1] == test_utils.single_op_call_string("h", 0) assert func[2] == test_utils.return_string() assert len(func) == 3 def test_no_measure_with_register(): circuit = QuantumCircuit(1, 1) circuit.name = "test_no_measure_with_register" circuit.h(0) generated_qir = str(to_qir_module(circuit)[0]).splitlines() test_utils.check_attributes(generated_qir, 1, 1) func = test_utils.get_entry_point_body(generated_qir) assert func[0] == test_utils.initialize_call_string() assert func[1] == test_utils.single_op_call_string("h", 0) assert func[2] == test_utils.array_record_output_string(1) assert func[3] == test_utils.result_record_output_string(0) assert func[4] == test_utils.return_string() assert len(func) == 5 def test_branching_on_bit_emits_correct_ir(): qr = QuantumRegister(1, "qreg") cr = ClassicalRegister(1, "creg") circuit = QuantumCircuit(qr, cr, name="branching_on_bit_emits_correct_ir") circuit.x(0) circuit.measure(0, 0) circuit.x(0).c_if(cr[0], 1) ir = str(to_qir_module(circuit)[0]) generated_qir = ir.splitlines() test_utils.check_attributes(generated_qir, 1, 1) func = test_utils.get_entry_point_body(generated_qir) assert func[0] == test_utils.initialize_call_string() assert func[1] == test_utils.single_op_call_string("x", 0) assert func[2] == test_utils.measure_call_string("mz", 0, 0) assert func[3] == test_utils.equal("0", 0) assert func[4] == f"br i1 %0, label %then, label %else" assert func[5] == "" assert ( func[6] == f"then: ; preds = %entry" ) assert func[7] == test_utils.single_op_call_string("x", 0) assert func[8] == f"br label %continue" assert func[9] == "" assert ( func[10] == f"else: ; preds = %entry" ) assert func[11] == f"br label %continue" assert func[12] == "" assert ( func[13] == f"continue: ; preds = %else, %then" ) assert func[14] == test_utils.array_record_output_string(1) assert func[15] == test_utils.result_record_output_string(0) assert func[16] == test_utils.return_string() assert len(func) == 17 def test_branching_on_register_with_one_bit_emits_correct_ir(): qr = QuantumRegister(1, "qreg") cr = ClassicalRegister(1, "creg") circuit = QuantumCircuit( qr, cr, name="branching_on_register_with_one_bit_emits_correct_ir" ) circuit.x(0) circuit.measure(0, 0) circuit.x(0).c_if(cr, 1) ir = str(to_qir_module(circuit)[0]) generated_qir = ir.splitlines() test_utils.check_attributes(generated_qir, 1, 1) func = test_utils.get_entry_point_body(generated_qir) assert func[0] == test_utils.initialize_call_string() assert func[1] == test_utils.single_op_call_string("x", 0) assert func[2] == test_utils.measure_call_string("mz", 0, 0) assert func[3] == test_utils.equal("0", 0) assert func[4] == f"br i1 %0, label %then, label %else" assert func[5] == "" assert ( func[6] == f"then: ; preds = %entry" ) assert func[7] == test_utils.single_op_call_string("x", 0) assert func[8] == f"br label %continue" assert func[9] == "" assert ( func[10] == f"else: ; preds = %entry" ) assert func[11] == f"br label %continue" assert func[12] == "" assert ( func[13] == f"continue: ; preds = %else, %then" ) assert func[14] == test_utils.array_record_output_string(1) assert func[15] == test_utils.result_record_output_string(0) assert func[16] == test_utils.return_string() assert len(func) == 17 def test_no_measure_without_registers(): circuit = QuantumCircuit(1) circuit.name = "test_no_measure_no_registers" circuit.h(0) generated_qir = str(to_qir_module(circuit)[0]).splitlines() test_utils.check_attributes(generated_qir, 1, 0) func = test_utils.get_entry_point_body(generated_qir) assert func[0] == test_utils.initialize_call_string() assert func[1] == test_utils.single_op_call_string("h", 0) assert func[2] == test_utils.return_string() assert len(func) == 3 def test_measurement_into_multiple_registers_is_mapped_correctly(): cr0 = ClassicalRegister(2, "first") cr1 = ClassicalRegister(3, "second") circuit = QuantumCircuit(5) circuit.add_register(cr0) circuit.add_register(cr1) circuit.name = "measurement_into_multiple_registers" circuit.h(0) circuit.measure([0, 0], [0, 2]) generated_qir = str(to_qir_module(circuit)[0]).splitlines() test_utils.check_attributes(generated_qir, 5, 5) func = test_utils.get_entry_point_body(generated_qir) assert func[0] == test_utils.initialize_call_string() assert func[1] == test_utils.single_op_call_string("h", 0) assert func[2] == test_utils.measure_call_string("mz", 0, 0) assert func[3] == test_utils.measure_call_string("mz", 2, 0) assert func[4] == test_utils.array_record_output_string(2) assert func[5] == test_utils.result_record_output_string(1) assert func[6] == test_utils.result_record_output_string(0) assert func[7] == test_utils.array_record_output_string(3) assert func[8] == test_utils.result_record_output_string(4) assert func[9] == test_utils.result_record_output_string(3) assert func[10] == test_utils.result_record_output_string(2) assert func[11] == test_utils.return_string() assert len(func) == 12 def test_using_static_allocation_is_mapped_correctly(): circuit = QuantumCircuit(1, 1) circuit.h(0) circuit.measure(0, 0) ir = str(to_qir_module(circuit)[0]) generated_qir = ir.splitlines() test_utils.check_attributes(generated_qir, 1, 1) func = test_utils.get_entry_point_body(generated_qir) assert func[0] == test_utils.initialize_call_string() assert func[1] == test_utils.single_op_call_string("h", 0) assert func[2] == test_utils.measure_call_string("mz", 0, 0) assert func[3] == test_utils.array_record_output_string(1) assert func[4] == test_utils.result_record_output_string(0) assert func[5] == test_utils.return_string() assert len(func) == 6 def test_record_output_when_true_mapped_correctly(): circuit = QuantumCircuit(1, 1) circuit.h(0) circuit.measure(0, 0) ir = str(to_qir_module(circuit, record_output=True)[0]) generated_qir = ir.splitlines() test_utils.check_attributes(generated_qir, 1, 1) func = test_utils.get_entry_point_body(generated_qir) assert func[0] == test_utils.initialize_call_string() assert func[1] == test_utils.single_op_call_string("h", 0) assert func[2] == test_utils.measure_call_string("mz", 0, 0) assert func[3] == test_utils.array_record_output_string(1) assert func[4] == test_utils.result_record_output_string(0) assert func[5] == test_utils.return_string() assert len(func) == 6 def test_record_output_when_false_mapped_correctly(): circuit = QuantumCircuit(1, 1) circuit.h(0) circuit.measure(0, 0) ir = str(to_qir_module(circuit, record_output=False)[0]) generated_qir = ir.splitlines() test_utils.check_attributes(generated_qir, 1, 1) func = test_utils.get_entry_point_body(generated_qir) assert func[0] == test_utils.initialize_call_string() assert func[1] == test_utils.single_op_call_string("h", 0) assert func[2] == test_utils.measure_call_string("mz", 0, 0) assert func[3] == test_utils.return_string() assert len(func) == 4 def test_barrier_default_bypass(): circuit = QuantumCircuit(1) circuit.barrier() circuit.x(0) ir = str(to_qir_module(circuit)[0]) generated_qir = ir.splitlines() test_utils.check_attributes(generated_qir, 1, 0) func = test_utils.get_entry_point_body(generated_qir) assert func[0] == test_utils.initialize_call_string() assert func[1] == test_utils.single_op_call_string("x", 0) assert func[2] == test_utils.return_string() assert len(func) == 3 def test_barrier_with_qubits_default_bypass(): circuit = QuantumCircuit(3) circuit.barrier([2, 0, 1]) circuit.x(0) ir = str(to_qir_module(circuit)[0]) generated_qir = ir.splitlines() test_utils.check_attributes(generated_qir, 3, 0) func = test_utils.get_entry_point_body(generated_qir) assert func[0] == test_utils.initialize_call_string() assert func[1] == test_utils.single_op_call_string("x", 0) assert func[2] == test_utils.return_string() assert len(func) == 3 def test_barrier_with_override(): circuit = QuantumCircuit(1) circuit.barrier() ir = str(to_qir_module(circuit, emit_barrier_calls=True)[0]) generated_qir = ir.splitlines() test_utils.check_attributes(generated_qir, 1, 0) func = test_utils.get_entry_point_body(generated_qir) assert func[0] == test_utils.initialize_call_string() assert func[1] == test_utils.generic_op_call_string("barrier", []) assert func[2] == test_utils.return_string() assert len(func) == 3 def test_barrier_with_qubits_with_override(): circuit = QuantumCircuit(3) circuit.barrier([2, 0, 1]) ir = str(to_qir_module(circuit, emit_barrier_calls=True)[0]) generated_qir = ir.splitlines() test_utils.check_attributes(generated_qir, 3, 0) func = test_utils.get_entry_point_body(generated_qir) assert func[0] == test_utils.initialize_call_string() assert func[1] == test_utils.generic_op_call_string("barrier", []) assert func[2] == test_utils.return_string() assert len(func) == 3 def test_swap(): circuit = QuantumCircuit(3) circuit.swap(2, 0) ir = str(to_qir_module(circuit)[0]) generated_qir = ir.splitlines() test_utils.check_attributes(generated_qir, 3, 0) func = test_utils.get_entry_point_body(generated_qir) assert func[0] == test_utils.initialize_call_string() assert func[1] == test_utils.double_op_call_string("swap", 2, 0) assert func[2] == test_utils.return_string() assert len(func) == 3 def test_ccx(): circuit = QuantumCircuit(3) circuit.ccx(2, 0, 1) ir = str(to_qir_module(circuit)[0]) generated_qir = ir.splitlines() test_utils.check_attributes(generated_qir, 3, 0) func = test_utils.get_entry_point_body(generated_qir) assert func[0] == test_utils.initialize_call_string() assert func[1] == test_utils.generic_op_call_string("ccx", [2, 0, 1]) assert func[2] == test_utils.return_string() assert len(func) == 3
https://github.com/unitaryfund/mitiq
unitaryfund
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. """Information about Mitiq and dependencies.""" import platform from cirq import __version__ as cirq_version from numpy import __version__ as numpy_version from scipy import __version__ as scipy_version import mitiq def about() -> None: """Displays information about Mitiq, core/optional packages, and Python version/platform information. """ try: from pyquil import __version__ as pyquil_version except ImportError: pyquil_version = "Not installed" try: from qiskit import __qiskit_version__ qiskit_version = __qiskit_version__["qiskit"] except ImportError: qiskit_version = "Not installed" try: from braket._sdk import __version__ as braket_version except ImportError: braket_version = "Not installed" about_str = f""" Mitiq: A Python toolkit for implementing error mitigation on quantum computers ============================================================================== Authored by: Mitiq team, 2020 & later (https://github.com/unitaryfund/mitiq) Mitiq Version:\t{mitiq.__version__} Core Dependencies ----------------- Cirq Version:\t{cirq_version} NumPy Version:\t{numpy_version} SciPy Version:\t{scipy_version} Optional Dependencies --------------------- PyQuil Version:\t{pyquil_version} Qiskit Version:\t{qiskit_version} Braket Version:\t{braket_version} Python Version:\t{platform.python_version()} Platform Info:\t{platform.system()} ({platform.machine()})""" print(about_str) if __name__ == "__main__": about()
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, ) es_problem = driver.run() from qiskit_nature.second_q.mappers import JordanWignerMapper mapper = JordanWignerMapper() from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver numpy_solver = NumPyMinimumEigensolver() from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit_nature.second_q.circuit.library import HartreeFock, UCCSD ansatz = UCCSD( es_problem.num_spatial_orbitals, es_problem.num_particles, mapper, initial_state=HartreeFock( es_problem.num_spatial_orbitals, es_problem.num_particles, mapper, ), ) vqe_solver = VQE(Estimator(), ansatz, SLSQP()) vqe_solver.initial_point = [0.0] * ansatz.num_parameters from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.circuit.library import TwoLocal tl_circuit = TwoLocal( rotation_blocks=["h", "rx"], entanglement_blocks="cz", entanglement="full", reps=2, parameter_prefix="y", ) another_solver = VQE(Estimator(), tl_circuit, SLSQP()) from qiskit_nature.second_q.algorithms import GroundStateEigensolver calc = GroundStateEigensolver(mapper, vqe_solver) res = calc.solve(es_problem) print(res) calc = GroundStateEigensolver(mapper, numpy_solver) res = calc.solve(es_problem) print(res) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.drivers import GaussianForcesDriver from qiskit_nature.second_q.mappers import DirectMapper from qiskit_nature.second_q.problems import HarmonicBasis driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") basis = HarmonicBasis([2, 2, 2, 2]) vib_problem = driver.run(basis=basis) vib_problem.hamiltonian.truncation_order = 2 mapper = DirectMapper() solver_without_filter = NumPyMinimumEigensolver() solver_with_filter = NumPyMinimumEigensolver( filter_criterion=vib_problem.get_default_filter_criterion() ) gsc_wo = GroundStateEigensolver(mapper, solver_without_filter) result_wo = gsc_wo.solve(vib_problem) gsc_w = GroundStateEigensolver(mapper, solver_with_filter) result_w = gsc_w.solve(vib_problem) print(result_wo) print("\n\n") print(result_w) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright