Exemple #1
0
    def run(self, schedules, validate=True, **run_options):
        """Run a qobj on the backend.

        Args:
            schedules (Schedule or list): The pulse :class:`~qiskit.pulse.Schedule`
                (or list of ``Schedule`` objects) to be executed.
            validate (bool): validate the Qobj before running (default: True).
            run_options (kwargs): additional run time backend options.

        Returns:
            AerJob: The simulation job.

        Additional Information:
            * kwarg options specified in ``run_options`` will override options
              of the same kwarg specified in the simulator options, the
              ``backend_options`` and the ``Qobj.config``.
        """
        if isinstance(schedules, list):
            new_schedules = []
            for i in schedules:
                if isinstance(i, QuantumCircuit):
                    new_schedules.append(schedule(i, self))
                else:
                    new_schedules.append(i)
            schedules = new_schedules
        elif isinstance(schedules, QuantumCircuit):
            schedules = schedule(schedules, self)
        return super().run(schedules, validate=validate, **run_options)
Exemple #2
0
    def test_call_gate_and_circuit(self):
        """Test calling circuit with gates."""
        h_control = circuit.QuantumCircuit(2)
        h_control.h(0)

        with pulse.build(self.backend) as schedule:
            with pulse.align_sequential():
                # this is circuit, a subroutine stored as Call instruction
                pulse.call(h_control)
                # this is instruction, not subroutine
                pulse.cx(0, 1)
                # this is macro, not subroutine
                pulse.measure([0, 1])

        # subroutine
        h_reference = compiler.schedule(compiler.transpile(h_control, self.backend), self.backend)

        # gate
        cx_circ = circuit.QuantumCircuit(2)
        cx_circ.cx(0, 1)
        cx_reference = compiler.schedule(compiler.transpile(cx_circ, self.backend), self.backend)

        # measurement
        measure_reference = macros.measure(
            qubits=[0, 1], inst_map=self.inst_map, meas_map=self.configuration.meas_map
        )

        reference = pulse.Schedule()
        reference += pulse.instructions.Call(h_reference)
        reference += cx_reference
        reference += measure_reference << reference.duration

        self.assertScheduleEqual(schedule, reference)
Exemple #3
0
 def test_transpile_and_sequence_agree_with_schedule_for_circuits_without_measures(self):
     qc = QuantumCircuit(2, name="bell_without_measurement")
     qc.h(0)
     qc.cx(0, 1)
     sc = transpile(qc, self.backend, scheduling_method="alap")
     actual = sequence(sc, self.backend)
     expected = schedule(transpile(qc, self.backend), self.backend)
     self.assertEqual(actual, pad(expected))
 def test_transpile_and_sequence_agree_with_schedule(self):
     qc = QuantumCircuit(2, name="bell")
     qc.h(0)
     qc.cx(0, 1)
     qc.measure_all()
     sc = transpile(qc, self.backend, scheduling_method='alap')
     actual = sequence(sc, self.backend)
     expected = schedule(transpile(qc, self.backend), self.backend)
     self.assertEqual(actual, pad(expected))
Exemple #5
0
    def test_u2(self):
        """Test u2 gate."""
        with pulse.build(self.backend) as schedule:
            pulse.u2(np.pi, 0, 0)

        reference_qc = circuit.QuantumCircuit(1)
        reference_qc.append(circuit.library.U2Gate(np.pi, 0), [0])
        reference = compiler.schedule(reference_qc, self.backend)

        self.assertEqual(schedule, reference)
    def test_u3(self):
        """Test u3 gate."""
        with pulse.build(self.backend) as schedule:
            pulse.u3(np.pi, 0, np.pi/2, 0)

        reference_qc = circuit.QuantumCircuit(1)
        reference_qc.u3(np.pi, 0, np.pi/2, 0)
        reference = compiler.schedule(reference_qc, self.backend)

        self.assertEqual(schedule, reference)
    def test_lazy_evaluation_with_transpiler(self):
        """Test that the two cx gates are optimizied away by the transpiler."""
        with pulse.build(self.backend) as schedule:
            pulse.cx(0, 1)
            pulse.cx(0, 1)

        reference_qc = circuit.QuantumCircuit(2)
        reference = compiler.schedule(reference_qc, self.backend)

        self.assertEqual(schedule, reference)
Exemple #8
0
    def test_u3(self):
        """Test u3 gate."""
        with pulse.build(self.backend) as schedule:
            pulse.u3(np.pi / 8, np.pi / 16, np.pi / 4, 0)

        reference_qc = circuit.QuantumCircuit(1)
        reference_qc.append(circuit.library.U3Gate(np.pi / 8, np.pi / 16, np.pi / 4), [0])
        reference = compiler.schedule(reference_qc, self.backend)

        self.assertScheduleEqual(schedule, reference)
    def test_cx(self):
        """Test cx gate."""
        with pulse.build(self.backend) as schedule:
            pulse.cx(0, 1)

        reference_qc = circuit.QuantumCircuit(2)
        reference_qc.cx(0, 1)
        reference = compiler.schedule(reference_qc, self.backend)

        self.assertEqual(schedule, reference)
    def test_x(self):
        """Test x gate."""
        with pulse.build(self.backend) as schedule:
            pulse.x(0)

        reference_qc = circuit.QuantumCircuit(1)
        reference_qc.x(0)
        reference_qc = compiler.transpile(reference_qc, self.backend)
        reference = compiler.schedule(reference_qc, self.backend)

        self.assertEqual(schedule, reference)
Exemple #11
0
    def test_u1(self):
        """Test u1 gate."""
        with pulse.build(self.backend) as schedule:
            with pulse.transpiler_settings(layout_method="trivial"):
                pulse.u1(np.pi / 2, 0)

        reference_qc = circuit.QuantumCircuit(1)
        reference_qc.append(circuit.library.U1Gate(np.pi / 2), [0])
        reference = compiler.schedule(reference_qc, self.backend)

        self.assertScheduleEqual(schedule, reference)
 def test_transpile_and_sequence_agree_with_schedule_for_circuit_with_delay(
         self):
     qc = QuantumCircuit(1, 1, name="t2")
     qc.h(0)
     qc.delay(500, 0, unit='ns')
     qc.h(0)
     qc.measure(0, 0)
     sc = transpile(qc, self.backend, scheduling_method='alap')
     actual = sequence(sc, self.backend)
     expected = schedule(qc.decompose(), self.backend)
     self.assertEqual(actual, pad(expected))
 def test_transpile_and_sequence_agree_with_schedule_for_circuit_with_delay(
         self):
     qc = QuantumCircuit(1, 1, name="t2")
     qc.h(0)
     qc.delay(500, 0, unit='ns')
     qc.h(0)
     qc.measure(0, 0)
     sc = transpile(qc, self.backend, scheduling_method='alap')
     actual = sequence(sc, self.backend)
     expected = schedule(transpile(qc, self.backend), self.backend)
     self.assertEqual(actual.exclude(instruction_types=[pulse.Delay]),
                      expected.exclude(instruction_types=[pulse.Delay]))
    def test_measure(self):
        """Test pulse measurement macro against circuit measurement and
        ensure agreement."""
        with pulse.build(self.backend) as schedule:
            with pulse.align_sequential():
                pulse.x(0)
                pulse.measure(0)

        reference_qc = circuit.QuantumCircuit(1, 1)
        reference_qc.x(0)
        reference_qc.measure(0, 0)
        reference_qc = compiler.transpile(reference_qc, self.backend)
        reference = compiler.schedule(reference_qc, self.backend)

        self.assertEqual(schedule, reference)
    def test_call_circuit_with_cregs(self):
        """Test calling of circuit wiht classical registers."""

        qc = circuit.QuantumCircuit(2, 2)
        qc.h(0)
        qc.cx(0, 1)
        qc.measure([0, 1], [0, 1])

        with pulse.build(self.backend) as schedule:
            pulse.call(qc)

        reference_qc = compiler.transpile(qc, self.backend)
        reference = compiler.schedule(reference_qc, self.backend)

        self.assertEqual(schedule, reference)
def main(
    backend,
    user_messenger,
    circuits,
    initial_layout=None,
    seed_transpiler=None,
    optimization_level=None,
    transpiler_options=None,
    scheduling_method=None,
    schedule_circuit=False,
    inst_map=None,
    meas_map=None,
    measurement_error_mitigation=False,
    **kwargs,
):
    """Run the circuits on the backend."""

    # transpiling the circuits using given transpile options
    transpiler_options = transpiler_options or {}
    circuits = transpile(
        circuits,
        initial_layout=initial_layout,
        seed_transpiler=seed_transpiler,
        optimization_level=optimization_level,
        backend=backend,
        **transpiler_options,
    )

    if schedule_circuit:
        circuits = schedule(
            circuits=circuits,
            backend=backend,
            inst_map=inst_map,
            meas_map=meas_map,
            method=scheduling_method,
        )

    if not isinstance(circuits, list):
        circuits = [circuits]

    # Compute raw results
    result = backend.run(circuits, **kwargs).result()

    if measurement_error_mitigation:
        # Performs measurement error mitigation.
        pass

    user_messenger.publish(result.to_dict(), final=True)
Exemple #17
0
def prep_experiments(qc_list: List[QuantumCircuit],
                     backend: IBMQBackend,
                     physical_dist_list: List[int],
                     save_path,
                     output=False):
    """prepare experiments multiple qcs varing hardware usage"""

    # prepare pandas dataframe
    columns = [
        "Backend", "Physical distance", "Hardware Usage (%)",
        "Total Circuit Duration Time", "Quantum Circuits", "Scheduled Pulse"
    ]
    df = pd.DataFrame(columns=columns)

    # backend info
    num_hw_qubit = backend.configuration().num_qubits

    for physical_dist in physical_dist_list:
        transpiled, num_usage = dynamic_multiqc_compose(
            queued_qc=qc_list,
            backend=backend,
            routing_method="sabre",
            scheduling_method="alap",
            num_hw_dist=physical_dist,
            return_num_usage=True,
        )

        scheduled = [schedule(_tqc, backend=backend) for _tqc in transpiled]
        usage = "{:.2%}".format(
            average([_usage / num_hw_qubit for _usage in num_usage[0:-1]]))
        tdt = sum([_sched._duration for _sched in scheduled])
        df = df.append(
            {
                "Backend": backend.name,
                "Physical distance": physical_dist,
                "Hardware Usage (%)": usage,
                "Total Circuit Duration Time": tdt,
                "Quantum Circuits": transpiled,
                "Scheduled Pulse": scheduled,
            },
            ignore_index=True)

    # save the DataFrame as pickle file
    pickle_dump(obj=df, path=save_path)

    if output:
        return df
def get_audio_waveform(string):
    words = string.split(" ")
    audio_waveform = np.array([])
    for word in words:
        word_waveforms = [
            pulse_schedule_to_complex_waveform(
                schedule(transpile(char_to_qc(char), backend), backend))
            for char in word
        ]
        waveform_size = max([waveform.size for waveform in word_waveforms])
        word_waveform = np.zeros(waveform_size)
        for waveform in word_waveforms:
            word_waveform = word_waveform + np.pad(
                waveform, (0, waveform_size - waveform.size), mode='constant')
        audio_waveform = np.concatenate(
            (audio_waveform, complex_waveform_to_amplitude_waveform(waveform)))
    return audio_waveform
Exemple #19
0
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 test_complex_build(self):
        """Test a general program build with nested contexts,
        circuits and macros."""
        d0 = pulse.DriveChannel(0)
        d1 = pulse.DriveChannel(1)
        d2 = pulse.DriveChannel(2)
        delay_dur = 19
        short_dur = 31
        long_dur = 101

        with pulse.build(self.backend) as schedule:
            with pulse.align_sequential():
                pulse.delay(delay_dur, d0)
                pulse.u2(0, pi/2, 1)
            with pulse.align_right():
                pulse.play(library.Constant(short_dur, 0.1), d1)
                pulse.play(library.Constant(long_dur, 0.1), d2)
                pulse.u2(0, pi/2, 1)
            with pulse.align_left():
                pulse.u2(0, pi/2, 0)
                pulse.u2(0, pi/2, 1)
                pulse.u2(0, pi/2, 0)
            pulse.measure(0)

        # prepare and schedule circuits that will be used.
        single_u2_qc = circuit.QuantumCircuit(2)
        single_u2_qc.u2(0, pi/2, 1)
        single_u2_qc = compiler.transpile(single_u2_qc, self.backend)
        single_u2_sched = compiler.schedule(single_u2_qc, self.backend)

        # sequential context
        sequential_reference = pulse.Schedule()
        sequential_reference += instructions.Delay(delay_dur, d0)
        sequential_reference.insert(delay_dur, single_u2_sched, inplace=True)

        # align right
        align_right_reference = pulse.Schedule()
        align_right_reference += pulse.Play(
            library.Constant(long_dur, 0.1), d2)
        align_right_reference.insert(long_dur-single_u2_sched.duration,
                                     single_u2_sched,
                                     inplace=True)
        align_right_reference.insert(
            long_dur-single_u2_sched.duration-short_dur,
            pulse.Play(library.Constant(short_dur, 0.1), d1),
            inplace=True)

        # align left
        triple_u2_qc = circuit.QuantumCircuit(2)
        triple_u2_qc.u2(0, pi/2, 0)
        triple_u2_qc.u2(0, pi/2, 1)
        triple_u2_qc.u2(0, pi/2, 0)
        triple_u2_qc = compiler.transpile(triple_u2_qc, self.backend)
        align_left_reference = compiler.schedule(
            triple_u2_qc, self.backend, method='alap')

        # measurement
        measure_reference = macros.measure(qubits=[0],
                                           inst_map=self.inst_map,
                                           meas_map=self.configuration.meas_map)
        reference = pulse.Schedule()
        reference += sequential_reference
        # Insert so that the long pulse on d2 occurs as early as possible
        # without an overval on d1.
        insert_time = (reference.ch_stop_time(d1) -
                       align_right_reference.ch_start_time(d1))
        reference.insert(insert_time,
                         align_right_reference,
                         inplace=True)
        reference.insert(reference.ch_stop_time(d0, d1),
                         align_left_reference,
                         inplace=True)
        reference += measure_reference
        self.assertEqual(schedule, reference)
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=None,  # common run options
    memory=None,
    max_credits=None,
    seed_simulator=None,
    default_qubit_los=None,
    default_meas_los=None,  # schedule run options
    qubit_lo_range=None,
    meas_lo_range=None,
    schedule_los=None,
    meas_level=None,
    meas_return=None,
    memory_slots=None,
    memory_slot_size=None,
    rep_time=None,
    rep_delay=None,
    parameter_binds=None,
    schedule_circuit=False,
    inst_map=None,
    meas_map=None,
    scheduling_method=None,
    init_qubits=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 (Backend):
            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): DEPRECATED: String identifier to annotate the Qobj.  This has no effect
            and the :attr:`~.QuantumCircuit.name` attribute of the input circuit(s) should be used
            instead.

        qobj_header (QobjHeader or dict): DEPRECATED: 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. Headers do not affect the run. This kwarg
            has no effect anymore and the :attr:`~.QuantumCircuit.metadata` attribute of the
            input circuit(s) should be used instead.

        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): DEPRECATED This parameter is deprecated as of Qiskit Terra 0.20.0
            and will be removed in a future release. This parameter has no effect on modern
            IBM Quantum systems, no alternative is necessary.

        seed_simulator (int): Random seed to control sampling, for when backend is a simulator

        default_qubit_los (Optional[List[float]]): List of job level qubit drive LO frequencies
            in Hz. Overridden by ``schedule_los`` if specified. Must have length ``n_qubits``.

        default_meas_los (Optional[List[float]]): List of job level measurement LO frequencies in
            Hz. Overridden by ``schedule_los`` if specified. Must have length ``n_qubits``.

        qubit_lo_range (Optional[List[List[float]]]): List of job level drive LO ranges each of form
            ``[range_min, range_max]`` in Hz. Used to validate ``qubit_lo_freq``. Must have length
            ``n_qubits``.

        meas_lo_range (Optional[List[List[float]]]): List of job level measurement LO ranges each of
            form ``[range_min, range_max]`` in Hz. Used to validate ``meas_lo_freq``. Must have
            length ``n_qubits``.

        schedule_los (list):
            Experiment level (ie circuit or schedule) LO frequency configurations for qubit drive
            and measurement channels. These values override the job level values from
            ``default_qubit_los`` and ``default_meas_los``. Frequencies are in Hz. Settable for qasm
            and pulse jobs.

            If a single LO config or dict is used, the values are set at job level. If a list is
            used, the list must be the size of the number of experiments in the job, except in the
            case of a single experiment. In this case, a frequency sweep will be assumed and one
            experiment will be created for every list entry.

            Not every channel is required to be specified. If not specified, the backend default
            value will be used.

        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): Time per program execution in seconds. Must be from the list provided
            by the backend (``backend.configuration().rep_times``). Defaults to the first entry.

        rep_delay (float): Delay between programs in seconds. Only supported on certain
            backends (``backend.configuration().dynamic_reprate_enabled`` ). If supported,
            ``rep_delay`` will be used instead of ``rep_time`` and must be from the range supplied
            by the backend (``backend.configuration().rep_delay_range``). Default is given by
            ``backend.configuration().default_rep_delay``.

        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-:math:`n` list, and there are :math:`m` experiments, a total of :math:`m \\times 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.

        init_qubits (bool): Whether to reset the qubits to the ground state for each shot.
                            Default: ``True``.

        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:
        Job: returns job instance derived from Job

    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)
    """
    if isinstance(experiments, (Schedule, ScheduleBlock)) or (
        isinstance(experiments, list) and isinstance(experiments[0], (Schedule, ScheduleBlock))
    ):
        # do not transpile a schedule circuit
        if schedule_circuit:
            raise QiskitError("Must supply QuantumCircuit to schedule circuit.")
    elif pass_manager is not None:
        # transpiling using pass_manager
        _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,
        )
        experiments = pass_manager.run(experiments)
    else:
        # 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,
        )

    if schedule_circuit:
        experiments = schedule(
            circuits=experiments,
            backend=backend,
            inst_map=inst_map,
            meas_map=meas_map,
            method=scheduling_method,
        )
    if max_credits is not None:
        warnings.warn(
            "The `max_credits` parameter is deprecated as of Qiskit Terra 0.20.0, "
            "and will be removed in a future release. This parameter has no effect on "
            "modern IBM Quantum systems, and no alternative is necessary.",
            DeprecationWarning,
            stacklevel=2,
        )

    if qobj_id is not None:
        warnings.warn(
            "The qobj_id argument is deprecated as of the Qiskit Terra 0.21.0, "
            "and will be remvoed in a future release. This argument has no effect and "
            "is not used by any backends."
        )

    if qobj_header is not None:
        warnings.warn(
            "The qobj_header argument is deprecated as of the Qiskit Terra 0.21.0, "
            "and will be remvoed in a future release. This argument has no effect and "
            "is not used by any backends."
        )

    if isinstance(backend, Backend):
        start_time = time()
        run_kwargs = {
            "shots": shots,
            "memory": memory,
            "seed_simulator": seed_simulator,
            "qubit_lo_freq": default_qubit_los,
            "meas_lo_freq": default_meas_los,
            "qubit_lo_range": qubit_lo_range,
            "meas_lo_range": meas_lo_range,
            "schedule_los": schedule_los,
            "meas_level": meas_level,
            "meas_return": meas_return,
            "memory_slots": memory_slots,
            "memory_slot_size": memory_slot_size,
            "rep_time": rep_time,
            "rep_delay": rep_delay,
            "init_qubits": init_qubits,
        }
        for key in list(run_kwargs.keys()):
            if not hasattr(backend.options, key):
                if run_kwargs[key] is not None:
                    logger.info(
                        "%s backend doesn't support option %s so not passing that kwarg to run()",
                        backend.name,
                        key,
                    )
                del run_kwargs[key]
            elif run_kwargs[key] is None:
                del run_kwargs[key]

        if parameter_binds:
            run_kwargs["parameter_binds"] = parameter_binds
        run_kwargs.update(run_config)
        job = backend.run(experiments, **run_kwargs)
        end_time = time()
        _log_submission_time(start_time, end_time)
    else:
        raise QiskitError("Invalid backend type %s" % type(backend))
    return job
Exemple #22
0
#Overwrite the default CNOT schedule in the inst_map
#inst_map.add('cx', [1,0], cnot_sched10)
#inst_map.add('cx', [0,1], cnot_sched01)


#import pyfits
#schedule the randomized branchmarking experiment into pulse schedules.
rb_schedules_seeds = []
#i = 0
#plt.figure()
for rb_circuits_seed in rb_circuits_seeds:
#    ax = plt.subplot(len(rb_circuits_seeds),1, i+1)
#    rb_fit.plot_rb_data(0,ax = ax)  
    rb_circuits_seed = transpile(rb_circuits_seed, backend, basis_gates)
    rb_schedules_seed = schedule(rb_circuits_seed, backend, inst_map)
    rb_schedules_seeds.append(rb_schedules_seed)
#    rb_schedules_seed[0].draw(label = True)
#    i += 1
#plt.show()

# Create a new circuit without the measurement
qr = rb_circuits_seeds[0][-1].qregs
cr = rb_circuits_seeds[0][-1].cregs
QC = qiskit.QuantumCircuit(*qr, *cr)
for i in rb_circuits_seeds[0][-1][0:-n]:
    QC.data.append(i)


# The Unitary is an identity (with a global phase)
backend = qiskit.Aer.get_backend('unitary_simulator')
    def run(
            self,
            schedules,
            *args,
            backend_options=None,  # DEPRECATED
            validate=True,
            **run_options):
        """Run a qobj on the backend.

        Args:
            schedules (Schedule or list): The pulse :class:`~qiskit.pulse.Schedule`
                (or list of ``Schedule`` objects) to be executed.
            backend_options (dict or None): DEPRECATED dictionary of backend options
                                            for the execution (default: None).
            validate (bool): validate the Qobj before running (default: True).
            run_options (kwargs): additional run time backend options.

        Returns:
            AerJob: The simulation job.

        Additional Information:
            * kwarg options specified in ``run_options`` will override options
              of the same kwarg specified in the simulator options, the
              ``backend_options`` and the ``Qobj.config``.

            * The entries in the ``backend_options`` will be combined with
              the ``Qobj.config`` dictionary with the values of entries in
              ``backend_options`` taking precedence. This kwarg is deprecated
              and direct kwarg's should be used for options to pass them to
              ``run_options``.
        """
        qobj = schedules
        if args:
            if isinstance(args[0], PulseSystemModel):
                warn(
                    'Passing `system_model` as a positional argument to'
                    ' `PulseSimulator.run` has been deprecated as of'
                    ' qiskit-aer 0.7.0 and will be removed no earlier than 3'
                    ' months from that release date. Pass `system_model` as a kwarg'
                    ' `system_model=model` instead.',
                    DeprecationWarning,
                    stacklevel=3)
                run_options['system_model'] = args[0]
                if len(args) > 1:
                    backend_options = args[1]
                if len(args) > 2:
                    validate = args[3]
            elif isinstance(args[0], bool):
                validate = args[0]
                if len(args) > 1:
                    backend_options = args[1]
        if isinstance(qobj, list):
            new_qobj = []
            for circuit in qobj:
                if isinstance(circuit, QuantumCircuit):
                    new_qobj.append(schedule(circuit, self))
                else:
                    new_qobj.append(circuit)
            qobj = new_qobj
        elif isinstance(qobj, QuantumCircuit):
            qobj = schedule(qobj, self)
        return super().run(qobj,
                           backend_options=backend_options,
                           validate=validate,
                           **run_options)