Debian Codegraph @

skrf/vi/vna/hp/hp8720b.py

raw symbols SCIP
1 """
2 .. module:: skrf.vi.vna.hp.hp8720b
3 =================================================
4 HP 8720B (:mod:`skrf.vi.vna.hp.hp8720b`)
5 =================================================
6
7 HP8720B Class
8 ================
9
10 .. autosummary::
11 :nosignatures:
12 :toctree: generated/
13 """
14
15 import numpy as np
16
17 import skrf
18 import skrf.network
19 from skrf.vi.vna import VNA
20
21
22 class HP8720B(VNA):
23 '''
24 HP 8720B driver, created by modifying the 8510C driver and commenting out
25 the additional sweep options. The instrument natively supports
26 (3/11/21/51/101/201/401/801/1601pts).
27
28 Segmented sweeps occur automatically when the user requests a short or
29 irregularly spaced sweep (see "Advanced Example" below). The 8510 actually
30 does support sweeps other than 51/101/201/401/801pts, but only in a separate
31 mode (segmented sweep mode) and with significant restrictions. This driver
32 knows how to handle segmented sweep mode to get what it wants.
33
34
35 Examples
36 ============
37
38 Basic one-port:
39
40 .. code-block:: python
41
42 vna = skrf.vi.vna.hp.HP8720B(address='GPIB0::16::INSTR', backend='C:\\WINDOWS\\system32\\visa32.dll')
43 vna.set_frequency_sweep(2e9,3e9,201)
44 vna.get_snp_network(ports=(1,))
45
46
47
48 Basic two-port:
49
50 .. code-block:: python
51
52 vna = skrf.vi.vna.hp.HP8720B(address='GPIB0::16::INSTR', backend='C:\\WINDOWS\\system32\\visa32.dll')
53 vna.set_frequency_sweep(2e9,3e9,201)
54 vna.get_snp_network(ports=(1,2))
55
56
57
58 Intermediate example -- note that 1001 point sweeps are not natively supported by the instrument; instead uses
59 the analysers frequency segment mode. Based off example 4B in the 8720B programming manual. Sometimes breaks
60 after the first output, for which the analyser requires a hard reset.
61
62 .. code-block:: python
63
64 vna = skrf.vi.vna.hp.HP8720B(address='GPIB0::16::INSTR', backend='C:\\WINDOWS\\system32\\visa32.dll')
65 vna.set_frequency_sweep(2e9,3e9,1001)
66 vna.get_snp_network(ports=(1,2))
67 '''
68 min_hz = 130E6 #: Minimum frequency supported by instrument
69 max_hz = 20E9 #: Maximum frequency supported by instrument
70
71 def __init__(self, address : str, backend : str = "@py", **kwargs):
72 super().__init__(address, backend, **kwargs)
73 # Tested 2024-05-29:
74 # HP8720B
75 # NI GPIB to USB
76 # address="gpib0,16::INSTR", backend='C:\\WINDOWS\\system32\\visa32.dll'
77
78 # 8720s are slow. This check ensures we won't wait 60s for connection error.
79 self._resource.timeout = 2_000 * (3_000 / self.if_bandwidth) # Speed dependent on IF bandwidth selected
80 id_str = self.query('OUTPIDEN;')
81 assert('8720' in id_str) # example: 'HP8720B,0,1.01'
82
83 self._resource.read_termination = '\n'
84 self.read_raw = self._resource.read_raw
85 self.min_hz = self.freq_start
86 self.max_hz = self.freq_stop
87 self.write('CONT;')
88
89 self.write('DEBUON;') # Debug HPIB mode ON to displace instrument commands on the instrument screen
90 # DEBUOFF to turn off (or just remove command)
91
92 # Compound sweeps can be added in the future using the subsweep menu commands
93
94 @property
95 def id(self):
96 ''' Instrument ID string '''
97 return self.query("OUTPIDEN;")
98
99 def reset(self):
100 ''' Preset instrument. '''
101 self.write("PRES;")
102 self.wait_until_finished()
103
104 def clear(self):
105 self._resource.clear()
106
107 def wait_until_finished(self):
108 self.query("OUTPIDEN;")
109
110 def get_snp_network(self, ports, **kwargs):
111 ''' MAIN METHOD for obtaining S parameters, like get_snp_network((1,)) or get_snp_network((1,2)). '''
112 ports = tuple(ports)
113 sweep = kwargs.get("sweep", True)
114
115 if ports==(1,):
116 self.write('S11;')
117 return self.one_port(fresh_sweep=sweep)
118 elif ports==(2,):
119 self.write('S22;')
120 return self.one_port(fresh_sweep=sweep)
121 elif ports==(1,2) or ports==(2,1):
122 return self.two_port(fresh_sweep=sweep)
123 else:
124 raise(ValueError("Invalid ports "+str(ports)+". Options: (1,) (2,) (1,2)."))
125
126 def get_switch_terms(self, ports=(1, 2), **kwargs):
127 '''
128 Returns (forward_one_port,reverse_one_port) switch terms.
129 The ports short be connected with a half decent THRU before calling.
130 These measure how much signal is reflected from the imperfect switched
131 termination on the non-stimulated port.
132 '''
133 raise(NotImplementedError("Not yet implemented for HP8720B"))
134
135 @property
136 def error(self):
137 ''' Error from OUTPERRO '''
138 return self.query('OUTPERRO')
139
140 @property
141 def if_bandwidth(self):
142 ''' Current IF Bandwidth [Hz] '''
143 return float(self.query('IFBW?'))
144
145 @if_bandwidth.setter
146 def if_bandwidth(self, if_bw):
147 ''' Allowed values (in Hz): 3000, 1000, 300, 100, 30, and 10'''
148 if if_bw in [3,10,30,100,300,1000,3000]:
149 self.write(f'IFBW {if_bw}')
150 # Changing the timeout due to change IF BW causing the VNA to be slower
151 self._resource.timeout = 2_000 * (3_000 / self.if_bandwidth)
152 else:
153 raise(ValueError('Takes a value from [3,10,30,100,300,1000,3000]'))
154
155 @property
156 def is_continuous(self):
157 ''' True if sweep mode is continuous. Can be set. '''
158 answer_dict={'1':False,'0':True}
159 return answer_dict[self.query('TRIG?')]
160
161 @is_continuous.setter
162 def is_continuous(self, choice):
163 if choice:
164 self.write('CONT;')
165 elif not choice:
166 self.write('SING;')
167 else:
168 raise(ValueError('takes a boolean'))
169
170 @property
171 def averaging(self):
172 ''' Averaging factor for AVERON '''
173 return int(float(self.query('AVERFACT?')))
174
175 @averaging.setter
176 def averaging(self, factor):
177 if not factor:
178 self.write('AVEROFF')
179 elif isinstance(factor, int):
180 self.write(f'AVERON; AVERFACT {factor};')
181 else:
182 raise(ValueError('takes an interger'))
183
184 @property
185 def _frequency(self):
186 ''' Frequencies of non-compound sweep '''
187 freq=skrf.Frequency( self.freq_start, self.freq_stop, self._npoints, unit='hz' )
188 return freq
189
190 @property
191 def frequency(self):
192 ''' Frequencies of compound sweep '''
193 return self._frequency
194
195 @frequency.setter
196 def frequency(self, frequency_obj: skrf.Frequency):
197 ''' List sweep using hz, an array of frequencies.
198 If hz is too long, multiple sweeps will automatically be performed.'''
199 hz = frequency_obj.f
200 valid = (self.min_hz<=hz) & (hz<=self.max_hz)
201 if not np.all(valid):
202 print("set_frequency called with %i/%i points out of VNA frequency range. Dropping them."
203 %(np.sum(valid),len(valid)))
204 hz = hz[valid]
205
206 def set_frequency_sweep(self, f_start, f_stop, f_npoints, **kwargs):
207 ''' Interprets units and calls set_frequency_step '''
208 f_unit = kwargs.get("f_unit", "hz").lower()
209 if f_unit != "hz":
210 hz_start = self.to_hz(f_start, f_unit)
211 hz_stop = self.to_hz(f_stop, f_unit)
212 else:
213 hz_start, hz_stop = f_start, f_stop
214 self.set_frequency_step(hz_start, hz_stop, f_npoints)
215
216 def set_frequency_step(self, hz_start, hz_stop, npoint=801):
217 ''' Step (slow, synthesized) sweep + logic to handle lots of npoint. '''
218 if (self._instrument_natively_supports_steps(npoint)):
219 self._set_instrument_step_state(hz_start, hz_stop, npoint)
220
221 @property
222 def freq_start(self):
223 ''' Start frequency [hz] '''
224 return float(self.query('STAR;OUTPACTI;'))
225
226 @freq_start.setter
227 def freq_start(self, new_start_hz):
228 self.write(f'STAR {new_start_hz};')
229
230 @property
231 def freq_stop(self):
232 ''' Stop frequency [hz] '''
233 return float(self.query('STOP;OUTPACTI;'))
234
235 @freq_stop.setter
236 def freq_stop(self, new_stop_hz):
237 self.write(f'STOP {new_stop_hz};')
238
239 @property
240 def _npoints(self):
241 ''' Number of points in non-compound sweep '''
242 instrument_ret_val = self.query('POIN;OUTPACTI;')
243 v1 = instrument_ret_val.strip()
244 v2 = float(v1)
245 v3 = int(v2)
246 return v3
247
248 @property
249 def npoints(self):
250 ''' Number of points in compound sweep (if programmed) or non-compound sweep '''
251 return self._npoints
252
253 @npoints.setter
254 def npoints(self, npoint):
255 ''' Set number of points in sweep'''
256 hz_start, hz_stop = self.freq_start, self.freq_stop
257 if (self._instrument_natively_supports_steps(npoint)):
258 self._set_instrument_step_state(hz_start, hz_stop, npoint)
259
260 def _instrument_natively_supports_steps(self, npoint):
261 if npoint in [3,11,21,51,101,201,401,801,1601]:
262 return True
263 if npoint<=1601: # Supported with a single native list sweep commented as only work once then breaks connection
264 return True
265 return False
266
267 def _set_instrument_step_state(self, hz_start, hz_stop, npoint=801):
268 assert(self._instrument_natively_supports_steps(npoint))
269 if self._resource is not None:
270 self._resource.clear()
271 if npoint in [3,11,21,51,101,201,401,801,1601]:
272 # If it's a directly supported step sweep npoints, use regular sweep
273 self.write(f'STAR {hz_start}; STOP {hz_stop}; POIN {npoint};')
274 elif npoint<=1601:
275 # List sweep lets us support, for example, 401<npoints<801 CURRENTLY BREAKS connection
276 self.write('EDITLIST;')
277 self.write('SDEL;')
278 self.write('SADD;')
279 self.write(f'STAR {hz_start}; STOP {hz_stop}; POIN {npoint};')
280 self.write('SDON; EDITDONE; LISFREQ;')
281
282 def _set_instrument_cwstep_state(self, hz_list):
283 assert(len(hz_list)<=30) # 8720 only supports CW lists up to length 30
284 self.write('EDITLIST;')
285 self.write('CLEL;')
286 for hz in hz_list:
287 self.write('SADD;')
288 self.write(f'CWFREQ {int(hz)};')
289 self.write('SDON; EDITDONE; LISFREQ;')
290
291 def ask_for_cmplx(self, outp_cmd, timeout_s=30):
292 """Like ask_for_values, but use FORM2 binary transfer, much faster than ASCII for HP8720.
293 Also could not get FORM4 working for HP8720B"""
294 # Benchmarks:
295 # %time i.write('FORM4; OUTPDATA'); i._read(); None # 543ms
296 # %time i.write('FORM2; OUTPDATA'); i._read_raw(); None # 97.5ms
297 self._resource.read_termination = False # Binary mode doesn't work if we allow premature termination on \n
298 self.write('FORM2;')
299 self.write(outp_cmd)
300 buf = self.read_raw()
301 float_bin = buf[4:] # Skip 4 header bytes and trailing newline
302 try:
303 floats = np.frombuffer(float_bin, dtype='>f4').reshape((-1,2))
304 except ValueError as e:
305 print(buf)
306 print("len(buf): %i"%(len(buf),))
307 raise(e)
308 cmplxs = (floats[:,0] + 1j*floats[:,1]).flatten()
309 self._resource.read_termination = '\n' # Switching back for other outputs
310 return cmplxs
311
312 def _one_port(self, expected_hz=None, fresh_sweep=True):
313 ''' Perform a single sweep and return Network data. '''
314 is_current_sweep_continous = self.is_continuous
315 if fresh_sweep:
316 self.write('SING;') # Poll for sweep status
317 s = self.ask_for_cmplx('OUTPDATA')
318 ntwk = skrf.Network()
319 ntwk.s = s
320 hz = expected_hz if expected_hz is not None else self._frequency.f
321 assert(len(s)==len(hz))
322 ntwk.frequency = skrf.Frequency.from_f(hz,unit='hz')
323 self.is_continuous = is_current_sweep_continous
324 return ntwk
325
326 def one_port(self, **kwargs):
327 ''' Performs a single sweep and returns Network data. '''
328 return self._one_port()
329
330 def _two_port(self, expected_hz=None, fresh_sweep=True):
331 ''' Performs a single sweep and returns Network data. '''
332
333 self.write('S11;')
334 s11 = self._one_port(expected_hz=expected_hz, fresh_sweep=fresh_sweep).s[:,0,0]
335 self.write('S12;')
336 s12 = self._one_port(expected_hz=expected_hz, fresh_sweep=fresh_sweep).s[:,0,0]
337 self.write('S22;')
338 s22 = self._one_port(expected_hz=expected_hz, fresh_sweep=fresh_sweep).s[:,0,0]
339 self.write('S21;')
340 s21 = self._one_port(expected_hz=expected_hz, fresh_sweep=fresh_sweep).s[:,0,0]
341
342 ntwk = skrf.Network()
343 ntwk.s = np.array(\
344 [[s11,s21],\
345 [ s12, s22]]\
346 ).transpose().reshape(-1,2,2)
347 hz = expected_hz if expected_hz is not None else self._frequency.f
348 assert(len(s11)==len(hz))
349 ntwk.frequency= skrf.Frequency.from_f(hz,unit='hz')
350
351 return ntwk
352
353 def two_port(self, **kwargs):
354 ''' Performs a single sweep OR COMPOUND SWEEP and returns Network data. '''
355 return self._two_port()
356
357 def switch_terms(self):
358 '''
359 Returns (forward_one_port,reverse_one_port) switch terms.
360 The ports short be connected with a half decent THRU before calling.
361 These measure how much signal is reflected from the imperfect switched
362 termination on the non-stimulated port.
363 '''
364 print('forward')
365 self.write('USER2;DRIVPORT1;LOCKA1;NUMEB2;DENOA2;CONV1S;')
366 forward = self.one_port()
367 forward.name = 'forward switch term'
368
369 print ('reverse')
370 self.write('USER1;DRIVPORT2;LOCKA2;NUMEB1;DENOA1;CONV1S;')
371 reverse = self.one_port()
372 reverse.name = 'reverse switch term'
373
374 return (forward,reverse)