-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathZVL13_VNA.py
562 lines (435 loc) · 20.9 KB
/
ZVL13_VNA.py
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
from typing import Any
import logging
from functools import partial
from typing import Optional
from qcodes.utils.validators import Enum, Strings
from qcodes import VisaInstrument, Instrument
from qcodes.utils import validators as vals
import numpy as np
from qcodes import MultiParameter, ArrayParameter
log = logging.getLogger(__name__)
class FrequencySweepMagPhase(MultiParameter):
def __init__(self, name: str, instrument: Instrument,
start: float, stop: float, npts: int, channel:int) -> None:
super().__init__(name, names=("", ""), shapes=((), ()))
self._instrument = instrument
self.set_sweep(start, stop, npts)
self._channel = channel
self.names = ('magnitude',
'phase')
self.labels = (f'{instrument.short_name} magnitude',
f'{instrument.short_name} phase')
self.units = ('', 'rad')
self.setpoint_units = (('Hz',), ('Hz',))
self.setpoint_labels = (
(f'{instrument.short_name} frequency',),
(f'{instrument.short_name} frequency',)
)
self.setpoint_names = (
(f'{instrument.short_name}_frequency',),
(f'{instrument.short_name}_frequency',)
)
def set_sweep(self, start: float, stop: float, npts: int) -> None:
f = tuple(np.linspace(int(start), int(stop), num=npts))
self.setpoints = ((f,), (f,))
self.shapes = ((npts,), (npts,))
def get_raw(self):
old_format = self._instrument.format()
self._instrument.format('Complex')
data = self._instrument._get_sweep_data(force_polar=True)
self._instrument.format(old_format)
return abs(data), np.angle(data)
class FrequencySweep(ArrayParameter):
def __init__(self, name: str, instrument: Instrument,
start: float, stop: float, npts: int, channel:int) -> None:
super().__init__(name, shape=(npts,),
instrument=instrument,
unit='dB',
label=f'{instrument.short_name} magnitude',
setpoint_units=('Hz',),
setpoint_labels=(f'{instrument.short_name}'
' frequency',),
setpoint_names=(f'{instrument.short_name}_frequency',)
)
self.set_sweep(start, stop, npts)
self._channel = channel
def set_sweep(self, start: float, stop: float, npts: int) -> None:
f = tuple(np.linspace(int(start), int(stop), num=npts))
self.setpoints = (f,)
self.shape = (npts,)
def get_raw(self):
data = self._instrument._get_sweep_data()
if self._instrument.format() in ['Polar', 'Complex',
'Smith', 'Inverse Smith']:
log.warning("QCoDeS Dataset does not currently support Complex "
"values. Will discard the imaginary part. In order to "
"acquire phase and amplitude use the "
"FrequencySweepMagPhase parameter.")
return data
class ComplexSweep(ArrayParameter):
def __init__(self, name: str, instrument: Instrument,
start: float, stop: float, npts: int, channel:int) -> None:
super().__init__(name, shape=(npts,),
instrument=instrument,
unit='dB',
label=f'{instrument.short_name} magnitude',
setpoint_units=('Hz',),
setpoint_labels=(f'{instrument.short_name}'
' frequency',),
setpoint_names=(f'{instrument.short_name}_frequency',)
)
self.set_sweep(start, stop, npts)
self._channel = channel
def set_sweep(self, start: float, stop: float, npts: int) -> None:
f = tuple(np.linspace(int(start), int(stop), num=2*npts))
self.setpoints = (f,)
self.shape = (2*npts,)
def get_raw(self):
data = self._instrument._get_sweep_data(force_polar=True)
if self._instrument.format() in ['Polar', 'Complex',
'Smith', 'Inverse Smith']:
log.warning("QCoDeS Dataset does not currently support Complex "
"values. Will discard the imaginary part. In order to "
"acquire phase and amplitude use the "
"FrequencySweepMagPhase parameter.")
return data
class SAFrequencySweep(ArrayParameter):
def __init__(self, name: str, instrument: Instrument,
start: float, stop: float, npts: int, channel:int) -> None:
super().__init__(name, shape=(npts,),
instrument=instrument,
unit='dBm',
label=f'{instrument.short_name} magnitude',
setpoint_units=('Hz',),
setpoint_labels=(f'{instrument.short_name}'
' frequency',),
setpoint_names=(f'{instrument.short_name}_frequency',)
)
self.set_sweep(start, stop, npts)
self._channel = channel
def set_sweep(self, start: float, stop: float, npts: int) -> None:
f = tuple(np.linspace(int(start), int(stop), num=npts))
self.setpoints = (f,)
self.shape = (npts,)
def get_raw(self):
data = self._instrument._get_sweep_data_SA()
return data
class ZVL(VisaInstrument):
def __init__(
self,
name: str,
address: str,
**kwargs: Any):
super().__init__(name, address, terminator='\n', **kwargs)
mode = (self.ask('INST?')).split('\n')[0]
if mode == 'SAN':
n = int(1)
self._tracename = 'Trc1'
if mode == 'NWA':
if len(self.ask("CONFigure:TRACe:CATalog?").split(',')) == 2:
ch , trace_name = self.ask("CONFigure:TRACe:CATalog?").split(',')
n = ch[1]
trace_name = trace_name[:-1]
else:
n = self.ask("CONFigure:TRACe:CATalog?").split(',')[0][1]
trace_name = self.ask("CONFigure:TRACe:CATalog?").split(',')[1]
self._tracename = trace_name
self.inf_lim = 9e+3
self.sup_lim = 13.6e+9
self.add_parameter('start',
get_cmd='FREQ:STAR?',
get_parser=float,
set_cmd=self._set_start,
unit = 'Hz',
label='Start Frequency')
self.add_parameter('stop',
get_cmd='FREQ:STOP?',
get_parser=float,
set_cmd=self._set_stop,
unit = 'Hz',
label='Stop Frequency')
self.add_parameter('center',
get_cmd='FREQ:CENT?',
get_parser=float,
set_cmd=self._set_center,
unit = 'Hz',
label='Center Frequency')
self.add_parameter('span',
get_cmd='FREQ:SPAN?',
get_parser=float,
set_cmd=self._set_span,
unit = 'Hz',
label='Center Frequency')
self.add_parameter('npts',
get_cmd='SWE:POIN?',
get_parser=int,
set_cmd=self._set_npts,
label='Number of points')
self.add_parameter('power',
get_cmd='SOUR:POW?',
get_parser=float,
set_cmd=self._set_power,
unit = 'dBm',
label='Power')
self.add_parameter('format',
vals=Strings(),
get_cmd=partial(self._get_format,
tracename=self._tracename),
set_cmd=self._form,
label='Format')
self.add_parameter('avg',
get_parser=int,
vals=vals.Ints(1, 5000),
get_cmd='AVER:COUN?',
set_cmd=self._average,
label='Averages')
self.add_parameter(name='num_ports',
get_cmd='INST:PORT:COUN?',
get_parser=int)
self.add_parameter(name='S_parameter',
label='S parameter',
get_cmd=f"CALC:PAR:MEAS? '{self._tracename}'",
set_cmd=self._set_s_parameter,
vals=Strings())
self.add_parameter(name='trace_mag_phase',
start=self.start(),
stop=self.stop(),
npts=self.npts(),
channel = n,
parameter_class=FrequencySweepMagPhase)
self.add_parameter(name='trace',
start=self.start(),
stop=self.stop(),
npts=self.npts(),
channel = n,
parameter_class=FrequencySweep)
self.add_parameter(name='S_trace',
start=self.start(),
stop=self.stop(),
npts=self.npts(),
channel = n,
parameter_class=ComplexSweep)
self.add_parameter(name='spectrum',
start=self.start(),
stop=self.stop(),
npts=self.npts(),
channel = n,
parameter_class=SAFrequencySweep)
self.add_parameter(name='status',
get_cmd='CONF:CHAN1:STAT?',
set_cmd='CONF:CHAN1:STAT {{}}',
get_parser=int)
self.add_parameter(name='rf_power',
get_cmd='OUTP?',
set_cmd=self._set_rf_power,
get_parser=int)
self.add_parameter(name='bandwidth',
label='Bandwidth',
unit='Hz',
get_cmd='SENS:BAND?',
set_cmd=self._set_bandwidth,
get_parser=int)
self.add_parameter(name='freq_step',
label='Frequency step size',
unit='Hz',
get_cmd='SENS:SWE:STEP?',
set_cmd=self._set_freq_step,
get_parser=int)
self.add_parameter(name='mode',
label='VNA Mode',
get_cmd='INST?',
set_cmd=self._set_mode,
get_parser=str)
self.add_function('na_mode', call_cmd = self._set_na_mode)
self.add_function('sa_mode', call_cmd= self._set_sa_mode)
self.add_function('reset',call_cmd = '*RST')
self.add_function('autoscale', call_cmd = 'DISP:WIND:TRAC:Y:AUTO ONCE')
self.add_function('calibration', call_cmd = "MMEMory:LOAD:CORRection 1, 'Cal_17_11_2021.cal'")
self.add_function('electrical_delay_auto',
call_cmd='CORR:EDEL:AUTO ONCE')
self.add_function('data_to_mem',
call_cmd='CALC:MATH:MEM')
self.add_function('cont_meas_on',
call_cmd='INIT:CONT:ALL ON')
self.add_function('cont_meas_off',
call_cmd='INIT:CONT:ALL OFF')
def _set_mode(self,mode:str):
if mode == 'sa':
self._set_sa_mode()
elif mode == 'na':
self._set_na_mode()
else:
raise AttributeError('Wrong string. To set in Spectrum Analyzer mode write "sa", to set in Network Analyzer mode write "na".')
def _set_sa_mode(self):
self.write('INST SAN')
n = int(1)
self._tracename = 'Trc1'
def _set_na_mode(self):
self.write('INST NWA')
if len(self.ask("CONFigure:TRACe:CATalog?").split(',')) == 2:
ch , trace_name = self.ask("CONFigure:TRACe:CATalog?").split(',')
n = ch[1]
trace_name = trace_name[:-1]
else:
n = self.ask("CONFigure:TRACe:CATalog?").split(',')[0][1]
trace_name = self.ask("CONFigure:TRACe:CATalog?").split(',')[1]
self._tracename = trace_name
def _set_freq_step(self, n:int):
min_step = (self.stop_f() - self.start_f())/(4001)
max_step = (self.stop_f() - self.start_f())/1
if n>min_step and n<max_step:
self.write("SENS:SWE:STEP " + str(n))
self.update_traces()
else:
raise AttributeError('Step size must be in the range between' + str(min_step) +' Hz and ' + str(max_step) + ' Hz.')
def _set_npts(self, n:int) -> None:
self.write("SWE:POIN " + str(n))
self.update_traces()
def _set_s_parameter(self, msg:str) -> None:
S_params = ['S11','S12','S21','S22']
if msg in S_params:
self.write(f"CALC:PAR:MEAS '{self._tracename}', '"+msg+"'")
else:
raise AttributeError('Illegal string. Allowed S parameters: S11, S12, S21, S22')
def _set_bandwidth(self, val:int) -> None:
if val <= 10e6 and val > 10:
self.write('SENS:BAND '+str(int(val)))
else:
raise AttributeError('Bandwidth value out of range')
def _set_rf_power(self, val: int) -> None:
if val == 0:
self.write('OUTP OFF')
elif val == 1:
self.write('OUTP ON')
else:
raise AttributeError('Write 1 to switch on and 0 to switch off')
def _get_format(self, tracename: str) -> str:
return self.ask("CALC:FORM?")
def _strip(var: str) -> str:
return var.rstrip()[1:-1]
def _form(self, msg:str) -> None:
if msg == 'phase':
self.write('CALC:FORM PHAS')
elif msg == 'dbm':
self.write('CALC:FORM MLOG')
elif msg == 'polar':
self.write('CALC:FORM POL')
elif msg == 'swr':
self.write('CALC:FORM SWR')
elif msg == 'magnitude':
self.write('CALC:FORM MLIN')
elif msg == 'real':
self.write('CALC:FORM REAL')
elif msg == 'img':
self.write('CALC:FORM IMAG')
elif msg == 'unwrapped phase':
self.write('CALC:FORM UPH')
elif msg == 'smith':
self.write('CALC:FORM SMIT')
elif msg == 'data/mem':
self.data_to_mem
self.write('CALC:MATH:FUNC DIV')
else:
raise AttributeError('Format does not exist. Choose one of the following: dbm, phase, polar, swr, magnitude, real, img, unwrapped phase, smith ')
def _average(self,num:float) -> None:
self.write('AVER:STAT OFF')
self.write('AVER:COUN ' + str(int(num)))
self.write('AVER:STAT ON')
self.write('AVER:CLE')
def _set_start(self, val: float):
start = val
stop = self.stop()
if start >= stop:
raise ValueError(
"Stop frequency must be larger than start frequency.")
else:
self.write('FREQ:STAR '+ str(int(start)))
self.update_traces()
def _set_stop(self, val: float):
stop = val
start = self.start()
if stop <= start:
raise ValueError(
"Stop frequency must be larger than start frequency.")
else:
self.write('FREQ:STOP '+ str(int(stop)))
self.update_traces()
def _set_center(self, val: float):
center = val
if center <= self.inf_lim or center >= self.sup_lim:
raise ValueError(
"Out of the VNA limit.")
else:
self.write('FREQ:CENT '+ str(int(center)))
self.update_traces()
def _set_span(self, val: float):
span = val
center = self.center()
if center + span * 0.5 >= self.sup_lim or center - span * 0.5 <= self.inf_lim:
raise ValueError(
"Out of the VNA limit.")
else:
self.write('FREQ:SPAN '+ str(int(span)))
self.update_traces()
def _set_power(self, val: float):
if val>0:
raise ValueError(
"Attenuation cannot be positive.")
elif val< -40:
raise ValueError(
"Unleveled power")
else:
self.write('SOUR:POW ' + str(int(val)))
def _get_sweep_data(self, force_polar: bool = False):
self.write('SENS:AVER:STAT ON')
self.write('SENS:AVER:CLE')
# preserve original state of the znb
with self.status.set_to(1):
self.root_instrument.cont_meas_off()
try:
if force_polar:
data_format_command = 'SDAT'
else:
data_format_command = 'FDAT'
timeout = 40
with self.root_instrument.timeout.set_to(timeout):
self.write('SENS:SWEEP:COUNT '+ str(self.avg()))
self.write('INIT:IMMEDIATE:SCOPE:SINGLE')
self.write('INIT:CONT OFF')
self.write('INIT:IMM; *WAI')
self.write("CALC:PAR:SEL "
f" '{self._tracename}' ")
data_str = self.ask(
f'CALC:DATA?'
f' {data_format_command}')
data = np.array(data_str.rstrip().split(',')).astype('float64')
finally:
self.root_instrument.cont_meas_on()
return data
def _get_sweep_data_SA(self):
self.write('SENS:AVER:STAT ON')
self.write('SENS:AVER:CLE')
self.root_instrument.cont_meas_off()
try:
timeout = 40
with self.root_instrument.timeout.set_to(timeout):
self.write('SENS:SWEEP:COUNT '+ str(self.avg()))
self.write('INIT:IMMEDIATE:SCOPE:SINGLE')
self.write('INIT:CONT OFF')
self.write('INIT:IMM; *WAI')
data_str = self.ask(
'FORM ASC;TRAC? TRACE1')
data = np.array(data_str.rstrip().split(',')).astype('float64')
finally:
self.root_instrument.cont_meas_on()
return data
def update_traces(self):
start = self.start()
stop = self.stop()
npts = self.npts()
for _, parameter in self.parameters.items():
if isinstance(parameter, (ArrayParameter, MultiParameter)):
try:
parameter.set_sweep(start, stop, npts)
except AttributeError:
pass