Repository navigation
Expand file tree
/
Copy pathRigolInterface.py
More file actions
1757 lines (1540 loc) · 75.8 KB
/
Copy pathRigolInterface.py
File metadata and controls
1757 lines (1540 loc) · 75.8 KB
1
2
3
4
5
6
7
8
9
10
11
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
39
40
41
42
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
502
503
504
505
506
507
508
509
510
511
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
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
730
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
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
from time import sleep, time
import warnings
from tqdm.auto import tqdm
# Directory containing GenericDevice must be in path
# Add parent directory of current file to path
parent_directory = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, parent_directory)
# Add also directory two levels up
sys.path.insert(0, os.path.dirname(parent_directory))
from GenericDevice import _GenericDevice
plt.ioff()
def set_time_unit(times):
"""Determine most appropriate SI prefix for time.
Return unit and rescaled time axis.
Args:
times (array-like): time values
Returns:
array-like, str: rescaled axis, new SI unit
"""
times = times.copy() # the input list or array is mutable
if (times[-1] < 1e-3):
times *= 1e6
tUnit = "µs"
elif (times[-1] < 1):
times *= 1e3
tUnit = "ms"
else:
tUnit = "s"
return times, tUnit
def set_freq_unit(freqs):
"""Determine most appropriate SI prefix for frequency.
Return unit and rescaled frequency axis.
Args:
freqs (array-like): frequency values
Returns:
array-like, str: rescaled axis, new SI unit
"""
freqs = freqs.copy() # the input list or array is mutable
if (freqs[-1] >= 1e9):
freqs *= 1e-9
fUnit = "GHz"
elif (freqs[-1] >= 1e6):
freqs *= 1e-6
fUnit = "MHz"
elif (freqs[-1] >= 1e3):
freqs *= 1e-3
fUnit = "kHz"
else:
fUnit = "Hz"
return freqs, fUnit
class _Preamble:
def __init__(self, s):
elems = s.split(',')
self.elems = elems
self.points = int(elems[2])
self.count = int(elems[3])
self.x_inc = float(elems[4])
self.x_orig = float(elems[5])
self.x_ref = float(elems[6])
self.y_inc = float(elems[7])
self.y_orig = int(elems[8])
self.y_ref = int(elems[9])
def normalize(self, raw_y):
yvals = raw_y.astype(np.float64)
yvals -= (self.y_orig + self.y_ref)
yvals *= self.y_inc
return yvals
def x_values(self):
xvals = np.linspace(0, self.points-1, self.points)
xvals *= self.x_inc
xvals += self.x_ref
# xvals += self.x_orig
return xvals
class Scope(_GenericDevice):
def get_waveform_raw(self, channels: list = [1], memdepth: str | int = None,
single = False, plot: bool = False, ndivs: int = None,
start: int = 1, stop: int = None,
barrier = None) -> np.ndarray:
"""
Gets the entire waveform data in the internal memory for a selection of channels
(!) To retrieve long timescale waveforms, enable single trigger mode
:param list channels: List of channels
:param float memdepth: Memory depth (number of points), specify as integer
(see device manual for possible values) or "AUTO",
defaults to None (does not modify)
:param boolean single: Use single trigger mode
:param bool plot: Will plot the traces
:param int ndivs: DEPRECATED, now set by query to oscilloscope.
:param int start: Set start position of waveform data reading, defaults to 1.
:param int stop: Set stop position of waveform data reading,
included in interval, defaults to maximum memory depth.
:param <multiprocessing.Barrier> barrier (optional): Useful for
synchronizing multiple processes (measurements)
:returns: Data, Time np.ndarrays containing the traces of shape
(channels, nbr of points) if len(channels)>1
"""
no_channels = len(channels)
if len(channels) > 4:
print("ERROR : Invalid channel list provided" +
" (List too long)")
sys.exit()
# Print message indicating from which channels waveforms are being retrieved
if no_channels == 1: message = f'{self.short_name} | Getting raw waveform from'
else: message = f'{self.short_name} | Getting raw waveforms from'
for chan in channels:
if chan > 4:
print("ERROR : Invalid channel list provided" +
" (Channels are 1,2,3,4)")
sys.exit()
if no_channels==2 and chan == channels[-1]:
message+= f' and Channel {chan}'
elif no_channels>2:
if chan != channels[-1]:
message+= f' Channel {chan},'
if chan == channels[-1]:
message+= f' and Channel {chan}'
else:
message+= f' Channel {chan}'
print(message)
Data = []
Time = []
trig_status = self.resource.query(':TRIGger:STATus?')
# Set memory depth if specified
if memdepth is not None:
prev_memdepth = self.get_mdepth()
if prev_memdepth != memdepth:
if trig_status == "STOP\n":
# Memory depth cannot be set while oscilloscope is in STOP state
self.resource.query(':RUN;*OPC?')
if memdepth == 'AUTO':
self.resource.query(f":ACQuire:MDEPth {memdepth};*OPC?")
else:
self.resource.query(f":ACQuire:MDEPth {int(memdepth)};*OPC?")
# Get memory depth
memory_depth = self.get_mdepth()
# Measure waveform, afterwards scope must be in STOP state to read from internal memory
if single:
if barrier is not None:
barrier.wait()
self.resource.write(":SINGle")
print(f'{self.short_name} | Waiting for trigger as of {time()} s')
else:
self.resource.write(":SINGle")
if trig_status.replace('\n','') == "STOP":
# Wait for trig status to change from "STOP" before while loop
sleep(1)
while self.resource.query(':TRIGger:STATus?').replace('\n','') != 'STOP':
sleep(0.1)
print(f"{self.short_name} | Waveform complete as of {time()} s")
else:
self.resource.write(":STOP")
# Transfer data from scope
for chan in channels:
self.resource.write(f":WAV:SOUR CHAN{chan}")
# Y origin for wav data
YORigin = self.resource.query_ascii_values(":WAV:YOR?")[0]
# Y REF for wav data
YREFerence = self.resource.query_ascii_values(":WAV:YREF?")[0]
# Y INC for wav data
YINCrement = self.resource.query_ascii_values(":WAV:YINC?")[0]
# X REF for wav data
XREFerence = self.resource.query_ascii_values(":WAV:XREF?")[0]
# X INC for wav data
XINCrement = self.resource.query_ascii_values(":WAV:XINC?")[0]
# Set the waveform reading mode to RAW.
self.resource.write(":WAV:MODE RAW")
# Set return format to Byte.
self.resource.write(":WAV:FORM BYTE")
# Set start position of waveform data reading
self.resource.write(f":WAV:STAR {int(start)}")
if stop is None:
stop = memory_depth
n_points = stop - start + 1 #+1 because both endpoints are included
if (n_points > 250000):
# Read 250000 points at a time, provide completion updates
loopmax = int(np.ceil(n_points/250000))
rawdata = []
for loopcount in range(0, loopmax):
iteration_start = (loopcount*250000) + start
# iteration_stop is included in interval, hence -1
iteration_stop = min(iteration_start + 250000 - 1, stop)
self.resource.write(f":WAV:STAR {iteration_start}")
self.resource.write(f":WAV:STOP {iteration_stop}")
sys.stdout.write(f"\rReading {iteration_stop - start + 1}/{n_points}")
# Extent the rawdata variables with the new values.
rawdata.extend(self.resource.query_binary_values(":WAV:DATA?",
datatype='B'))
else:
# Read whole waveform in one go
self.resource.write(f":WAV:STOP {int(stop)}")
# Read data from the resource, excluding the first 9 bytes
# (TMC header).
sys.stdout.write(f"\rReading {n_points}/{n_points}")
rawdata = self.resource.query_binary_values(":WAV:DATA?",
datatype='B')
data = (np.asarray(rawdata) - YORigin - YREFerence) * YINCrement
Data.append(data)
# Create time axis
times = np.linspace(XREFerence, XINCrement*len(data), len(data))
Time.append(times)
if plot:
# Assumes waveforms all have same time axis
fig, ax = plt.subplots()
times_rescaled, tUnit = set_time_unit(Time[0])
[ax.plot(times_rescaled, Data[n], label = f"Channel {chan}") for n, chan in enumerate(channels)]
ax.set_ylabel("Voltage (V)")
ax.set_xlabel("Time (" + tUnit + ")")
ax.set_xlim(times_rescaled[0], times_rescaled[-1])
ax.legend()
plt.show()
self.resource.write(":RUN")
Data = np.asarray(Data)
Time = np.asarray(Time)
if len(channels) == 1:
Data = Data[0, :]
Time = Time[0, :]
return Time, Data
def get_wf_fromtrig(self, timespan,
channels: list = [1], memdepth: str | int = None,
single = False, plot: bool = False, ndivs: int = None,) -> np.ndarray:
"""Get the raw waveform from oscilloscope for a specified time duration
starting from the trigger.
Args:
timespan (float): duration of retrieved waveform.
See get_waveform_raw for info on other parameters.
Returns:
np.ndarray, np.ndarray : Data, Time arrays of shape
(channels, nbr of points) if len(channels)>1
"""
# Determine index of trigger for raw waveform
XORigin = self.resource.query_ascii_values(":WAV:XOR?")[0]
XINCrement = self.resource.query_ascii_values(":WAV:XINC?")[0]
trig_index = int(abs(XORigin)/XINCrement)
# Determine index of final point to retrieve
n_points = int(timespan / XINCrement)
endpoint = trig_index + n_points - 1 #-1 because endpoint is retrieved
# Call get_waveform_raw
return self.get_waveform_raw(channels = channels,
memdepth = memdepth,
single = single,
plot = plot,
ndivs = ndivs,
start = trig_index,
stop = endpoint)
def get_waveform(self, channels: list = [1], memdepth: str | int = None,
single = False, plot: bool = False,
ndivs: int = None, barrier = None) -> np.ndarray:
"""Retrieves the displayed waveform.
Gets the waveform data in the internal memory for the time interval displayed on screen.
From the displayed time scale and the sampling rate, will compute how many
points of the memory correspond to the displayed signal.
It will then retrieve the displayed signal (the part delimited by the
shaded area on top of the screen).
See the :WAVeform Commands documentation for futher details.
(!) To retrieve long timescale waveforms, enable single trigger mode, and
beware of VISA timeout if transferring large number of data points.
(timeout issue can be resolved by reducing memory depth).
Args:
channels (list, optional): List of channels. Defaults to [1].
memdepth (float, optional): Memory depth (number of points), specify
as integer (see device manual for possible values) or "AUTO",
defaults to None (does not modify)
single (boolean, optional): Use single trigger mode
plot (bool, optional): Whether to plot the result. Defaults to False.
ndivs (int, optional): DEPRECATED, now set by query to oscilloscope.
barrier (<multiprocessing.Barrier>, optional): Useful for
synchronizing multiple processes (measurements)
Returns:
np.ndarray: Data, Time
"""
no_channels = len(channels)
if len(channels) > 4:
print("ERROR : Invalid channel list provided" +
" (List too long)")
sys.exit()
# Print message indicating from which channels waveforms are being retrieved
if no_channels == 1: message = f'{self.short_name} | Getting waveform from'
else: message = f'{self.short_name} | Getting waveforms from'
for chan in channels:
if chan > 4:
print("ERROR : Invalid channel list provided" +
" (Channels are 1,2,3,4)")
sys.exit()
if no_channels==2 and chan == channels[-1]:
message+= f' and Channel {chan}'
elif no_channels>2:
if chan != channels[-1]:
message+= f' Channel {chan},'
if chan == channels[-1]:
message+= f' and Channel {chan}'
else:
message+= f' Channel {chan}'
print(message)
Data = []
Time = []
trig_status = self.resource.query(':TRIGger:STATus?')
# Set memory depth if specified
if memdepth is not None:
prev_memdepth = self.get_mdepth()
if prev_memdepth != memdepth:
if trig_status == "STOP\n":
# Memory depth cannot be set while oscilloscope is in STOP state
self.resource.query(':RUN;*OPC?')
if memdepth == 'AUTO':
self.resource.query(f":ACQuire:MDEPth {memdepth};*OPC?")
else:
self.resource.query(f":ACQuire:MDEPth {int(memdepth)};*OPC?")
# ndivs is number of horizontal grids on the screen
ndivs = self.get_ndivs()
# get horizontal timebase
time_scale = self.get_xscale()
# get sample rate
sample_rate = self.get_srate()
# Get memory depth
memory_depth = self.get_mdepth()
# Exit before measurement if data transfer from scope will be unsuccessful
x_inc = 1/sample_rate
screen_points = np.floor(time_scale/x_inc)*ndivs
if screen_points > 250000:
sys.exit("ERROR: The number of waveform data points exceeds the" +
" maximum number which can be read from the oscilloscope at" +
" a single time (see manual).\nEither reduce memory depth" +
" or use <Scope>.get_waveform_raw().")
# Measure waveform, afterwards scope must be in STOP state to read from internal memory
if single:
if barrier is not None:
barrier.wait()
self.resource.write(":SINGle")
print(f'{self.short_name} | Waiting for trigger as of {time()} s')
else:
self.resource.write(":SINGle")
if trig_status == "STOP\n":
# Wait for trig status to change from "STOP" before while loop
sleep(1)
while self.resource.query(':TRIGger:STATus?').replace('\n','') != 'STOP':
sleep(0.1)
print(f"{self.short_name} | Waveform complete as of {time()} s")
else:
self.resource.write(":STOP")
# Transfer data from scope
for chan in channels:
self.resource.write(f':WAV:SOUR CHAN{chan}')
self.resource.write(':WAV:MODE RAW')
self.resource.write(':WAV:FORM BYTE')
self.resource.query('*OPC?')
preamble = _Preamble(self.resource.query(':WAV:PRE?'))
# we look for the middle of the memory and take what's displayed
# on the screen
self.resource.write(
f"WAV:STAR {memory_depth//2 - screen_points//2+1}")
self.resource.write(
f"WAV:STOP {memory_depth//2 + screen_points//2}")
print(f'{self.short_name} | Transferring {int(screen_points)} data points from Channel {chan}')
data = self.resource.query_binary_values(':WAV:DATA?', datatype='B',
container=np.array,
delay=0.5,
data_points=screen_points)
data = preamble.normalize(data)
times = np.arange(0, np.round(len(data)*preamble.x_inc, 9), preamble.x_inc)
Data.append(data)
Time.append(times)
if plot:
# Assumes waveforms all have same time axis
fig, ax = plt.subplots()
times_rescaled, tUnit = set_time_unit(Time[0])
[ax.plot(times_rescaled, Data[n], label = f"Channel {chan}") for n, chan in enumerate(channels)]
ax.set_ylabel("Voltage (V)")
ax.set_xlabel("Time (" + tUnit + ")")
ax.set_xlim(times_rescaled[0], times_rescaled[-1])
ax.legend()
plt.show()
self.resource.write(":RUN")
return np.asarray(Time), np.asarray(Data)
def get_waveform_screen(self, channels: list = [1], plot: bool = False) -> np.ndarray:
"""Gets the waveform data currently displayed on the screen.
Unlike reading waveform data from the internal memory, the oscilloscope does not need to be put into STOP state.
Args:
channels (list, optional): List of channels. Defaults to [1].
plot (bool, optional): Whether to plot the result. Defaults to False.
Returns:
np.ndarray: Data, Time
"""
Data = []
Time = []
for chan in channels:
# Set the channel source of waveform data
self.resource.write(f':WAVeform:SOURce CHANnel{chan}')
# Set the waveform data reading mode to NORMal
self.resource.write(':WAVeform:MODE NORMal')
# Set the return format of waveform data to BYTE
self.resource.write(':WAVeform:FORMat BYTE')
# Query and return ten different waveform parameters, see manual
# Required to convert retrieved waveform data into time and volts below
preamble = _Preamble(self.resource.query(':WAVeform:PREamble?'))
# Obtain data from the buffer
data = self.resource.query_binary_values(':WAVeform:DATA?', datatype='B',
container=np.array,
delay=0.5)
data = preamble.normalize(data)
times = np.arange(0, np.round(len(data)*preamble.x_inc, 9), preamble.x_inc)
Data.append(data)
Time.append(times)
if plot:
# Assumes waveforms all have same time axis
fig, ax = plt.subplots()
times_rescaled, tUnit = set_time_unit(Time[0])
[ax.plot(times_rescaled, Data[n], label = f"Channel {chan}") for n, chan in enumerate(channels)]
ax.set_ylabel("Voltage (V)")
ax.set_xlabel("Time (" + tUnit + ")")
ax.set_xlim(times_rescaled[0], times_rescaled[-1])
ax.legend()
plt.show()
return np.asarray(Time), np.asarray(Data)
def get_mdepth(self):
mdepth = self.resource.query(":ACQuire:MDEPth?").strip()
try:
mdepth = int(float(mdepth))
except Exception: # query can return "AUTO"
if mdepth == 'AUTO':
self.resource.write(":WAVeform:MODE RAW")
mdepth = int(float(self.resource.query(":WAVeform:STOP?").strip()))
return mdepth
def get_srate(self):
"""Query the current sample rate. The default unit is Sa/s.
Returns:
float: sampling rate
"""
srate = float(self.resource.query(":ACQuire:SRATe?"))
return srate
def get_xinc(self):
"""Queries the time interval between two neighboring points of the currently selected
channel source in the X direction.
Returns:
float: time [s]
"""
return self.resource.query_ascii_values(":WAV:XINC?")[0]
def get_xscale(self):
"""Queries the scale of the main time base.
Returns:
float: time/div [s/div]
"""
return float(self.resource.query_ascii_values(":TIMebase:SCALe?")[0])
def set_yscale(self, scale:float, channels : list = [1]):
for chan in channels:
self.resource.write(f":CHAN{chan}:SCAL {scale}")
def get_yscale(self, channels: list = [1]):
for chan in channels:
return self.resource.query_ascii_values(f":CHAN{chan}:SCAL?")[0]
def get_trig_position(self):
"""Queries the offset of the main time base (ie. the trigger position).
When the waveform trigger point is at the left (right) side of the screen center,
the horizontal position is a positive (negative) value.
Returns:
float: time [s]
"""
return self.resource.query_ascii_values("TIMebase:OFFSet?")[0]
def get_ndivs(self):
# get number of horizontal grids on the screen,
# ndivs is fixed for each instrument
return int(self.resource.query_ascii_values(":SYSTem:GAM?")[0])
def get_dur_scr(self):
"""Return duration of waveform displayed on the screen
Returns:
float: waveform length [s]
"""
# Get duration of displayed waveform
# obtained by multiplying the horizontal
# time base by the number of grids in the horizontal direction.
time_scale = self.get_xscale()
ndivs = self.get_ndivs()
return time_scale * ndivs
def get_dur_raw(self, onscreen = False):
"""Return duration of waveform in internal memory
Returns:
float: waveform length [s]
"""
return self.get_mdepth() / self.get_srate()
def get_screenshot(self, filename: str = None, format: str = 'png'):
"""
Recovers a screenshot of the screen and returns the image
:param filename: Location where the image will be saved
:param format: Image format in ['jpg', 'png', 'tiff','bmp8', 'bmp24']
"""
assert format in ('jpeg', 'png', 'bmp8', 'bmp24', 'tiff')
self.resource.timeout = 60000
self.resource.write(':disp:data? on,off,%s' % format)
raw_img = self.resource.read()
self.resource.timeout = 25000
img = np.asarray(raw_img).reshape((600, 1024))
if filename:
try:
os.remove(filename)
except OSError:
pass
with open(filename, 'wb') as fs:
fs.write(raw_img)
return img
def close(self):
self.resource.write(":RUN")
self.resource.close()
self.rm.close()
class SpectrumAnalyzer(_GenericDevice):
def zero_span(self, center: float = 1e6, rbw: int = 100,
vbw: int = 30, swt: float = 'auto',
trig: bool = None, single = False,
plot: bool = False):
"""Zero span measurement.
(!) For long sweep times, use single sweep mode
:param float center: Center frequency in Hz, converted to int
:param float rbw: Resolution bandwidth
:param float vbw: Video bandwidth
:param float swt: Total measurement time. Except if set to 'auto'
:param bool trig: External trigger
:param bool single: Set True for single sweep mode,
defaults to False for continuous sweep mode
:param bool plot: option to plot
:return: data, time for data and time
:rtype: np.ndarray
"""
self.resource.write(':FREQuency:SPAN 0')
self.resource.write(f':FREQuency:CENTer {center}')
self.resource.write(f':BANDwidth:RESolution {int(rbw)}')
self.resource.write(f':BANDwidth:VIDeo {int(vbw)}')
if swt != 'auto':
self.resource.write(f':SENSe:SWEep:TIME {swt}') # in s.
else:
self.resource.write(':SENSe:SWEep:TIME:AUTO ON')
self.resource.write(
':DISPlay:WINdow:TRACe:Y:SCALe:SPACing LOGarithmic')
if trig is not None:
trigstate = self.resource.query(':TRIGger:SEQuence:SOURce?').replace('\n','')
istrigged = trigstate != 'IMM' # whether SA is initially triggered
# If trigger true and initial trigger type IMMediate, then set to EXTernal
if trig and not (istrigged):
self.resource.write(':TRIGger:SEQuence:SOURce EXTernal')
self.resource.write(
':TRIGger:SEQuence:EXTernal:SLOPe POSitive')
# If trigger false and initial trigger type not IMMediate, set to IMMediate
elif not (trig) and istrigged:
self.resource.write(':TRIGger:SEQuence:SOURce IMMediate')
set_trigstate = self.resource.query(':TRIGger:SEQuence:SOURce?').replace('\n','')
# Query current instrument sweep state
sweep_state = int(self.resource.query(':INITiate:CONTinuous?'))
if single == False:
if sweep_state == 1:
# Already in continuous
pass
elif sweep_state == 0:
# Put into continous
self.resource.write(':INITiate:CONTinuous 1')
triginfo_msg = ' with trigger' if set_trigstate == 'EXT' else ''
print(f'{self.short_name} | Getting zero span scan (continuous sweep mode' +
triginfo_msg + ')')
elif single == True:
# In following conditional blocks, *OPC command (operation complete)
# is sent subsequent to command intializing scan so that operation
# complete status can be polled (must wait for scan completion).
self.resource.write('*CLS') # Reset status registers, clear error queue
if sweep_state == 1:
# Put into single
self.resource.write(':INITiate:CONTinuous 0')
self.resource.write(':INITiate:IMMediate; *OPC')
elif sweep_state == 0:
if trig is None or trig == False:
self.resource.write(':INITiate:IMMediate; *OPC')
elif trig == True:
# Must reset trigger just before initiating scan, otherwise
# it seems trigger success condition is stored, because scan
# starts immediately instead of waiting for next trigger
self.resource.write(':TRIGger:SEQuence:SOURce EXTernal')
self.resource.write(':INITiate:IMMediate; *OPC')
triginfo_msg = ' on trigger' if set_trigstate == 'EXT' else ''
print(f'{self.short_name} | Getting zero span scan (single sweep' +
triginfo_msg + ')')
# Poll the operation complete status in the event status
# register (ESR). (Once all commands before *OPC have been executed,
# the operation complete bit in the ESR is set to 1)
while int(self.resource.query('*ESR?')) != 1:
sleep(0.1)
self.resource.write(':FORMat:TRACe:DATA ASCii')
data = self.query_data()
# If SA was trigged before, put it back in the same state
if trig is not None:
if not (trig) and istrigged:
self.resource.write(f":TRIGger:SEQuence:SOURce {trigstate}")
# Put SA back into the state it started in
if sweep_state != int(self.resource.query(':INITiate:CONTinuous?')):
self.resource.write(f':INITiate:CONTinuous {int(sweep_state)}')
sweeptime = float(self.resource.query(':SWEep:TIME?'))
times = np.linspace(0, sweeptime, len(data))
if plot:
fig, ax = plt.subplots()
times_rescaled, tUnit = set_time_unit(times)
ax.plot(times_rescaled, data)
ax.set_xlabel(f'Time ({tUnit})')
ax.set_ylabel('Noise Power (dBm)')
plt.show()
return data, times
def span(self, center: float = 22.5e6, span: float = 45e6, rbw: int = 100,
vbw: int = 30, swt: float = 'auto', trig: bool = None, single = False,
plot: bool = False):
"""Configure and execute measurement of noise power spectrum
(!) For long sweep times, use single sweep mode
:param float center: Center frequency in Hz
:param float span: span
:param float rbw: Resolution bandwidth
:param float vbw: Video bandwidth
:param float swt: Total measurement time
:param bool trig: External trigger
:param bool single: Set True for single sweep mode,
defaults to False for continuous sweep mode
:param bool plot: option to plot
:return: data, freqs for data and frequencies
:rtype: np.ndarray
"""
self.resource.write(f':FREQuency:SPAN {span}')
self.resource.write(f':FREQuency:CENTer {center}')
self.resource.write(f':BANDwidth:RESolution {int(rbw)}')
self.resource.write(f':BANDwidth:VIDeo {int(vbw)}')
if swt != 'auto':
self.resource.write(f':SENSe:SWEep:TIME {swt}') # in s.
else:
self.resource.write(':SENSe:SWEep:TIME:AUTO ON')
self.resource.write(
':DISPlay:WINdow:TRACe:Y:SCALe:SPACing LOGarithmic')
self.resource.query('*OPC?')
if trig is not None:
trigstate = self.resource.query(':TRIGger:SEQuence:SOURce?').replace('\n','')
istrigged = trigstate != 'IMM' # whether SA is initially triggered
# If trigger true and initial trigger type IMMediate, then set to EXTernal
if trig and not (istrigged):
self.resource.write(':TRIGger:SEQuence:SOURce EXTernal')
self.resource.write(
':TRIGger:SEQuence:EXTernal:SLOPe POSitive')
# If trigger false and initial trigger type not IMMediate, set to IMMediate
elif not (trig) and istrigged:
self.resource.write(':TRIGger:SEQuence:SOURce IMMediate')
self.resource.query('*OPC?')
set_trigstate = self.resource.query(':TRIGger:SEQuence:SOURce?').replace('\n','')
# Query current instrument sweep state
sweep_state = int(self.resource.query(':INITiate:CONTinuous?'))
if single == False:
if sweep_state == 1:
# Already in continuous
pass
elif sweep_state == 0:
# Put into continous
self.resource.write(':INITiate:CONTinuous 1')
triginfo_msg = ' with trigger' if set_trigstate == 'EXT' else ''
print(f'{self.short_name} | Getting power spectrum (continuous sweep mode' +
triginfo_msg + ')')
elif single == True:
# In following conditional blocks, *OPC command (operation complete)
# is sent subsequent to command intializing scan so that operation
# complete status can be polled (must wait for scan completion).
self.resource.write('*CLS') # Reset status registers, clear error queue
if sweep_state == 1:
# Put into single
self.resource.write(':INITiate:CONTinuous 0')
self.resource.write(':INITiate:IMMediate; *OPC')
elif sweep_state == 0:
if trig is None or trig == False:
self.resource.write(':INITiate:IMMediate; *OPC')
elif trig == True:
# Must reset trigger just before initiating scan, otherwise
# it seems trigger success condition is stored, because scan
# starts immediately instead of waiting for next trigger
self.resource.write(':TRIGger:SEQuence:SOURce EXTernal')
self.resource.write(':INITiate:IMMediate; *OPC')
triginfo_msg = ' on trigger' if set_trigstate == 'EXT' else ''
print(f'{self.short_name} | Getting power spectrum (single sweep' +
triginfo_msg + ')')
# Poll the operation complete status in the event status
# register (ESR). (Once all commands before *OPC have been executed,
# the operation complete bit in the ESR is set to 1)
while int(self.resource.query('*ESR?')) != 1:
sleep(0.1)
self.resource.write(':FORMat:TRACe:DATA ASCii')
data = self.query_data()
# If SA was trigged before, put it back in the same state
if trig is not None:
if not (trig) and istrigged:
self.resource.write(f":TRIGger:SEQuence:SOURce {trigstate}")
# Put SA back into the state it started in
if sweep_state != int(self.resource.query(':INITiate:CONTinuous?')):
self.resource.write(f':INITiate:CONTinuous {int(sweep_state)}')
freqs = np.linspace(center-span//2, center+span//2, len(data))
if plot:
fig, ax = plt.subplots()
freq_rescaled, fUnit = set_freq_unit(freqs)
ax.plot(freq_rescaled, data)
ax.set_xlabel(f'Frequency ({fUnit})')
ax.set_ylabel('Noise Power (dBm)')
plt.show()
return data, freqs
def query_data(self):
"""Lower level function to grab the data from the SpecAnalyzer
:return: data
:rtype: list
"""
rawdata = self.resource.query(':TRACe? TRACE1')
data = rawdata.split(', ')[1:]
data = [float(i) for i in data]
return np.asarray(data)
### BANDwidth Subsection
@property
def rbw(self):
"""Resolution bandwidth
"""
return float(self.resource.query(":SENSe:BANDwidth:RESolution?").strip())
@rbw.setter
def rbw(self, value):
self.resource.write(f":SENSe:BANDwidth:RESolution {value}")
@property
def vbw(self):
"""Video bandwidth
"""
return float(self.resource.query(":SENSe:BANDwidth:VIDeo?").strip())
@vbw.setter
def vbw(self, value):
self.resource.write(f":SENSe:BANDwidth:VIDeo {value}")
### FREQuency Subsection
@property
def center(self):
"""Center frequency
"""
return float(self.resource.query(":SENSe:FREQuency:CENTer?").strip())
@center.setter
def center(self, value):
self.resource.write(f":SENSe:FREQuency:CENTer {value}")
@property
def span(self):
"""Frequency span
"""
return float(self.resource.query(":SENSe:FREQuency:SPAN?").strip())
@span.setter
def span(self, value):
self.resource.write(f":SENSe:FREQuency:SPAN {value}")
class ArbitraryFG(_GenericDevice):
def get_waveform(self, output: int = 1, amp_unit: int = False) -> list:
"""
Gets the waveform type as well as its specs
:param int output: Description of parameter `output`.
:param int amp_unit: If true, amp is returned as tuple with its unit, eg. Vrms
Otherwise, BY DEFAULT amplitude returned as Vpp
:return: List containing all the parameters
:rtype: list
"""
if output not in [1, 2]:
print("ERROR : Invalid output specified")
return None
ison = self.resource.query(f"OUTPut{output}?")[:-1] == "ON"
if amp_unit == False:
# Before querying waveform parameters, need to change amplitude unit
# to Vpp. Otherwise, value is returned for whatever unit user specified
curr_amp_unit = self.resource.query(f"SOURce{output}:VOLT:UNIT?").replace('\n','')
self.resource.write(f"SOURce{output}:VOLT:UNIT VPP")
ret = self.resource.query(f"SOURce{output}:APPLy?")
ret = ret[1:-2].split(",")
for i in range(len(ret)):
try:
ret[i] = float(ret[i])
except ValueError: # When generating noise, phase and freq are undefined
pass
type = ret[0]
freq = ret[1]
amp = ret[2]
offset = ret[3]
phase = ret[4]
if amp_unit == True:
unit = self.resource.query(f"SOURce{output}:VOLT:UNIT?").replace('\n','')
amp = (amp, unit)
else:
# Change amplitude unit back to whatever user had set
self.resource.write(f"SOURce{output}:VOLT:UNIT {curr_amp_unit}")
return [ison, type, freq, amp, offset, phase]
def turn_on(self, output: int = 1):
"""
Turns on an output channel on the last preset
:param int output: Output channel
:return: None
"""
self.resource.write(f"OUTPut{output} ON")
def turn_off(self, output: int = 1):
"""
Turns off an output channel on the last preset
:param int output: Output channel
:return: None
"""
self.resource.write(f"OUTPut{output} OFF")
def set_impedance(self, output: int = 1, load: str = 'INF'):
"""
Sets the output impedance to specified value. It doesn't actually
change the physical impendance of the instrument, but changes the
displayed voltage to match the actual voltage on the device under test.
:param int output: Output channel
:param str load: specified impedance value. {<ohms>|INFinity|MINimum|MAXimum}
:return: None
"""
if output not in [1, 2]:
print("ERROR : Invalid output specified")
return None
self.resource.write(f':OUTP{output}:IMP ' + load)
print(f'Impedance OUTP{output} set to :', self.resource.query(f':OUTP{output}:IMP?'))
def get_impedance(self, output: int = 1):
"""Queries the output impedance of the specified channel(s).
If no channel is specified, returns output impedance for Channel 1
Args:
output (int or list of int, optional): Channel. Defaults to 1.
Returns:
float or list of float: impedances
"""
if type(output) is list:
output_impedance=[]
for ch in output:
ch_impedance = float(self.resource.query(f':OUTP{ch}:IMP?'))
output_impedance.append(ch_impedance)
elif type(output) is int:
output_impedance = float(self.resource.query(f':OUTP{output}:IMP?'))
return output_impedance
def set_voltage_unit(self, output: int = 1, unit: str = 'VPP'):
"""
Sets the amplitude unit of the specified channel to
Vpp (VPP), Vrms (VRMS), or dBm (DBM)
:param int output: Output channel
:param str unit: amplitude unit
:return: None
"""
self.resource.write(f":SOURce{output}:VOLTage:UNIT {unit}")
def get_voltage_unit(self, output: int = 1):
"""
Returns the amplitude unit of the specified channel
:param int output: Output channel
:return: amplitude unit
"""
unit = self.resource.query(f":SOURce{output}:VOLTage:UNIT?")
return unit.replace('\n','')
def dc_offset(self, output: int = 1, offset: float = 2.0):
"""
Applies a constant voltage on the specified output
:param int output: Output channel
:param float offset: Voltage applied in Volts
:return: None
"""
if output not in [1, 2]:
print("ERROR : Invalid output specified")
return None
self.resource.write(f":SOURce{output}:FUNCtion DC")
self.resource.write(f":SOURce{output}:APPLy:USER 1, 1, {offset}, 0")
self.turn_on(output)
def sine(self, output: int = 1, freq: float = 100.0, ampl: float = 2.0,
offset: float = 0.0, phase: float = 0.0):
"""
Sets a sine wave on specified output
:param int output: Output channel
:param float freq: Frequency of the signa in Hz
:param float ampl: Amplitude of the wave in Volts
:param float offset: Voltage offset in Volts
:param float phase: Signal phase in degree
:return: None
"""
if output not in [1, 2]:
print("ERROR : Invalid output specified")
return None
self.resource.write(f":SOURce{output}:APPLy:SINusoid {freq}, {ampl}, " +
f"{offset}, {phase}")
self.turn_on(output)
def square(self, output: int = 1, freq: float = 100.0, ampl: float = 2.0,
offset: float = 0.0, phase: float = 0.0, duty: float = 50.0):
"""
Sets a square wave on specified output
:param int output: Output channel
:param float freq: Frequency of the signa in Hz
:param float ampl: Amplitude of the wave in Volts
:param float offset: Voltage offset in Volts
:param float phase: Signal phase in degree
:param float duty: Duty cycle in percent
:return: None
"""
if output not in [1, 2]:
print("ERROR : Invalid output specified")
return None
self.resource.write(f":SOURce{output}:APPLy:SQUare {freq}, {ampl}, " +
f"{offset}, {phase}")
self.resource.write(f":SOURce{output}:FUNCtion:SQUare:DCYCle {duty}")
self.turn_on(output)
def ramp(self, output: int = 1, freq: float = 100.0, ampl: float = 2.0,
offset: float = 0.0, phase: float = 0.0, symm: float = 50.0):
"""
Sets a triangular wave on specified output
:param int output: Output channel
:param float freq: Frequency of the signa in Hz
:param float ampl: Amplitude of the wave in Volts
:param float offset: Voltage offset in Volts
:param float phase: Signal phase in degree