From 147c9107230aaa88888b70f39f4c9de25cc35809 Mon Sep 17 00:00:00 2001
From: sldesnoo-Delft <s.l.desnoo@tudelft.nl>
Date: Mon, 8 May 2023 17:36:21 +0200
Subject: [PATCH] Improved alignment of phase shifts on Qblox

---
 pulse_lib/qblox/pulsar_sequencers.py  | 11 ++++++---
 pulse_lib/tests/test_iq/test_phase.py | 33 +++++++++++++++++++++++++--
 2 files changed, 39 insertions(+), 5 deletions(-)

diff --git a/pulse_lib/qblox/pulsar_sequencers.py b/pulse_lib/qblox/pulsar_sequencers.py
index 86c17ec0..fa338d22 100644
--- a/pulse_lib/qblox/pulsar_sequencers.py
+++ b/pulse_lib/qblox/pulsar_sequencers.py
@@ -535,11 +535,16 @@ class IQSequenceBuilder(SequenceBuilderBase):
         Arguments:
             phase (float): phase in rad.
         '''
-        t = PulsarConfig.floor(t+self.offset_ns)
-        self._update_time_and_markers(t, 0.0)
+        # The phase shift can be before or after MW pulse.
+        # First try to align towards lower t
+        t_phase = PulsarConfig.floor(t + self.offset_ns)
+        if t_phase < self.t_end:
+            # Align towards higher t.
+            t_phase = PulsarConfig.ceil(t + self.offset_ns)
+        self._update_time_and_markers(t_phase, 0.0)
         # normalize phase to -1.0 .. + 1.0 for Q1Pulse sequencer
         norm_phase = (phase/np.pi + 1) % 2 - 1
-        self.seq.shift_phase(norm_phase, t_offset=t)
+        self.seq.shift_phase(norm_phase, t_offset=t_phase)
 
     def chirp(self, t_start, t_end, amplitude, start_frequency, stop_frequency):
         # set NCO frequency if valid. Otherwise set 0.0 to enable modulation
diff --git a/pulse_lib/tests/test_iq/test_phase.py b/pulse_lib/tests/test_iq/test_phase.py
index 0af3ea2c..c1565d5c 100644
--- a/pulse_lib/tests/test_iq/test_phase.py
+++ b/pulse_lib/tests/test_iq/test_phase.py
@@ -4,7 +4,7 @@ from pulse_lib.tests.configurations.test_configuration import context
 #%%
 from numpy import pi
 
-def test():
+def test1():
     pulse = context.init_pulselib(n_qubits=1)
 
     s = pulse.mk_segment()
@@ -29,5 +29,34 @@ def test():
 
     return None
 
+def test2():
+    # not aligned pulses
+    pulse = context.init_pulselib(n_qubits=1)
+
+    s = pulse.mk_segment()
+
+    s.q1.add_MW_pulse(0, 10, 100, 2.450e9)
+    s.q1.add_phase_shift(10, pi/2)
+    s.q1.add_phase_shift(10, pi/2)
+    s.q1.add_MW_pulse(12, 30, 100, 2.450e9)
+    s.q1.add_phase_shift(40, pi)
+    s.reset_time()
+    s.q1.add_phase_shift(0, -pi/2)
+    s.q1.add_MW_pulse(2, 10, 100, 2.450e9)
+    s.q1.add_phase_shift(18, pi/2)
+    s.q1.add_MW_pulse(20, 40, 100, 2.450e9)
+
+    context.plot_segments([s])
+
+    sequence = pulse.mk_sequence([s])
+    sequence.n_rep = 1
+    context.add_hw_schedule(sequence)
+    context.plot_awgs(sequence)
+
+    return None
+
+#%%
+
 if __name__ == '__main__':
-    ds = test()
+    ds1 = test1()
+    ds2 = test2()
-- 
GitLab