def test_get_qasm_all_gates(self): """Test the get_qasm for more gates. If all correct the qasm output should be of a certain lenght Previusly: Libraries: from qiskit import QuantumProgram """ QP_program = QuantumProgram(specs=QPS_SPECS) qc = QP_program.get_circuit("circuitName") qr = QP_program.get_quantum_register("qname") cr = QP_program.get_classical_register("cname") qc.u1(0.3, qr[0]) qc.u2(0.2, 0.1, qr[1]) qc.u3(0.3, 0.2, 0.1, qr[2]) qc.s(qr[1]) qc.s(qr[2]).inverse() qc.cx(qr[1], qr[2]) qc.barrier() qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.x(qr[2]).c_if(cr, 0) qc.y(qr[2]).c_if(cr, 1) qc.z(qr[2]).c_if(cr, 2) qc.barrier(qr) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.measure(qr[2], cr[2]) result = QP_program.get_qasm('circuitName') self.assertEqual(len(result), 535)
def test_local_qasm_simulator(self): """Test execute. If all correct should the data. """ QP_program = QuantumProgram(specs=QPS_SPECS) qr = QP_program.get_quantum_register("qname") cr = QP_program.get_classical_register("cname") qc2 = QP_program.create_circuit("qc2", [qr], [cr]) qc3 = QP_program.create_circuit("qc3", [qr], [cr]) qc2.h(qr[0]) qc2.cx(qr[0], qr[1]) qc2.cx(qr[0], qr[2]) qc3.h(qr) qc2.measure(qr[0], cr[0]) qc3.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) qc3.measure(qr[1], cr[1]) qc2.measure(qr[2], cr[2]) qc3.measure(qr[2], cr[2]) circuits = ['qc2', 'qc3'] shots = 1024 # the number of shots in the experiment. backend = 'local_qasm_simulator' out = QP_program.execute(circuits, backend=backend, shots=shots, seed=88) results2 = out.get_counts('qc2') results3 = out.get_counts('qc3') # print(QP_program.get_data('qc3')) self.assertEqual(results2, {'000': 518, '111': 506}) self.assertEqual(results3, {'001': 119, '111': 129, '110': 134, '100': 117, '000': 129, '101': 126, '010': 145, '011': 125})
def test_local_qasm_simulator_one_shot(self): """Test sinlge shot of local simulator . If all correct should the quantum state. """ QP_program = QuantumProgram(specs=QPS_SPECS) qr = QP_program.get_quantum_register("qname") cr = QP_program.get_classical_register("cname") qc2 = QP_program.create_circuit("qc2", [qr], [cr]) qc3 = QP_program.create_circuit("qc3", [qr], [cr]) qc2.h(qr[0]) qc3.h(qr[0]) qc3.cx(qr[0], qr[1]) qc3.cx(qr[0], qr[2]) circuits = ['qc2', 'qc3'] backend = 'local_qasm_simulator' # the backend to run on shots = 1 # the number of shots in the experiment. result = QP_program.execute(circuits, backend=backend, shots=shots, seed=9) quantum_state = np.array([0.70710678+0.j, 0.70710678+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.00000000+0.j]) norm = np.dot(np.conj(quantum_state), result.get_data('qc2')['quantum_state']) self.assertAlmostEqual(norm, 1) quantum_state = np.array([0.70710678+0.j, 0+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.70710678+0.j]) norm = np.dot(np.conj(quantum_state), result.get_data('qc3')['quantum_state']) self.assertAlmostEqual(norm, 1)
def test_get_qasms(self): """Test the get_qasms. If all correct the qasm output for each circuit should be of a certain lenght Previusly: Libraries: from qiskit import QuantumProgram """ QP_program = QuantumProgram() qr = QP_program.create_quantum_register("qr", 3, verbose=False) cr = QP_program.create_classical_register("cr", 3, verbose=False) qc1 = QP_program.create_circuit("qc1", [qr], [cr]) qc2 = QP_program.create_circuit("qc2", [qr], [cr]) qc1.h(qr[0]) qc1.cx(qr[0], qr[1]) qc1.cx(qr[1], qr[2]) qc1.measure(qr[0], cr[0]) qc1.measure(qr[1], cr[1]) qc1.measure(qr[2], cr[2]) qc2.h(qr) qc2.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) qc2.measure(qr[2], cr[2]) result = QP_program.get_qasms(["qc1", "qc2"]) self.assertEqual(len(result[0]), 173) self.assertEqual(len(result[1]), 159)
def test_local_unitary_simulator(self): """Test unitary simulator. If all correct should the h otimes h and cx. """ QP_program = QuantumProgram() q = QP_program.create_quantum_register("q", 2, verbose=False) c = QP_program.create_classical_register("c", 2, verbose=False) qc1 = QP_program.create_circuit("qc1", [q], [c]) qc2 = QP_program.create_circuit("qc2", [q], [c]) qc1.h(q) qc2.cx(q[0], q[1]) circuits = ['qc1', 'qc2'] backend = 'local_unitary_simulator' # the backend to run on result = QP_program.execute(circuits, backend=backend) unitary1 = result.get_data('qc1')['unitary'] unitary2 = result.get_data('qc2')['unitary'] unitaryreal1 = np.array([[0.5, 0.5, 0.5, 0.5], [0.5, -0.5, 0.5, -0.5], [0.5, 0.5, -0.5, -0.5], [0.5, -0.5, -0.5, 0.5]]) unitaryreal2 = np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0., 0, 1, 0], [0, 1, 0, 0]]) norm1 = np.trace(np.dot(np.transpose(np.conj(unitaryreal1)), unitary1)) norm2 = np.trace(np.dot(np.transpose(np.conj(unitaryreal2)), unitary2)) self.assertAlmostEqual(norm1, 4) self.assertAlmostEqual(norm2, 4)
def test_average_data(self): """Test average_data. If all correct should the data. """ QP_program = QuantumProgram() q = QP_program.create_quantum_register("q", 2, verbose=False) c = QP_program.create_classical_register("c", 2, verbose=False) qc = QP_program.create_circuit("qc", [q], [c]) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) circuits = ['qc'] shots = 10000 # the number of shots in the experiment. backend = 'local_qasm_simulator' results = QP_program.execute(circuits, backend=backend, shots=shots) observable = {"00": 1, "11": 1, "01": -1, "10": -1} meanzz = results.average_data("qc", observable) observable = {"00": 1, "11": -1, "01": 1, "10": -1} meanzi = results.average_data("qc", observable) observable = {"00": 1, "11": -1, "01": -1, "10": 1} meaniz = results.average_data("qc", observable) self.assertAlmostEqual(meanzz, 1, places=1) self.assertAlmostEqual(meanzi, 0, places=1) self.assertAlmostEqual(meaniz, 0, places=1)
def test_get_qasm_all_gates(self): """Test the get_qasm for more gates, using an specification without names. """ q_program = QuantumProgram(specs=self.QPS_SPECS_NONAMES) qc = q_program.get_circuit() qr = q_program.get_quantum_register() cr = q_program.get_classical_register() qc.u1(0.3, qr[0]) qc.u2(0.2, 0.1, qr[1]) qc.u3(0.3, 0.2, 0.1, qr[2]) qc.s(qr[1]) qc.s(qr[2]).inverse() qc.cx(qr[1], qr[2]) qc.barrier() qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.x(qr[2]).c_if(cr, 0) qc.y(qr[2]).c_if(cr, 1) qc.z(qr[2]).c_if(cr, 2) qc.barrier(qr) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.measure(qr[2], cr[2]) result = q_program.get_qasm() self.assertEqual(len(result), (len(qr.name) * 23 + len(cr.name) * 7 + 385))
def test_backend_status(self): """Test backend_status. If all correct should return dictionary with available: True/False. """ QP_program = QuantumProgram(specs=QPS_SPECS) out = QP_program.get_backend_status("local_qasm_simulator") self.assertIn(out['available'], [True])
def test_create_circuit_noname(self): """Test create_circuit with no name """ q_program = QuantumProgram() qr = q_program.create_quantum_register(size=3) cr = q_program.create_classical_register(size=3) qc = q_program.create_circuit(qregisters=[qr], cregisters=[cr]) self.assertIsInstance(qc, QuantumCircuit)
def test_setup_api(self): """Check the api is set up. If all correct is should be true. """ QP_program = QuantumProgram(specs=QPS_SPECS) QP_program.set_api(API_TOKEN, URL) config = QP_program.get_api_config() self.assertTrue(config)
def test_local_backends_exist(self): """Test if there are local backends. If all correct some should exists (even if ofline). """ QP_program = QuantumProgram(specs=QPS_SPECS) QP_program.set_api(API_TOKEN, URL) local_backends = QP_program.local_backends() self.assertTrue(local_backends)
def _get_quantum_program(): quantum_program = QuantumProgram() qr = quantum_program.create_quantum_register("q", 1) cr = quantum_program.create_classical_register("c", 1) qc = quantum_program.create_circuit("qc", [qr], [cr]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) return quantum_program
def test_create_quantum_registers_noname(self): """Test create_quantum_registers with no name. """ q_program = QuantumProgram() quantum_registers = [{"size": 4}, {"size": 2}] qrs = q_program.create_quantum_registers(quantum_registers) for i in qrs: self.assertIsInstance(i, QuantumRegister)
def test_get_backend_configuration(self): """Test get_backend_configuration. If all correct should return configuration for the local_qasm_simulator. """ qp = QuantumProgram(specs=QPS_SPECS) test = len(qp.get_backend_configuration("local_qasm_simulator")) self.assertEqual(test, 6)
def test_create_classical_registers_noname(self): """Test create_classical_registers with no name """ q_program = QuantumProgram() classical_registers = [{"size": 4}, {"size": 2}] crs = q_program.create_classical_registers(classical_registers) for i in crs: self.assertIsInstance(i, ClassicalRegister)
def test_json_output(self): qp = QuantumProgram() qp.load_qasm_file(self.QASM_FILE_PATH, name="example") basis_gates = [] # unroll to base gates, change to test unroller = unroll.Unroller(qasm.Qasm(data=qp.get_qasm("example")).parse(), unroll.JsonBackend(basis_gates)) circuit = unroller.execute() self.log.info('test_json_ouptut: %s', circuit)
def test_get_initial_circuit(self): """Test get_initial_circuit. If all correct is should be of the circuit form. Previusly: Libraries: from qiskit import QuantumProgram """ QP_program = QuantumProgram(specs=QPS_SPECS) qc = QP_program.get_initial_circuit() self.assertIsInstance(qc, QuantumCircuit)
def test_load(self): """ Load a Json Quantum Program """ QP_program = QuantumProgram(specs=QPS_SPECS) result = QP_program.load("./test/python/test_load.json") self.assertEqual(result['status'], 'Done') check_result = QP_program.get_qasm('circuitName') self.assertEqual(len(check_result), 1872)
def test_online_backends_exist(self): """Test if there are online backends. If all correct some should exists. """ # TODO: Jay should we check if we the QX is online before runing. QP_program = QuantumProgram(specs=QPS_SPECS) QP_program.set_api(API_TOKEN, URL) online_backends = QP_program.online_backends() # print(online_backends) self.assertTrue(online_backends)
def test_online_simulators(self): """Test if there are online backends (which are simulators). If all correct some should exists. NEED internet connection for this. """ # TODO: Jay should we check if we the QX is online before runing. qp = QuantumProgram(specs=QPS_SPECS) qp.set_api(API_TOKEN, URL) online_simulators = qp.online_simulators() # print(online_simulators) self.assertTrue(isinstance(online_simulators, list))
def vqe(molecule='H2', depth=6, max_trials=200, shots=1): if molecule == 'H2': n_qubits = 2 Z1 = 1 Z2 = 1 min_distance = 0.2 max_distance = 4 elif molecule == 'LiH': n_qubits = 4 Z1 = 1 Z2 = 3 min_distance = 0.5 max_distance = 5 else: raise QISKitError("Unknown molecule for VQE.") # Read Hamiltonian ham_name = os.path.join(os.path.dirname(__file__), molecule + '/' + molecule + 'Equilibrium.txt') pauli_list = Hamiltonian_from_file(ham_name) H = make_Hamiltonian(pauli_list) # Exact Energy exact = np.amin(la.eig(H)[0]).real print('The exact ground state energy is: {}'.format(exact)) # Optimization device = 'local_qasm_simulator' qp = QuantumProgram() if shots != 1: H = group_paulis(pauli_list) entangler_map = qp.get_backend_configuration(device)['coupling_map'] if entangler_map == 'all-to-all': entangler_map = {i: [j for j in range(n_qubits) if j != i] for i in range(n_qubits)} else: entangler_map = mapper.coupling_list2dict(entangler_map) initial_theta = np.random.randn(2 * n_qubits * depth) # initial angles initial_c = 0.01 # first theta perturbations target_update = 2 * np.pi * 0.1 # aimed update on first trial save_step = 20 # print optimization trajectory cost = partial(cost_function, qp, H, n_qubits, depth, entangler_map, shots, device) SPSA_params = SPSA_calibration(cost, initial_theta, initial_c, target_update, stat=25) output = SPSA_optimization(cost, initial_theta, SPSA_params, max_trials, save_step, last_avg=1) return qp
def _test_circuits_2qubit(): qp = QuantumProgram() qr = qp.create_quantum_register('qr', 2) cr = qp.create_classical_register('cr', 2) # Test Circuits Bell state circ = qp.create_circuit('Bell', [qr], [cr]) circ.h(qr[0]) circ.cx(qr[0], qr[1]) circ = qp.create_circuit('X1Id0', [qr], [cr]) circ.x(qr[1]) return qp, qr, cr
def test_get_backend_parameters(self): """Test get_backend_parameters. If all correct should return dictionay on length 4. """ QP_program = QuantumProgram(specs=QPS_SPECS) QP_program.set_api(API_TOKEN, URL) backend_list = QP_program.online_backends() if backend_list: backend = backend_list[0] result = QP_program.get_backend_parameters(backend) # print(result) self.assertEqual(len(result), 4)
def test_create_classical_register(self): """Test create_classical_register. If all is correct we get a object intstance of ClassicalRegister Previusly: Libraries: from qiskit import QuantumProgram from qiskit import ClassicalRegister """ QP_program = QuantumProgram() cr = QP_program.create_classical_register("cr", 3, verbose=False) self.assertIsInstance(cr, ClassicalRegister)
def test_create_quantum_register(self): """Test create_quantum_register. If all is correct we get a object intstance of QuantumRegister Previusly: Libraries: from qiskit import QuantumProgram from qiskit import QuantumRegister """ QP_program = QuantumProgram() qr = QP_program.create_quantum_register("qr", 3, verbose=False) self.assertIsInstance(qr, QuantumRegister)
def test_create_classical_register_same(self): """Test create_classical_register of same name and size. If all is correct we get a single classical register Previusly: Libraries: from qiskit import QuantumProgram from qiskit import ClassicalRegister """ QP_program = QuantumProgram() cr1 = QP_program.create_classical_register("cr", 3, verbose=False) cr2 = QP_program.create_classical_register("cr", 3, verbose=False) self.assertIs(cr1, cr2)
def test_compile_program_noname(self): """Test compile with a no name. """ q_program = QuantumProgram(specs=self.QPS_SPECS_NONAMES) qc = q_program.get_circuit() qr = q_program.get_quantum_register() cr = q_program.get_classical_register() qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) out = q_program.compile() self.log.info(out) self.assertEqual(len(out), 3)
def simulate(grid): qp = QuantumProgram() qr = qp.create_quantum_register('qr', 2) cr = qp.create_classical_register('cr', 2) qc = qp.create_circuit('pi', [qr], [cr]) qc = build_qc(qc, grid, qr, cr) result = qp.execute('pi') tmp = result.get_counts('pi') tmp = dict([(x[0], round(x[1] / 1024, 2)) for x in list(tmp.items())]) return tmp
def test_create_circuit(self): """Test create_circuit. If all is correct we get a object intstance of QuantumCircuit Previusly: Libraries: from qiskit import QuantumProgram from qiskit import QuantumCircuit """ QP_program = QuantumProgram() qr = QP_program.create_quantum_register("qr", 3, verbose=False) cr = QP_program.create_classical_register("cr", 3, verbose=False) qc = QP_program.create_circuit("qc", [qr], [cr]) self.assertIsInstance(qc, QuantumCircuit)
def setUp(self): self.seed = 88 self.qasm_filename = self._get_resource_path('qasm/example.qasm') self.qp = QuantumProgram() self.qp.load_qasm_file(self.qasm_filename, name='example') basis_gates = [] # unroll to base gates unroller = unroll.Unroller( qasm.Qasm(data=self.qp.get_qasm('example')).parse(), unroll.JsonBackend(basis_gates)) circuit = unroller.execute() circuit_config = {'coupling_map': None, 'basis_gates': 'u1,u2,u3,cx,id', 'layout': None, 'seed': self.seed} resources = {'max_credits': 3} self.qobj = {'id': 'test_sim_single_shot', 'config': { 'max_credits': resources['max_credits'], 'shots': 1024, 'backend_name': 'local_qasm_simulator_py', }, 'circuits': [ { 'name': 'test', 'compiled_circuit': circuit, 'compiled_circuit_qasm': None, 'config': circuit_config } ]} self.q_job = QuantumJob(self.qobj, backend=QasmSimulatorPy(), circuit_config=circuit_config, seed=self.seed, resources=resources, preformatted=True)
import matplotlib.pyplot as plt #%matplotlib inline import numpy as np from scipy import linalg as la #import quantum computing fuctions from qiskit import QuantumProgram from qiskit.tools.visualization import plot_histogram, plot_state quantum = QuantumProgram() qubit = quantum.create_quantum_register("qubit", 7) classic = quantum.create_classical_register("classic", 7) qCircuit = quantum.create_circuit("linear_solver", [qubit], [classic]) qCircuit.h(qubit[0]) qCircuit.x(qubit[2]) qCircuit.cx(qubit[0], qubit[4]) qCircuit.measure(qubit[4], classic[4]) qCircuit.reset(qubit[4]) if (classic[4] == 0): qCircuit.cx(qubit[1], qubit[2]) qCircuit.cx(qubit[2], qubit[1]) qCircuit.cx(qubit[1], qubit[2]) qCircuit.cx(qubit[1], qubit[5]) qCircuit.cx(qubit[2], qubit[6]) qCircuit.measure(qubit[5], classic[5]) qCircuit.measure(qubit[6], classic[6]) if (classic[6] == 1):
def input_state(circ, q, n): """n-qubit input state for QFT that produces output 1.""" for j in range(n): circ.h(q[j]) circ.u1(math.pi / float(2**(j)), q[j]).inverse() def qft(circ, q, n): """n-qubit QFT on q in circ.""" for j in range(n): for k in range(j): circ.cu1(math.pi / float(2**(j - k)), q[j], q[k]) circ.h(q[j]) qp = QuantumProgram(specs=QPS_SPECS) q = qp.get_quantum_register("q") c = qp.get_classical_register("c") qft3 = qp.get_circuit("qft3") qft4 = qp.get_circuit("qft4") qft5 = qp.get_circuit("qft5") input_state(qft3, q, 3) qft3.barrier() qft(qft3, q, 3) qft3.barrier() for j in range(3): qft3.measure(q[j], c[j]) input_state(qft4, q, 4)
import numpy as np from qiskit import QuantumCircuit, QuantumProgram import Qconfig import qiskit.tools.qcvv.tomography as tomography from qiskit.tools.visualization import plot_state, plot_histogram from qiskit.tools.qi.qi import state_fidelity, concurrence, purity, outer QProgram = QuantumProgram() QProgram.set_api(Qconfig.APItoken, Qconfig.config['url']) qr = QProgram.create_quantum_register('qr',2) cr = QProgram.create_classical_register('cr',2) bell = QProgram.create_circuit('bell', [qr], [cr]) bell.h(qr[0]) bell.cx(qr[0], qr[1]) bell_result = QProgram.execute(['bell'], backend = 'local_qasm_simulator', shots = 1) bell_psi = bell_result.get_data('bell') ['quantum_state'] bell_rho = outer(bell_psi) plot_state(bell_rho, 'paulivec')
def setUp(self): self.seed = 42 self.qp = QuantumProgram()
from qiskit import QuantumProgram qp = QuantumProgram() qr = qp.create_quantum_register('qr',2) cr = qp.create_classical_register('cr',2) qc = qp.create_circuit('Bell',[qr],[cr]) qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) result = qp.execute('Bell') print(result.get_counts('Bell'))
Q_SPECS = { "name": "Program-tutorial", "circuits": [{ "name": "initializer_circ", "quantum_registers": [{ "name": "qr", "size": 4 }], "classical_registers": [{ "name": "cr", "size": 4 }] }], } Q_program = QuantumProgram(specs=Q_SPECS) circuit = Q_program.get_circuit("initializer_circ") qr = Q_program.get_quantum_register("qr") cr = Q_program.get_classical_register('cr') desired_vector = [ 1 / math.sqrt(4) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 0, 0, 0, 1 / math.sqrt(4) * complex(1, 0), 1 / math.sqrt(8) * complex(1, 0) ] circuit.initialize("QInit", desired_vector, [qr[0], qr[1], qr[2], qr[3]]) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[1])
"name": "cin", "size": 1 }, { "name": "cout", "size": 1 }], "classical_registers": [ { "name": "ans", "size": n + 1 }, ] }] } qp = QuantumProgram(specs=QPS_SPECS) qc = qp.get_circuit("rippleadd") a = qp.get_quantum_register("a") b = qp.get_quantum_register("b") cin = qp.get_quantum_register("cin") cout = qp.get_quantum_register("cout") ans = qp.get_classical_register("ans") def majority(p, a, b, c): """Majority gate.""" p.cx(c, b) p.cx(c, a) p.ccx(a, b, c)
# RUN WITH PYTHON 3.5! # Import the Qiskit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QuantumProgram from qiskit import available_backends, execute from qiskit.tools.visualization import circuit_drawer # initialise quantum program qp = QuantumProgram() # Create a qubyte, Quantum Register with 8 qubits. qbyte = qp.create_quantum_register('q1', 8) cbyte = qp.create_classical_register('c1', 8) # Create a Quantum Circuit qc = qp.create_circuit('helloworld', [qbyte], [cbyte]) # Add a H gate on qubit 0, putting this qubit in superposition. #qc.h(q[1]) #qc.h(q[2]) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting # the qubits in a Bell state. #qc.cx(q[0], q[1]) # Measure for i in range(0, 8): qc.measure(qbyte[i], cbyte[i]) print(qp.get_qasm('helloworld')) """ # See a list of available local simulators print("Local backends: ", available_backends({'local': True}))
import sys if sys.version_info < (3, 5): raise Exception('Please Use Python Version 3.5 or greater.') import numpy as np #Imporing QISKit from qiskit import QuantumCircuit, QuantumProgram import Qconfig #Import basic plotting tools from qiskit.tools.visualization import plot_histogram #Quantum program setup Q_program = QuantumProgram() Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) #set APIToken and API Url #Creating Quantum Registers q = Q_program.create_quantum_register('q', 3) c0 = Q_program.create_classical_register('c0', 1) c1 = Q_program.create_classical_register('c1', 1) c2 = Q_program.create_classical_register('c2', 1) #Quantum circuit to make the shared entangled state teleport = Q_program.create_circuit('teleport', [q], [c0, c1, c2]) teleport.h(q[1]) teleport.cx(q[1], q[2]) #Applying a rotation around the Y axis to prepare quantum state to be teleported
"name": "c0", "size": 1 }, { "name": "c1", "size": 1 }, { "name": "c2", "size": 1 }, ] }] } qp = QuantumProgram(specs=QPS_SPECS) qc = qp.get_circuit("teleport") q = qp.get_quantum_register("q") c0 = qp.get_classical_register("c0") c1 = qp.get_classical_register("c1") c2 = qp.get_classical_register("c2") # Prepare an initial state qc.u3(0.3, 0.2, 0.1, q[0]) # Prepare a Bell pair qc.h(q[1]) qc.cx(q[1], q[2]) # Barrier following state preparation qc.barrier(q)
def run(self): scores = deque(maxlen=100) for e in range(self.n_episodes): eigenState = self.env.reset() done = False i = 0 eigenState = repr(np.round(eigenState, decimals=0)) while not done: #self.env.render() if eigenState in self.memory: memList = self.memory[eigenState] action = memList[0] stateValue = memList[1] nextState = memList[2] if nextState in self.memory: nextStateValue = self.memory[nextState][1] else: nextStateValue = 1.0 reward = memList[3] Q_program = QuantumProgram() qr = Q_program.create_quantum_register("qr", 2) cr = Q_program.create_classical_register("cr", 2) eigenAction = Q_program.create_circuit( "superposition", [qr], [cr]) eigenAction.h(qr) eigenAction, qr = self.groverIteration( Q_program, eigenAction, qr, action, reward, nextStateValue) else: #################### Prepare the n-qubit registers ######################################### Q_program = QuantumProgram() qr = Q_program.create_quantum_register("qr", 2) cr = Q_program.create_classical_register("cr", 2) eigenAction = Q_program.create_circuit( "superposition", [qr], [cr]) eigenAction.h(qr) ############################################################################################ stateValue = 0.0 action = self.collapseActionSelectionMethod( Q_program, eigenAction, qr, cr) nextEigenState, reward, done, _ = self.env.step(action) if done: print(reward) nextEigenState = repr(np.round(nextEigenState, decimals=0)) if nextEigenState in self.memory: memList = self.memory[nextEigenState] nextStateValue = memList[1] else: nextStateValue = 0.0 #Update state value stateValue = stateValue + self.alpha * ( reward + (self.discount_factor * nextStateValue) - stateValue) self.remember(eigenState, action, stateValue, nextEigenState, reward) eigenState = nextEigenState i += 1 scores.append(i) mean_score = np.mean(scores) if mean_score >= self.n_win_ticks and e >= 100: if not self.quiet: print('Ran {} episodes. Solved after {} trials ✔'.format( e, e - 100)) return e - 100 if e % 100 == 0 and not self.quiet: print( '[Episode {}] - Mean survival time over last 100 episodes was {} ticks.' .format(e, mean_score)) #Update alpha #self.alpha = self.alpha - self.alpha_decay if not self.quiet: print('Did not solve after {} episodes 😞'.format(e)) return e
from qiskit import QuantumProgram, QISKitError # Create a QuantumProgram object instance. Q_program = QuantumProgram() backend = 'local_qasm_simulator' if __name__ == "__main__": try: # Create a Quantum Register called "qr" with 2 qubits. qr = Q_program.create_quantum_register("qr", 2) # Create a Classical Register called "cr" with 2 bits. cr = Q_program.create_classical_register("cr", 2) # Create a Quantum Circuit called "qc" involving the Quantum Register "qr" # and the Classical Register "cr". qc = Q_program.create_circuit("bell", [qr], [cr]) # Add the H gate in the Qubit 0, putting this qubit in superposition. qc.h(qr[0]) # Add the CX gate on control qubit 0 and target qubit 1, putting # the qubits in a Bell state qc.cx(qr[0], qr[1]) # Add a Measure gate to see the state. qc.measure(qr, cr) # Compile and execute the Quantum Program in the local_qasm_simulator. result = Q_program.execute(["bell"], backend=backend, shots=1024, seed=1) # Show the results.
class MapperTest(QiskitTestCase): """Test the mapper.""" def setUp(self): self.seed = 42 self.qp = QuantumProgram() def test_mapper_overoptimization(self): """ The mapper should not change the semantics of the input. An overoptimization introduced the issue #81: https://github.com/QISKit/qiskit-core/issues/81 """ self.qp.load_qasm_file(self._get_resource_path('qasm/overoptimization.qasm'), name='test') coupling_map = [[0, 2], [1, 2], [2, 3]] result1 = self.qp.execute(["test"], backend="local_qasm_simulator", coupling_map=coupling_map) count1 = result1.get_counts("test") result2 = self.qp.execute(["test"], backend="local_qasm_simulator", coupling_map=None) count2 = result2.get_counts("test") self.assertEqual(count1.keys(), count2.keys(), ) def test_math_domain_error(self): """ The math library operates over floats and introduce floating point errors that should be avoided. See: https://github.com/QISKit/qiskit-core/issues/111 """ self.qp.load_qasm_file(self._get_resource_path('qasm/math_domain_error.qasm'), name='test') coupling_map = [[0, 2], [1, 2], [2, 3]] shots = 2000 result = self.qp.execute("test", backend="local_qasm_simulator", coupling_map=coupling_map, seed=self.seed, shots=shots) counts = result.get_counts("test") target = {'0001': shots / 2, '0101': shots / 2} threshold = 0.04 * shots self.assertDictAlmostEqual(counts, target, threshold) def test_optimize_1q_gates_issue159(self): """Test change in behavior for optimize_1q_gates that removes u1(2*pi) rotations. See: https://github.com/QISKit/qiskit-core/issues/159 """ self.qp = QuantumProgram() qr = self.qp.create_quantum_register('qr', 2) cr = self.qp.create_classical_register('cr', 2) qc = self.qp.create_circuit('Bell', [qr], [cr]) qc.h(qr[0]) qc.cx(qr[1], qr[0]) qc.cx(qr[1], qr[0]) qc.cx(qr[1], qr[0]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) backend = 'local_qasm_simulator' coupling_map = [[1, 0], [2, 0], [2, 1], [2, 4], [3, 2], [3, 4]] initial_layout = {('qr', 0): ('q', 1), ('qr', 1): ('q', 0)} qobj = self.qp.compile(["Bell"], backend=backend, initial_layout=initial_layout, coupling_map=coupling_map) self.assertEqual(self.qp.get_compiled_qasm(qobj, "Bell"), EXPECTED_QASM_1Q_GATES_3_5) def test_random_parameter_circuit(self): """Run a circuit with randomly generated parameters.""" self.qp.load_qasm_file(self._get_resource_path('qasm/random_n5_d5.qasm'), name='rand') coupling_map = [[0, 1], [1, 2], [2, 3], [3, 4]] shots = 1024 result1 = self.qp.execute(["rand"], backend="local_qasm_simulator", coupling_map=coupling_map, shots=shots, seed=self.seed) counts = result1.get_counts("rand") expected_probs = { '00000': 0.079239867254200971, '00001': 0.032859032998526903, '00010': 0.10752610993531816, '00011': 0.018818532050952699, '00100': 0.054830807251011054, '00101': 0.0034141983951965164, '00110': 0.041649309748902276, '00111': 0.039967731207338125, '01000': 0.10516937819949743, '01001': 0.026635620063700002, '01010': 0.0053475143548793866, '01011': 0.01940513314416064, '01100': 0.0044028405481225047, '01101': 0.057524760052126644, '01110': 0.010795354134597078, '01111': 0.026491296821535528, '10000': 0.094827455395274859, '10001': 0.0008373965072688836, '10010': 0.029082297894094441, '10011': 0.012386622870598416, '10100': 0.018739140061148799, '10101': 0.01367656456536896, '10110': 0.039184170706009248, '10111': 0.062339335178438288, '11000': 0.00293674365989009, '11001': 0.012848433960739968, '11010': 0.018472497159499782, '11011': 0.0088903691234912003, '11100': 0.031305389080034329, '11101': 0.0004788556283690458, '11110': 0.002232419390471667, '11111': 0.017684822659235985 } target = {key: shots * val for key, val in expected_probs.items()} threshold = 0.04 * shots self.assertDictAlmostEqual(counts, target, threshold) def test_symbolic_unary(self): """Test symbolic math in DAGBackend and optimizer with a prefix. See: https://github.com/QISKit/qiskit-core/issues/172 """ ast = qasm.Qasm(filename=self._get_resource_path( 'qasm/issue172_unary.qasm')).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_UNARY) def test_symbolic_binary(self): """Test symbolic math in DAGBackend and optimizer with a binary operation. See: https://github.com/QISKit/qiskit-core/issues/172 """ ast = qasm.Qasm(filename=self._get_resource_path( 'qasm/issue172_binary.qasm')).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_BINARY) def test_symbolic_extern(self): """Test symbolic math in DAGBackend and optimizer with an external function. See: https://github.com/QISKit/qiskit-core/issues/172 """ ast = qasm.Qasm(filename=self._get_resource_path( 'qasm/issue172_extern.qasm')).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_EXTERN) def test_symbolic_power(self): """Test symbolic math in DAGBackend and optimizer with a power (^). See: https://github.com/QISKit/qiskit-core/issues/172 """ ast = qasm.Qasm(data=QASM_SYMBOLIC_POWER).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_POWER) def test_already_mapped(self): """Test that if the circuit already matches the backend topology, it is not remapped. See: https://github.com/QISKit/qiskit-core/issues/342 """ self.qp = QuantumProgram() qr = self.qp.create_quantum_register('qr', 16) cr = self.qp.create_classical_register('cr', 16) qc = self.qp.create_circuit('native_cx', [qr], [cr]) qc.cx(qr[3], qr[14]) qc.cx(qr[5], qr[4]) qc.h(qr[9]) qc.cx(qr[9], qr[8]) qc.x(qr[11]) qc.cx(qr[3], qr[4]) qc.cx(qr[12], qr[11]) qc.cx(qr[13], qr[4]) for j in range(16): qc.measure(qr[j], cr[j]) backend = 'local_qasm_simulator' coupling_map = [[1, 0], [1, 2], [2, 3], [3, 4], [3, 14], [5, 4], [6, 5], [6, 7], [6, 11], [7, 10], [8, 7], [9, 8], [9, 10], [11, 10], [12, 5], [12, 11], [12, 13], [13, 4], [13, 14], [15, 0], [15, 2], [15, 14]] qobj = self.qp.compile(["native_cx"], backend=backend, coupling_map=coupling_map) cx_qubits = [x["qubits"] for x in qobj["circuits"][0]["compiled_circuit"]["operations"] if x["name"] == "cx"] self.assertEqual(sorted(cx_qubits), [[3, 4], [3, 14], [5, 4], [9, 8], [12, 11], [13, 4]])
def test_get_register_and_circuit_names_nonames(self): """Get the names of the circuits and registers after create them without a name """ q_program = QuantumProgram() qr1 = q_program.create_quantum_register(size=3) cr1 = q_program.create_classical_register(size=3) qr2 = q_program.create_quantum_register(size=3) cr2 = q_program.create_classical_register(size=3) q_program.create_circuit(qregisters=[qr1], cregisters=[cr1]) q_program.create_circuit(qregisters=[qr2], cregisters=[cr2]) q_program.create_circuit(qregisters=[qr1, qr2], cregisters=[cr1, cr2]) qrn = q_program.get_quantum_register_names() crn = q_program.get_classical_register_names() qcn = q_program.get_circuit_names() self.assertEqual(len(qrn), 2) self.assertEqual(len(crn), 2) self.assertEqual(len(qcn), 3)
import matplotlib.pyplot as plt #%matplotlib inline import numpy as np import pandas as pd import math from scipy import linalg as la #import quantum computing fuctions from qiskit import QuantumProgram #from qiskit.tools.visualization import plot_histogram, plot_state from DATAImport import getData from QIC_function import makeQubits, makeClassical, makeCircuit, initializeCircuit, addDataPoint, finalizeCircuit, runCircuit, getQASM quantum = QuantumProgram() qubits = makeQubits(quantum, 4) classical = makeClassical(quantum, 4) qcircuit = makeCircuit(quantum, qubits, classical) qcircuit = initializeCircuit(qcircuit, 3.036, qubits) dataPoints = getData() #run for loop here to add the points for x in range(0, len(dataPoints)): thetaVar = math.acos(dataPoints[x, 0]) * 2 print("Adding theta point: " + str(thetaVar)) qcircuit = addDataPoint(qcircuit, thetaVar, qubits) print("Generating quantum circuit...") qcircuit = finalizeCircuit(qcircuit, qubits, classical) QASM_source = getQASM(quantum) print(QASM_source)
def q_learning(env, num_episodes, discount_factor=0.9, alpha=0.8): #, epsilon=0.1): """ Q-Learning algorithm: Off-policy TD control. Finds the optimal greedy policy while following an epsilon-greedy policy Args: env: OpenAI environment. num_episodes: Number of episodes to run for. discount_factor: Gamma discount factor. alpha: TD learning rate. epsilon: Chance the sample a random action. Float betwen 0 and 1. Returns: A tuple (Q, episode_lengths). Q is the optimal action-value function, a dictionary mapping state -> action values. stats is an EpisodeStats object with two numpy arrays for episode_lengths and episode_rewards. """ # The final action-value function. # A nested dictionary that maps state -> (action -> action-value). Q = defaultdict(lambda: np.zeros(env.action_space.n)) memory = defaultdict(list) # Keeps track of useful statistics stats = plotting.EpisodeStats(episode_lengths=np.zeros(num_episodes), episode_rewards=np.zeros(num_episodes)) # The policy we're following #policy = make_epsilon_greedy_policy(Q, epsilon, env.action_space.n) for i_episode in range(num_episodes): # Print out which episode we're on, useful for debugging. #print("Episode ", i_episode) if (i_episode + 1) % 100 == 0: print("\rEpisode {}/{}.".format(i_episode + 1, num_episodes), end="") #sys.stdout.flush() # Reset the environment and pick the first action eigenState = env.reset() # One step in the environment # total_reward = 0.0 for t in itertools.count(): if eigenState in memory: memList = memory[eigenState] action = memList[0] stateValue = memList[1] nextState = memList[2] if nextState in memory: nextStateValue = memory[nextState][1] else: nextStateValue = 0.0 reward = memList[3] Q_program = QuantumProgram() qr = Q_program.create_quantum_register("qr", 2) cr = Q_program.create_classical_register("cr", 2) eigenAction = Q_program.create_circuit("superposition", [qr], [cr]) eigenAction.h(qr) eigenAction, qr = groverIteration(Q_program, eigenAction, qr, action, reward, nextStateValue) else: #################### Prepare the n-qubit registers ######################################### Q_program = QuantumProgram() qr = Q_program.create_quantum_register("qr", 2) cr = Q_program.create_classical_register("cr", 2) eigenAction = Q_program.create_circuit("superposition", [qr], [cr]) eigenAction.h(qr) ############################################################################################ stateValue = 0.0 action = collapseActionSelectionMethod(Q_program, eigenAction, qr, cr) nextEigenState, reward, done, _ = env.step(action) #if done: # print(reward) #reward += 1 if nextEigenState in memory: memList = memory[nextEigenState] nextStateValue = memList[1] else: nextStateValue = 0.0 #Update state value stateValue = stateValue + alpha * ( reward + (discount_factor * nextStateValue) - stateValue) memory[eigenState] = (action, stateValue, nextEigenState, reward) stats.episode_rewards[i_episode] += (discount_factor**t) * reward stats.episode_lengths[i_episode] = t if done: break eigenState = nextEigenState return Q, stats, memory
class MapperTest(QiskitTestCase): """Test the mapper.""" def setUp(self): self.seed = 42 self.qp = QuantumProgram() def test_mapper_overoptimization(self): """ The mapper should not change the semantics of the input. An overoptimization introduced the issue #81: https://github.com/QISKit/qiskit-sdk-py/issues/81 """ self.qp.load_qasm_file( self._get_resource_path('qasm/overoptimization.qasm'), name='test') coupling_map = {0: [2], 1: [2], 2: [3], 3: []} result1 = self.qp.execute(["test"], backend="local_qasm_simulator", coupling_map=coupling_map) count1 = result1.get_counts("test") result2 = self.qp.execute(["test"], backend="local_qasm_simulator", coupling_map=None) count2 = result2.get_counts("test") self.assertEqual( count1.keys(), count2.keys(), ) def test_math_domain_error(self): """ The math library operates over floats and introduce floating point errors that should be avoided. See: https://github.com/QISKit/qiskit-sdk-py/issues/111 """ self.qp.load_qasm_file( self._get_resource_path('qasm/math_domain_error.qasm'), name='test') coupling_map = {0: [2], 1: [2], 2: [3], 3: []} result1 = self.qp.execute(["test"], backend="local_qasm_simulator", coupling_map=coupling_map, seed=self.seed) # TODO: the circuit produces different results under different versions # of Python, which defeats the purpose of the "seed" parameter. A proper # fix should be issued - this is a workaround for this particular test. if version_info.minor == 5: # Python 3.5 self.assertEqual(result1.get_counts("test"), { '0001': 507, '0101': 517 }) else: # Python 3.6 and higher self.assertEqual(result1.get_counts("test"), { '0001': 517, '0101': 507 }) def test_optimize_1q_gates_issue159(self): """Test change in behavior for optimize_1q_gates that removes u1(2*pi) rotations. See: https://github.com/QISKit/qiskit-sdk-py/issues/159 """ self.qp = QuantumProgram() qr = self.qp.create_quantum_register('qr', 2) cr = self.qp.create_classical_register('cr', 2) qc = self.qp.create_circuit('Bell', [qr], [cr]) qc.h(qr[0]) qc.cx(qr[1], qr[0]) qc.cx(qr[1], qr[0]) qc.cx(qr[1], qr[0]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) backend = 'local_qasm_simulator' cmap = {1: [0], 2: [0, 1, 4], 3: [2, 4]} qobj = self.qp.compile(["Bell"], backend=backend, coupling_map=cmap) # TODO: Python 3.5 produces an equivalent but different QASM, with the # last lines swapped. This assertion compares the output with the two # expected programs, but proper revision should be done. self.assertIn(self.qp.get_compiled_qasm(qobj, "Bell"), (EXPECTED_QASM_1Q_GATES, EXPECTED_QASM_1Q_GATES_3_5)) def test_random_parameter_circuit(self): """Run a circuit with randomly generated parameters.""" self.qp.load_qasm_file( self._get_resource_path('qasm/random_n5_d5.qasm'), name='rand') coupling_map = {0: [1], 1: [2], 2: [3], 3: [4]} result1 = self.qp.execute(["rand"], backend="local_qasm_simulator", coupling_map=coupling_map, seed=self.seed) res = result1.get_counts("rand") expected_result = { '10000': 97, '00011': 24, '01000': 120, '10111': 59, '01111': 37, '11010': 14, '00001': 34, '00100': 42, '10110': 41, '00010': 102, '00110': 48, '10101': 19, '01101': 61, '00111': 46, '11100': 28, '01100': 1, '00000': 86, '11111': 14, '11011': 9, '10010': 35, '10100': 20, '01001': 21, '01011': 19, '10011': 10, '11001': 13, '00101': 4, '01010': 2, '01110': 17, '11000': 1 } # TODO: the circuit produces different results under different versions # of Python and NetworkX package, which defeats the purpose of the # "seed" parameter. A proper fix should be issued - this is a workaround # for this particular test. if version_info.minor == 5: # Python 3.5 import networkx if networkx.__version__ == '1.11': expected_result = { '01001': 41, '10010': 25, '00111': 53, '01101': 68, '10101': 11, '10110': 34, '01110': 6, '11100': 27, '00100': 54, '11010': 20, '10100': 20, '01100': 1, '10000': 96, '11000': 1, '11011': 9, '10011': 15, '00101': 3, '00001': 25, '00010': 113, '01011': 16, '11111': 19, '11001': 16, '00011': 22, '00000': 89, '00110': 40, '01000': 110, '10111': 60, '11110': 4, '01010': 9, '01111': 17 } else: expected_result = { '01001': 32, '11110': 1, '10010': 36, '11100': 34, '11011': 10, '00001': 41, '00000': 83, '10000': 94, '11001': 15, '01011': 24, '00100': 43, '11000': 5, '11010': 9, '01100': 5, '10100': 23, '01101': 54, '01110': 6, '00011': 13, '10101': 12, '00111': 36, '00110': 40, '01000': 119, '11111': 19, '01010': 8, '10111': 61, '10110': 52, '01111': 23, '00010': 110, '00101': 2, '10011': 14 } self.assertEqual(res, expected_result) def test_symbolic_unary(self): """Test symbolic math in DAGBackend and optimizer with a prefix. See: https://github.com/QISKit/qiskit-sdk-py/issues/172 """ ast = qasm.Qasm(filename=self._get_resource_path( 'qasm/issue172_unary.qasm')).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend( ["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_UNARY) def test_symbolic_binary(self): """Test symbolic math in DAGBackend and optimizer with a binary operation. See: https://github.com/QISKit/qiskit-sdk-py/issues/172 """ ast = qasm.Qasm(filename=self._get_resource_path( 'qasm/issue172_binary.qasm')).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend( ["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_BINARY) def test_symbolic_extern(self): """Test symbolic math in DAGBackend and optimizer with an external function. See: https://github.com/QISKit/qiskit-sdk-py/issues/172 """ ast = qasm.Qasm(filename=self._get_resource_path( 'qasm/issue172_extern.qasm')).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend( ["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_EXTERN) def test_symbolic_power(self): """Test symbolic math in DAGBackend and optimizer with a power (^). See: https://github.com/QISKit/qiskit-sdk-py/issues/172 """ ast = qasm.Qasm(data=QASM_SYMBOLIC_POWER).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend( ["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_POWER)
def test_get_quantum_register_noname(self): q_program = QuantumProgram(specs=self.QPS_SPECS_NONAMES) qr = q_program.get_quantum_register() self.assertIsInstance(qr, QuantumRegister)
import sys from qiskit import QuantumCircuit, QuantumProgram import Qconfig from plot_histogram_file import * backend = 'ibmqx2' shots = 1024 # the number of shots in the experiment program = QuantumProgram() program.set_api(Qconfig.APItoken, Qconfig.config['url']) # set the APIToken and API url # Creating registers q_register = program.create_quantum_register('q_register', 5) c_register = program.create_classical_register('c_register', 5) # Quantum circuit two Hadamards qc_twohadamard = program.create_circuit('twohadamard', [q_register], [c_register]) qc_twohadamard.h(q_register) qc_twohadamard.barrier() qc_twohadamard.h(q_register) qc_twohadamard.measure(q_register[0], c_register[0]) circuits = ['twohadamard'] result = program.execute(circuits, backend=backend, shots=shots, max_credits=3,
#!/usr/bin/env python3 # Example from https://github.com/QISKit/qiskit-sdk-py from qiskit import QuantumProgram # Creating Programs create your first QuantumProgram object instance. qp = QuantumProgram() # Creating Registers create your first Quantum Register called 'qr' with 2 qubits qr = qp.create_quantum_register('qr', 2) # create your first Classical Register called 'cr' with 2 bits cr = qp.create_classical_register('cr', 2) # Creating Circuits create your first Quantum Circuit called 'qc' involving your Quantum Register 'qr' # and your Classical Register 'cr' qc = qp.create_circuit('superposition', [qr], [cr]) # add the H gate in the Qubit 0, we put this Qubit in superposition qc.h(qr[0]) # add measure to see the state qc.measure(qr, cr) # Compiled and execute in the local_qasm_simulator #print(qp.get_qasm('superposition')) result = qp.execute(['superposition'], backend='local_qasm_simulator', shots=1000)
def groverminimize(opt_oracle, backendcode=0, withancilla=True, fvalues=fvalues, silent=False): #,shots=1024): """" inputs are the oracle (function), and the number of bits ... each iteration it narrows it further https://arxiv.org/abs/quant-ph/9607014v2 """ showancilla = False starttime = time.time() nvalues = len(fvalues) nqubits = num_qubits_from_length(nvalues) if nqubits <= 3: # no need for ancilla if too few qubits withancilla = False # set up quantum environment. (design): is this the right place to define these? backend = backendarray[backendcode] qprog = QuantumProgram() # qprog.set_api(Qconfig.APItoken,Qconfig.config['url']) numOiterations = numGroverOptimizeiterations(nqubits) #numGiterations = numGroveriterations(2 ** nqubits, numsolutions) optimized_index = random.randint(0, nvalues - 1) max_repeats = nqubits # number of iterations repeats = 0 for j in range(numOiterations): qreg = qprog.create_quantum_register("qr", nqubits) creg = qprog.create_classical_register("cr", nqubits) circ_qregs = [qreg] circ_cregs = [creg] qubits = getqubitlist(qreg) if withancilla: qareg = qprog.create_quantum_register("qar", nqubits - 3) # ancilla registers circ_qregs.append(qareg) if showancilla: careg = qprog.create_classical_register("car", nqubits - 3) circ_cregs.append(careg) ancillaqubits = getqubitlist(qareg) else: ancillaqubits = None qcirc = qprog.create_circuit("qc", circ_qregs, circ_cregs) # construct initial state - uniform superposition allqubitsH(qcirc, qubits) # Iterate # use very rough heuristic for number of solutions, should be high to start and gets smaller, halves each time ..., improvement TODO numsol = np.ceil( 2**(nqubits - j * 2 / 3)) #numsol=np.ceil(nqubits/(2*sqrt(j+1))) n_iter = numGroveriterations(2**nqubits, numsol) # print("assumed ",numsol, " solutions to calculate ",n_iter, " Grover oracle+diffusion cycles") for i in range(0, n_iter): # the oracle opt_oracle(qcirc, qubits, optimized_index, ancillaqubits, fvalues=fvalues) # Grover groverdiffusion groverdiffusion(qcirc, qubits, ancillaqubits) qcirc.measure(qreg, creg) res = qprog.execute(["qc"], backend, timeout=3000) #,shots=1)#024) counts = res.get_counts("qc") #print(counts) # index with maximum counts trial_index = int( max(counts.items(), key=operator.itemgetter(1))[0], 2) # np.random.choice(range(0, 7), p=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2]) #trial_index=int(list(counts.keys())[0], 2) #trial_index = int(max(counts.items(), key=operator.itemgetter(1))[0],2) # print("func(trial_index)", func(trial_index), " and func(optimized_index) ",func(optimized_index)) # print("trial ", trial_index, "opt ind:", optimized_index) # get rid of padded indices - use knowledge of fvalues again here (this must be built into oracle) if trial_index < nvalues and fvalues[trial_index] < fvalues[ optimized_index]: # update index optimized_index = trial_index repeats = 0 else: # same index repeats += 1 #print("Iteration ",j, " with optimal index ", optimized_index, " and result:\n",counts) # test output # print("Iteration ", j, " with trial index ", trial_index, " and optimal index ", optimized_index) if repeats == max_repeats: break executiontime = time.time() - starttime if not silent: print("Grover's Optimization algorithm executed over ", j, " iterations in ", timestring(executiontime), " Used %s," % backend.replace("_", " "), " on ", nqubits, " qubits") #, over ", shots, " shots.") print("Optimized index ", optimized_index) return optimized_index
def test_create_anonymous_classical_register(self): """Test create_classical_register with no name. """ q_program = QuantumProgram() cr = q_program.create_classical_register(size=3) self.assertIsInstance(cr, ClassicalRegister)
# ``` # ## Implementation <a id='implementation'></a> # In[1]: # Importing QISKit import math from qiskit import QuantumCircuit, QuantumProgram import Qconfig # Import basic plotting tools from qiskit.tools.visualization import plot_histogram # Quantum program setup Q_program = QuantumProgram() Q_program.set_api(Qconfig.APItoken, Qconfig.config["url"]) # set the APIToken and API url # First let's define the QFT function, as well as a function that creates a state from which a QFT will return 1: # In[2]: def input_state(circ, q, n): """n-qubit input state for QFT that produces output 1.""" for j in range(n): circ.h(q[j]) circ.u1(math.pi / float(2**(j)), q[j]).inverse()
def test_create_anonymous_quantum_register(self): """Test create_quantum_register with no name. """ q_program = QuantumProgram() qr = q_program.create_quantum_register(size=3) self.assertIsInstance(qr, QuantumRegister)
def evaluate(compiler_function=None, test_circuits=None, verbose=False, backend='local_qiskit_simulator'): """ Evaluates the given complier_function with the circuits in test_circuits and compares the output circuit and quantum state with the original and a reference obtained with the qiskit compiler. Args: compiler_function (function): reference to user compiler function test_circuits (dict): named dict of circuits for which the compiler performance is evaluated test_circuits: { "name": { "qasm": 'qasm_str', "coupling_map": 'target_coupling_map } } verbose (bool): specifies if performance of basic QISKit unroler and mapper circuit is shown for each circuit backend (string): backend to use. For Windows Systems you should specify 'local_qasm_simulator' until 'local_qiskit_simulator' is available. Returns: dict { "name": circuit name { "optimizer_time": time taken by user compiler, "reference_time": reference time taken by qiskit circuit mapper/unroler (if verbose), "cost_original": original circuit cost function value (if verbose), "cost_reference": reference circuit cost function value (if verbose), "cost_optimized": optimized circuit cost function value, "coupling_correct_original": (bool) does original circuit satisfy the coupling map (if verbose), "coupling_correct_reference": (bool) does circuit produced by the qiskit mapper/unroler satisfy the coupling map (if verbose), "coupling_correct_optimized": (bool) does optimized circuit satisfy the coupling map, "state_correct_optimized": (bool) does optimized circuit return correct state } } """ # Initial Setup basis_gates = 'u1,u2,u3,cx,id' # or use "U,CX?" gate_costs = { 'id': 0, 'u1': 0, 'measure': 0, 'reset': 0, 'barrier': 0, 'u2': 1, 'u3': 1, 'U': 1, 'cx': 10, 'CX': 10 } # Results data structure results = {} # Load QASM files and extract DAG circuits for name, circuit in test_circuits.items(): qp = QuantumProgram() qp.load_qasm_text(circuit["qasm"], name, basis_gates=basis_gates) circuit["dag_original"] = qasm_to_dag_circuit(circuit["qasm"], basis_gates=basis_gates) test_circuits[name] = circuit results[name] = {} # build empty result dict to be filled later # Only return results if a valid compiler function is provided if compiler_function is not None: # step through all the test circuits using multiprocessing compile_jobs = [[name, circuit, 0, compiler_function, gate_costs] for name, circuit in test_circuits.items()] with Pool(len(compile_jobs)) as job: res_values_opt = job.map(_compile_circuits, compile_jobs) # stash the results in the respective dicts for job in range(len(compile_jobs)): name = res_values_opt[job].pop("name") test_circuits[name] = res_values_opt[job].pop( "circuit") # remove the circuit from the results and store it results[name] = res_values_opt[job] # do the same for the reference compiler in qiskit if verbose == True if verbose: compile_jobs = [[name, circuit, 1, _qiskit_compiler, gate_costs] for name, circuit in test_circuits.items()] with Pool(len(compile_jobs)) as job: res_values = job.map(_compile_circuits, compile_jobs) # also stash this but use update so we don't overwrite anything for job in range(len(compile_jobs)): name = res_values[job].pop("name") test_circuits[name].update( res_values[job].pop("circuit") ) # remove the circuit from the results and store it results[name].update(res_values[job]) # determine the final permutation of the qubits # this is done by analyzing the measurements on the qubits compile_jobs = [[name, circuit, verbose] for name, circuit in test_circuits.items()] with Pool(len(compile_jobs)) as job: res_values = job.map(_prep_sim, compile_jobs) for job in range(len(compile_jobs)): name = res_values[job].pop("name") test_circuits[name].update(res_values[job].pop( "circuit")) # remove the circuit from the results and store it results[name].update(res_values[job]) # Compose qobj for simulation config = { 'data': ['quantum_state'], } # generate qobj for original circuit qobj_original = _compose_qobj("original", test_circuits, backend=backend, config=config, basis_gates=basis_gates, shots=1, seed=None) # Compute original cost and check original coupling map for circuit in qobj_original["circuits"]: name = circuit["name"] coupling_map = test_circuits[name].get("coupling_map", None) coupling_map_passes = True cost = 0 for op in circuit["compiled_circuit"]["operations"]: cost += gate_costs.get(op["name"]) # compute cost if op["name"] in ["cx", "CX"] \ and coupling_map is not None: # check coupling map coupling_map_passes &= (op["qubits"][0] in coupling_map) if op["qubits"][0] in coupling_map: coupling_map_passes &= ( op["qubits"][1] in coupling_map[op["qubits"][0]]) if verbose: results[name]["cost_original"] = cost results[name][ "coupling_correct_original"] = coupling_map_passes # Run simulation time_start = time.process_time() res_original = qp.run(qobj_original, timeout=GLOBAL_TIMEOUT) results[name]["sim_time_orig"] = time.process_time() - time_start # Generate qobj for optimized circuit qobj_optimized = _compose_qobj("optimized", test_circuits, backend=backend, config=config, basis_gates=basis_gates, shots=1, seed=None) # Compute compiled circuit cost and check coupling map for circuit in qobj_optimized["circuits"]: name = circuit["name"] coupling_map = test_circuits[name].get("coupling_map", None) coupling_map_passes = True cost = 0 for op in circuit["compiled_circuit"]["operations"]: cost += gate_costs.get(op["name"]) # compute cost if op["name"] in ["cx", "CX"] \ and coupling_map is not None: # check coupling map coupling_map_passes &= (op["qubits"][0] in coupling_map) if op["qubits"][0] in coupling_map: coupling_map_passes &= ( op["qubits"][1] in coupling_map[op["qubits"][0]]) results[name]["cost_optimized"] = cost results[name]["coupling_correct_optimized"] = coupling_map_passes # Run simulation time_start = time.process_time() res_optimized = qp.run(qobj_optimized, timeout=GLOBAL_TIMEOUT) results[name]["sim_time_opti"] = time.process_time() - time_start if verbose: # Generate qobj for reference circuit optimized by qiskit compiler qobj_reference = _compose_qobj("reference", test_circuits, backend=backend, config=config, basis_gates=basis_gates, shots=1, seed=None) # Compute reference cost and check reference coupling map for circuit in qobj_reference["circuits"]: name = circuit["name"] coupling_map = test_circuits[name].get("coupling_map", None) coupling_map_passes = True cost = 0 for op in circuit["compiled_circuit"]["operations"]: cost += gate_costs.get(op["name"]) # compute cost if op["name"] in ["cx", "CX"] \ and coupling_map is not None: # check coupling map coupling_map_passes &= (op["qubits"][0] in coupling_map) if op["qubits"][0] in coupling_map: coupling_map_passes &= ( op["qubits"][1] in coupling_map[op["qubits"][0]]) results[name]["cost_reference"] = cost results[name][ "coupling_correct_reference"] = coupling_map_passes # Skip simulation of reference State to speed things up! # time_start = time.process_time() # res_reference = qp.run(qobj_reference, timeout=GLOBAL_TIMEOUT) # results[name]["sim_time_ref"] = time.process_time() - time_start # Check output quantum state of optimized circuit is correct in comparison to original for name in results.keys(): # handle errors here data_original = res_original.get_data(name) if test_circuits[name]["dag_optimized"] is not None: data_optimized = res_optimized.get_data(name) correct = _compare_outputs( data_original, data_optimized, test_circuits[name]["perm_optimized"]) results[name]["state_correct_optimized"] = correct else: results[name]["state_correct_optimized"] = False # Skip verification of the reference State to speed things up! # if verbose: # if test_circuits[name]["dag_reference"] is not None: # data_reference = res_reference.get_data(name) # correct = _compare_outputs(data_original, data_reference, test_circuits[name]["perm_reference"]) # results[name]["state_correct_reference"] = correct # else: # results[name]["state_correct_reference"] = False return results
class RandomQasmGenerator(): """ Generate random size circuits for profiling. """ def __init__(self, seed=None, maxQubits=5, minQubits=1, maxDepth=100, minDepth=1): """ Args: seed: Random number seed. If none, don't seed the generator. maxDepth: Maximum number of operations in a circuit. maxQubits: Maximum number of qubits in a circuit. """ self.maxDepth = maxDepth self.maxQubits = maxQubits self.minDepth = minDepth self.minQubits = minQubits self.qp = QuantumProgram() self.qr = self.qp.create_quantum_register('qr', maxQubits) self.cr = self.qp.create_classical_register('cr', maxQubits) self.circuitNameList = [] self.nQubitList = [] self.depthList = [] if seed is not None: random.seed(a=seed) def add_circuits(self, nCircuits, doMeasure=True): """Adds circuits to program. Generates a circuit with a random number of operations equally weighted between U3 and CX. Also adds a random number of measurements in [1,nQubits] to end of circuit. Args: nCircuits (int): Number of circuits to add. doMeasure (boolean): whether to add measurements """ self.circuitNameList = [] self.nQubitList = numpy.random.choice(range(self.minQubits, self.maxQubits + 1), size=nCircuits) self.depthList = numpy.random.choice(range(self.minDepth, self.maxDepth + 1), size=nCircuits) for i in range(nCircuits): circuitName = ''.join( numpy.random.choice(list(string.ascii_letters + string.digits), size=10)) self.circuitNameList.append(circuitName) nQubits = self.nQubitList[i] depth = self.depthList[i] circuit = self.qp.create_circuit(circuitName, [self.qr], [self.cr]) for j in range(depth): if nQubits == 1: opInd = 0 else: opInd = random.randint(0, 1) if opInd == 0: # U3 qind = random.randint(0, nQubits - 1) circuit.u3(random.random(), random.random(), random.random(), self.qr[qind]) elif opInd == 1: # CX source, target = random.sample(range(nQubits), 2) circuit.cx(self.qr[source], self.qr[target]) nmeasure = random.randint(1, nQubits) for j in range(nmeasure): qind = random.randint(0, nQubits - 1) if doMeasure: # doing this if here keeps the RNG from depending on # whether measurements are done. circuit.measure(self.qr[qind], self.cr[qind]) def get_circuit_names(self): return self.circuitNameList def getProgram(self): return self.qp
def test_get_classical_register_noname(self): q_program = QuantumProgram(specs=self.QPS_SPECS_NONAMES) cr = q_program.get_classical_register() self.assertIsInstance(cr, ClassicalRegister)
def playGame(device, shipPos): gameOver = False bombPos = [ [0, 0, 0, 0, 0], [0, 0, 0, 0, 0] ] grid = [0, 0] gameOver = False while (not gameOver): bombShip(0, bombPos) bombShip(1, bombPos) for player in range(2): print("Measuring damage to Player " + str(player + 1) + "...") Q_SPECS = { "circuits": [{ "name": "gridScript", "quantum_registers": [{ "name": "q", "size": 5 }], "classical_registers": [{ "name": "c", "size": 5 }]}], } Q_program = QuantumProgram(specs=Q_SPECS) gridScript = Q_program.get_circuit("gridScript") q = Q_program.get_quantum_registers("q") c = Q_program.get_classical_registers("c") for position in range(5): for hit in range(bombPos[(player + 1) % 2][position]): for ship in range(3): if (position == shipPos[player][ship]): frac = 1/(ship + 1) gridScript.u3(frac * math.pi, 0.0, 0.0, q[position]) for qubit in range(5): gridScript.measure(q[qubit], c[qubit]) Q_program.set_api(Qconfig.APItoken, Qconfig.config["url"]) Q_program.execute(["gridScript"], device, SHOTS, wait=2, timeout=60) grid[player] = Q_program.get_counts("gridScript") if (('Error' in grid[0].values()) or ('Error' in grid[1].values())): print("\nThe process timed out. Try this round again.\n") else: damage = calculateDamageToShips(grid) displayBoards(damage) for player in range(2): if ( damage[player][shipPos[player][0]] > 0.95 and damage[player][shipPos[player][1]] > 0.95 and damage[player][shipPos[player][2]] > .95 ): print("All ships on Player " + str(player) + "'s board are destroyed! \n") gameOver = True if (gameOver): print("Game Over")
def test_get_circuit_noname(self): q_program = QuantumProgram(specs=self.QPS_SPECS_NONAMES) qc = q_program.get_circuit() self.assertIsInstance(qc, QuantumCircuit)
def test_create_program_with_specsnonames(self): """Test Quantum Object Factory creation using Specs definition object with no names for circuit nor records. """ result = QuantumProgram(specs=self.QPS_SPECS_NONAMES) self.assertIsInstance(result, QuantumProgram)