def test_control_fusion(self): """Test Fusion enable/disable option""" shots = 100 circuit = transpile(self.create_statevector_circuit(), backend=self.SIMULATOR, optimization_level=0) qobj = assemble([circuit], self.SIMULATOR, shots=shots, seed_simulator=1) with self.subTest(msg='fusion enabled'): backend_options = self.fusion_options(enabled=True, threshold=1) result = self.SIMULATOR.run(qobj, **backend_options).result() meta = self.fusion_metadata(result) self.assertSuccess(result) self.assertTrue(meta.get('applied', False)) with self.subTest(msg='fusion disabled'): backend_options = backend_options = self.fusion_options( enabled=False, threshold=1) result = self.SIMULATOR.run(qobj, **backend_options).result() meta = self.fusion_metadata(result) self.assertSuccess(result) self.assertFalse(meta.get('applied', False)) with self.subTest(msg='fusion default'): backend_options = self.fusion_options() result = self.SIMULATOR.run(qobj, **backend_options).result() meta = self.fusion_metadata(result) self.assertSuccess(result) self.assertFalse(meta.get('applied', False))
def test_retrieve_jobs_db_filter(self): """Test retrieving jobs using db_filter.""" # Submit jobs with desired attributes. qc = QuantumCircuit(3, 3) qc.h(0) qc.measure([0, 1, 2], [0, 1, 2]) qobj = assemble(transpile(qc, backend=self.sim_backend), backend=self.sim_backend) job = self.sim_backend.run(qobj, validate_qobj=True) job.wait_for_final_state() my_filter = {'backend.name': self.sim_backend.name(), 'summaryData.summary.qobj_config.n_qubits': 3, 'status': 'COMPLETED'} job_list = self.provider.backends.jobs(backend_name=self.sim_backend.name(), limit=2, skip=0, db_filter=my_filter) self.assertTrue(job_list) for job in job_list: job.refresh() self.assertEqual( job.summary_data_['summary']['qobj_config']['n_qubits'], 3, "Job {} does not have correct data.".format(job.job_id()) )
def test_measure_sampling_with_quantum_noise(self): """Test QasmSimulator measure with deterministic counts with sampling and readout-error""" readout_error = [0.01, 0.1] noise_model = NoiseModel() depolarizing = {'u3': (1, 0.001), 'cx': (2, 0.02)} readout = [[1.0 - readout_error[0], readout_error[0]], [readout_error[1], 1.0 - readout_error[1]]] noise_model.add_all_qubit_readout_error(ReadoutError(readout)) for gate, (num_qubits, gate_error) in depolarizing.items(): noise_model.add_all_qubit_quantum_error( depolarizing_error(gate_error, num_qubits), gate) shots = 1000 circuits = ref_measure.measure_circuits_deterministic( allow_sampling=True) targets = ref_measure.measure_counts_deterministic(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( qobj, noise_model=noise_model, backend_options=self.BACKEND_OPTS).result() self.assertTrue(getattr(result, 'success', False)) sampling = (self.BACKEND_OPTS.get("method") == "density_matrix") self.compare_result_metadata(result, circuits, "measure_sampling", sampling)
def test_fusion_qv(self): """Test Fusion with quantum volume""" shots = 100 circuit = quantum_volume_circuit(10, 1, measure=True, seed=0) qobj = assemble([circuit], self.SIMULATOR, shots=shots, seed_simulator=1) backend_options = self.BACKEND_OPTS.copy() backend_options['fusion_enable'] = True backend_options['fusion_verbose'] = True backend_options['fusion_threshold'] = 1 backend_options['optimize_ideal_threshold'] = 1 backend_options['optimize_noise_threshold'] = 1 result_fusion = self.SIMULATOR.run( qobj, backend_options=backend_options).result() self.is_completed(result_fusion) backend_options = self.BACKEND_OPTS.copy() backend_options['fusion_enable'] = False backend_options['fusion_verbose'] = True backend_options['fusion_threshold'] = 1 backend_options['optimize_ideal_threshold'] = 1 backend_options['optimize_noise_threshold'] = 1 result_nonfusion = self.SIMULATOR.run( qobj, backend_options=backend_options).result() self.is_completed(result_nonfusion) self.assertDictAlmostEqual(result_fusion.get_counts(circuit), result_nonfusion.get_counts(circuit), delta=0.0, msg="fusion for qv was failed")
def _run_job(self, job_id, qc): """Run circuits in q_job""" if isinstance(qc, qobj_mod.QasmQobj): qobj = qc else: qobj = assemble(qc) result_list = [] self._validate(qobj) s = DMSimWrapper(qobj, self) start = time.time() for experiment in qobj.experiments: result_list.append(s.run_experiment(experiment)) end = time.time() result = { 'backend_name': self._configuration.backend_name, 'backend_version': VERSION, 'qobj_id': qobj.qobj_id, 'job_id': job_id, 'results': result_list, 'status': 'COMPLETED', 'success': True, 'time_taken': (end - start) } return Result.from_dict(result)
def test_fusion_qft(self): """Test Fusion with qft""" shots = 100 circuit = qft_circuit(10, measure=True) qobj = assemble([circuit], self.SIMULATOR, shots=shots, seed_simulator=1) backend_options = self.BACKEND_OPTS.copy() backend_options['fusion_enable'] = True backend_options['fusion_verbose'] = True backend_options['fusion_threshold'] = 1 backend_options['optimize_ideal_threshold'] = 1 backend_options['optimize_noise_threshold'] = 1 result_fusion = self.SIMULATOR.run( qobj, backend_options=backend_options).result() self.assertTrue(getattr(result_fusion, 'success', 'False')) backend_options = self.BACKEND_OPTS.copy() backend_options['fusion_enable'] = False backend_options['fusion_verbose'] = True backend_options['fusion_threshold'] = 1 backend_options['optimize_ideal_threshold'] = 1 backend_options['optimize_noise_threshold'] = 1 result_nonfusion = self.SIMULATOR.run( qobj, backend_options=backend_options).result() self.assertTrue(getattr(result_nonfusion, 'success', 'False')) self.assertDictAlmostEqual(result_fusion.get_counts(circuit), result_nonfusion.get_counts(circuit), delta=0.0, msg="fusion for qft was failed")
def raw_run_return_result(self, circuit: Circuit, shots: int, circ_name: str, seed: int = None) -> np.ndarray: """Run a circuit on Qiskit Aer Qasm simulator. :param circuit: The circuit to run :type circuit: Circuit :param shots: Number of shots (repeats) to run :type shots: int :param fit_to_constraints: Compile the circuit to meet the contstraints of the backend, defaults to True :type fit_to_constraints: bool, optional :param seed: random seed to for simulator :type seed: int :return: Table of shot results, each row is a shot, columns are ordered by qubit ordering. Values are 0 or 1, corresponding to qubit basis states. :rtype: numpy.ndarray """ c = circuit.copy() dag = tk_to_named_dagcircuit(circ_name, c) qc = dag_to_circuit(dag) qobj = assemble(qc, shots=shots, seed_simulator=seed, memory=True) job = self._backend.run(qobj, noise_model=self.noise_model) return job.result()
def test_pulse_qobj(self): """Test serializing pulse qobj data.""" backends = self.provider.backends(operational=True, open_pulse=True) if not backends: self.skipTest('Need pulse backends.') backend = backends[0] config = backend.configuration() defaults = backend.defaults() inst_map = defaults.circuit_instruction_map x = inst_map.get('x', 0) measure = inst_map.get('measure', range(config.n_qubits)) << x.duration schedules = x | measure qobj = assemble(schedules, backend, meas_level=1, shots=256) job = backend.run(qobj, validate_qobj=True) rqobj = backend.retrieve_job(job.job_id()).qobj() # Convert numpy arrays to lists since they now get converted right # before being sent to the server. self.assertEqual(_array_to_list(qobj.to_dict()), rqobj.to_dict()) cancel_job(job)
def test_clifford_no_fusion(self): """Test Fusion with clifford simulator""" shots = 100 circuits = ref_2q_clifford.cx_gate_circuits_deterministic( final_measure=True) qobj = assemble(circuits, self.SIMULATOR, shots=shots) backend_options = self.BACKEND_OPTS.copy() backend_options['fusion_verbose'] = True backend_options['optimize_ideal_threshold'] = 1 backend_options['optimize_noise_threshold'] = 1 result = self.SIMULATOR.run( qobj, backend_options=backend_options).result() self.is_completed(result) self.assertTrue( 'results' in result.as_dict(), msg="results must exist in result") self.assertTrue( 'metadata' in result.as_dict()['results'][0], msg="metadata must exist in results[0]") self.assertTrue( 'fusion_verbose' not in result.as_dict()['results'][0]['metadata'], msg="fusion must not work for clifford")
def test_run_simulation_from_backend(self): """Construct from a backend and run a simulation.""" armonk_backend = FakeArmonk() # manually override parameters to insulate from future changes to FakeArmonk freq_est = 4.97e9 drive_est = 6.35e7 armonk_backend.defaults().qubit_freq_est = [freq_est] armonk_backend.configuration().hamiltonian['h_str'] = [ 'wq0*0.5*(I0-Z0)', 'omegad0*X0||D0' ] armonk_backend.configuration().hamiltonian['vars'] = { 'wq0': 2 * np.pi * freq_est, 'omegad0': drive_est } armonk_backend.configuration().hamiltonian['qub'] = {'0': 2} dt = 2.2222222222222221e-10 armonk_backend.configuration().dt = dt armonk_sim = PulseSimulator.from_backend(armonk_backend) total_samples = 250 amp = np.pi / (drive_est * dt * total_samples) sched = self._1Q_schedule(total_samples, amp) qobj = assemble([sched], backend=armonk_sim, meas_level=2, meas_return='single', shots=1) # run and verify that a pi pulse had been done result = armonk_sim.run(qobj).result() final_vec = result.get_statevector() probabilities = np.abs(final_vec)**2 self.assertTrue(probabilities[0] < 1e-5) self.assertTrue(probabilities[1] > 1 - 1e-5)
def test_unitary_parallel(self): """ Test for parallel solving in unitary simulation. Uses same schedule as test_x_gate but runs it twice to trigger parallel execution. """ # setup system model total_samples = 100 omega_0 = 2 * np.pi omega_d0 = omega_0 omega_a = np.pi / total_samples system_model = self._system_model_1Q(omega_0, omega_a) # set up schedule and qobj # run schedule twice to trigger parallel execution schedule = self._simple_1Q_schedule(0, total_samples) qobj = assemble([schedule, schedule], backend=self.backend_sim, meas_level=2, meas_return='single', meas_map=[[0]], qubit_lo_freq=[omega_d0/(2*np.pi)], memory_slots=2, shots=256) # set backend backend_options backend_options = {'seed' : 9000} # run simulation result = self.backend_sim.run(qobj, system_model=system_model, backend_options=backend_options).result() # test results, checking both runs in parallel counts = result.get_counts() exp_counts = {'1': 256} self.assertDictAlmostEqual(counts[0], exp_counts) self.assertDictAlmostEqual(counts[1], exp_counts)
def test_backend_method_clifford_circuits_and_reset_noise(self): """Test statevector method is used for Clifford circuit""" # Test noise model noise_circs = [[{ "name": "reset", "qubits": [0] }], [{ "name": "id", "qubits": [0] }]] noise_probs = [0.5, 0.5] error = QuantumError(zip(noise_circs, noise_probs)) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error( error, ['id', 'x', 'y', 'z', 'h', 's', 'sdg']) # Test circuits shots = 100 circuits = ref_2q_clifford.cz_gate_circuits_deterministic( final_measure=True) qobj = assemble(circuits, self.SIMULATOR, shots=shots) def get_result(): return self.SIMULATOR.run(qobj, backend_options=self.BACKEND_OPTS, noise_model=noise_model).result() # Check simulation method method = self.BACKEND_OPTS.get('method', 'automatic') result = get_result() self.is_completed(result) if method != 'automatic': self.compare_result_metadata(result, circuits, 'method', method) else: self.compare_result_metadata(result, circuits, 'method', 'stabilizer')
def scale_test(scale): # set omega_0, omega_d0 equal (use qubit frequency) -> drive on resonance # Require omega_a*time = pi to implement pi pulse (x gate) omega_0 = 2 * np.pi / scale omega_d0 = omega_0 omega_a = np.pi / total_samples / scale # set up system model system_model = self._system_model_1Q(omega_0, omega_a) system_model.dt = system_model.dt * scale # set up schedule and qobj schedule = self._simple_1Q_schedule(0, total_samples) qobj = assemble([schedule], backend=self.backend_sim, meas_level=2, meas_return='single', meas_map=[[0]], qubit_lo_freq=[omega_d0 / (2 * np.pi)], memory_slots=2, shots=256) # set backend backend_options backend_options = {'seed': 9000} backend_options[ 'use_cpp_ode_func'] = True if USE_CPP_ODE_FUNC else False # run simulation result = self.backend_sim.run( qobj, system_model=system_model, backend_options=backend_options).result() counts = result.get_counts() exp_counts = {'1': 256} self.assertDictAlmostEqual(counts, exp_counts)
def test_nonlocal_pauli_error_reset_25percent(self): """Test 25% Pauli-X error on qubit-1 when reseting qubit 0""" qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.barrier(qr) circuit.reset(qr[1]) circuit.barrier(qr) circuit.reset(qr[0]) circuit.barrier(qr) circuit.measure(qr, cr) backend = QasmSimulator() shots = 2000 # test noise model error = pauli_error([('X', 0.25), ('I', 0.75)]) noise_model = NoiseModel() noise_model.add_nonlocal_quantum_error(error, 'reset', [0], [1]) # Execute target = {'0x0': 3 * shots / 4, '0x2': shots / 4} circuit = transpile(circuit, basis_gates=noise_model.basis_gates) qobj = assemble([circuit], backend, shots=shots) result = backend.run(qobj, noise_model=noise_model).result() self.is_completed(result) self.compare_counts(result, [circuit], [target], delta=0.05 * shots)
def test_delay_measure_enable(self): """Test measure sampling works with delay measure optimization""" # Circuit that allows delay measure circuit = self.delay_measure_circuit() shots = 100 qobj = assemble([circuit], self.SIMULATOR, shots=shots, seed_simulator=1) # Delay measure default backend_options = self.BACKEND_OPTS.copy() backend_options['optimize_ideal_threshold'] = 0 result = self.SIMULATOR.run(qobj, **backend_options).result() self.assertSuccess(result) metadata = result.results[0].metadata self.assertTrue(metadata.get('measure_sampling')) # Delay measure enabled backend_options = self.BACKEND_OPTS.copy() backend_options['delay_measure_enable'] = True backend_options['optimize_ideal_threshold'] = 0 result = self.SIMULATOR.run(qobj, **backend_options).result() self.assertSuccess(result) metadata = result.results[0].metadata self.assertTrue(metadata.get('measure_sampling')) # Delay measure disabled backend_options = self.BACKEND_OPTS.copy() backend_options['delay_measure_enable'] = False backend_options['optimize_ideal_threshold'] = 0 result = self.SIMULATOR.run(qobj, **backend_options).result() self.assertSuccess(result) metadata = result.results[0].metadata self.assertFalse(metadata.get('measure_sampling'))
def test_save_expval_var_stabilizer_hermitian(self, qubits): """Test expval_var for stabilizer circuit and Hermitian operator""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'density_matrix', 'density_matrix_gpu', 'density_matrix_thrust', 'matrix_product_state', 'stabilizer', 'extended_stabilizer' ] SEED = 7123 # Stabilizer test circuit state_circ = qi.random_clifford(3, seed=SEED).to_circuit() oper = qi.random_hermitian(4, traceless=True, seed=SEED) state = qi.Statevector(state_circ) expval = state.expectation_value(oper, qubits).real variance = state.expectation_value(oper**2, qubits).real - expval**2 target = [expval, variance] # Snapshot circuit opts = self.BACKEND_OPTS.copy() method = opts.get('method', 'automatic') circ = transpile(state_circ, basis_gates=[ 'id', 'x', 'y', 'z', 'h', 's', 'sdg', 'cx', 'cz', 'swap' ]) circ.save_expectation_value_variance(oper, qubits, label='expval') qobj = assemble(circ) result = self.SIMULATOR.run(qobj, **opts).result() if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) value = result.data(0)['expval'] self.assertTrue(allclose(value, target))
def test_access_token_not_in_exception_traceback(self): """Check that access token is replaced within chained request exceptions.""" backend_name = 'ibmq_qasm_simulator' backend = self.provider.get_backend(backend_name) circuit = transpile(self.qc1, backend, seed_transpiler=self.seed) qobj = assemble(circuit, backend, shots=1) api = backend._api exception_message = 'The access token in this exception ' \ 'message should be replaced: {}'.format(self.access_token) exception_traceback_str = '' try: with mock.patch.object( HTTPConnectionPool, 'urlopen', side_effect=MaxRetryError( HTTPConnectionPool('host'), 'url', reason=exception_message)): _ = api.job_submit(backend.name(), qobj.to_dict()) except RequestsApiError: exception_traceback_str = traceback.format_exc() self.assertTrue(exception_traceback_str) if self.access_token in exception_traceback_str: self.fail('Access token not replaced in request exception traceback.')
def test_execute_several_circuits_simulator_online(self, qe_token, qe_url): """Test execute_several_circuits_simulator_online.""" IBMQ.enable_account(qe_token, qe_url) backend = IBMQ.get_backend('ibmq_qasm_simulator') qr = QuantumRegister(2) cr = ClassicalRegister(2) qcr1 = QuantumCircuit(qr, cr, name='qc1') qcr2 = QuantumCircuit(qr, cr, name='qc2') qcr1.h(qr) qcr2.h(qr[0]) qcr2.cx(qr[0], qr[1]) qcr1.measure(qr[0], cr[0]) qcr1.measure(qr[1], cr[1]) qcr2.measure(qr[0], cr[0]) qcr2.measure(qr[1], cr[1]) shots = 1024 qobj = assemble(transpile([qcr1, qcr2], backend=backend, seed_transpiler=73846087), backend=backend, shots=shots) job = backend.run(qobj) result = job.result() counts1 = result.get_counts(qcr1) counts2 = result.get_counts(qcr2) target1 = { '00': shots / 4, '01': shots / 4, '10': shots / 4, '11': shots / 4 } target2 = {'00': shots / 2, '11': shots / 2} threshold = 0.04 * shots self.assertDictAlmostEqual(counts1, target1, threshold) self.assertDictAlmostEqual(counts2, target2, threshold)
def __init__(self): self.timeout = 60 * 20 self.qft_circuits = [] self.backend = QasmSimulator() for num_qubits in (5, 10, 15): circ = quantum_fourier_transform_circuit(num_qubits) circ = transpile(circ, basis_gates=['u1', 'u2', 'u3', 'cx'], optimization_level=0, seed_transpiler=1) qobj = assemble(circ, self.backend, shots=1) self.qft_circuits.append(qobj) self.param_names = ["Quantum Fourier Transform", "Noise Model"] # This will run every benchmark for one of the combinations we have: # bench(qft_circuits, None) => bench(qft_circuits, mixed()) => # bench(qft_circuits, reset) => bench(qft_circuits, kraus()) self.params = (self.qft_circuits, [ no_noise(), mixed_unitary_noise_model(), reset_noise_model(), kraus_noise_model() ])
def test_compile_single_qubit(self): """ Compile a single-qubit circuit in a non-trivial layout """ qr = QuantumRegister(1, 'qr') circuit = QuantumCircuit(qr) circuit.h(qr[0]) layout = {(qr, 0): 12} cmap = [[1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12]] circuit2 = transpile(circuit, backend=None, coupling_map=cmap, basis_gates=['u2'], initial_layout=layout) qobj = assemble(circuit2) compiled_instruction = qobj.experiments[0].instructions[0] self.assertEqual(compiled_instruction.name, 'u2') self.assertEqual(compiled_instruction.qubits, [12]) self.assertEqual(str(compiled_instruction.params), str([0, 3.14159265358979]))
def process_circuits( self, circuits: Iterable[Circuit], n_shots: Optional[int] = None, valid_check: bool = True, **kwargs: KwargTypes, ) -> List[ResultHandle]: """ See :py:meth:`pytket.backends.Backend.process_circuits`. Supported kwargs: none. """ if n_shots is None or n_shots < 1: raise ValueError("Parameter n_shots is required for this backend") handle_list = [] for chunk in itertools.zip_longest(*([iter(circuits)] * self._max_per_job)): filtchunk = list(filter(lambda x: x is not None, chunk)) if valid_check: self._check_all_circuits(filtchunk) qcs = [tk_to_qiskit(tkc) for tkc in filtchunk] qobj = assemble(qcs, shots=n_shots, memory=self._config.memory) if self._MACHINE_DEBUG: handle_list += [ ResultHandle( _DEBUG_HANDLE_PREFIX + str((c.n_qubits, n_shots)), i) for i, c in enumerate(filtchunk) ] else: job = self._backend.run(qobj) jobid = job.job_id() handle_list += [ ResultHandle(jobid, i) for i in range(len(filtchunk)) ] for handle in handle_list: self._cache[handle] = dict() return handle_list
def test_all_qubit_pauli_error_measure_25percent(self): """Test 25% Pauli-X error on measure""" qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) backend = QasmSimulator() shots = 2000 # test noise model error = pauli_error([('X', 0.25), ('I', 0.75)]) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error, 'measure') # Execute target = { '0x0': 9 * shots / 16, '0x1': 3 * shots / 16, '0x2': 3 * shots / 16, '0x3': shots / 16 } circuit = transpile(circuit, basis_gates=noise_model.basis_gates) qobj = assemble([circuit], backend, shots=shots) result = backend.run(qobj, noise_model=noise_model).result() self.is_completed(result) self.compare_counts(result, [circuit], [target], delta=0.05 * shots)
def execute(experiments, backend, basis_gates=None, coupling_map=None, # circuit transpile options backend_properties=None, initial_layout=None, seed_transpiler=None, optimization_level=None, pass_manager=None, qobj_id=None, qobj_header=None, shots=1024, # common run options memory=False, max_credits=10, seed_simulator=None, default_qubit_los=None, default_meas_los=None, # schedule run options schedule_los=None, meas_level=MeasLevel.CLASSIFIED, meas_return=MeasReturnType.AVERAGE, memory_slots=None, memory_slot_size=100, rep_time=None, parameter_binds=None, schedule_circuit=False, inst_map=None, meas_map=None, scheduling_method=None, **run_config): """Execute a list of :class:`qiskit.circuit.QuantumCircuit` or :class:`qiskit.pulse.Schedule` on a backend. The execution is asynchronous, and a handle to a job instance is returned. Args: experiments (QuantumCircuit or list[QuantumCircuit] or Schedule or list[Schedule]): Circuit(s) or pulse schedule(s) to execute backend (BaseBackend): Backend to execute circuits on. Transpiler options are automatically grabbed from backend.configuration() and backend.properties(). If any other option is explicitly set (e.g. coupling_map), it will override the backend's. basis_gates (list[str]): List of basis gate names to unroll to. e.g: ``['u1', 'u2', 'u3', 'cx']`` If ``None``, do not unroll. coupling_map (CouplingMap or list): Coupling map (perhaps custom) to target in mapping. Multiple formats are supported: #. CouplingMap instance #. list Must be given as an adjacency matrix, where each entry specifies all two-qubit interactions supported by backend e.g: ``[[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]`` backend_properties (BackendProperties): Properties returned by a backend, including information on gate errors, readout errors, qubit coherence times, etc. Find a backend that provides this information with: ``backend.properties()`` initial_layout (Layout or dict or list): Initial position of virtual qubits on physical qubits. If this layout makes the circuit compatible with the coupling_map constraints, it will be used. The final layout is not guaranteed to be the same, as the transpiler may permute qubits through swaps or other means. Multiple formats are supported: #. :class:`qiskit.transpiler.Layout` instance #. ``dict``: virtual to physical:: {qr[0]: 0, qr[1]: 3, qr[2]: 5} physical to virtual:: {0: qr[0], 3: qr[1], 5: qr[2]} #. ``list`` virtual to physical:: [0, 3, 5] # virtual qubits are ordered (in addition to named) physical to virtual:: [qr[0], None, None, qr[1], None, qr[2]] seed_transpiler (int): Sets random seed for the stochastic parts of the transpiler optimization_level (int): How much optimization to perform on the circuits. Higher levels generate more optimized circuits, at the expense of longer transpilation time. #. No optimization #. Light optimization #. Heavy optimization #. Highest optimization If None, level 1 will be chosen as default. pass_manager (PassManager): The pass manager to use during transpilation. If this arg is present, auto-selection of pass manager based on the transpile options will be turned off and this pass manager will be used directly. qobj_id (str): String identifier to annotate the Qobj qobj_header (QobjHeader or dict): User input that will be inserted in Qobj header, and will also be copied to the corresponding :class:`qiskit.result.Result` header. Headers do not affect the run. shots (int): Number of repetitions of each circuit, for sampling. Default: 1024 memory (bool): If True, per-shot measurement bitstrings are returned as well (provided the backend supports it). For OpenPulse jobs, only measurement level 2 supports this option. Default: False max_credits (int): Maximum credits to spend on job. Default: 10 seed_simulator (int): Random seed to control sampling, for when backend is a simulator default_qubit_los (list): List of default qubit LO frequencies in Hz default_meas_los (list): List of default meas LO frequencies in Hz schedule_los (None or list or dict or LoConfig): Experiment LO configurations, if specified the list is in the format:: list[Union[Dict[PulseChannel, float], LoConfig]] or Union[Dict[PulseChannel, float], LoConfig] meas_level (int or MeasLevel): Set the appropriate level of the measurement output for pulse experiments. meas_return (str or MeasReturn): Level of measurement data for the backend to return For ``meas_level`` 0 and 1: ``"single"`` returns information from every shot. ``"avg"`` returns average measurement output (averaged over number of shots). memory_slots (int): Number of classical memory slots used in this job. memory_slot_size (int): Size of each memory slot if the output is Level 0. rep_time (int): repetition time of the experiment in μs. The delay between experiments will be rep_time. Must be from the list provided by the device. parameter_binds (list[dict]): List of Parameter bindings over which the set of experiments will be executed. Each list element (bind) should be of the form ``{Parameter1: value1, Parameter2: value2, ...}``. All binds will be executed across all experiments, e.g. if parameter_binds is a length-n list, and there are m experiments, a total of :math:`m x n` experiments will be run (one for each experiment/bind pair). schedule_circuit (bool): If ``True``, ``experiments`` will be converted to :class:`qiskit.pulse.Schedule` objects prior to execution. inst_map (InstructionScheduleMap): Mapping of circuit operations to pulse schedules. If None, defaults to the ``instruction_schedule_map`` of ``backend``. meas_map (list(list(int))): List of sets of qubits that must be measured together. If None, defaults to the ``meas_map`` of ``backend``. scheduling_method (str or list(str)): Optionally specify a particular scheduling method. run_config (dict): Extra arguments used to configure the run (e.g. for Aer configurable backends). Refer to the backend documentation for details on these arguments. Note: for now, these keyword arguments will both be copied to the Qobj config, and passed to backend.run() Returns: BaseJob: returns job instance derived from BaseJob Raises: QiskitError: if the execution cannot be interpreted as either circuits or schedules Example: Construct a 5-qubit GHZ circuit and execute 4321 shots on a backend. .. jupyter-execute:: from qiskit import QuantumCircuit, execute, BasicAer backend = BasicAer.get_backend('qasm_simulator') qc = QuantumCircuit(5, 5) qc.h(0) qc.cx(0, range(1, 5)) qc.measure_all() job = execute(qc, backend, shots=4321) """ # transpiling the circuits using given transpile options if pass_manager is not None: _check_conflicting_argument(optimization_level=optimization_level, basis_gates=basis_gates, coupling_map=coupling_map, seed_transpiler=seed_transpiler, backend_properties=backend_properties, initial_layout=initial_layout, backend=backend) experiments = pass_manager.run(experiments) else: experiments = transpile(experiments, basis_gates=basis_gates, coupling_map=coupling_map, backend_properties=backend_properties, initial_layout=initial_layout, seed_transpiler=seed_transpiler, optimization_level=optimization_level, backend=backend) if schedule_circuit: if isinstance(experiments, Schedule) or isinstance(experiments[0], Schedule): raise QiskitError("Must supply QuantumCircuit to schedule circuit.") experiments = schedule(circuits=experiments, backend=backend, inst_map=inst_map, meas_map=meas_map, method=scheduling_method ) # assembling the circuits into a qobj to be run on the backend qobj = assemble(experiments, qobj_id=qobj_id, qobj_header=qobj_header, shots=shots, memory=memory, max_credits=max_credits, seed_simulator=seed_simulator, default_qubit_los=default_qubit_los, default_meas_los=default_meas_los, schedule_los=schedule_los, meas_level=meas_level, meas_return=meas_return, memory_slots=memory_slots, memory_slot_size=memory_slot_size, rep_time=rep_time, parameter_binds=parameter_binds, backend=backend, **run_config ) # executing the circuits on the backend and returning the job start_time = time() job = backend.run(qobj, **run_config) end_time = time() _log_submission_time(start_time, end_time) return job
def execute( experiments, backend, basis_gates=None, coupling_map=None, # circuit transpile options backend_properties=None, initial_layout=None, seed_transpiler=None, optimization_level=None, pass_manager=None, qobj_id=None, qobj_header=None, shots=1024, # common run options memory=False, max_credits=10, seed_simulator=None, default_qubit_los=None, default_meas_los=None, # schedule run options schedule_los=None, meas_level=2, meas_return='avg', memory_slots=None, memory_slot_size=100, rep_time=None, parameter_binds=None, seed=None, seed_mapper=None, # deprecated config=None, circuits=None, **run_config): """Execute a list of circuits or pulse schedules on a backend. The execution is asynchronous, and a handle to a job instance is returned. Args: experiments (QuantumCircuit or list[QuantumCircuit] or Schedule or list[Schedule]): Circuit(s) or pulse schedule(s) to execute backend (BaseBackend): Backend to execute circuits on. Transpiler options are automatically grabbed from backend.configuration() and backend.properties(). If any other option is explicitly set (e.g. coupling_map), it will override the backend's. basis_gates (list[str]): List of basis gate names to unroll to. e.g: ['u1', 'u2', 'u3', 'cx'] If None, do not unroll. coupling_map (CouplingMap or list): Coupling map (perhaps custom) to target in mapping. Multiple formats are supported: a. CouplingMap instance b. list Must be given as an adjacency matrix, where each entry specifies all two-qubit interactions supported by backend e.g: [[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]] backend_properties (BackendProperties): Properties returned by a backend, including information on gate errors, readout errors, qubit coherence times, etc. For a backend that provides this information, it can be obtained with: ``backend.properties()`` initial_layout (Layout or dict or list): Initial position of virtual qubits on physical qubits. If this layout makes the circuit compatible with the coupling_map constraints, it will be used. The final layout is not guaranteed to be the same, as the transpiler may permute qubits through swaps or other means. Multiple formats are supported: a. Layout instance b. dict virtual to physical: {qr[0]: 0, qr[1]: 3, qr[2]: 5} physical to virtual: {0: qr[0], 3: qr[1], 5: qr[2]} c. list virtual to physical: [0, 3, 5] # virtual qubits are ordered (in addition to named) physical to virtual: [qr[0], None, None, qr[1], None, qr[2]] seed_transpiler (int): Sets random seed for the stochastic parts of the transpiler optimization_level (int): How much optimization to perform on the circuits. Higher levels generate more optimized circuits, at the expense of longer transpilation time. 0: no optimization 1: light optimization 2: heavy optimization pass_manager (PassManager): The pass manager to use during transpilation. If this arg is present, auto-selection of pass manager based on the transpile options will be turned off and this pass manager will be used directly. qobj_id (str): String identifier to annotate the Qobj qobj_header (QobjHeader or dict): User input that will be inserted in Qobj header, and will also be copied to the corresponding Result header. Headers do not affect the run. shots (int): Number of repetitions of each circuit, for sampling. Default: 2014 memory (bool): If True, per-shot measurement bitstrings are returned as well (provided the backend supports it). For OpenPulse jobs, only measurement level 2 supports this option. Default: False max_credits (int): Maximum credits to spend on job. Default: 10 seed_simulator (int): Random seed to control sampling, for when backend is a simulator default_qubit_los (list): List of default qubit lo frequencies default_meas_los (list): List of default meas lo frequencies schedule_los (None or list[Union[Dict[PulseChannel, float], LoConfig]] or Union[Dict[PulseChannel, float], LoConfig]): Experiment LO configurations meas_level (int): Set the appropriate level of the measurement output for pulse experiments. meas_return (str): Level of measurement data for the backend to return For `meas_level` 0 and 1: "single" returns information from every shot. "avg" returns average measurement output (averaged over number of shots). memory_slots (int): Number of classical memory slots used in this job. memory_slot_size (int): Size of each memory slot if the output is Level 0. rep_time (int): repetition time of the experiment in μs. The delay between experiments will be rep_time. Must be from the list provided by the device. parameter_binds (list[dict{Parameter: Value}]): List of Parameter bindings over which the set of experiments will be executed. Each list element (bind) should be of the form {Parameter1: value1, Parameter2: value2, ...}. All binds will be executed across all experiments, e.g. if parameter_binds is a length-n list, and there are m experiments, a total of m x n experiments will be run (one for each experiment/bind pair). seed (int): DEPRECATED in 0.8: use ``seed_simulator`` kwarg instead seed_mapper (int): DEPRECATED in 0.8: use ``seed_transpiler`` kwarg instead config (dict): DEPRECATED in 0.8: use run_config instead circuits (QuantumCircuit or list[QuantumCircuit]): DEPRECATED in 0.8: use ``experiments`` kwarg instead. run_config (dict): Extra arguments used to configure the run (e.g. for Aer configurable backends) Refer to the backend documentation for details on these arguments Note: for now, these keyword arguments will both be copied to the Qobj config, and passed to backend.run() Returns: BaseJob: returns job instance derived from BaseJob Raises: QiskitError: if the execution cannot be interpreted as either circuits or schedules """ if circuits is not None: experiments = circuits warnings.warn( "the `circuits` arg in `execute()` has been deprecated. " "please use `experiments`, which can handle both circuit " "and pulse Schedules", DeprecationWarning) # transpiling the circuits using given transpile options experiments = transpile( experiments, basis_gates=basis_gates, coupling_map=coupling_map, backend_properties=backend_properties, initial_layout=initial_layout, seed_transpiler=seed_transpiler, optimization_level=optimization_level, backend=backend, pass_manager=pass_manager, seed_mapper=seed_mapper, # deprecated ) # assembling the circuits into a qobj to be run on the backend qobj = assemble( experiments, qobj_id=qobj_id, qobj_header=qobj_header, shots=shots, memory=memory, max_credits=max_credits, seed_simulator=seed_simulator, default_qubit_los=default_qubit_los, default_meas_los=default_meas_los, schedule_los=schedule_los, meas_level=meas_level, meas_return=meas_return, memory_slots=memory_slots, memory_slot_size=memory_slot_size, rep_time=rep_time, parameter_binds=parameter_binds, backend=backend, config=config, # deprecated seed=seed, # deprecated run_config=run_config) # executing the circuits on the backend and returning the job return backend.run(qobj, **run_config)
sigma=drive_sigma, name='rabi_01_pulse_%d' % ii) # add commands to schedule schedule = pulse.Schedule(name='Rabi Experiment at drive amp = %s' % drive_amp) schedule |= pulse.Play(rabi_01_pulse, drive_chan) schedule |= measure << schedule.duration # shift measurement to after drive pulse rabi_01_schedules.append(schedule) # Assemble the schedules into a program # Note: We drive at the calibrated frequency. rabi_01_expt_program = assemble(rabi_01_schedules, backend=backend, meas_level=1, meas_return='avg', shots=NUM_SHOTS, schedule_los=[{ drive_chan: cal_qubit_freq }] * num_rabi_points) rabi_01_job = backend.run(rabi_01_expt_program) print(rabi_01_job.job_id()) job_monitor(rabi_01_job) rabi_01_data = get_job_data(rabi_01_job, average=True) def baseline_remove(values): """Center data around 0.""" return np.array(values) - np.mean(values)
def test_fusion_operations(self): """Test Fusion enable/disable option""" shots = 100 num_qubits = 8 qr = QuantumRegister(num_qubits) cr = ClassicalRegister(num_qubits) circuit = QuantumCircuit(qr, cr) circuit.h(qr) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[0]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[1]) circuit.barrier(qr) circuit.cx(qr[1], qr[0]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[0]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[1]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[3]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.cx(qr[2], qr[3]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[3]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[3]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.cx(qr[2], qr[3]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[3]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[3]) circuit.barrier(qr) circuit.measure(qr, cr) circuit = transpile(circuit, backend=self.SIMULATOR, optimization_level=0) qobj = assemble([circuit], self.SIMULATOR, shots=shots, seed_simulator=1) backend_options = self.fusion_options(enabled=False, threshold=1) result_disabled = self.SIMULATOR.run( qobj, **backend_options).result() meta_disabled = self.fusion_metadata(result_disabled) backend_options = self.fusion_options(enabled=True, threshold=1) result_enabled = self.SIMULATOR.run( qobj, **backend_options).result() meta_enabled = self.fusion_metadata(result_enabled) self.assertTrue(getattr(result_disabled, 'success', 'False')) self.assertTrue(getattr(result_enabled, 'success', 'False')) self.assertFalse(meta_disabled.get('enabled')) self.assertTrue(meta_enabled.get('enabled')) self.assertTrue(meta_enabled.get('applied')) self.assertDictAlmostEqual(result_enabled.get_counts(circuit), result_disabled.get_counts(circuit), delta=0.0, msg="fusion for qft was failed")
def build_measurement_error_mitigation_qobj(qubit_list, fitter_cls, backend, backend_config=None, compile_config=None, run_config=None): """ Args: qubit_list (list[int]): list of ordered qubits used in the algorithm fitter_cls (callable): CompleteMeasFitter or TensoredMeasFitter backend (BaseBackend): backend instance backend_config (dict, optional): configuration for backend compile_config (dict, optional): configuration for compilation run_config (RunConfig, optional): configuration for running a circuit Returns: QasmQobj: the Qobj with calibration circuits at the beginning list[str]: the state labels for build MeasFitter list[str]: the labels of the calibration circuits Raises: QiskitError: when the fitter_cls is not recognizable. MissingOptionalLibraryError: Qiskit-Ignis not installed """ try: from qiskit.ignis.mitigation.measurement import ( complete_meas_cal, CompleteMeasFitter, TensoredMeasFitter, ) except ImportError as ex: raise MissingOptionalLibraryError( libname="qiskit-ignis", name="build_measurement_error_mitigation_qobj", pip_install="pip install qiskit-ignis", ) from ex circlabel = "mcal" if not qubit_list: raise QiskitError("The measured qubit list can not be [].") if fitter_cls == CompleteMeasFitter: meas_calibs_circuits, state_labels = complete_meas_cal( qubit_list=range(len(qubit_list)), circlabel=circlabel) elif fitter_cls == TensoredMeasFitter: # TODO support different calibration raise QiskitError("Does not support TensoredMeasFitter yet.") else: raise QiskitError("Unknown fitter {}".format(fitter_cls)) # the provided `qubit_list` would be used as the initial layout to # assure the consistent qubit mapping used in the main circuits. tmp_compile_config = copy.deepcopy(compile_config) tmp_compile_config["initial_layout"] = qubit_list t_meas_calibs_circuits = compiler.transpile(meas_calibs_circuits, backend, **backend_config, **tmp_compile_config) cals_qobj = compiler.assemble(t_meas_calibs_circuits, backend, **run_config.to_dict()) if hasattr(cals_qobj.config, "parameterizations"): del cals_qobj.config.parameterizations return cals_qobj, state_labels, circlabel
#job_monitor(ground_freq_sweep_job) # Get the job data (average) #ground_freq_sweep_data = get_job_data(ground_freq_sweep_job, average=True) #To simulate the Rabi experiments, assemble the Schedule list into a qobj. When assembling, pass the PulseSimulator as the backend.#To simulate the Rabi experiments, assemble the Schedule list into a qobj. When assembling, pass the PulseSimulator as the backend. # instantiate the pulse simulator #backend_sim = PulseSimulator() backend_sim = qiskit.providers.aer.PulseSimulator() # compute frequencies from the Hamiltonian qubit_lo_freq0 = two_qubit_model.hamiltonian.get_qubit_lo_from_drift() rabi_qobjlo0 = assemble(rabi_experiments0, backend=backend_sim, qubit_lo_freq=qubit_lo_freq0, meas_level=1, meas_return='avg', noise_model = noise.NoiseModel(), shots=256) # run the simulation rabi_resultlo0 = backend_sim.run(rabi_qobjlo0, two_qubit_model).result() rabifitlo0 = RabiFitter(rabi_resultlo0, rabi_amps0, qubits, fit_p0 = [0.5,0.5,0.6,1.5]) plt.figure(figsize=(15, 10)) q_offset = 0 multiplier = 0.5 for qubit in qubits: ax = plt.subplot(2, 2, qubit + 1) #Xvmin, Xvmax = ax.xaxis.get_data_interval()
def test_running_job_properties(self, provider, backend): # pylint: disable=unused-argument """Test fetching properties of a running job.""" qobj = assemble(transpile(self._qc, backend=backend), backend=backend) job = backend.run(qobj) _ = job.properties()
def test_qobj_failure(self): backend = FAKE_PROVIDER.backends()[-1] tqc = transpile(self.circuit, backend) qobj = assemble(tqc, backend) with self.assertRaises(QiskitError): backend.run(qobj)