def test_user_mapping_for_memslots_3Q(self):
     """Test measuring two of three qubits."""
     backend = FakeOpenPulse3Q()
     cmd_def = backend.defaults().build_cmd_def()
     q = QuantumRegister(3)
     c = ClassicalRegister(3)
     qc = QuantumCircuit(q, c)
     qc.measure(q[1], c[2])
     qc.measure(q[2], c[0])
     sched = schedule(qc, backend)
     acquire = Acquire(duration=10)
     expected = Schedule(
         cmd_def.get('measure', [0, 1, 2]).filter(
             channels=[MeasureChannel(1), MeasureChannel(2)]),
         acquire(AcquireChannel(0), MemorySlot(1)),
         acquire(AcquireChannel(1), MemorySlot(2)),
         acquire(AcquireChannel(2), MemorySlot(0)))
     self.assertEqual(sched.instructions, expected.instructions)
    def _1Q_schedule(self, total_samples=100, amp=1., num_acquires=1):
        """Creates a schedule for a single qubit.

        Args:
            total_samples (int): number of samples in the drive pulse
            amp (complex): amplitude of drive pulse
            num_acquires (int): number of acquire instructions to include in the schedule

        Returns:
            schedule (pulse schedule):
        """

        schedule = Schedule()
        schedule |= Play(Waveform(amp * np.ones(total_samples)), DriveChannel(0))
        for _ in range(num_acquires):
            schedule |= Acquire(total_samples, AcquireChannel(0),
                                MemorySlot(0)) << schedule.duration
        return schedule
    def _1Q_constant_sched(self, total_samples, amp=1.):
        """Creates a runnable schedule for 1Q with a constant drive pulse of a given length.

        Args:
            total_samples (int): length of pulse
            amp (float): amplitude of constant pulse (can be complex)

        Returns:
            schedule (pulse schedule): schedule with a drive pulse followed by an acquire
        """

        # set up constant pulse for doing a pi pulse
        drive_pulse = SamplePulse(amp * np.ones(total_samples))
        schedule = Schedule()
        schedule |= Play(drive_pulse, DriveChannel(0))
        schedule |= Acquire(total_samples, AcquireChannel(0), MemorySlot(0)) << schedule.duration

        return schedule
Beispiel #4
0
    def test_pulse_name_conflicts_in_other_schedule(self):
        """Test two pulses with the same name in different schedule can be resolved."""
        backend = FakeAlmaden()

        schedules = []
        ch_d0 = pulse.DriveChannel(0)
        for amp in (0.1, 0.2):
            sched = Schedule()
            sched += Play(
                gaussian(duration=100, amp=amp, sigma=30, name='my_pulse'),
                ch_d0)
            sched += measure(qubits=[0], backend=backend) << 100
            schedules.append(sched)

        qobj = assemble(schedules, backend)

        # two user pulses and one measurement pulse should be contained
        self.assertEqual(len(qobj.config.pulse_library), 3)
Beispiel #5
0
def add_implicit_acquires(schedule: ScheduleComponent, meas_map: List[List[int]]) -> Schedule:
    """Return a new schedule with implicit acquires from the measurement mapping replaced by
    explicit ones.

    .. warning:: Since new acquires are being added, Memory Slots will be set to match the
                 qubit index. This may overwrite your specification.

    Args:
        schedule: Schedule to be aligned.
        meas_map: List of lists of qubits that are measured together.

    Returns:
        A ``Schedule`` with the additional acquisition commands.
    """
    new_schedule = Schedule(name=schedule.name)
    acquire_map = dict()

    for time, inst in schedule.instructions:
        if isinstance(inst, AcquireInstruction):
            if any([acq.index != mem.index for acq, mem in zip(inst.acquires, inst.mem_slots)]):
                warnings.warn("One of your acquires was mapped to a memory slot which didn't match"
                              " the qubit index. I'm relabeling them to match.")

            cmd = Acquire(inst.duration, inst.command.discriminator, inst.command.kernel)
            # Get the label of all qubits that are measured with the qubit(s) in this instruction
            existing_qubits = {chan.index for chan in inst.acquires}
            all_qubits = []
            for sublist in meas_map:
                if existing_qubits.intersection(set(sublist)):
                    all_qubits.extend(sublist)
            # Replace the old acquire instruction by a new one explicitly acquiring all qubits in
            # the measurement group.
            for i in all_qubits:
                explicit_inst = AcquireInstruction(cmd, AcquireChannel(i), MemorySlot(i)) << time
                if time not in acquire_map:
                    new_schedule |= explicit_inst
                    acquire_map = {time: {i}}
                elif i not in acquire_map[time]:
                    new_schedule |= explicit_inst
                    acquire_map[time].add(i)
        else:
            new_schedule |= inst << time

    return new_schedule
    def get_measure_schedule(
            qubit_mem_slots: Dict[int, int]) -> CircuitPulseDef:
        """Create a schedule to measure the qubits queued for measuring."""
        sched = Schedule()
        # Exclude acquisition on these qubits, since they are handled by the user calibrations
        acquire_excludes = {}
        if Measure().name in circuit.calibrations.keys():
            qubits = tuple(sorted(qubit_mem_slots.keys()))
            params = ()
            for qubit in qubits:
                try:
                    meas_q = circuit.calibrations[Measure().name][((qubit, ),
                                                                   params)]
                    acquire_q = meas_q.filter(channels=[AcquireChannel(qubit)])
                    mem_slot_index = [
                        chan.index for chan in acquire_q.channels
                        if isinstance(chan, MemorySlot)
                    ][0]
                    if mem_slot_index != qubit_mem_slots[qubit]:
                        raise KeyError(
                            "The measurement calibration is not defined on "
                            "the requested classical bits")
                    sched |= meas_q
                    del qubit_mem_slots[qubit]
                    acquire_excludes[qubit] = mem_slot_index
                except KeyError:
                    pass

        if qubit_mem_slots:
            qubits = list(qubit_mem_slots.keys())
            qubit_mem_slots.update(acquire_excludes)
            meas_sched = measure(qubits=qubits,
                                 inst_map=inst_map,
                                 meas_map=schedule_config.meas_map,
                                 qubit_mem_slots=qubit_mem_slots)
            meas_sched = meas_sched.exclude(
                channels=[AcquireChannel(qubit) for qubit in acquire_excludes])
            sched |= meas_sched
        qubit_mem_slots.clear()
        return CircuitPulseDef(schedule=sched,
                               qubits=[
                                   chan.index for chan in sched.channels
                                   if isinstance(chan, AcquireChannel)
                               ])
    def test_parametric_pulses_with_no_duplicates(self):
        """Test parametric pulses with no duplicates."""
        schedule = Schedule()
        drive_channel = DriveChannel(0)
        schedule += Play(Gaussian(duration=25, sigma=4, amp=0.5j), drive_channel)
        schedule += Play(Gaussian(duration=25, sigma=4, amp=0.49j), drive_channel)
        schedule += Play(GaussianSquare(duration=150, amp=0.2,
                                        sigma=8, width=140), drive_channel)
        schedule += Play(GaussianSquare(duration=150, amp=0.19,
                                        sigma=8, width=140), drive_channel)
        schedule += Play(Constant(duration=150, amp=0.1 + 0.4j), drive_channel)
        schedule += Play(Constant(duration=150, amp=0.1 + 0.41j), drive_channel)
        schedule += Play(Drag(duration=25, amp=0.2 + 0.3j, sigma=7.8, beta=4), drive_channel)
        schedule += Play(Drag(duration=25, amp=0.2 + 0.31j, sigma=7.8, beta=4), drive_channel)

        compressed_schedule = transforms.compress_pulses([schedule])
        original_pulse_ids = get_pulse_ids([schedule])
        compressed_pulse_ids = get_pulse_ids(compressed_schedule)
        self.assertEqual(len(original_pulse_ids), len(compressed_pulse_ids))
Beispiel #8
0
 def test_measure_sched_with_meas_map(self):
     """Test measure with custom meas_map as list and dict."""
     sched_with_meas_map_list = macros.measure(qubits=[0],
                                               backend=self.backend,
                                               meas_map=[[0, 1]])
     sched_with_meas_map_dict = macros.measure(qubits=[0],
                                               backend=self.backend,
                                               meas_map={
                                                   0: [0, 1],
                                                   1: [0, 1]
                                               })
     expected = Schedule(
         self.inst_map.get('measure',
                           [0, 1]).filter(channels=[MeasureChannel(0)]),
         Acquire(10, AcquireChannel(0), MemorySlot(0)))
     self.assertEqual(sched_with_meas_map_list.instructions,
                      expected.instructions)
     self.assertEqual(sched_with_meas_map_dict.instructions,
                      expected.instructions)
Beispiel #9
0
    def test_schedule_generator(self):
        """Test schedule generator functionalty."""

        dur_val = 10
        amp = 1.0

        def test_func(dur: int):
            sched = Schedule()
            sched += Play(library.constant(int(dur), amp), DriveChannel(0))
            return sched

        expected_sched = Schedule()
        expected_sched += Play(library.constant(dur_val, amp), DriveChannel(0))

        inst_map = InstructionScheduleMap()
        inst_map.add('f', (0, ), test_func)
        self.assertEqual(inst_map.get('f', (0, ), dur_val), expected_sched)

        self.assertEqual(inst_map.get_parameters('f', (0, )), ('dur', ))
Beispiel #10
0
    def test_schedule_generator(self):
        """Test schedule generator functionalty."""

        x_test = 10
        amp_test = 1.0

        def test_func(x):
            sched = Schedule()
            sched += Play(library.constant(int(x), amp_test), DriveChannel(0))
            return sched

        ref_sched = Schedule()
        ref_sched += Play(library.constant(x_test, amp_test), DriveChannel(0))

        inst_map = InstructionScheduleMap()
        inst_map.add('f', (0,), test_func)
        self.assertEqual(inst_map.get('f', (0,), x_test), ref_sched)

        self.assertEqual(inst_map.get_parameters('f', (0,)), ('x',))
    def test_subset_calibrated_measurements(self):
        """Test that measurement calibrations can be added and used for some qubits, even
        if the other qubits do not also have calibrated measurements."""
        qc = QuantumCircuit(3, 3)
        qc.measure(0, 0)
        qc.measure(1, 1)
        qc.measure(2, 2)
        meas_scheds = []
        for qubit in [0, 2]:
            meas = (Play(Gaussian(1200, 0.2, 4), MeasureChannel(qubit)) +
                    Acquire(1200, AcquireChannel(qubit), MemorySlot(qubit)))
            meas_scheds.append(meas)
            qc.add_calibration('measure', [qubit], meas)

        meas = macros.measure([1], FakeOpenPulse3Q())
        meas = meas.exclude(channels=[AcquireChannel(0), AcquireChannel(2)])
        sched = schedule(qc, FakeOpenPulse3Q())
        expected = Schedule(meas_scheds[0], meas_scheds[1], meas)
        self.assertEqual(sched.instructions, expected.instructions)
    def test_schedule_block_in_instmap(self):
        """Test schedule block in instmap can be scheduled."""
        duration = Parameter("duration")

        with build() as pulse_prog:
            play(Gaussian(duration, 0.1, 10), DriveChannel(0))

        instmap = InstructionScheduleMap()
        instmap.add("block_gate", (0, ), pulse_prog, ["duration"])

        qc = QuantumCircuit(1)
        qc.append(Gate("block_gate", 1, [duration]), [0])
        qc.assign_parameters({duration: 100}, inplace=True)

        sched = schedule(qc, self.backend, inst_map=instmap)

        ref_sched = Schedule()
        ref_sched += Play(Gaussian(100, 0.1, 10), DriveChannel(0))

        self.assertEqual(sched, ref_sched)
    def test_uneven_pulse_length(self):
        """Test conversion when length of pulses on a schedule is uneven."""

        schedule = Schedule()
        schedule |= Play(Waveform(np.ones(10)), DriveChannel(0))
        schedule += Play(Constant(20, 1), DriveChannel(1))

        converter = InstructionToSignals(dt=0.1, carriers=[2.0, 3.0])

        signals = converter.get_signals(schedule)

        self.assertTrue(signals[0].duration == 20)
        self.assertTrue(signals[1].duration == 20)

        self.assertAllClose(signals[0]._samples,
                            np.append(np.ones(10), np.zeros(10)))
        self.assertAllClose(signals[1]._samples, np.ones(20))

        self.assertTrue(signals[0].carrier_freq == 2.0)
        self.assertTrue(signals[1].carrier_freq == 3.0)
    def test_schedule_generator_supports_parameter_expressions(self):
        """Test expression-based schedule generator functionalty."""

        t_param = Parameter('t')
        amp = 1.0

        def test_func(dur: ParameterExpression, t_val: int):
            dur_bound = dur.bind({t_param: t_val})
            sched = Schedule()
            sched += Play(library.constant(int(float(dur_bound)), amp), DriveChannel(0))
            return sched

        expected_sched = Schedule()
        expected_sched += Play(library.constant(10, amp), DriveChannel(0))

        inst_map = InstructionScheduleMap()
        inst_map.add('f', (0,), test_func)
        self.assertEqual(inst_map.get('f', (0,), dur=2*t_param, t_val=5), expected_sched)

        self.assertEqual(inst_map.get_parameters('f', (0,)), ('dur', 't_val',))
    def _2Q_constant_sched(self, total_samples, amp=1., u_idx=0):
        """Creates a runnable schedule with a single pulse on a U channel for two qubits.

        Args:
            total_samples (int): length of pulse
            amp (float): amplitude of constant pulse (can be complex)
            u_idx (int): index of U channel

        Returns:
            schedule (pulse schedule): schedule with a drive pulse followed by an acquire
        """

        # set up constant pulse for doing a pi pulse
        drive_pulse = SamplePulse(amp * np.ones(total_samples))
        schedule = Schedule()
        schedule |= Play(drive_pulse, ControlChannel(u_idx))
        schedule |= Acquire(total_samples, AcquireChannel(0), MemorySlot(0)) << total_samples
        schedule |= Acquire(total_samples, AcquireChannel(1), MemorySlot(1)) << total_samples

        return schedule
Beispiel #16
0
 def test_measure_combined(self):
     """Test that measures on different qubits are combined, but measures on the same qubit
     adds another measure to the schedule."""
     q = QuantumRegister(2)
     c = ClassicalRegister(2)
     qc = QuantumCircuit(q, c)
     qc.u2(3.14, 1.57, q[0])
     qc.cx(q[0], q[1])
     qc.measure(q[0], c[0])
     qc.measure(q[1], c[1])
     qc.measure(q[1], c[1])
     sched = schedule(qc, self.backend, method="as_soon_as_possible")
     expected = Schedule(self.cmd_def.get('u2', [0], 3.14, 1.57),
                         (28, self.cmd_def.get('cx', [0, 1])),
                         (50, self.cmd_def.get('measure', [0, 1])),
                         (60, self.cmd_def.get('measure', [0, 1])))
     for actual, expected in zip(sched.instructions, expected.instructions):
         self.assertEqual(actual[0], expected[0])
         self.assertEqual(actual[1].command, expected[1].command)
         self.assertEqual(actual[1].channels, expected[1].channels)
Beispiel #17
0
 def test_barriers_in_middle(self):
     """As a follow on to `test_can_add_gates_into_free_space`, similar issues
     arose for barriers, specifically.
     """
     qr = QuantumRegister(2)
     qc = QuantumCircuit(qr)
     for i in range(2):
         qc.u2(0, 0, [qr[i]])
         qc.barrier(qr[i])
         qc.u1(3.14, [qr[i]])
         qc.barrier(qr[i])
         qc.u2(0, 0, [qr[i]])
     sched = schedule(qc, self.backend, method="alap")
     expected = Schedule(self.cmd_def.get('u2', [0], 0, 0),
                         self.cmd_def.get('u2', [1], 0, 0),
                         (28, self.cmd_def.get('u1', [0], 3.14)),
                         (28, self.cmd_def.get('u1', [1], 3.14)),
                         (28, self.cmd_def.get('u2', [0], 0, 0)),
                         (28, self.cmd_def.get('u2', [1], 0, 0)))
     self.assertEqual(sched.instructions, expected.instructions)
Beispiel #18
0
 def test_asap_pass(self):
     """Test ASAP scheduling."""
     q = QuantumRegister(2)
     c = ClassicalRegister(2)
     qc = QuantumCircuit(q, c)
     qc.u2(3.14, 1.57, q[0])
     qc.u2(0.5, 0.25, q[1])
     qc.barrier(q[1])
     qc.u2(0.5, 0.25, q[1])
     qc.barrier(q[0], q[1])
     qc.cx(q[0], q[1])
     qc.measure(q, c)
     sched = schedule(qc, self.backend, method="as_soon_as_possible")
     # X pulse on q0 should start at t=0
     expected = Schedule(self.cmd_def.get('u2', [0], 3.14, 1.57),
                         self.cmd_def.get('u2', [1], 0.5, 0.25),
                         (28, self.cmd_def.get('u2', [1], 0.5, 0.25)),
                         (56, self.cmd_def.get('cx', [0, 1])),
                         (78, self.cmd_def.get('measure', [0, 1])))
     self.assertEqual(sched.instructions, expected.instructions)
Beispiel #19
0
 def test_3q_schedule(self):
     """Test a schedule that was recommended by David McKay :D """
     backend = FakeOpenPulse3Q()
     cmd_def = backend.defaults().build_cmd_def()
     q = QuantumRegister(3)
     c = ClassicalRegister(3)
     qc = QuantumCircuit(q, c)
     qc.cx(q[0], q[1])
     qc.u2(0.778, 0.122, q[2])
     qc.u3(3.14, 1.57, 0., q[0])
     qc.u2(3.14, 1.57, q[1])
     qc.cx(q[1], q[2])
     qc.u2(0.778, 0.122, q[2])
     sched = schedule(qc, backend)
     expected = Schedule(cmd_def.get('cx', [0, 1]),
                         (22, cmd_def.get('u2', [1], 3.14, 1.57)),
                         (46, cmd_def.get('u2', [2], 0.778, 0.122)),
                         (50, cmd_def.get('cx', [1, 2])),
                         (72, cmd_def.get('u2', [2], 0.778, 0.122)),
                         (74, cmd_def.get('u3', [0], 3.14, 1.57)))
     self.assertEqual(sched.instructions, expected.instructions)
Beispiel #20
0
def model_and_pi_schedule():
    """Return a simple model and schedule for pulse simulation"""

    # construct model
    model = duffing_system_model(dim_oscillators=2,
                                 oscillator_freqs=[5.0],
                                 anharm_freqs=[0],
                                 drive_strengths=[0.01],
                                 coupling_dict={},
                                 dt=1.0)

    # note: parameters set so that area under curve is 1/4
    sample_pulse = SamplePulse(np.ones(50))

    # construct schedule
    schedule = Schedule(name='test_sched')
    schedule |= Play(sample_pulse, DriveChannel(0))
    schedule += Acquire(10, AcquireChannel(0),
                        MemorySlot(0)) << schedule.duration

    return model, schedule
Beispiel #21
0
 def test_asap_pass(self):
     """Test ASAP scheduling."""
     q = QuantumRegister(2)
     c = ClassicalRegister(2)
     qc = QuantumCircuit(q, c)
     qc.append(U2Gate(3.14, 1.57), [q[0]])
     qc.append(U2Gate(0.5, 0.25), [q[1]])
     qc.barrier(q[1])
     qc.append(U2Gate(0.5, 0.25), [q[1]])
     qc.barrier(q[0], q[1])
     qc.cx(q[0], q[1])
     qc.measure(q, c)
     sched = schedule(qc, self.backend, method="as_soon_as_possible")
     # X pulse on q0 should start at t=0
     expected = Schedule(self.inst_map.get('u2', [0], 3.14, 1.57),
                         self.inst_map.get('u2', [1], 0.5, 0.25),
                         (28, self.inst_map.get('u2', [1], 0.5, 0.25)),
                         (56, self.inst_map.get('cx', [0, 1])),
                         (78, self.inst_map.get('measure', [0, 1])))
     for actual, expected in zip(sched.instructions, expected.instructions):
         self.assertEqual(actual[0], expected[0])
         self.assertEqual(actual[1], expected[1])
    def test_assemble_with_unequal_kernels(self):
        """Test that assembly works with incorrect number of discriminators for
        number of qubits."""
        disc_one = Kernel('disc_one', test_params=True)
        disc_two = Kernel('disc_two', test_params=False)

        schedule = Schedule()
        schedule += Acquire(5,
                            AcquireChannel(0),
                            MemorySlot(0),
                            kernel=disc_one)
        schedule += Acquire(5,
                            AcquireChannel(1),
                            MemorySlot(1),
                            kernel=disc_two)
        schedule += Acquire(5, AcquireChannel(2), MemorySlot(2))

        with self.assertRaises(QiskitError):
            assemble(schedule,
                     qubit_lo_freq=self.default_qubit_lo_freq,
                     meas_lo_freq=self.default_meas_lo_freq,
                     meas_map=[[0, 1, 2]])
 def test_barriers_in_middle(self):
     """As a follow on to `test_can_add_gates_into_free_space`, similar issues
     arose for barriers, specifically.
     """
     qr = QuantumRegister(2)
     qc = QuantumCircuit(qr)
     for i in range(2):
         qc.append(U2Gate(0, 0), [qr[i]])
         qc.barrier(qr[i])
         qc.append(U1Gate(3.14), [qr[i]])
         qc.barrier(qr[i])
         qc.append(U2Gate(0, 0), [qr[i]])
     sched = schedule(qc, self.backend, method="alap")
     expected = Schedule(self.inst_map.get('u2', [0], 0, 0),
                         self.inst_map.get('u2', [1], 0, 0),
                         (2, self.inst_map.get('u1', [0], 3.14)),
                         (2, self.inst_map.get('u1', [1], 3.14)),
                         (2, self.inst_map.get('u2', [0], 0, 0)),
                         (2, self.inst_map.get('u2', [1], 0, 0)))
     for actual, expected in zip(sched.instructions, expected.instructions):
         self.assertEqual(actual[0], expected[0])
         self.assertEqual(actual[1], expected[1])
def filter_instructions(sched: Schedule,
                        filters: List[Callable],
                        negate: bool = False,
                        recurse_subroutines: bool = True) -> Schedule:
    """A filtering function that takes a schedule and returns a schedule consisting of
    filtered instructions.

    Args:
        sched: A pulse schedule to be filtered.
        filters: List of callback functions that take an instruction and return boolean.
        negate: Set `True` to accept an instruction if a filter function returns `False`.
            Otherwise the instruction is accepted when the filter function returns `False`.
        recurse_subroutines: Set `True` to individually filter instructions inside of a subroutine
            defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction.

    Returns:
        Filtered pulse schedule.
    """
    from qiskit.pulse.transforms import flatten, inline_subroutines

    target_sched = flatten(sched)
    if recurse_subroutines:
        target_sched = inline_subroutines(target_sched)

    time_inst_tuples = np.array(target_sched.instructions)

    valid_insts = np.ones(len(time_inst_tuples), dtype=bool)
    for filt in filters:
        valid_insts = np.logical_and(
            valid_insts, np.array(list(map(filt, time_inst_tuples))))

    if negate and len(filters) > 0:
        valid_insts = ~valid_insts

    filter_schedule = Schedule.initialize_from(sched)
    for time, inst in time_inst_tuples[valid_insts]:
        filter_schedule.insert(time, inst, inplace=True)

    return filter_schedule
 def test_alap_pass(self):
     """Test ALAP scheduling."""
     q = QuantumRegister(2)
     c = ClassicalRegister(2)
     qc = QuantumCircuit(q, c)
     qc.u2(3.14, 1.57, q[0])
     qc.u2(0.5, 0.25, q[1])
     qc.barrier(q[1])
     qc.u2(0.5, 0.25, q[1])
     qc.barrier(q[0], q[1])
     qc.cx(q[0], q[1])
     qc.measure(q, c)
     sched = schedule(qc, self.backend)
     # X pulse on q0 should end at the start of the CNOT
     expected = Schedule((28, self.inst_map.get('u2', [0], 3.14, 1.57)),
                         self.inst_map.get('u2', [1], 0.5, 0.25),
                         (28, self.inst_map.get('u2', [1], 0.5, 0.25)),
                         (56, self.inst_map.get('cx', [0, 1])),
                         (78, self.inst_map.get('measure', [0, 1])))
     for actual, expected in zip(sched.instructions, expected.instructions):
         self.assertEqual(actual[0], expected[0])
         self.assertEqual(actual[1], expected[1])
Beispiel #26
0
    def test_sequenced_parameterized_schedule(self):
        """Test parameterized schedule consists of multiple instruction. """

        converter = QobjToInstructionConverter([], buffer=0)
        qobjs = [
            PulseQobjInstruction(name='fc', ch='d0', t0=10, phase='P1'),
            PulseQobjInstruction(name='fc', ch='d0', t0=20, phase='P2'),
            PulseQobjInstruction(name='fc', ch='d0', t0=30, phase='P3')
        ]
        converted_instruction = [converter(qobj) for qobj in qobjs]

        inst_map = InstructionScheduleMap()

        inst_map.add('inst_seq', 0,
                     Schedule(*converted_instruction, name='inst_seq'))

        with self.assertRaises(PulseError):
            inst_map.get('inst_seq', 0, P1=1, P2=2, P3=3, P4=4, P5=5)

        with self.assertRaises(PulseError):
            inst_map.get('inst_seq', 0, 1, 2, 3, 4, 5, 6, 7, 8)

        p3_expr = Parameter('p3')
        p3_expr = p3_expr.bind({p3_expr: 3})

        sched = inst_map.get('inst_seq', 0, 1, 2, p3_expr)
        self.assertEqual(sched.instructions[0][-1].phase, 1)
        self.assertEqual(sched.instructions[1][-1].phase, 2)
        self.assertEqual(sched.instructions[2][-1].phase, 3)

        sched = inst_map.get('inst_seq', 0, P1=1, P2=2, P3=p3_expr)
        self.assertEqual(sched.instructions[0][-1].phase, 1)
        self.assertEqual(sched.instructions[1][-1].phase, 2)
        self.assertEqual(sched.instructions[2][-1].phase, 3)

        sched = inst_map.get('inst_seq', 0, 1, 2, P3=p3_expr)
        self.assertEqual(sched.instructions[0][-1].phase, 1)
        self.assertEqual(sched.instructions[1][-1].phase, 2)
        self.assertEqual(sched.instructions[2][-1].phase, 3)
Beispiel #27
0
    def load_program(cls, program: pulse.Schedule,
                     channel: pulse.channels.Channel):
        """Load a pulse program represented by ``Schedule``.

        Args:
            program: Target ``Schedule`` to visualize.
            channel: The channel managed by this instance.

        Returns:
            ChannelEvents: The channel event manager for the specified channel.
        """
        waveforms = dict()
        frames = defaultdict(list)

        # parse instructions
        for t0, inst in program.filter(channels=[channel]).instructions:
            if isinstance(inst, cls._waveform_group):
                waveforms[t0] = inst
            elif isinstance(inst, cls._frame_group):
                frames[t0].append(inst)

        return ChannelEvents(waveforms, frames, channel)
    def test_multiple_measure_in_3Q(self):
        """Test multiple measure, user memslot mapping, 3Q."""
        backend = FakeOpenPulse3Q()
        cmd_def = backend.defaults().build_cmd_def()
        q = QuantumRegister(3)
        c = ClassicalRegister(5)
        qc = QuantumCircuit(q, c)
        qc.measure(q[0], c[2])
        qc.measure(q[0], c[4])
        sched = schedule(qc, backend)

        acquire = Acquire(duration=10)
        expected = Schedule(
            cmd_def.get('measure', [0, 1, 2]).filter(channels=[MeasureChannel(0)]),
            acquire(AcquireChannel(0), MemorySlot(2)),
            acquire(AcquireChannel(1), MemorySlot(0)),
            acquire(AcquireChannel(2), MemorySlot(1)),
            (10, cmd_def.get('measure', [0, 1, 2]).filter(channels=[MeasureChannel(0)])),
            (10, acquire(AcquireChannel(0), MemorySlot(4))),
            (10, acquire(AcquireChannel(1), MemorySlot(0))),
            (10, acquire(AcquireChannel(2), MemorySlot(1)))
        )
        self.assertEqual(sched.instructions, expected.instructions)
 def test_3q_schedule(self):
     """Test a schedule that was recommended by David McKay :D """
     backend = FakeOpenPulse3Q()
     inst_map = backend.defaults().instruction_schedule_map
     q = QuantumRegister(3)
     c = ClassicalRegister(3)
     qc = QuantumCircuit(q, c)
     qc.cx(q[0], q[1])
     qc.u2(0.778, 0.122, q[2])
     qc.u3(3.14, 1.57, 0., q[0])
     qc.u2(3.14, 1.57, q[1])
     qc.cx(q[1], q[2])
     qc.u2(0.778, 0.122, q[2])
     sched = schedule(qc, backend)
     expected = Schedule(inst_map.get('cx', [0, 1]),
                         (22, inst_map.get('u2', [1], 3.14, 1.57)),
                         (46, inst_map.get('u2', [2], 0.778, 0.122)),
                         (50, inst_map.get('cx', [1, 2])),
                         (72, inst_map.get('u2', [2], 0.778, 0.122)),
                         (74, inst_map.get('u3', [0], 3.14, 1.57)))
     for actual, expected in zip(sched.instructions, expected.instructions):
         self.assertEqual(actual[0], expected[0])
         self.assertEqual(actual[1], expected[1])
Beispiel #30
0
def model_and_pi_schedule():
    """Return a simple model and schedule for pulse simulation"""

    # construct model
    model = duffing_system_model(dim_oscillators=2,
                                 oscillator_freqs=[5.0],
                                 anharm_freqs=[0],
                                 drive_strengths=[1.0],
                                 coupling_dict={},
                                 dt=1.0)

    # note: parameters set so that area under curve is 1/4
    gauss_pulse = Gaussian(duration=10,
                           amp=(1.0 / 4) / 2.506627719963857,
                           sigma=1)

    # construct schedule
    schedule = Schedule(name='test_sched')
    schedule |= Play(gauss_pulse, DriveChannel(0))
    schedule += Acquire(10, AcquireChannel(0),
                        MemorySlot(0)) << schedule.duration

    return model, schedule