Debian Codegraph @

skrf/vi/vna/hp/hp8510c.py

raw symbols SCIP
1 """
2 .. module:: skrf.vi.vna.hp.hp8510c
3 =================================================
4 HP 8510C (:mod:`skrf.vi.vna.hp.hp8510c`)
5 =================================================
6
7 HP8510C Class
8 ================
9
10 .. autosummary::
11 :nosignatures:
12 :toctree: generated/
13 """
14
15 import time
16
17 import numpy as np
18 import pyvisa
19
20 import skrf
21 import skrf.network
22 from skrf.vi.vna import VNA
23
24 from .hp8510c_sweep_plan import SweepPlan
25
26
27 class HP8510C(VNA):
28 '''
29 HP 8510 driver that is capable of compound sweeps, segmented sweeps,
30 and fast binary transfers. These features make this venerable old instrument
31 much more pleasant to use in the 21st century. Likely works with "A" and
32 "B" versions of the instrument as well.
33
34 Compound sweeps occur automatically when the user requests a sweep larger
35 than what the instrument natively supports (51/101/201/401/801pts). This
36 driver takes multiple shorter sweeps and stitches them together.
37
38 Segmented sweeps occur automatically when the user requests a short or
39 irregularly spaced sweep (see "Advanced Example" below). The 8510 actually
40 does support sweeps other than 51/101/201/401/801pts, but only in a separate
41 mode (segmented sweep mode) and with significant restrictions. This driver
42 knows how to handle segmented sweep mode to get what it wants.
43
44
45 Examples
46 ============
47
48 Basic one-port:
49
50 .. code-block:: python
51
52 vna = skrf.vi.vna.hp.HP8510C(address='TCPIP::ad007-right.lan::gpib0,16::INSTR', backend='@py')
53 vna.set_frequency_sweep(2e9,3e9,201)
54 vna.get_snp_network(ports=(1,))
55
56
57
58 Basic two-port:
59
60 .. code-block:: python
61
62 vna = skrf.vi.vna.hp.HP8510C(address='TCPIP::ad007-right.lan::gpib0,16::INSTR', backend='@py')
63 vna.set_frequency_sweep(2e9,3e9,201)
64 vna.get_snp_network(ports=(1,2))
65
66
67
68 Intermediate example -- note that 1001 point sweeps are not natively supported by the instrument; this driver
69 takes multiple sweeps and stitches the results together.
70
71 .. code-block:: python
72
73 vna = skrf.vi.vna.hp.HP8510C(address='TCPIP::ad007-right.lan::gpib0,16::INSTR', backend='@py')
74 vna.set_frequency_sweep(2e9,3e9,1001)
75 vna.get_snp_network(ports=(1,2))
76
77 Advanced example. The driver is handed a bucket of frequencies containing
78 two separate bands mashed together. Behind the scenes it will construct a
79 sweep plan consisting of one native sweep and one segmented sweep, perform
80 both, and stitch the results together -- but all the user need worry about
81 is constructing the request and interpreting the results.
82
83 .. code-block:: python
84
85 vna = skrf.vi.vna.hp.HP8510C(address='TCPIP::ad007-right.lan::gpib0,16::INSTR', backend='@py')
86 freq_block_1 = np.linspace(1e9,2e9,801)
87 freq_block_2 = [10e9,11e9,12e9]
88 freqs = np.concatenate((freq_block_1, freq_block_2))
89 vna.frequency = skrf.Frequency.from_f(freqs)
90 vna.get_snp_network(ports=(1,2))
91 '''
92 min_hz = None #: Minimum frequency supported by instrument
93 max_hz = None #: Maximum frequency supported by instrument
94 compound_sweep_plan = None
95 #: If None, get_snp_network()/one_port()/two_port() just ask the VNA for data.
96 # If populated, those methods perform the multiple sweeps in the plan and stitch together the results.
97
98 def __init__(self, address : str, backend : str = "@py", **kwargs):
99 super().__init__(address, backend, **kwargs)
100 # Tested 2024-03-09:
101 # HP8510C.07.14
102 # AD007 (a VXI11-complaint GPIB-Ethernet adapter)
103 # address="TCPIP::ad007-right.lan::gpib0,16::INSTR", backend="@py"
104
105 # 8510s are slow. This check ensures we won't wait 60s for connection error.
106 self._resource.timeout = 2_000
107 id_str = self.query('OUTPIDEN;')
108 assert('HP8510' in id_str) # example: 'HP8510C.07.14: Aug 26 1998 '
109
110 # 8510s are slow. Actual work might take actual 60 seconds.
111 self._resource.timeout = 60_000
112 self._resource.read_termination = False # Binary mode doesn't work if we allow premature termination on \n
113 self.read_raw = self._resource.read_raw
114 self.reset()
115 self.min_hz = self.freq_start
116 self.max_hz = self.freq_stop
117 self.write('STEP;')
118
119 # If compound_sweep_plan is None, we rely on the internal state of the analyzer.
120 # If compound_sweep_plan is a SweepPlan object, we must take multiple short sweeps
121 # on the 8510 and stitch them into a single compound sweep ourselves.
122 self.compound_sweep_plan = None
123
124 @property
125 def id(self):
126 ''' Instrument ID string '''
127 return self.query("OUTPIDEN;")
128
129 def reset(self):
130 ''' Preset instrument. '''
131 self.write("FACTPRES;")
132 self.wait_until_finished()
133
134 def clear(self):
135 self._resource.clear()
136
137 def wait_until_finished(self):
138 self.query("OUTPIDEN;")
139
140 def get_snp_network(self, ports, cw=False, **kwargs):
141 ''' MAIN METHOD for obtaining S parameters, like get_snp_network((1,)) or get_snp_network((1,2)). '''
142 ports = tuple(ports)
143 sweep = kwargs.get("sweep", True)
144 if ports==(1,):
145 self.write('s11;')
146 return self.one_port(fresh_sweep=sweep, cw=cw)
147 elif ports==(2,):
148 self.write('s22;')
149 return self.one_port(fresh_sweep=sweep, cw=cw)
150 elif ports==(1,2) or ports==(2,1):
151 return self.two_port(fresh_sweep=sweep, cw=cw)
152 else:
153 raise(ValueError("Invalid ports "+str(ports)+". Options: (1,) (2,) (1,2)."))
154
155 def get_switch_terms(self, ports=(1, 2), **kwargs):
156 '''
157 Returns (forward_one_port,reverse_one_port) switch terms.
158 The ports short be connected with a half decent THRU before calling.
159 These measure how much signal is reflected from the imperfect switched
160 termination on the non-stimulated port.
161 '''
162 return self.switch_terms()
163
164 @property
165 def error(self):
166 ''' Error from OUTPERRO '''
167 return self.query('OUTPERRO')
168
169 @property
170 def is_continuous(self):
171 ''' True iff sweep mode is continuous. Can be set. '''
172 answer_dict={'\"HOLD\"':False,'\"CONTINUAL\"':True}
173 return answer_dict[self.query('GROU?')]
174
175 @is_continuous.setter
176 def is_continuous(self, choice):
177 if choice:
178 self.write('CONT;')
179 elif not choice:
180 self.write('SING;')
181 else:
182 raise(ValueError('takes a boolean'))
183
184 @property
185 def averaging(self):
186 ''' Averaging factor for AVERON '''
187 raise NotImplementedError
188
189 @averaging.setter
190 def averaging(self, factor ):
191 self.write('AVERON %i;'%factor )
192
193 @property
194 def _frequency(self):
195 ''' Frequencies of non-compound sweep '''
196 freq=skrf.Frequency( self.freq_start, self.freq_stop, self._npoints, unit='hz' )
197 return freq
198
199 @property
200 def frequency(self):
201 ''' Frequencies of compound sweep '''
202 if self.compound_sweep_plan is None:
203 return self._frequency
204 return skrf.Frequency.from_f(self.compound_sweep_plan.get_hz(), unit='hz')
205
206 @frequency.setter
207 def frequency(self, frequency_obj: skrf.Frequency):
208 ''' List sweep using hz, an array of frequencies.
209 If hz is too long, multiple sweeps will automatically be performed.'''
210 hz = frequency_obj.f
211 valid = (self.min_hz<=hz) & (hz<=self.max_hz)
212 if not np.all(valid):
213 print("set_frequency called with %i/%i points out of VNA frequency range. Dropping them."
214 %(np.sum(valid),len(valid)))
215 hz = hz[valid]
216 self.compound_sweep_plan = SweepPlan.from_hz(hz)
217
218 def set_frequency_single_point(self, f_cw, npoint=51, **kwargs):
219 ''' Set single point mode (CW) '''
220 self.compound_sweep_plan = None
221 f_unit = kwargs.get("f_unit", "hz").lower()
222 if f_unit != "hz":
223 hz_cw = self.to_hz(f_cw, f_unit)
224 else:
225 hz_cw = f_cw
226 if self._resource is not None:
227 self._resource.clear()
228 if npoint not in [51,101,201,401,801]:
229 raise(ValueError("Invalid npoints "+str(npoint)+". Options: 51,101,201,401,801."))
230 self.write('SINP; CWFREQ %f;POIN%i;'%(hz_cw, npoint))
231
232
233 def set_frequency_sweep(self, f_start, f_stop, f_npoints, **kwargs):
234 ''' Interprets units and calls set_frequency_step '''
235 f_unit = kwargs.get("f_unit", "hz").lower()
236 if f_unit != "hz":
237 hz_start = self.to_hz(f_start, f_unit)
238 hz_stop = self.to_hz(f_stop, f_unit)
239 else:
240 hz_start, hz_stop = f_start, f_stop
241 self.set_frequency_step(hz_start, hz_stop, f_npoints)
242
243 def set_frequency_step(self, hz_start, hz_stop, npoint=801):
244 ''' Step (slow, synthesized) sweep + logic to handle lots of npoint. '''
245 if (self._instrument_natively_supports_steps(npoint)):
246 self.compound_sweep_plan = None
247 self._set_instrument_step_state(hz_start, hz_stop, npoint)
248 else:
249 self.compound_sweep_plan = SweepPlan.from_ssn(hz_start, hz_stop, npoint)
250
251 def set_frequency_ramp(self, hz_start, hz_stop, npoint=801):
252 ''' Ramp (fast, not synthesized) sweep. Must have standard npoint. '''
253 if npoint not in [51,101,201,401,801]:
254 print("Warning: 8510C only supports NPOINT in [51,101,201,401,801]")
255 self._resource.clear()
256 self.write('RAMP; STAR %f; STOP %f; POIN%i;'%(hz_start,hz_stop,npoint))
257
258 @property
259 def freq_start(self):
260 ''' Start frequency [hz] '''
261 return float(self.query('STAR;OUTPACTI;'))
262
263 @freq_start.setter
264 def freq_start(self, new_start_hz):
265 self.write(f'STEP; STAR {new_start_hz};')
266
267 @property
268 def freq_stop(self):
269 ''' Stop frequency [hz] '''
270 return float(self.query('STOP;OUTPACTI;'))
271
272 @freq_stop.setter
273 def freq_stop(self, new_stop_hz):
274 self.write(f'STEP; STOP {new_stop_hz};')
275
276 @property
277 def _npoints(self):
278 ''' Number of points in non-compound sweep '''
279 instrument_ret_val = self.query('POIN;OUTPACTI;')
280 v1 = instrument_ret_val.strip()
281 v2 = float(v1)
282 v3 = int(v2)
283 return v3
284
285 @property
286 def npoints(self):
287 ''' Number of points in compound sweep (if programmed) or non-compound sweep '''
288 if self.compound_sweep_plan is None:
289 return self._npoints
290 return len(self.compound_sweep_plan.get_hz())
291
292 @npoints.setter
293 def npoints(self, npoint):
294 ''' Set number of points in sweep'''
295 hz_start, hz_stop = self.freq_start, self.freq_stop
296 if (self._instrument_natively_supports_steps(npoint)):
297 self.compound_sweep_plan = None
298 self._set_instrument_step_state(hz_start, hz_stop, npoint)
299 else:
300 self.compound_sweep_plan = SweepPlan.from_ssn(hz_start, hz_stop, npoint)
301
302 def _instrument_natively_supports_steps(self, npoint):
303 if npoint in [51,101,201,401,801]:
304 return True
305 if npoint<=792: # Supported with a single native list sweep
306 return True
307 return False
308
309 def _set_instrument_step_state(self, hz_start, hz_stop, npoint=801):
310 assert(self._instrument_natively_supports_steps(npoint))
311 if self._resource is not None:
312 self._resource.clear()
313 if npoint in [51,101,201,401,801]:
314 # If it's a directly supported step sweep npoints, use regular sweep
315 self.write('STEP; STAR %f; STOP %f; POIN%i;'%(hz_start,hz_stop,npoint))
316 elif npoint<=792:
317 # List sweep lets us support, for example, 401<npoints<801
318 self.write('STEP;')
319 self.write('EDITLIST;')
320 self.write('CLEL;')
321 self.write('SADD;')
322 self.write('STAR %f; STOP %f; POIN %i;'%(hz_start,hz_stop,npoint))
323 self.write('SDON; EDITDONE; LISFREQ;')
324
325 def _set_instrument_cwstep_state(self, hz_list):
326 assert(len(hz_list)<=30) # 8510 only supports CW lists up to length 30
327 self.write('STEP;')
328 self.write('EDITLIST;')
329 self.write('CLEL;')
330 for hz in hz_list:
331 self.write('SADD;')
332 self.write(f'CWFREQ {int(hz)};')
333 self.write('SDON; EDITDONE; LISFREQ;')
334
335 def ask_for_cmplx(self, outp_cmd, timeout_s=30):
336 """Like ask_for_values, but use FORM2 binary transfer, much faster than ASCII."""
337 # Benchmarks:
338 # %time i.write('FORM4; OUTPDATA'); i._read(); None # 7960ms
339 # %time i.write('FORM2; OUTPDATA'); i._read_raw(); None # 399ms
340 self.wait_for_status(max_wait_seconds=timeout_s)
341 self.write('FORM2;')
342 self.write(outp_cmd)
343 buf = self.read_raw()
344 float_bin = buf[4:] # Skip 4 header bytes and trailing newline
345 try:
346 floats = np.frombuffer(float_bin, dtype='>f4').reshape((-1,2))
347 except ValueError as e:
348 print(buf)
349 print("len(buf): %i"%(len(buf),))
350 raise(e)
351 cmplxs = (floats[:,0] + 1j*floats[:,1]).flatten()
352 return cmplxs
353
354 def _one_port(self, cw=False, expected_hz=None, fresh_sweep=True):
355 ''' Perform a single sweep and return Network data. '''
356 if fresh_sweep:
357 if cw:
358 self.write('SINP;') # Poll for sweep status
359 else:
360 self.write('SING;') # Poll for sweep status
361 s = self.ask_for_cmplx('OUTPDATA')
362 ntwk = skrf.Network()
363 ntwk.s = s
364 hz = expected_hz if expected_hz is not None else self._frequency.f
365 assert(len(s)==len(hz))
366 ntwk.frequency = skrf.Frequency.from_f(hz,unit='hz')
367 return ntwk
368
369 def one_port(self, cw=False, **kwargs):
370 ''' Performs a single sweep OR COMPOUND SWEEP and returns Network data. '''
371 if self.compound_sweep_plan is None:
372 return self._one_port(cw=cw)
373 old_start_hz, old_stop_hz = self.freq_start, self.freq_stop
374 stitched_network = None
375 for sweep_section in self.compound_sweep_plan.get_sections():
376 sweep_section.apply_8510(self)
377 chunk_net_nomask = self._one_port(expected_hz=sweep_section.get_raw_hz())
378 chunk_net = sweep_section.mask_8510(chunk_net_nomask)
379 stitched_network = (chunk_net if stitched_network is None
380 else skrf.network.stitch(stitched_network, chunk_net))
381 self.freq_start = old_start_hz
382 self.freq_stop = old_stop_hz
383 return stitched_network
384
385 def _two_port(self, cw=False, expected_hz=None, fresh_sweep=True):
386 ''' Performs a single sweep and returns Network data. '''
387 # ASCII vs Binary transfer performance:
388 # ascii_xfer separate_sweep: 32s
389 # bin_xfer separate_sweep: 08s
390 # ------------------------------
391 # Decision: spend time to implement binary transfer. It matters.
392 #
393 # Sweep mode:
394 # source mode strategy time
395 # 83651 ramp FOUPOVER 12.8s
396 # 83651 ramp 4xSxx 11.6s <-- in ramp mode + faststep, consecutive Sxx sweeps are fastest
397 # 83651 ramp FULL2PORT 14.5s
398 # 83651 step FOUPOVER 50.0s <-- in step mode, FOUPOVER is a tad faster.
399 # 83651 step 4xSxx 52.5s
400 # 83651 step FULL2PORT 52.3s
401 # --------------------------
402 # Decision: use consecutive Sxx sweeps everywhere for simplicity + max speed of fast sweeps
403 self.write('s11;')
404 s11 = self._one_port(expected_hz=expected_hz, cw=cw, fresh_sweep=fresh_sweep).s[:,0,0]
405 self.write('s12;')
406 s12 = self._one_port(expected_hz=expected_hz, cw=cw, fresh_sweep=fresh_sweep).s[:,0,0]
407 self.write('s22;')
408 s22 = self._one_port(expected_hz=expected_hz, cw=cw, fresh_sweep=fresh_sweep).s[:,0,0]
409 self.write('s21;')
410 s21 = self._one_port(expected_hz=expected_hz, cw=cw, fresh_sweep=fresh_sweep).s[:,0,0]
411
412 ntwk = skrf.Network()
413 ntwk.s = np.array(\
414 [[s11,s21],\
415 [ s12, s22]]\
416 ).transpose().reshape(-1,2,2)
417 hz = expected_hz if expected_hz is not None else self._frequency.f
418 assert(len(s11)==len(hz))
419 ntwk.frequency= skrf.Frequency.from_f(hz,unit='hz')
420
421 return ntwk
422
423 def two_port(self, cw=False, **kwargs):
424 ''' Performs a single sweep OR COMPOUND SWEEP and returns Network data. '''
425 if self.compound_sweep_plan is None:
426 return self._two_port(cw=cw)
427 old_start_hz, old_stop_hz = self.freq_start, self.freq_stop
428 stitched_network = None
429 for sweep_chunk in self.compound_sweep_plan.get_sections():
430 sweep_chunk.apply_8510(self)
431 chunk_net_nomask = self._two_port(expected_hz=sweep_chunk.get_raw_hz())
432 chunk_net = sweep_chunk.mask_8510(chunk_net_nomask)
433 stitched_network = (chunk_net if stitched_network is None
434 else skrf.network.stitch(stitched_network,chunk_net))
435 self.freq_start = old_start_hz
436 self.freq_stop = old_stop_hz
437 return stitched_network
438
439 def wait_for_status(self, max_wait_seconds=30):
440 ''' Fetches status bytes respecting max_wait_seconds even if it must tank a few timeouts along the way. '''
441 t0 = time.time()
442 while True:
443 try:
444 status_str = self.query('OUTPSTAT')
445 s0str, s1str = status_str.strip().split(',')
446 s0 = int(s0str)
447 s1 = int(s1str)
448 break
449 except pyvisa.errors.VisaIOError as e:
450 waited = time.time()-t0
451 if waited > max_wait_seconds:
452 raise e
453 return s0,s1
454
455 def switch_terms(self):
456 '''
457 Returns (forward_one_port,reverse_one_port) switch terms.
458 The ports short be connected with a half decent THRU before calling.
459 These measure how much signal is reflected from the imperfect switched
460 termination on the non-stimulated port.
461 '''
462 print('forward')
463 self.write('USER2;DRIVPORT1;LOCKA1;NUMEB2;DENOA2;CONV1S;')
464 forward = self.one_port()
465 forward.name = 'forward switch term'
466
467 print ('reverse')
468 self.write('USER1;DRIVPORT2;LOCKA2;NUMEB1;DENOA1;CONV1S;')
469 reverse = self.one_port()
470 reverse.name = 'reverse switch term'
471
472 return (forward,reverse)