def _1Q_frame_change_schedule(self, phi, fc_phi, total_samples, dur_drive1,
                                  dur_drive2):
        """Creates schedule for frame change test. Does a pulse w/ phase phi of duration dur_drive1,
        then frame change of phase fc_phi, then another pulse of phase phi of duration dur_drive2.
        The different durations for the pulses allow manipulation of rotation angles on Bloch sphere

        Args:
            phi (float): drive phase (phi in Hamiltonian)
            fc_phi (float): phase for frame change
            total_samples (int): length of pulses
            dur_drive1 (int): duration of first pulse
            dur_drive2 (int): duration of second pulse

        Returns:
            schedule (pulse schedule): schedule for frame change test
        """
        phase = np.exp(1j * phi)
        drive_pulse_1 = SamplePulse(phase * np.ones(dur_drive1),
                                    name='drive_pulse_1')
        drive_pulse_2 = SamplePulse(phase * np.ones(dur_drive2),
                                    name='drive_pulse_2')

        # add commands to schedule
        schedule = Schedule(name='fc_schedule')
        schedule |= Play(drive_pulse_1, DriveChannel(0))
        schedule += ShiftPhase(fc_phi, DriveChannel(0))
        schedule += Play(drive_pulse_2, DriveChannel(0))
        schedule |= Acquire(total_samples, AcquireChannel(0),
                            MemorySlot(0)) << schedule.duration

        return schedule
Exemplo n.º 2
0
    def test_single_channel_out_of_order(self):
        """Test that schedule with single channel equal when out of order."""
        instructions = [(0, FrameChange(0)(DriveChannel(0))),
                        (15, SamplePulse(np.ones(10))(DriveChannel(0))),
                        (5, SamplePulse(np.ones(10))(DriveChannel(0)))]

        self.assertEqual(Schedule(*instructions), Schedule(*reversed(instructions)))
    def _simple_1Q_schedule(self,
                            phi,
                            total_samples,
                            shape="square",
                            gauss_sigma=0):
        """Creates schedule for single pulse test
        Args:
            phi (float): drive phase (phi in Hamiltonian)
            total_samples (int): length of pulses
            shape (str): shape of the pulse; defaults to square pulse
            gauss_sigma (float): std dev for gaussian pulse if shape=="gaussian"
        Returns:
            schedule (pulse schedule): schedule for this test
        """

        # set up pulse command
        phase = np.exp(1j * phi)
        drive_pulse = None
        if shape == "square":
            const_pulse = np.ones(total_samples)
            drive_pulse = SamplePulse(phase * const_pulse, name='drive_pulse')
        if shape == "gaussian":
            times = 1.0 * np.arange(total_samples)
            gaussian = np.exp(-times**2 / 2 / gauss_sigma**2)
            drive_pulse = SamplePulse(phase * gaussian, name='drive_pulse')

        # add commands into a schedule for first qubit
        schedule = Schedule(name='drive_pulse')
        schedule |= Play(drive_pulse, DriveChannel(0))
        schedule |= Acquire(total_samples, AcquireChannel(0),
                            MemorySlot(0)) << schedule.duration

        return schedule
    def test_with_different_channels(self):
        """Test with different channels."""
        schedule = Schedule()
        schedule += Play(SamplePulse([0.0, 0.1]), DriveChannel(0))
        schedule += Play(SamplePulse([0.0, 0.1]), DriveChannel(1))

        compressed_schedule = compress_pulses([schedule])
        original_pulse_ids = get_pulse_ids([schedule])
        compressed_pulse_ids = get_pulse_ids(compressed_schedule)
        self.assertEqual(len(original_pulse_ids), 2)
        self.assertEqual(len(compressed_pulse_ids), 1)
    def test_no_duplicates(self):
        """Test with no pulse duplicates."""
        schedule = Schedule()
        drive_channel = DriveChannel(0)
        schedule += Play(SamplePulse([0.0, 1.0]), drive_channel)
        schedule += Play(SamplePulse([0.0, 0.9]), drive_channel)
        schedule += Play(SamplePulse([0.0, 0.3]), drive_channel)

        compressed_schedule = 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))
    def test_sample_pulses_with_tolerance(self):
        """Test sample pulses with tolerance."""
        schedule = Schedule()
        schedule += Play(SamplePulse([0.0, 0.1001], epsilon=1e-3),
                         DriveChannel(0))
        schedule += Play(SamplePulse([0.0, 0.1], epsilon=1e-3),
                         DriveChannel(1))

        compressed_schedule = compress_pulses([schedule])
        original_pulse_ids = get_pulse_ids([schedule])
        compressed_pulse_ids = get_pulse_ids(compressed_schedule)
        self.assertEqual(len(original_pulse_ids), 2)
        self.assertEqual(len(compressed_pulse_ids), 1)
Exemplo n.º 7
0
    def test_set_phase(self):
        """Test SetPhase command. Similar to the ShiftPhase test but includes a mixing of
        ShiftPhase and SetPhase instructions to test relative vs absolute changes"""

        omega_0 = 1.3981
        r = 1.

        system_model = self._system_model_1Q(omega_0, r)

        # intermix shift and set phase instructions to verify absolute v.s. relative changes
        sched = Schedule()
        amp1 = 0.12
        sched += Play(SamplePulse([amp1]), DriveChannel(0))
        phi1 = 0.12374 * np.pi
        sched += ShiftPhase(phi1, DriveChannel(0))
        amp2 = 0.492
        sched += Play(SamplePulse([amp2]), DriveChannel(0))
        phi2 = 0.5839 * np.pi
        sched += SetPhase(phi2, DriveChannel(0))
        amp3 = 0.12 + 0.21 * 1j
        sched += Play(SamplePulse([amp3]), DriveChannel(0))
        phi3 = 0.1 * np.pi
        sched += ShiftPhase(phi3, DriveChannel(0))
        amp4 = 0.2 + 0.3 * 1j
        sched += Play(SamplePulse([amp4]), DriveChannel(0))

        sched |= Acquire(1, AcquireChannel(0), MemorySlot(0)) << sched.duration

        qobj = assemble([sched],
                        backend=self.backend_sim,
                        meas_level=2,
                        meas_return='single',
                        meas_map=[[0]],
                        qubit_lo_freq=[omega_0],
                        memory_slots=2,
                        shots=1)

        y0 = np.array([1., 0.])
        backend_options = {'initial_state': y0}

        results = self.backend_sim.run(qobj, system_model, backend_options).result()
        pulse_sim_yf = results.get_statevector()

        #run independent simulation
        samples = np.array([[amp1],
                            [amp2 * np.exp(1j * phi1)],
                            [amp3 * np.exp(1j * phi2)],
                            [amp4 * np.exp(1j * (phi2 + phi3))]])
        indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_0]), samples, 1.)

        self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), 1 - (10**-5))
    def test_with_duplicates(self):
        """Test compression of schedule."""
        schedule = Schedule()
        drive_channel = DriveChannel(0)
        schedule += Play(SamplePulse([0.0, 0.1]), drive_channel)
        schedule += Play(SamplePulse([0.0, 0.1]), drive_channel)

        compressed_schedule = compress_pulses([schedule])
        original_pulse_ids = get_pulse_ids([schedule])
        compressed_pulse_ids = get_pulse_ids(compressed_schedule)

        self.assertEqual(len(compressed_pulse_ids), 1)
        self.assertEqual(len(original_pulse_ids), 2)
        self.assertTrue(next(iter(compressed_pulse_ids)) in original_pulse_ids)
    def _schedule_2Q_interaction(self, total_samples):
        """Creates schedule for testing two qubit interaction. Specifically, do a pi pulse on qub 0
        so it starts in the `1` state (drive channel) and then apply constant pulses to each
        qubit (on control channel 1). This will allow us to test a swap gate.

        Args:
            total_samples (int): length of pulses
        Returns:
            schedule (pulse schedule): schedule for 2q experiment
        """

        # create acquire schedule
        acq_sched = Schedule(name='acq_sched')
        acq_sched |= Acquire(total_samples, AcquireChannel(0), MemorySlot(0))
        acq_sched += Acquire(total_samples, AcquireChannel(1), MemorySlot(1))

        # set up const pulse
        const_pulse = SamplePulse(np.ones(total_samples), name='const_pulse')

        # add commands to schedule
        schedule = Schedule(name='2q_schedule')
        schedule |= Play(const_pulse, DriveChannel(0))
        schedule += Play(const_pulse, ControlChannel(1)) << schedule.duration
        schedule |= acq_sched << schedule.duration

        return schedule
Exemplo n.º 10
0
    def test_set_phase_rwa(self):
        """Test SetPhase command using an RWA approximate solution."""
        omega_0 = 5.123
        r = 0.01

        system_model = self._system_model_1Q(omega_0, r)

        sched = Schedule()
        sched += SetPhase(np.pi / 2, DriveChannel(0))
        sched += Play(SamplePulse(np.ones(100)), DriveChannel(0))

        sched |= Acquire(1, AcquireChannel(0), MemorySlot(0)) << sched.duration

        qobj = assemble([sched],
                        backend=self.backend_sim,
                        meas_level=2,
                        meas_return='single',
                        meas_map=[[0]],
                        qubit_lo_freq=[omega_0],
                        memory_slots=2,
                        shots=1)

        y0 = np.array([1., 1.]) / np.sqrt(2)
        backend_options = {'initial_state': y0}

        results = self.backend_sim.run(qobj, system_model, backend_options).result()
        pulse_sim_yf = results.get_statevector()

        #run independent simulation
        phases = np.exp((-1j * 2 * np.pi * omega_0 * np.array([1, -1]) / 2) * 100)
        approx_yf = phases * (expm(-1j * (np.pi / 2) * self.Y) @ y0)

        self.assertGreaterEqual(state_fidelity(pulse_sim_yf, approx_yf), 0.99)
Exemplo n.º 11
0
 def my_test_par_sched_two(x, y, z):
     with self.assertWarns(DeprecationWarning):
         result = PulseInstruction(
             SamplePulse(np.array([x, y, z]), name='sample'),
             self.config.drive(0)
         )
     return 5, result
Exemplo n.º 12
0
    def test_multiple_schedules(self):
        """Test multiple schedules."""
        schedules = []
        for _ in range(2):
            schedule = Schedule()
            drive_channel = DriveChannel(0)
            schedule += Play(SamplePulse([0.0, 0.1]), drive_channel)
            schedule += Play(SamplePulse([0.0, 0.1]), drive_channel)
            schedule += Play(SamplePulse([0.0, 0.2]), drive_channel)
            schedules.append(schedule)

        compressed_schedule = compress_pulses(schedules)
        original_pulse_ids = get_pulse_ids(schedules)
        compressed_pulse_ids = get_pulse_ids(compressed_schedule)
        self.assertEqual(len(original_pulse_ids), 6)
        self.assertEqual(len(compressed_pulse_ids), 2)
Exemplo n.º 13
0
    def test_sample_pulse_with_clipping(self):
        """Test sample pulses with clipping."""
        schedule = Schedule()
        drive_channel = DriveChannel(0)
        schedule += Play(SamplePulse([0.0, 1.0]), drive_channel)
        schedule += Play(SamplePulse([0.0, 1.001], epsilon=1e-3),
                         drive_channel)
        schedule += Play(SamplePulse([0.0, 1.0000000001]), drive_channel)

        compressed_schedule = compress_pulses([schedule])
        original_pulse_ids = get_pulse_ids([schedule])
        compressed_pulse_ids = get_pulse_ids(compressed_schedule)

        self.assertEqual(len(compressed_pulse_ids), 1)
        self.assertEqual(len(original_pulse_ids), 3)
        self.assertTrue(next(iter(compressed_pulse_ids)) in original_pulse_ids)
Exemplo n.º 14
0
def build_sample_pulse_schedule(number_of_unique_pulses, number_of_channels):
    rng = np.random.RandomState(42)
    sched = Schedule()
    for _ in range(number_of_unique_pulses):
        for channel in range(number_of_channels):
            sched.append(
                Play(SamplePulse(rng.random(50)), DriveChannel(channel)))
    return sched
Exemplo n.º 15
0
    def test_type_casting(self):
        """Test casting of input samples to numpy array."""
        n_samples = 100
        samples_f64 = np.linspace(0, 1., n_samples, dtype=np.float64)

        sample_pulse_f64 = SamplePulse(samples_f64)
        self.assertEqual(sample_pulse_f64.samples.dtype, np.complex128)

        samples_c64 = np.linspace(0, 1., n_samples, dtype=np.complex64)

        sample_pulse_c64 = SamplePulse(samples_c64)
        self.assertEqual(sample_pulse_c64.samples.dtype, np.complex128)

        samples_list = np.linspace(0, 1., n_samples).tolist()

        sample_pulse_list = SamplePulse(samples_list)
        self.assertEqual(sample_pulse_list.samples.dtype, np.complex128)
Exemplo n.º 16
0
    def test_get(self):
        """Test `get`."""
        sched = Schedule()
        sched.append(SamplePulse(np.ones(5))(DriveChannel(0)))
        inst_map = InstructionScheduleMap()

        inst_map.add('u1', 0, sched)

        self.assertEqual(sched, inst_map.get('u1', (0, )))
Exemplo n.º 17
0
def apply_sideband(pulse, sb_freq, dt):
    from qiskit.pulse import SamplePulse

    t_samples = np.linspace(0, dt * pulse.duration, pulse.duration)
    sine_pulse = np.sin(2 * np.pi * sb_freq * t_samples)

    sideband_pulse = SamplePulse(np.multiply(np.real(pulse.samples),
                                             sine_pulse),
                                 name='sideband_pulse')

    return sideband_pulse
Exemplo n.º 18
0
    def test_delay_measure_channel(self):
        """Test Delay on MeasureChannel"""

        measure_ch = self.config.measure(0)
        pulse = SamplePulse(np.full(10, 0.1))
        # should pass as is an append
        sched = self.delay(measure_ch) + pulse(measure_ch)
        self.assertIsInstance(sched, Schedule)
        # should fail due to overlap
        with self.assertRaises(PulseError):
            sched = self.delay(measure_ch) | pulse(measure_ch)
Exemplo n.º 19
0
    def test_pop(self):
        """Test pop with default."""
        sched = Schedule()
        sched.append(SamplePulse(np.ones(5))(self.config.drive(0)))
        cmd_def = CmdDef()
        cmd_def.add('tmp', 0, sched)
        cmd_def.pop('tmp', 0)
        self.assertFalse(cmd_def.has('tmp', 0))

        with self.assertRaises(PulseError):
            cmd_def.pop('not_there', (0, ))
Exemplo n.º 20
0
    def test_add(self):
        """Test `add`, `has`, `get`, `cmdss`."""
        sched = Schedule()
        sched.append(SamplePulse(np.ones(5))(self.config.drive(0)))
        cmd_def = CmdDef()
        cmd_def.add('tmp', 1, sched)
        cmd_def.add('tmp', 0, sched)
        self.assertEqual(sched.instructions, cmd_def.get('tmp', (0,)).instructions)

        self.assertIn('tmp', cmd_def.cmds())
        self.assertEqual(cmd_def.cmd_qubits('tmp'), [(0,), (1,)])
Exemplo n.º 21
0
    def test_delay_control_channel(self):
        """Test Delay on ControlChannel"""

        control_ch = self.two_qubit_device.controls[0]
        pulse = SamplePulse(np.full(10, 0.1))
        # should pass as is an append
        sched = self.delay(control_ch) + pulse(control_ch)
        self.assertIsInstance(sched, Schedule)
        # should fail due to overlap
        with self.assertRaises(PulseError):
            sched = self.delay(control_ch) | pulse(control_ch)
            self.assertIsInstance(sched, Schedule)
Exemplo n.º 22
0
    def test_sample_pulse(self):
        """Test pulse initialization."""
        n_samples = 100
        samples = np.linspace(0, 1., n_samples, dtype=np.complex128)
        name = 'test'
        sample_pulse = SamplePulse(samples, name=name)

        self.assertEqual(sample_pulse.samples.dtype, np.complex128)
        np.testing.assert_almost_equal(sample_pulse.samples, samples)

        self.assertEqual(sample_pulse.duration, n_samples)
        self.assertEqual(sample_pulse.name, name)
Exemplo n.º 23
0
    def test_delay_control_channel(self):
        """Test Delay on ControlChannel"""

        control_ch = self.config.control([0, 1])[0]
        pulse = SamplePulse(np.full(10, 0.1))
        # should pass as is an append
        sched = Delay(self.delay_time, control_ch) + Play(pulse, control_ch)
        self.assertIsInstance(sched, Schedule)
        # should fail due to overlap
        with self.assertRaises(PulseError):
            sched = Delay(self.delay_time, control_ch) | Play(pulse, control_ch)
            self.assertIsInstance(sched, Schedule)
Exemplo n.º 24
0
    def test_pulse_limits(self):
        """Test that limits of pulse norm of one are enforced properly."""

        # test norm is correct for complex128 numpy data
        unit_pulse_c128 = np.exp(1j * 2 * np.pi * np.linspace(0, 1, 1000),
                                 dtype=np.complex128)
        # test does not raise error
        try:
            SamplePulse(unit_pulse_c128)
        except PulseError:
            self.fail(
                'SamplePulse incorrectly failed on approximately unit norm samples.'
            )

        invalid_const = 1.1
        with self.assertRaises(PulseError):
            SamplePulse(invalid_const *
                        np.exp(1j * 2 * np.pi * np.linspace(0, 1, 1000)))

        # Test case where data is converted to python types with complex as a list
        # with form [re, im] and back to a numpy array.
        # This is how the transport layer handles samples in the qobj so it is important
        # to test.
        unit_pulse_c64 = np.exp(1j * 2 * np.pi * np.linspace(0, 1, 1000),
                                dtype=np.complex64)
        sample_components = np.stack(
            np.transpose([np.real(unit_pulse_c64),
                          np.imag(unit_pulse_c64)]))
        pulse_list = sample_components.tolist()
        recombined_pulse = [
            sample[0] + sample[1] * 1j for sample in pulse_list
        ]

        # test does not raise error
        try:
            SamplePulse(recombined_pulse)
        except PulseError:
            self.fail(
                'SamplePulse incorrectly failed to approximately unit norm samples.'
            )
Exemplo n.º 25
0
    def test_gaussian_drive(self):
        """Test gaussian drive pulse using meas_level_2. Set omega_d0=omega_0 (drive on resonance),
        phi=0, omega_a = pi/time
        """

        # set omega_0, omega_d0 equal (use qubit frequency) -> drive on resonance
        total_samples = 100
        omega_0 = 1.
        omega_d = omega_0

        # Require omega_a*time = pi to implement pi pulse (x gate)
        # num of samples gives time
        r = np.pi / total_samples

        # Test gaussian drive results for a few different sigma
        gauss_sigmas = [total_samples / 6, total_samples / 3, total_samples]

        system_model = self._system_model_1Q(omega_0, r)

        for gauss_sigma in gauss_sigmas:
            with self.subTest(gauss_sigma=gauss_sigma):
                times = 1.0 * np.arange(total_samples)
                gaussian_samples = np.exp(-times**2 / 2 / gauss_sigma**2)
                drive_pulse = SamplePulse(gaussian_samples, name='drive_pulse')

                # construct schedule
                schedule = Schedule()
                schedule |= Play(drive_pulse, DriveChannel(0))
                schedule |= Acquire(1, AcquireChannel(0), MemorySlot(0)) << schedule.duration

                qobj = assemble([schedule],
                                backend=self.backend_sim,
                                meas_level=2,
                                meas_return='single',
                                meas_map=[[0]],
                                qubit_lo_freq=[omega_d],
                                memory_slots=2,
                                shots=1)
                y0 = np.array([1., 0.])
                backend_options = {'seed' : 9000, 'initial_state' : y0}

                result = self.backend_sim.run(qobj, system_model, backend_options).result()
                pulse_sim_yf = result.get_statevector()

                # run independent simulation
                yf = simulate_1q_model(y0, omega_0, r, np.array([omega_d]), gaussian_samples, 1.)

                # Check fidelity of statevectors
                self.assertGreaterEqual(state_fidelity(pulse_sim_yf, yf), 1-(10**-5))
Exemplo n.º 26
0
 def test_delay_drive_channel(self):
     """Test Delay on DriveChannel"""
     drive_ch = self.config.drive(0)
     pulse = SamplePulse(np.full(10, 0.1))
     # should pass as is an append
     sched = Delay(self.delay_time, drive_ch) + Play(pulse, drive_ch)
     self.assertIsInstance(sched, Schedule)
     pulse_instr = sched.instructions[-1]
     # assert last instruction is pulse
     self.assertIsInstance(pulse_instr[1], Play)
     # assert pulse is scheduled at time 10
     self.assertEqual(pulse_instr[0], 10)
     # should fail due to overlap
     with self.assertRaises(PulseError):
         sched = Delay(self.delay_time, drive_ch) | Play(pulse, drive_ch)
Exemplo n.º 27
0
    def test_add(self):
        """Test add, and that errors are raised when expected."""
        sched = Schedule()
        sched.append(SamplePulse(np.ones(5))(DriveChannel(0)))
        inst_map = InstructionScheduleMap()

        inst_map.add('u1', 1, sched)
        inst_map.add('u1', 0, sched)

        self.assertIn('u1', inst_map.instructions)
        self.assertEqual(inst_map.qubits_with_instruction('u1'), [0, 1])
        self.assertTrue('u1' in inst_map.qubit_instructions(0))

        with self.assertRaises(PulseError):
            inst_map.add('u1', (), sched)
        with self.assertRaises(PulseError):
            inst_map.add('u1', 1, "not a schedule")
Exemplo n.º 28
0
    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
Exemplo n.º 29
0
    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
Exemplo n.º 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=[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