def test_fail_to_assemble_circuits_with_unbounded_parameters(self): idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) qc = transpile(qc, self.backend_with_dt) with self.assertRaises(QiskitError): assemble(qc, self.backend_with_dt)
def test_save_amplitudes(self, params): """Test save_amplitudes instruction""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'matrix_product_state' ] # Stabilizer test circuit circ = QFT(3) # Target statevector target = qi.Statevector(circ).data[params] # Add save to circuit save_key = 'amps' circ.save_amplitudes(save_key, params) # Run opts = self.BACKEND_OPTS.copy() qobj = assemble(circ, self.SIMULATOR) result = self.SIMULATOR.run(qobj, **opts).result() method = opts.get('method', 'automatic') if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) data = result.data(0) self.assertIn(save_key, data) value = result.data(0)[save_key] self.assertTrue(np.allclose(value, target))
def sweep_program(backend, frequencies=None ,qbit=0 ): backend_config = backend.configuration() backend_defaults = backend.defaults() ## Get qubit frequency center_est_freq = backend_defaults.qubit_freq_est[qbit] print(f'Estimated frequency for qbit {qbit} is {center_est_freq}') freq_span = .02 count = 50 if not frequencies: frequencies = np.linspace(center_est_freq-freq_span/2, center_est_freq+freq_span/2, count ) drive_chan = pulse.DriveChannel(qbit) schedule = freq_sweep_schedule(qbit, backend_config, drive_chan) # Create the frequency settings for the sweep (MUST BE IN HZ) schedule_frequencies = [{drive_chan: freq} for freq in frequencies] num_shots_per_frequency = 1024 frequency_sweep_program = assemble(schedule, backend=backend, meas_level=1, meas_return='avg', shots=num_shots_per_frequency, schedule_los=schedule_frequencies) return frequency_sweep_program
def test_plugins_submit_qiskit_qobj_to_ionq(self): from qiskit import assemble circuit = self._3_qubit_ghz() qobj = assemble(circuit) self._test_qiskit_submit_ionq(circuit=qobj, num_shots=1024, num_shots_actual=1024)
def submit(self): running_jobs = [] configuration = self._backend.configuration() max_circuits_per_job = configuration.max_experiments for i in range(0, len(self._circuits), max_circuits_per_job): # Submit some jobs down = i * max_circuits_per_job up = max(len(self._circuits), (i + 1) * max_circuits_per_job) qobj = assemble( self._circuits[down:up], backend=self._backend, shots=configuration.max_shots, ) job = self._backend.run(qobj, job_tags=self._tags) running_jobs.append(job) # If we have too much submitted jobs, wait for the first one to finish. if len(running_jobs) == self._maximum_batch_job: self._wait_for_first_job_to_complete(running_jobs) self._circuits_results.append(running_jobs[0].result()) self._job_ids.append(running_jobs.pop(0).job_id()) # Wait for the last jobs to finish while running_jobs: self._wait_for_first_job_to_complete(running_jobs) self._circuits_results.append(running_jobs[0].result()) self._job_ids.append(running_jobs.pop(0).job_id())
def test_save_statevector(self): """Test save statevector for instruction""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'matrix_product_state', 'extended_stabilizer' ] # Stabilizer test circuit circ = QuantumCircuit(3) circ.h(0) circ.sdg(0) circ.cx(0, 1) circ.cx(0, 2) # Target statevector target = qi.Statevector(circ) # Add save to circuit save_key = 'sv' circ.save_statevector(save_key) # Run opts = self.BACKEND_OPTS.copy() qobj = assemble(circ, self.SIMULATOR) result = self.SIMULATOR.run(qobj, **opts).result() method = opts.get('method', 'automatic') if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) data = result.data(0) self.assertIn(save_key, data) value = qi.Statevector(result.data(0)[save_key]) self.assertAlmostEqual(value, target)
def snapshot_circuit_instr(circ_qubits, label, qubits, variance=False): """Return QobjInstruction for circuit monkey patch method.""" circuit = QuantumCircuit(circ_qubits) circuit.snapshot_probabilities(label, qubits, variance) qobj = assemble(circuit) instr = qobj.experiments[0].instructions[0] return instr
def run_on_ibmq(draw=False, waitForResult=False, backend='ibmq_burlington'): print('Loading account .. ', end='', flush=True) provider = IBMQ.load_account() print('done') backend = getattr(provider.backends, backend) circuit = define_circuit(draw) print('Transpiling .. ', end='') transpiled = transpile(circuit, backend) print('done') print('Assembling .. ', end='') qobj = assemble(transpiled, backend, shots=1000) print('done') exit() print(f'Sending to {backend} .. ', end='') job = backend.run(qobj) print('done') if waitForResult: print(f'Waiting for result .. ', end='', flush=True) delayed_result = backend.retrieve_job(job.job_id()).result() delayed_counts = delayed_result.get_counts() print('done') print(f'\nTotal counts: {delayed_counts}') else: print(f'\nJob ID: {job.job_id()}')
def test_run_qobj(self): """Test running a Qobj.""" qobj = assemble(transpile(ReferenceCircuits.bell(), self.backend), self.backend) with self.assertWarns(DeprecationWarning): job = self.backend.run(qobj) cancel_job(job)
def quac_time_qasm_transpiler(circuit: QuantumCircuit, backend: BaseBackend) -> str: """Converts a circuit of type QuantumCircuit to a string of TIMEQASM specification :param circuit: a QuantumCircuit (need not be transpiled) :param backend: a specific backend to generate the QASM for (for tranpsilation) :return: a string containing necessary QASM with times for each gate """ # Get original QASM transpiled_circuit = transpile(circuit, backend) original_qasm = transpiled_circuit.qasm() # Get body of original QASM start = 2 + len(circuit.qregs) + len(circuit.cregs) original_qasm_body = original_qasm.splitlines()[start:] # Formulate header qasm_modified = "TIMEQASM 1.0;\n" qasm_modified += "\n".join(original_qasm.splitlines()[1:start]) qasm_modified += "\n" # Schedule circuit qobj = assemble(transpiled_circuit, backend) qexp = qobj.experiments[0] qschedule = list_schedule_experiment(qexp, backend.properties()) # Formulate body for instruction, time in qschedule: # Note: ID was custom injected by the scheduler in this plugin qasm_modified += f"{original_qasm_body[instruction.id][:-1]} @{time};\n" return qasm_modified
def test_save_stabilizer(self): """Test save statevector for instruction""" SUPPORTED_METHODS = ['automatic', 'stabilizer'] # Stabilizer test circuit circ = QuantumCircuit(3) circ.h(0) circ.sdg(0) circ.cx(0, 1) circ.cx(0, 2) # Target statevector target = qi.Clifford(circ) # Add save to circuit label = 'state' circ.save_stabilizer(label) # Run opts = self.BACKEND_OPTS.copy() qobj = assemble(circ, self.SIMULATOR) result = self.SIMULATOR.run(qobj, **opts).result() method = opts.get('method', 'automatic') if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) data = result.data(0) self.assertIn(label, data) value = qi.Clifford.from_dict(result.data(0)[label]) self.assertEqual(value, target)
def test_list_schedule(self): example_circ = QuantumCircuit(5) example_circ.h(0) example_circ.x(2) example_circ.x(0) example_circ.cx(0, 2) example_circ.y(3) example_circ.y(2) example_circ.measure_all() qobj = assemble(transpile(example_circ, FakeBogota()), backend=FakeBogota()) list_scheduled_circ = list_schedule_experiment( qobj.experiments[0], FakeBogota().properties()) expected_gates = [ 'u3', 'u3', 'u2', 'cx', 'cx', 'cx', 'cx', 'u3', 'barrier', 'measure', 'measure', 'measure', 'measure', 'measure' ] expected_times = [ 1, 1, 1, 72.11111111111111, 513.0, 918.3333333333333, 1359.2222222222222, 1693.4444444444443, 1764.5555555555554, 1764.5555555555554, 1764.5555555555554, 1764.5555555555554, 1764.5555555555554, 1764.5555555555554 ] index = 0 for gate, time in list_scheduled_circ: self.assertEqual(gate.name, expected_gates[index]) self.assertEqual(time, expected_times[index]) index += 1
def snapshot_circuit_instr(circ_qubits, label, qubits=None): """Return QobjInstruction for circuit monkey patch method.""" circuit = QuantumCircuit(circ_qubits) circuit.snapshot_density_matrix(label, qubits) qobj = assemble(circuit) instr = qobj.experiments[0].instructions[0] return instr
def parameterized_qobj( backend, shots=1000, measure=True, snapshot=False, save_state=False, ): """Return ParameterizedQobj for settings.""" pershot = shots == 1 pcirc1, param1 = save_expval_circuit_parameterized( pershot=pershot, measure=measure, snapshot=snapshot, ) circuits2to4 = save_expval_circuits( pauli=True, skip_measure=(not measure), pershot=pershot, ) pcirc2, param2 = save_expval_circuit_parameterized( pershot=pershot, measure=measure, snapshot=snapshot, ) circuits = [pcirc1] + circuits2to4 + [pcirc2] if save_state: for circuit in circuits: circuit.save_statevector(pershot=pershot) params = [param1, [], [], [], param2] qobj = assemble(circuits, backend=backend, shots=shots, parameterizations=params) return qobj
def test_set_density_matrix(self, num_qubits): """Test SetDensityMatrix instruction""" SUPPORTED_METHODS = [ 'automatic', 'density_matrix', 'density_matrix_gpu', 'density_matrix_thrust' ] seed = 100 save_label = 'state' target = qi.random_density_matrix(2 ** num_qubits, seed=seed) circ = QuantumCircuit(num_qubits) circ.set_density_matrix(target) circ.save_density_matrix(label=save_label) # Run opts = self.BACKEND_OPTS.copy() qobj = assemble(circ, self.SIMULATOR) result = self.SIMULATOR.run(qobj, **opts).result() method = opts.get('method', 'automatic') if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) data = result.data(0) self.assertIn(save_label, data) value = qi.DensityMatrix(result.data(0)[save_label]) self.assertAlmostEqual(value, target)
def test_set_stabilizer(self, num_qubits): """Test SetStabilizer instruction""" SUPPORTED_METHODS = [ 'automatic', 'stabilizer' ] seed = 100 save_label = 'state' target = qi.random_clifford(num_qubits, seed=seed) circ = QuantumCircuit(num_qubits) circ.set_stabilizer(target) circ.save_stabilizer(label=save_label) # Run opts = self.BACKEND_OPTS.copy() qobj = assemble(circ, self.SIMULATOR) result = self.SIMULATOR.run(qobj, **opts).result() method = opts.get('method', 'automatic') if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) data = result.data(0) self.assertIn(save_label, data) value = qi.Clifford.from_dict(result.data(0)[save_label]) self.assertEqual(value, target)
def snapshot_circuit_instr(circ_qubits, label): """Return QobjInstruction for circuit monkey patch method.""" circuit = QuantumCircuit(circ_qubits) circuit.snapshot_statevector(label) qobj = assemble(circuit) instr = qobj.experiments[0].instructions[0] return instr
def test_save_unitary(self): """Test save unitary for instruction""" SUPPORTED_METHODS = [ 'automatic', 'unitary', 'unitary_gpu', 'unitary_thrust' ] # Stabilizer test circuit circ = transpile(QuantumVolume(3), self.SIMULATOR) # Target unitary target = qi.Operator(circ) # Add save to circuit save_key = 'state' circ.save_unitary(save_key) # Run opts = self.BACKEND_OPTS.copy() qobj = assemble(circ, self.SIMULATOR) result = self.SIMULATOR.run(qobj, **opts).result() method = opts.get('method', 'automatic') if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) data = result.data(0) self.assertIn(save_key, data) value = qi.Operator(result.data(0)[save_key]) self.assertEqual(value, target)
def test_save_amplitudes_squared_nonclifford(self, params): """Test save_amplitudes_squared instruction""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'density_matrix', 'density_matrix_gpu', 'density_matrix_thrust', 'matrix_product_state' ] # Stabilizer test circuit circ = QFT(3) # Target statevector target = np.abs(qi.Statevector(circ).data[params]) ** 2 # Add save to circuit label = 'amps' circ.save_amplitudes_squared(params, label=label) # Run opts = self.BACKEND_OPTS.copy() qobj = assemble(circ, self.SIMULATOR) result = self.SIMULATOR.run(qobj, **opts).result() method = opts.get('method', 'automatic') if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) data = result.data(0) self.assertIn(label, data) value = result.data(0)[label] self.assertTrue(np.allclose(value, target))
def _run_jobs(self, circuits: List[QuantumCircuit], **run_options) -> List[BaseJob]: """Run circuits on backend as 1 or more jobs.""" # Run experiment jobs max_experiments = getattr(self.backend.configuration(), "max_experiments", None) if max_experiments and len(circuits) > max_experiments: # Split jobs for backends that have a maximum job size job_circuits = [ circuits[i:i + max_experiments] for i in range(0, len(circuits), max_experiments) ] else: # Run as single job job_circuits = [circuits] # Run jobs jobs = [] for circs in job_circuits: if isinstance(self.backend, LegacyBackend): qobj = assemble(circs, backend=self.backend, **run_options) job = self.backend.run(qobj) else: job = self.backend.run(circs, **run_options) jobs.append(job) return jobs
def test_run(self): creg = ClassicalRegister(2) qreg = QuantumRegister(2) qc = QuantumCircuit(qreg, creg, name='test') qc.h(0) qc.cx(0, 1) measure(qc, qreg, creg) qc_transpiled = transpile(qc, self.backend) qobj = assemble(qc_transpiled, self.backend, shots=1) extra_data = { 'test': [ 'yes', 'is', 'there' ] } job = self.backend.run(qobj, extra_data=extra_data) LOG.info(job.job_id()) self.assertIsNotNone(job) self.assertEqual(job.job_id(), qobj.qobj_id) self.assertTrue(job.status() in [JobStatus.INITIALIZING, JobStatus.QUEUED]) while job.status() != JobStatus.QUEUED: time.sleep(1) job.cancel()
def add_custom_instruction(self): backend = self.backend(max_job_size=1, max_shot_size=1) circ = random_circuit(num_qubits=2, depth=4) circ.save_statevector() circ = transpile(circ, backend) qobj = assemble(circ) split_qobj(qobj, max_size=1, max_shot_size=1, qobj_id='testing')
def game(Circuitlist, init_state): qr = QuantumRegister(2) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.initialize(init_state, qr) for i in Circuitlist: if i[0] == 1: qc.x(*i[1]) elif i[0] == 2: qc.y(*i[1]) elif i[0] == 3: qc.z(*i[1]) elif i[0] == 4: qc.h(*i[1]) elif i[0] == 5: qc.i(*i[1]) elif i[0] == 6: qc.rx(*i[1]) elif i[0] == 7: qc.ry(*i[1]) elif i[0] == 8: qc.rz(*i[1]) elif i[0] == 9: qc.cx(*i[1]) else: raise ValueError('operation not recognized') qc.measure(1, 0) sv_sim = Aer.get_backend('statevector_simulator') qobj = assemble(qc) job = sv_sim.run(qobj) measurement_result = job.result().get_counts() for i in measurement_result: return i
def run(self, thetas): #acting on a simulator t_qc = transpile( self._circuit, self.backend) #matching the features of a quantum device qobj = assemble( t_qc, shots=self.shots, parameter_binds=[ { self.theta: theta } for theta in thetas ]) #assembling features (circuit, sampling, parameter list) job = self.backend.run(qobj) #running on the simulator result = job.result().get_counts( ) #counts for each values: |0> or |1>. DIVERSO DA LINK counts = np.array(list(result.values())) states = np.array(list(result.keys())).astype(float) # Compute probability for each state probabilities = counts / self.shots # Get state expectation expectation = np.sum(states * probabilities) return np.array([expectation])
def cost_function_one_point_fidelity(self, x, y): """Method for computing the cost function for a given sample (in the datasets), using fidelity. Args: x (array): Point to create the circuit. y (int): label of x. Returns: float with the cost function. """ C = self.my_circuit(x) C.measure_all() t_qc = transpile(C, self.backend) qobj = assemble(t_qc, shots=self.shots) job = self.backend.run(qobj) result = job.result().get_counts() counts = np.array(list(result.values())) states = np.array(list(result.keys())).astype(float) probabilities = counts / self.shots expectation = np.sum(states * probabilities) res = np.array([expectation]) state_real = np.array( [mt.sqrt(1 - res[0]), mt.sqrt(res[0])], dtype='complex') cf = .5 * (1 - fidelity(state_real, self.target[y]))**2 return cf
def split_compare(self, circs, backend, parameterizations=None): """Qobj split test""" qobj = assemble(circs, parameterizations=parameterizations, qobj_id='testing') if parameterizations: qobjs = [ assemble(c, parameterizations=[p], qobj_id='testing') for (c, p) in zip(circs, parameterizations) ] else: qobjs = [assemble(c, qobj_id='testing') for c in circs] test_qobjs = split_qobj(qobj, max_size=1, qobj_id='testing') self.assertEqual(len(test_qobjs[0]), len(qobjs)) for ref, test in zip(qobjs, test_qobjs[0]): self.assertEqual(ref, test)
def run_circuit(self, circuit: QuantumCircuit) -> Result: """ Runs a given QuantumCircuit. This assembles your quantum circut and executes self.run() """ qobj = assemble(circuit) return self.run(qobj)
def run_with_measure(qiskit_schedule, backend_name, meas_level=1): try: from qiskit import providers, assemble from qiskit.pulse import DriveChannel, SetFrequency from qiskit.pulse.macros import measure from qiskit.result.result import Result if qiskit_schedule.duration == 0: return Result(backend_name, None, None, None, None, None) if backend_name == 'Armonk': backend = get_qiskit_backend(backend_name) pulse_sim = providers.aer.PulseSimulator.from_backend(backend) pulse_qobj = assemble(qiskit_schedule, backend=pulse_sim) measure_qubits = [] for channel in qiskit_schedule.channels: if isinstance(channel, DriveChannel): measure_qubits.append(channel.index) frequency = None for start_time, instruction in qiskit_schedule.instructions: if isinstance(instruction, SetFrequency): frequency = {instruction.channel: instruction.frequency} break def strip_frequencies(instruction): if isinstance(instruction[1], SetFrequency): return False return True # Setting frequences isn't supported on simulators, so instead we use `schedule_los` to set a single frequency # and subsequently strip any SetFrequency instructions from the schedule. qiskit_schedule = qiskit_schedule.filter(strip_frequencies) qiskit_schedule += measure(measure_qubits, pulse_sim) << qiskit_schedule.duration pulse_qobj = assemble(qiskit_schedule, backend=pulse_sim, meas_level=meas_level, schedule_los=frequency) job = pulse_sim.run(pulse_qobj) return job.result() else: print( "Only FakeArmonk is supported for simulation currently because other backends are too slow" ) return Result(backend_name, None, None, None, None, None) except ImportError: pass
def test_save_state(self): """Test save_amplitudes instruction""" REFERENCE_SAVE = { 'automatic': SaveStabilizer, 'stabilizer': SaveStabilizer, 'statevector': SaveStatevector, 'statevector_gpu': SaveStatevector, 'statevector_thrust': SaveStatevector, 'density_matrix': SaveDensityMatrix, 'density_matrix_gpu': SaveDensityMatrix, 'density_matrix_thrust': SaveDensityMatrix, 'matrix_product_state': SaveMatrixProductState } REFERENCE_LABEL = { 'automatic': 'stabilizer', 'stabilizer': 'stabilizer', 'statevector': 'statevector', 'statevector_gpu': 'statevector', 'statevector_thrust': 'statevector', 'density_matrix': 'density_matrix', 'density_matrix_gpu': 'density_matrix', 'density_matrix_thrust': 'density_matrix', 'matrix_product_state': 'matrix_product_state' } opts = self.BACKEND_OPTS.copy() method = opts.get('method', 'automatic') if method in REFERENCE_SAVE: # Stabilizer test circuit num_qubits = 4 target_instr = REFERENCE_SAVE[method](num_qubits, label='target') circ = QuantumCircuit(num_qubits) circ.h(0) for i in range(1, num_qubits): circ.cx(i - 1, i) circ.save_state() circ.append(target_instr, range(num_qubits)) label = REFERENCE_LABEL[method] # Run qobj = assemble(circ, self.SIMULATOR) result = self.SIMULATOR.run(qobj, **opts).result() self.assertTrue(result.success) data = result.data(0) self.assertIn(label, data) self.assertIn('target', data) value = data[label] target = data['target'] if method == 'matrix_product_state': for val, targ in zip(value[0], target[0]): self.assertTrue(np.allclose(val, targ)) for val, targ in zip(value[1], target[1]): self.assertTrue(np.allclose(val, targ)) else: self.assertTrue(np.all(value == target))
def test_transpile_and_assemble_delay_circuit_for_simulator(self): """See: https://github.com/Qiskit/qiskit-terra/issues/5962""" qc = QuantumCircuit(1) qc.delay(100, 0, "ns") circ = transpile(qc, self.simulator_backend) self.assertEqual(circ.duration, None) # not scheduled qobj = assemble(circ, self.simulator_backend) self.assertEqual(qobj.experiments[0].instructions[0].name, "delay") self.assertEqual(qobj.experiments[0].instructions[0].params[0], 1e-7)