IQCALIBRATIONNEW.py 69.6 KB
Newer Older
User expired's avatar
User expired committed
1
2
3
4
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep  2 16:28:12 2017
User expired's avatar
User expired committed
5

User expired's avatar
User expired committed
6
7
@author: Oscar,Moritz

8
9
10
11
v1.2.0 - OSC:
    - the correction is applied by the AWG class
    - renamed apply_corr to apply_correction

User expired's avatar
User expired committed
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
v1.1.1 - OSC:
    - improved the calibration routine for speedup and quality

v1.1.0 - MOR:
    - added documentation for all classes and functions
    - improved the calibration procedure for the offset, phase and ratio
    - added new functionality to the measure_SB() function: you can now measure
      whatever sideband you wnat
    - added functionality to measure the signal for a grid of offset values
    - added function to initialize the entire calibration
    - added function to run the entire calibration

v1.0.1 - OSC:
    - added compatibility with SignalHound spectrum analyzer
    - added a lower edge of -95 dBm to stop the automation

v1.0.0 - OSC:
    - LIbrary used to perform the calibration of an IQ mixer
"""


import numpy as np
import time
import matplotlib.pyplot as plt
from UtilitiesLib import progressive_plot_2d


39
40
print('IQCalAM ver: 1.2.0')

User expired's avatar
User expired committed
41
class CalibrationParameters(object):
42
    version = '1.2.0'
User expired's avatar
User expired committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
    
    
    def __init__(self, offI = 0., offQ = 0., amp_ratio = 1., amp_channel = 0, phase_corr = 0.):
        """
        This object contains the calibration parameters of an IQ mixer.
        
        It is possible to initialize the parameters when initializing the 
        object or do it later with the proper functions.
        
        Parameters
        ----------
        offI : float, optional
            The offset at the I entry of the IQ mixer (default: 0.). The value
            is given in (V).
        offQ : float, optional
            The offset at the Q entry of the IQ mixer (default: 0.). The value
            is given in (V).
        amp_ratio: float, optional
            The ratio between the amplitudes of the signals in I and Q 
            (default: 1.). 
        amp_channel : int, optional
            The channel of the input signal (default: 1).
        phase_corr : float, optional
            The phase correction between the two input signals (default: 0.). 
            The value is given in degrees and always divided by 360°. It is 
            applied to the signal in channel Q.
        
        """
        
        self.set_cal_parameters(offI, offQ, amp_ratio, amp_channel, phase_corr)
        self.__MAXF = 12                                                        #GHz
        self.__MINF = 3                                                         #GHz
        self.__frequency = None
        self.__AWG_freq = None
        self.__AWG_chI = 0
        self.__AWG_chQ = 1
        self.__SB = None
        self.__LSB = None
        self.__carrier = None
        self.__RSB = None
    

    def set_cal_parameters(self, offI = 0., offQ = 0., amp_ratio = 1., amp_channel = 0, phase_corr = 0.):
        """
        Set the calibration parameters to specific values.
    
        Parameters
        ----------
        offI : float, optional
            The offset at the I entry of the IQ mixer (default: 0.). The value
            is given in (V).
        offQ : float, optional
            The offset at the Q entry of the IQ mixer (default: 0.). The value
            is given in (V).
        amp_ratio: float, optional
            The ratio between the amplitudes of the signals in I and Q 
            (default: 1.). 
        amp_channel : int, optional
            The channel of the input signal (default: 1).
        phase_corr : float, optional
            The phase correction between the two input signals (default: 0.). 
            The value is given in degrees and always divided by 360°. It is 
            applied to the signal in channel Q.
    
        Returns
        -------
        nothing: None
            This function sets the internal values of the class to the values
            given to the parameters.
    
        See Also
        --------
        __init__()
    
    
        Notes
        -----
        If no values whatsoever are given, then the function simply initializes
        all the parameters to the default values specified in Parameters.
        All the input values are rounded according to the function np.round(). 
        This is done to avoid infinite internal representations of certain 
        numbers.
    
        """
       
        self.offI = np.round(offI, 12)
        self.offQ = np.round(offQ, 12)
        self.amp_ratio = np.round(amp_ratio, 12)
        self.amp_channel = int(amp_channel)
        self.phase_corr = np.round(phase_corr % 360, 12)
    
    
    #----------------------------------------------------------------------------------------------------------------------------Output functions, delete at end-------------------
    def LSB(self):
        return self.__LSB
    
    def carrier(self):
        return self.__carrier
    
    def RSB(self):
        return self.__RSB
    
    def AWG_freq(self):
        return self.__AWG_freq


    #--------------------------------------------------------------------------

    def cal_par_list(self):
        """
        Return the parameters of the calibration in a tuple.
    
        Parameters
        ----------
        none
    
        Returns
        -------
        tuple: tuple
            The return value is a tuple containing all the values of the 
            parameters set by the function set_cal_parameters().
            
            (offI, offQ, amp_ratio, amp_channel, phase_corr)
    
        See Also
        --------
        set_cal_parameters()
    
        """
        
        return self.offI, self.offQ, self.amp_ratio, self.amp_channel, self.phase_corr
    
        
    #--------------------------------------------------------------------------
    
    def frequency(self, frequency = None, SB = 'R'):
        """
        Query or set the up-mixed frequency. It is possible to specify the 
        sideband that is calibrated.
    
        Parameters
        ----------
        frequency : float, optional
            The calibrated frequency (default: None). The value is given in 
            (GHz).
        SB : string, optional
            Defines which sideband is used for the calibration (default: 'R').
            The used convention is:
            'R' or 'r':         right
            'L' or 'l':         left
    
        Returns
        -------
        Tuple: tuple
            This function returns the frequency and the sideband in a tuple:
            
            (frequency, SB)
    
    
        Notes
        -----
        The frequency has to be an element of a certain range: [3, 12].
    
        """
        
        # If no values are given, return the current values.
        if frequency is None:
            return self.__frequency, self.__SB
        
        # Ensure that the frequency is positive.
        frequency = abs(frequency)
        
        # Check that the frequency is inside given bounds.
        if frequency < self.__MINF:
            print('Warning: very low frequency, is it correct?')
            raise Exception('LOWFREQ')
        
        if frequency > self.__MAXF:
            print('Warning: high frequency, is it correct?')
            raise Exception('HIGHFREQ')
        
        # Define the sideband for the calibration.
        if SB.upper() == 'R':
            self.__SB = 'RSB'
        elif SB.upper() == 'L':
            self.__SB = 'LSB'
        else:
            print('ERROR: wrong sideband specified')
            raise Exception('SBERR')
        
        # Set the new value for the frequency.
        self.__frequency = np.round(frequency, 12)
        return self.__frequency, self.__SB
    

    
    #--------------------------------------------------------------------------    
    
    def AWG_parameters(self, AWG_freq = None, chI = 0, chQ = 1):
        """
        Set or return the AWG parameters.
    
        Parameters
        ----------
        AWG_freq : float, optional
            The frequency of the AWG (default: None). The value is given in 
            (MHz)
        chI : int, optional
            The channel of the AWG connected to the I port (default: 0).
        chQ : int, optional
            The channel of the AWG connected to the Q port (default: 1).
    
        Returns
        -------
        Tuple: tuple
            This function returns the frequency and the channels of the AWG in 
            a tuple:
            
            (AWG_freq, chI, chQ)
    
        Notes
        -----
        The value for the AWG frequency is entered and returned in MHz. 
        Internally it is saved in GHz.
    
        """
        
        # Check if you want to set or return values.
        if AWG_freq is None:
            if self.__AWG_freq is None:
                return None, self.__AWG_chI, self.__AWG_chQ
            return self.__AWG_freq*1e3, self.__AWG_chI, self.__AWG_chQ
        
        # Check that the frequency is positive.
        if AWG_freq < 0:
            print('Error: frequency is negative')
            raise Exception('NEGVAL')
        
        # Check that the frequency doesn't get too high.
        if AWG_freq > 450.:
            print('WARNING: frequency is high, is it correct?')
        
        # Set the values.
        self.__AWG_freq = np.round(AWG_freq*1e-3, 12)
        self.__AWG_chI = int(chI)
        self.__AWG_chQ = int(chQ)
        
        return self.__AWG_freq*1e3, self.__AWG_chI, self.__AWG_chQ
        
    
    #--------------------------------------------------------------------------    
    
    def Sidebands(self):
        """
        Calculate and set the frequencies for the sidebands of the calibration.
    
        Parameters
        ----------
        none
    
        Returns
        -------
        Tuple: tuple
            This function returns the frequencies in the sidebands a tuple:
            
            (LSB_freq, carrier_freq, RSB_freq)
    
        Notes
        -----
        First it is checked if a value for the frequency and the AWG frequency
        have been entered. Otherwise the calculation would fail. The 
        frequencies are calculated based on which sideband is being calibrated.
    
        """
        
        # Check if initial setup is done.
        if self.__frequency is None or self.__AWG_freq is None:
            print('Setup not complete')
            return 0, 0, 0
        else:
            # Calculate the frequencies of the sidebands.
            AWG_freq = self.__AWG_freq
            if self.__SB == 'RSB':
                self.__LSB, self.__carrier, self.__RSB = np.round_([self.__frequency - 2*AWG_freq, 
                                                                    self.__frequency - AWG_freq, 
                                                                    self.__frequency], 
                                                                    9)
                return self.__LSB, self.__carrier, self.__RSB
            elif self.__SB == 'LSB':
                self.__LSB, self.__carrier, self.__RSB = np.round_([self.__frequency, 
                                                                    self.__frequency + AWG_freq, 
                                                                    self.__frequency + 2*AWG_freq], 
                                                                    9)
                return self.__LSB, self.__carrier, self.__RSB
            else:
                print('Sideband not yet specified!')
                raise Exception('SBERR')
    

    #--------------------------------------------------------------------------

    def print_parameters(self):
        """
        Print all the parameters that have already been initialized.
    
        Parameters
        ----------
        none
    
        Returns
        -------
        nothing: None
    
        Notes
        -----
        Depending on the setup, a different amount of parameters is printed.
        The output looks always at least like:
        
        offI: {}V
        offQ: {}V
        amp_ratio: {}
        amp_channel: {}
        phase_corr: {} deg
        
        If the AWG has been initialized the following is added:
        AWG_frequency: {} MHz
        chI: {}
        chQ: {}
        
        If the sidebands have been initialized the following is added:
        LSB: {} GHz
        LO: {} GHz
        RSB: {} GHz
        calibrated for: {}
    
        """
        
        text = '\noffI: {}V\noffQ: {}V\namp_ratio: {}\namp_channel: {}\nphase_corr: {} deg\n'.format(self.offI,self.offQ,self.amp_ratio,self.amp_channel,self.phase_corr)
        text2, text3 = '', ''
        
        if self.__AWG_freq is not None:
            text2 = 'AWG_frequency: {} MHz\nchI: {}\nchQ: {}\n'.format(*self.AWG_parameters())
        if self.__frequency is not None:
            text3 = 'LSB: {} GHz\nLO: {} GHz\nRSB: {} GHz\ncalibrated for: {}\n'.format(*self.Sidebands(),self.__SB)
            
        print(text + text2 + text3)
    
    
    #--------------------------------------------------------------------------    
    
    def save(self, fname, Force = False):
        """
        Save the calibration into a file.
    
        Parameters
        ----------
        fname : string
            The path and filename for where to save the file.
        Force : bool, optional
            Defines if an already existing file should be overwritten 
            (default: False).
    
        Returns
        -------
        nothing : None
    
        Notes
        -----
        First it is checked if a value for the frequency and the AWG frequency
        have been entered. Otherwise the calibration is not yet completed. Then
        the folder is search and created if needed. The file extension is then 
        set to '*.cal'. If a file with the given name already exists in this 
        directory and the parameter Force is True, then the existing file is
        overwritten.
    
        """
        
        import os
        import pickle
        
        if self.__frequency is None or self.__AWG_freq is None:
            print('Calibration not complete, impossible to save!\n')
            raise Exception('CALERR')
        
        
        #Split fname in folder and filename
        folder = os.path.split(fname)[0]
        file_name = os.path.split(fname)[1]

        #Create directory if not already existent
        if not os.path.exists(folder) and folder:
            os.makedirs(folder)

        # Check for file extension
        if file_name[-4:].lower() != '.cal':
            file_name += '.cal'

        # Append Folder and be adaptive to windows, etc.
        file_name = os.path.normpath(os.path.join(folder, file_name))

        # Check for Overwrite
        if not Force:
            if os.path.isfile(file_name):
                print('File already exists!\n')
                raise Exception('FILEEXISTSERR')
        
        with open(file_name, "wb") as f:
            pickle.dump(self, f, -1)


    #--------------------------------------------------------------------------

    def copy(self):
        """
        Copy this object.
    
        Parameters
        ----------
        none
    
        Returns
        -------
        nothing : None
    
        Notes
        -----
        Creates a deep copy of the given object.
    
        """
        
        import copy
        return copy.deepcopy(self)
 
##------------------------------------------------------------------------------------------------------------------------------


def load_calibration_file(filename):
    """
    Load a saved calibration from a given file.

    Parameters
    ----------
    filename : string
        The path and filename for the saved file.

    Returns
    -------
    nothing : None

    Notes
    -----
    The function checks if the given filename does exist before attempting to
    load the saved calibration.

    """
    
    import pickle,os
    
    if not os.path.exists(filename):
502
        print('Wrong path or file does not exist.\n: {}\n\n'.format(filename))
User expired's avatar
User expired committed
503
504
505
506
507
508
509
510
        raise Exception('FILEEXISTSERR')
    
    with open(filename, 'rb') as f:
        return pickle.load(f)


##-------------------------------------------------------------------------------------------------------------------------------
class IQCalAM(object):
511
    version = '1.2.0'
User expired's avatar
User expired committed
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
    
    
    #----------------------------------------------------------------------------------------------------------------------------Initialization of the Class-----------------------
    
    def __init__(self, AWG, sgLOIP, sgLOch, SpecAna = 'SH', AWG_channel_cal_amplitude = 1., cal_file = None):
        """
        This object contains the calibration parameters of an IQAM.
        
        It is possible to initialize the parameters when initializing the 
        object or do it later with the proper functions.
        
        Parameters
        ----------
        AWG : object
            The AWG object providing the interaction with the AWG in use.
        sgLOIP : string
            The IP adress for the LO written in a string.
        sgLOch : int
            The channel of the LO used for the experiment.
        SpecAna : string, optional
            The spectrum analyzer used for the experiment (default: 'SH'). The 
            two options are:
            'SH':               Signal Hound
            'RS':               Rohde Schwarz
        AWG_channel_cal_amplitude : float, optional
            The amplitude for the AWG signal given in (V) (default: 1.).
        cal_file : string, optional
            The filepath to a saved calibration file (default: None).
        
        Notes
        -----
        If a calibration file is used, all the other parameters still have to 
        be initialized. Only the parameters of the CalibrationParameters class 
        are initialized.
        
        """
        
        if SpecAna.upper() == 'RS':
            from SPECAN import Specan
            self._SpecAna = Specan()  
        elif SpecAna.upper()=='SH':
            from SIGNALHOUND import SignalHound
            self._SpecAna = SignalHound()
        else:
            print('Wrong spectrum analyzer specified')
            raise Exception('SpecAnaERR')
        
        self._SpecAnaType = SpecAna.upper()
        self._AWG = AWG
        self._sgLOIP = sgLOIP
        self._sgLOch = sgLOch
        self._amplitude = AWG_channel_cal_amplitude                             # Amplitude of the AWG
        self.__cal_tol = 0.3                                                    #dB
        
        if cal_file is not None:
            self.calibration = load_calibration_file(cal_file)
        else:
            self.calibration = CalibrationParameters()
    
    
    
    #----------------------------------------------------------------------------------------------------------------------------Initialization of the instruments-----------------
    
    def set_AWG(self, AWG_freq, chI = 0, chQ = 1):
        """
        Set the values of the AWG using the methods provided from the 
        CalibrationParameters class.
    
        Parameters
        ----------
        AWG_freq : float
            The frequency for the AWG.
        chI : int, optional
            The channel for the I signal (default: 0).
        chQ : int, optional
            The channel for the Q signal (default: 1).
    
        Returns
        -------
        nothing : None
    
        """
        
        self.calibration.AWG_parameters(AWG_freq, chI, chQ)
        


    #--------------------------------------------------------------------------
    
    def set_frequency(self, frequency, SB = 'R'):
        """
        Set the up-mixed frequency for the experiment. It is possible to 
        specify the sideband that is calibrated.
    
        Parameters
        ----------
        frequency : float
            The calibrated frequency for the experiment. The value is given in 
            (GHz).
        SB : string, optional
            Defines which sideband is used for the calibration (default: 'R').
            The used convention is:
            'R' or 'r':         right
            'L' or 'l':         left
    
        Returns
        -------
        nothing: None
    
        """
        
        self.calibration.frequency(frequency, SB)



    #--------------------------------------------------------------------------
    
629
    def apply_correction(self):
User expired's avatar
User expired committed
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
        """
        Apply the values determined by the calibration to the AWG.
    
        Parameters
        ----------
        none : None
    
        Returns
        -------
        nothing: None
    
        """

        
        freq, chI, chQ = self.calibration.AWG_parameters()
        offI, offQ, amp_ratio, amp_channel, phase_corr = self.calibration.cal_par_list()
        
647
648
        self._AWG.mode(chI,'sin')
        self._AWG.mode(chQ,'sin')
User expired's avatar
User expired committed
649
        
650
        self._AWG.apply_correction(self.calibration,self._amplitude)
User expired's avatar
User expired committed
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729


    #--------------------------------------------------------------------------
    
    def set_LO(self, power = 13, channel = 1):
        """
        Apply the values determined by the calibration to the LO.
    
        Parameters
        ----------
        power : float, optional
            The power provided by the LO (default: 13). The value is given in 
            (dbm).
        channel : int, optional
            The channel of the LO (default: 1).
    
        Returns
        -------
        nothing: None
    
        """
        
        from SIGGEN import Siggen
        
        # Parameters
        LOfreq = self.calibration.Sidebands()[1]
        
        # LO setup
        sgLO = Siggen(self._sgLOIP)
        sgLO.pulse_triggered(0, 0, 0)
        sgLO.ALC('ON')
        sgLO.power(power, channel)
        sgLO.frequency(LOfreq, channel)
        sgLO.frequency_reference('EXT')
        sgLO.output(1, channel)
        sgLO.close()
        del sgLO


 
    #--------------------------------------------------------------------------
    
    def initialize_calibration(self, AWG_pulse, SB = 'R', *LO_para):
        """
        Initializes all the parameters for the calibration of the experiment. 
        
        Parameters
        ----------
        AWG_pulse : list: [awg_freq,awg_chI,awg_chQ]
            This list contains all the parameters for the calibration of the 
            I/Q mixer.
        SB : string, optional
            Defines which sideband is used for the calibration (default: 'R').
            The used convention is:
            'R' or 'r':         right
            'L' or 'l':         left
        LO_parameters : array, optional
            This array contains the parameters for the LO: [power,channel]
            power:              default to 13 dbm
            channel:            default to 1
        
        Returns
        -------
        nothing: None
        
        Notes
        -----
        If values for the LO are given, the first one is always used for the 
        power and the second one for the channel. It is possible to give zero, 
        one or two values for those parameters. Depending on the number of the 
        given values, the default values are used.
        
        """
        
        self.set_AWG(AWG_pulse.par['awg_freq'], 
                     AWG_pulse.par['awg_chan1'], 
                     AWG_pulse.par['awg_chan2'])
        self.set_frequency(AWG_pulse.frequency(), 
                           SB)
730
        self.apply_correction()
User expired's avatar
User expired committed
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
        
        if len(LO_para) == 0:
            power = 13
            channel = 1
        elif len(LO_para) == 1:
            power = LO_para[0]
            channel = 1
        else:
            power = LO_para[0]
            channel = LO_para[1]
        
        self.set_LO(power, channel)



    #----------------------------------------------------------------------------------------------------------------------------Measurement of the Sidebands----------------------
    
    def measure_SB(self, plot = False, print_diff = False, bands = 'ALL', *args):
        """
        Measure the power in the sidebands. 
        
        Parameters
        ----------
        plot : bool, optional
            This defines if the measured power should be plotted by one of two
            engines (default: False).
        print_diff : bool, optional
            This defines if the difference in power between the two sidebands 
            is to be printed (default: False).
        bands : string, optional
            This string sets which sidebands are to be measured (default: ALL):
            'ALL':              Measure all three peaks
            'R' or 'r':         Measure only the right sideband
            'C' or 'c':         Measure only the carrier
            'L' or 'l':         Measure only the left sideband
        *args : array, optional
            This array contains the parameters for the spectrum analyzer:
            averages:           default to 50
            peak_span:          default to 5 MHz
            Only the 'RS' spectrum analyzer can use both values. The 
            Signalhound only uses the peak_span variable.
        
        Returns
        -------
        Tuple: tuple
            The return value of this function is a tuple that always contains 
            three values, depending on which bands were measured:
            'ALL':              (max left peak, max center peak, max right peak)
            'R' or 'r':         (0, 0, max right peak)
            'C' or 'c':         (0, max center peak, 0)
            'L' or 'l':         (max left peak, 0, 0)
        
        Notes
        -----
        The parameter bands is only useful if the Signalhound is used. The 'RS'
        spectrum analyzer always measures the entire width of the sidebands.
        
        """
        
        if len(args) == 0:
            ave = 50
            peak_span = 5
        elif len(args) == 1:
            ave = args[0]
            peak_span = 5
        else:
            ave = args[0]
            peak_span = args[1]
        
        if self._SpecAnaType == 'RS':
            left, middle, right = self.__measure_SB_RS(ave, peak_span, plot)
        else:
            left, middle, right = self.__measure_SB_SH(peak_span, plot, bands)
        
        if print_diff:
            print("The difference between the sidebands is {0:.5f} dB".format(abs(right - left)))
        
        return left, middle, right
    

    def __measure_SB_SH(self, peak_span, plot, bands):
        """
        This function measures the power in the sidebands using a SignalHound. 
        It can be chosen which sideband is measured.
        
        """
        
        peak_span /= 1e3        
        
        # Set up the Spectrum Analyzer
        self._SpecAna.default_settings()
        self._SpecAna.Reference()
        self._SpecAna.ConfigLevel(-30)
        self._SpecAna.BandWidth(100e3)                                          # in Hz
        
        # Set the variables
        LSB = self.calibration.LSB()
        Carrier = self.calibration.carrier()
        RSB = self.calibration.RSB()
        
        #------------------------------------------------------        
        
        if bands == 'ALL':
            #Measure left Sideband
            self._SpecAna.CenterSpan(LSB, peak_span)
            self._SpecAna.Initiate()
            measL = self._SpecAna.GetSweep()
        
            #------------------------------------------------------
    
            #Measure Carrier
            self._SpecAna.CenterSpan(Carrier, peak_span)
            self._SpecAna.Initiate()
            measC = self._SpecAna.GetSweep()
            
            #------------------------------------------------------
    
            #Measure right Sideband
            self._SpecAna.CenterSpan(RSB, peak_span)
            self._SpecAna.Initiate()
            measR = self._SpecAna.GetSweep()
            
            #------------------------------------------------------
            if plot is True:
                measL.plot(engine = 'p')
                measC.plot(engine = 'p')
                measR.plot(engine = 'p')
                
                plt.xlim([measL.x[0] - peak_span, measR.x[-1] + peak_span])
                
                min_y = np.min((measL.y.min(), measC.y.min(), measR.y.min(), ))
                max_y = np.max((measL.y.max(), measC.y.max(), measR.y.max(), ))
                
                plt.ylim([min_y, max_y + 2])
            
            #------------------------------------------------------       
        
            #return data
            return measL.y.max(), measC.y.max(), measR.y.max()
            
        elif bands.upper() == 'L':
            #Measure left Sideband
            self._SpecAna.CenterSpan(LSB, peak_span)
            self._SpecAna.Initiate()
            measL = self._SpecAna.GetSweep()
            
            #------------------------------------------------------
            if plot is True:
                measL.plot(engine = 'p')
                
                plt.xlim([measL.x[0] - peak_span, measL.x[-1] + peak_span])
                
                min_y = measL.y.min()
                max_y = measL.y.max()
                
                plt.ylim([min_y, max_y + 2])
            
            #------------------------------------------------------       
        
            #return data
            return measL.y.max(), 0, 0
                
        elif bands.upper() == 'C':
            #Measure Carrier
            self._SpecAna.CenterSpan(Carrier, peak_span)
            self._SpecAna.Initiate()
            measC = self._SpecAna.GetSweep()
            
            #------------------------------------------------------
            if plot is True:
                measC.plot(engine = 'p')
                
                plt.xlim([measC.x[0] - peak_span, measC.x[-1] + peak_span])
                
                min_y = measC.y.min()
                max_y = measC.y.max()
                
                plt.ylim([min_y, max_y + 2])
            
            #------------------------------------------------------       
        
            #return data
            return 0, measC.y.max(), 0
            
        elif bands.upper() == 'R':
            #Measure right Sideband
            self._SpecAna.CenterSpan(RSB, peak_span)
            self._SpecAna.Initiate()
            measR = self._SpecAna.GetSweep()
            
            #------------------------------------------------------
            if plot is True:
                measR.plot(engine = 'p')
                
                plt.xlim([measR.x[0] - peak_span, measR.x[-1] + peak_span])
                
                min_y = measR.y.min()
                max_y = measR.y.max()
                
                plt.ylim([min_y, max_y + 2])
            
            #------------------------------------------------------       
        
            #return data
            return 0, 0, measR.y.max()
            
            

        





    def __measure_SB_RS(self, ave, peaks_span, plot):
        """
        This function measures the power in the sidebands using the Rohde Schwarz
        spectrum analyzer.
        
        """
        
        import DataModule as dm
        import time
        
        # Set the variables
        peaks_span /= 1e3                                                       #MHz -> GHz
        LSB = self.calibration.LSB()
        carrier = self.calibration.carrier()
        RSB = self.calibration.RSB()
        AWG_freq = self.calibration.AWG_parameters()[0]
        
        # Initialize the spectrum analyzer
        self._SpecAna.Center(carrier)
        self._SpecAna.Span(2.5*AWG_freq)
        self._SpecAna.Averages(1, ave)
        self._SpecAna.Single()
        
    
        
        # Start the spectrum analyzer
        self._SpecAna.Run()
        time.sleep(0.001)
        while self._SpecAna.Count() < ave:
            time.sleep(0.0001)
        
        # Completing the measurement
        x, y = self._SpecAna.Read()
978
        tmp = dm.data_table([x/1e9, y], ['Frequency (GHz)', 'PSD (dB)'])
User expired's avatar
User expired committed
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
        
        # Obtain the data for the LSB, carrier and RSB
        tmp.select([LSB - peaks_span, LSB + peaks_span])
        left = tmp.return_ysel().max()
        
        tmp.select([carrier - peaks_span, carrier + peaks_span])
        center = tmp.return_ysel().max()
        
        tmp.select([RSB - peaks_span, RSB + peaks_span])
        right = tmp.return_ysel().max()
        
        # Plot the measurement if necessary
        if plot is True:
            tmp.select()
            tmp.plot(engine = 'p')
        
        return left, center, right


    
    #----------------------------------------------------------------------------------------------------------------------------Calibration of the setup--------------------------
    
For faster browsing, not all history is shown. View entire blame