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)
    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
Example #3
0
    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
Example #4
0
    def test_parametric_pulses_with_duplicates(self):
        """Test with parametric pulses."""
        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.5j), drive_channel)
        schedule += Play(GaussianSquare(duration=150, amp=0.2,
                                        sigma=8, width=140), drive_channel)
        schedule += Play(GaussianSquare(duration=150, amp=0.2,
                                        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.4j), 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.3j, 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), 8)
        self.assertEqual(len(compressed_pulse_ids), 4)
Example #5
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', ))
Example #6
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_pulse_name_conflicts(self):
        """Test that pulse name conflicts can be resolved."""
        name_conflict_pulse = pulse.Waveform(samples=np.array(
            [0.02, 0.05, 0.05, 0.05, 0.02], dtype=np.complex128),
                                             name='pulse0')

        self.schedule = self.schedule.insert(
            1, Play(name_conflict_pulse, self.backend_config.drive(1)))

        qobj = assemble(self.schedule,
                        qobj_header=self.header,
                        qubit_lo_freq=self.default_qubit_lo_freq,
                        meas_lo_freq=self.default_meas_lo_freq,
                        schedule_los=[],
                        **self.config)
        validate_qobj_against_schema(qobj)

        self.assertNotEqual(qobj.config.pulse_library[0].name,
                            qobj.config.pulse_library[1].name)
    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 _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
    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 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)
Example #12
0
    def test_name_inherited(self):
        """Test that schedule keeps name if an instruction is added."""
        gp0 = library.gaussian(duration=100, amp=0.7, sigma=3, name="pulse_name")
        snapshot = Snapshot("snapshot_label", "state")

        sched1 = Schedule(name="test_name")
        sched2 = Schedule(name=None)
        sched3 = sched1 | sched2
        self.assertEqual(sched3.name, "test_name")

        sched_acq = Acquire(10, self.config.acquire(1), MemorySlot(1), name="acq_name") | sched1
        self.assertEqual(sched_acq.name, "acq_name")

        sched_pulse = Play(gp0, self.config.drive(0)) | sched1
        self.assertEqual(sched_pulse.name, "pulse_name")

        sched_fc = ShiftPhase(0.1, self.config.drive(0), name="fc_name") | sched1
        self.assertEqual(sched_fc.name, "fc_name")

        sched_snapshot = snapshot | sched1
        self.assertEqual(sched_snapshot.name, "snapshot_label")
Example #13
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
Example #14
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
Example #15
0
 def test_rzx_calibration_builder_duration(self, theta: float):
     """Test that pulse durations are computed correctly."""
     width = 512.00000001
     sigma = 64
     n_sigmas = 4
     duration = width + n_sigmas * sigma
     sample_mult = 16
     amp = 1.0
     pulse = GaussianSquare(duration=duration,
                            amp=amp,
                            sigma=sigma,
                            width=width)
     instruction = Play(pulse, ControlChannel(1))
     scaled = RZXCalibrationBuilder.rescale_cr_inst(instruction,
                                                    theta,
                                                    sample_mult=sample_mult)
     gaussian_area = abs(amp) * sigma * np.sqrt(2 * np.pi) * erf(n_sigmas)
     area = gaussian_area + abs(amp) * width
     target_area = abs(theta) / (np.pi / 2.0) * area
     width = (target_area - gaussian_area) / abs(amp)
     expected_duration = round(
         (width + n_sigmas * sigma) / sample_mult) * sample_mult
     self.assertEqual(scaled.duration, expected_duration)
    def _3Q_constant_sched(self, total_samples, amp=1., u_idx=0, subsystem_list=[0, 2]):
        """Creates a runnable schedule for the 3Q system after the system is restricted to
        2 qubits.

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

        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))
        for idx in subsystem_list:
            schedule |= Acquire(total_samples,
                                AcquireChannel(idx),
                                MemorySlot(idx)) << total_samples

        return schedule
    def test_align_measures(self):
        """Test that one acquire is delayed to match the time of the later acquire."""
        sched = pulse.Schedule(name='fake_experiment')
        sched.insert(0,
                     Play(self.short_pulse, self.config.drive(0)),
                     inplace=True)
        sched.insert(1,
                     Acquire(5, self.config.acquire(0), MemorySlot(0)),
                     inplace=True)
        sched.insert(10,
                     Acquire(5, self.config.acquire(1), MemorySlot(1)),
                     inplace=True)
        sched.insert(10,
                     Play(self.short_pulse, self.config.measure(0)),
                     inplace=True)
        sched.insert(11,
                     Play(self.short_pulse, self.config.measure(0)),
                     inplace=True)
        sched.insert(10,
                     Play(self.short_pulse, self.config.measure(1)),
                     inplace=True)
        aligned = transforms.align_measures([sched])[0]
        self.assertEqual(aligned.name, 'fake_experiment')

        ref = pulse.Schedule(name='fake_experiment')
        ref.insert(0,
                   Play(self.short_pulse, self.config.drive(0)),
                   inplace=True)
        ref.insert(10,
                   Acquire(5, self.config.acquire(0), MemorySlot(0)),
                   inplace=True)
        ref.insert(10,
                   Acquire(5, self.config.acquire(1), MemorySlot(1)),
                   inplace=True)
        ref.insert(19,
                   Play(self.short_pulse, self.config.measure(0)),
                   inplace=True)
        ref.insert(20,
                   Play(self.short_pulse, self.config.measure(0)),
                   inplace=True)
        ref.insert(10,
                   Play(self.short_pulse, self.config.measure(1)),
                   inplace=True)

        self.assertEqual(aligned, ref)

        aligned = transforms.align_measures([sched],
                                            self.inst_map,
                                            align_time=20)[0]

        ref = pulse.Schedule(name='fake_experiment')
        ref.insert(10,
                   Play(self.short_pulse, self.config.drive(0)),
                   inplace=True)
        ref.insert(20,
                   Acquire(5, self.config.acquire(0), MemorySlot(0)),
                   inplace=True)
        ref.insert(20,
                   Acquire(5, self.config.acquire(1), MemorySlot(1)),
                   inplace=True)
        ref.insert(29,
                   Play(self.short_pulse, self.config.measure(0)),
                   inplace=True)
        ref.insert(30,
                   Play(self.short_pulse, self.config.measure(0)),
                   inplace=True)
        ref.insert(20,
                   Play(self.short_pulse, self.config.measure(1)),
                   inplace=True)
        self.assertEqual(aligned, ref)
                             qubits=backend_config.meas_map[meas_map_idx])

### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)

# Create two schedules

# Ground state schedule
gnd_schedule = pulse.Schedule(name="ground state")
gnd_schedule += measure

# Excited state schedule
exc_schedule = pulse.Schedule(name="excited state")
exc_schedule += Play(pi_pulse, drive_chan)  # We found this in Part 2A above
exc_schedule += measure << exc_schedule.duration

# Execution settings
num_shots = 1024 * 8

gnd_exc_program = assemble([gnd_schedule, exc_schedule],
                           backend=backend,
                           meas_level=0,
                           meas_return='single',
                           shots=num_shots,
                           schedule_los=[{
                               drive_chan: rough_qubit_frequency
                           }] * 2)

# print(job.job_id())
Example #19
0
    def test_filter_inst_types(self):
        """Test filtering on instruction types."""
        lp0 = self.linear(duration=3, slope=0.2, intercept=0.1)
        sched = Schedule(name='fake_experiment')
        sched = sched.insert(0, Play(lp0, self.config.drive(0)))
        sched = sched.insert(10, Play(lp0, self.config.drive(1)))
        sched = sched.insert(30, ShiftPhase(-1.57, self.config.drive(0)))
        sched = sched.insert(40, SetFrequency(8.0, self.config.drive(0)))
        sched = sched.insert(50, ShiftFrequency(4.0e6, self.config.drive(0)))
        sched = sched.insert(55, SetPhase(3.14, self.config.drive(0)))
        for i in range(2):
            sched = sched.insert(
                60, Acquire(5, self.config.acquire(i), MemorySlot(i)))
        sched = sched.insert(90, Play(lp0, self.config.drive(0)))

        # test on Acquire
        only_acquire, no_acquire = \
            self._filter_and_test_consistency(sched, instruction_types=[Acquire])
        for _, inst in only_acquire.instructions:
            self.assertIsInstance(inst, Acquire)
        for _, inst in no_acquire.instructions:
            self.assertFalse(isinstance(inst, Acquire))

        # test two instruction types
        only_pulse_and_fc, no_pulse_and_fc = \
            self._filter_and_test_consistency(sched, instruction_types=[Play,
                                                                        ShiftPhase])
        for _, inst in only_pulse_and_fc.instructions:
            self.assertIsInstance(inst, (Play, ShiftPhase))
        for _, inst in no_pulse_and_fc.instructions:
            self.assertFalse(isinstance(inst, (Play, ShiftPhase)))
        self.assertEqual(len(only_pulse_and_fc.instructions), 4)
        self.assertEqual(len(no_pulse_and_fc.instructions), 5)

        # test on ShiftPhase
        only_fc, no_fc = \
            self._filter_and_test_consistency(sched, instruction_types={ShiftPhase})
        self.assertEqual(len(only_fc.instructions), 1)
        self.assertEqual(len(no_fc.instructions), 8)

        # test on SetPhase
        only_setp, no_setp = \
            self._filter_and_test_consistency(sched, instruction_types={SetPhase})
        self.assertEqual(len(only_setp.instructions), 1)
        self.assertEqual(len(no_setp.instructions), 8)

        # test on SetFrequency
        only_setf, no_setf = self._filter_and_test_consistency(
            sched, instruction_types=[SetFrequency])
        for _, inst in only_setf.instructions:
            self.assertTrue(isinstance(inst, SetFrequency))
        self.assertEqual(len(only_setf.instructions), 1)
        self.assertEqual(len(no_setf.instructions), 8)

        # test on ShiftFrequency
        only_shiftf, no_shiftf = \
            self._filter_and_test_consistency(sched,
                                              instruction_types=[ShiftFrequency])
        for _, inst in only_shiftf.instructions:
            self.assertTrue(isinstance(inst, ShiftFrequency))
        self.assertEqual(len(only_shiftf.instructions), 1)
        self.assertEqual(len(no_shiftf.instructions), 8)
Example #20
0
 def my_test_par_sched_two(x, y, z):
     result = Play(Waveform(np.array([x, y, z]), name="sample"), self.config.drive(0))
     return 5, result
Example #21
0
 def test_numpy_integer_input(self):
     """Test that mixed integer duration types can build a schedule (#5754)."""
     sched = Schedule()
     sched += Delay(np.int32(25), DriveChannel(0))
     sched += Play(Constant(duration=30, amp=0.1), DriveChannel(0))
     self.assertEqual(sched.duration, 55)
Example #22
0
def update_u_gates(drag_params, pi2_pulse_schedules=None,
                   qubits=None, inst_map=None, drives=None):
    """Update the cmd_def with new single qubit gate values

    Will update U2, U3

    Args:
        drag_params (list): list of drag params
        pi2_pulse_schedules (list): list of new pi/2 gate as a pulse schedule
                             will use the drag_params if this is None.
        qubits (list): list of qubits to update
        inst_map (InstructionScheduleMap): InstructionScheduleMap providing
            circuit instruction to schedule definitions.
        drives (list): List of drive chs
    """

    # U2 is -P1.Y90p.-P0
    # U3 is -P2.X90p.-P0.X90m.-P1

    def parametrized_fc(kw_name, phi0, chan, t_offset):
        def _parametrized_fc(**kwargs):
            return ShiftPhase(phase=-kwargs[kw_name]+phi0, channel=chan).shift(t_offset)
        return _parametrized_fc

    for qubit in qubits:

        drive_ch = drives[qubit]

        if pi2_pulse_schedules is None:
            x90_pulse = pulse_lib.drag(**drag_params[qubit])
            x90_sched = Schedule()
            x90_sched += Play(x90_pulse, drive_ch).shift(0)
        else:
            x90_sched = pi2_pulse_schedules[qubit]

        pulse_dur = x90_sched.duration

        # find channel dependency for u2
        for _u2_group in _find_channel_groups('u2', qubits=qubit, inst_map=inst_map):
            if drive_ch in _u2_group:
                break
        else:
            _u2_group = (drive_ch, )

        u2_fc1s = [parametrized_fc('P1', np.pi/2, ch, 0) for ch in _u2_group]
        u2_fc2s = [parametrized_fc('P0', -np.pi/2, ch, pulse_dur) for ch in _u2_group]

        # find channel dependency for u3
        for _u3_group in _find_channel_groups('u3', qubits=qubit, inst_map=inst_map):
            if drive_ch in _u3_group:
                break
        else:
            _u3_group = (drive_ch, )

        u3_fc1s = [parametrized_fc('P2', 0, ch, 0) for ch in _u3_group]
        u3_fc2s = [parametrized_fc('P0', -np.pi, ch, pulse_dur) for ch in _u3_group]
        u3_fc3s = [parametrized_fc('P1', np.pi, ch, 2*pulse_dur) for ch in _u3_group]

        # add commands to schedule
        # u2
        sched_components = [*u2_fc1s, x90_sched, *u2_fc2s]
        schedule1 = ParameterizedSchedule(*sched_components,
                                          parameters=['P0', 'P1'], name='u2_%d' % qubit)

        # u3
        sched_components = [*u3_fc1s, x90_sched, *u3_fc2s, x90_sched.shift(pulse_dur), *u3_fc3s]
        schedule2 = ParameterizedSchedule(*sched_components,
                                          parameters=['P0', 'P1', 'P2'], name='u3_%d' % qubit)

        inst_map.add('u2', qubits=qubit, schedule=schedule1)
        inst_map.add('u3', qubits=qubit, schedule=schedule2)
Example #23
0
 def test_func(dur: int):
     sched = Schedule()
     sched += Play(library.constant(int(dur), amp), DriveChannel(0))
     return sched
Example #24
0
def update_u_gates(drag_params,
                   pi2_pulse_schedules=None,
                   qubits=None,
                   inst_map=None,
                   drives=None):
    """Update the cmd_def with new single qubit gate values

    Will update U2, U3

    Args:
        drag_params (list): list of drag params
        pi2_pulse_schedules (list): list of new pi/2 gate as a pulse schedule
                             will use the drag_params if this is None.
        qubits (list): list of qubits to update
        inst_map (InstructionScheduleMap): InstructionScheduleMap providing
            circuit instruction to schedule definitions.
        drives (list): List of drive chs
    """
    # pylint: disable = invalid-name

    # U2 is -P1.Y90p.-P0
    # U3 is -P2.X90p.-P0.X90m.-P1

    for qubit in qubits:

        drive_ch = drives[qubit]

        if pi2_pulse_schedules is None:
            x90_pulse = pulse_lib.drag(**drag_params[qubit])
            x90_sched = Schedule()
            x90_sched += Play(x90_pulse, drive_ch).shift(0)
        else:
            x90_sched = pi2_pulse_schedules[qubit]

        # find channel dependency for u2
        for _u2_group in _find_channel_groups('u2',
                                              qubits=qubit,
                                              inst_map=inst_map):
            if drive_ch in _u2_group:
                break
        else:
            _u2_group = (drive_ch, )

        # find channel dependency for u3
        for _u3_group in _find_channel_groups('u3',
                                              qubits=qubit,
                                              inst_map=inst_map):
            if drive_ch in _u3_group:
                break
        else:
            _u3_group = (drive_ch, )

        # add commands to schedule

        # u2
        with pulse.build(name=f"u2_{qubit}",
                         default_alignment="sequential") as u2_sched:
            P0 = Parameter("P0")
            P1 = Parameter("P1")
            for ch in _u2_group:
                pulse.shift_phase(-P1 + np.pi / 2, ch)
            pulse.call(x90_sched)
            for ch in _u2_group:
                pulse.shift_phase(-P0 - np.pi / 2, ch)

        # u3
        with pulse.build(name=f"u3_{qubit}",
                         default_alignment="sequential") as u3_sched:
            P0 = Parameter("P0")
            P1 = Parameter("P1")
            P2 = Parameter("P2")
            for ch in _u3_group:
                pulse.shift_phase(-P2, ch)
            pulse.call(x90_sched)
            for ch in _u3_group:
                pulse.shift_phase(-P0 - np.pi, ch)
            pulse.call(x90_sched)
            for ch in _u3_group:
                pulse.shift_phase(-P1 + np.pi, ch)

        inst_map.add('u2', qubits=qubit, schedule=u2_sched)
        inst_map.add('u3', qubits=qubit, schedule=u3_sched)
def _assemble_instructions(
    schedule: Schedule, instruction_converter: InstructionToQobjConverter,
    run_config: RunConfig,
    user_pulselib: Dict[str,
                        Command]) -> Tuple[List[PulseQobjInstruction], int]:
    """Assembles the instructions in a schedule into a list of PulseQobjInstructions and returns
    related metadata that will be assembled into the Qobj configuration. Lookup table for
    pulses defined in all experiments are registered in ``user_pulselib``. This object should be
    mutable python dictionary so that items are properly updated after each instruction assemble.
    The dictionary is not returned to avoid redundancy.

    Args:
        schedule: Schedule to assemble.
        instruction_converter: A converter instance which can convert PulseInstructions to
                               PulseQobjInstructions.
        run_config: Configuration of the runtime environment.
        user_pulselib: User pulse library from previous schedule.

    Returns:
        A list of converted instructions, the user pulse library dictionary (from pulse name to
        pulse command), and the maximum number of readout memory slots used by this Schedule.
    """
    max_memory_slot = 0
    qobj_instructions = []

    acquire_instruction_map = defaultdict(list)
    for time, instruction in schedule.instructions:

        if isinstance(instruction, ParametricInstruction):  # deprecated
            instruction = Play(instruction.command,
                               instruction.channels[0],
                               name=instruction.name)

        if isinstance(instruction, Play) and isinstance(
                instruction.pulse, ParametricPulse):
            pulse_shape = ParametricPulseShapes(type(instruction.pulse)).name
            if pulse_shape not in run_config.parametric_pulses:
                instruction = Play(instruction.pulse.get_sample_pulse(),
                                   instruction.channel,
                                   name=instruction.name)

        if isinstance(instruction, PulseInstruction):  # deprecated
            instruction = Play(SamplePulse(
                name=name, samples=instruction.command.samples),
                               instruction.channels[0],
                               name=name)

        if isinstance(instruction, Play) and isinstance(
                instruction.pulse, SamplePulse):
            name = hashlib.sha256(instruction.pulse.samples).hexdigest()
            instruction = Play(SamplePulse(name=name,
                                           samples=instruction.pulse.samples),
                               channel=instruction.channel,
                               name=name)
            user_pulselib[name] = instruction.pulse.samples

        if isinstance(instruction, (AcquireInstruction, Acquire)):
            max_memory_slot = max(
                max_memory_slot,
                *[slot.index for slot in instruction.mem_slots])
            # Acquires have a single AcquireChannel per inst, but we have to bundle them
            # together into the Qobj as one instruction with many channels
            acquire_instruction_map[(time,
                                     instruction.command)].append(instruction)
            continue

        if isinstance(instruction, (DelayInstruction, Delay)):
            # delay instructions are ignored as timing is explicit within qobj
            continue

        qobj_instructions.append(instruction_converter(time, instruction))

    if acquire_instruction_map:
        if hasattr(run_config, 'meas_map'):
            _validate_meas_map(acquire_instruction_map, run_config.meas_map)
        for (time, _), instructions in acquire_instruction_map.items():
            qubits, mem_slots, reg_slots = _bundle_channel_indices(
                instructions)
            qobj_instructions.append(
                instruction_converter.convert_single_acquires(
                    time,
                    instructions[0],
                    qubits=qubits,
                    memory_slot=mem_slots,
                    register_slot=reg_slots))

    return qobj_instructions, max_memory_slot
Example #26
0
        break
assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!"

inst_sched_map = backend_defaults.instruction_schedule_map
measure = inst_sched_map.get('measure',
                             qubits=backend_config.meas_map[meas_map_idx])

### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)

# Create the base schedule
# Start with drive pulse acting on the drive channel
schedule = pulse.Schedule(name='Frequency sweep')
schedule += Play(drive_pulse, drive_chan)
# The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration
schedule += measure << schedule.duration

# Create the frequency settings for the sweep (MUST BE IN HZ)
frequencies_Hz = frequencies_GHz * GHz
schedule_frequencies = [{drive_chan: freq} for freq in frequencies_Hz]

from qiskit import assemble

num_shots_per_frequency = 1024
frequency_sweep_program = assemble(schedule,
                                   backend=backend,
                                   meas_level=1,
                                   meas_return='avg',
                                   shots=num_shots_per_frequency,
Example #27
0
 def test_func(x):
     sched = Schedule()
     sched += Play(library.constant(int(x), amp_test), DriveChannel(0))
     return sched
Example #28
0
        break
assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!"

inst_sched_map = backend_defaults.instruction_schedule_map
measure = inst_sched_map.get('measure',
                             qubits=backend_config.meas_map[meas_map_idx])

### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)

# Create the base schedule
# Start with drive pulse acting on the drive channel
schedule = pulse.Schedule(name='Frequency sweep')
schedule += Play(drive_pulse, drive_chan)
# The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration
schedule += measure << schedule.duration

# Create the frequency settings for the sweep (MUST BE IN HZ)
frequencies_Hz = frequencies_GHz * GHz
schedule_frequencies = [{drive_chan: freq} for freq in frequencies_Hz]

from qiskit import assemble

num_shots_per_frequency = 1024
frequency_sweep_program = assemble(schedule,
                                   backend=backend,
                                   meas_level=1,
                                   meas_return='avg',
                                   shots=num_shots_per_frequency,
Example #29
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
Example #30
0
 def my_test_par_sched_one(x, y, z):
     result = Play(Waveform(np.array([x, y, z]), name='sample'),
                   self.config.drive(0))
     return 0, result