Debian Codegraph @

pymeasure/instruments/hp/hp8116a.py

raw
1 #
2 # This file is part of the PyMeasure package.
3 #
4 # Copyright (c) 2013-2024 PyMeasure Developers
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a copy
7 # of this software and associated documentation files (the "Software"), to deal
8 # in the Software without restriction, including without limitation the rights
9 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 # copies of the Software, and to permit persons to whom the Software is
11 # furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 # THE SOFTWARE.
23 #
24
25 import logging
26 import time
27 import numpy as np
28 from enum import Enum, IntFlag
29 from pymeasure.instruments import Instrument
30 from pymeasure.instruments.validators import (
31 strict_discrete_set, strict_range, truncated_discrete_set
32 )
33
34 log = logging.getLogger(__name__)
35 log.addHandler(logging.NullHandler())
36
37
38 # for Python>3.9, these two methods can be static methods in the class
39 def _generate_1_2_5_sequence(min, max):
40 """ Generate a list of a 1-2-5 sequence between min and max. """
41 exp_min = int(np.log10(min))
42 exp_max = int(np.log10(max))
43
44 seq_1_2_5 = np.array([1, 2, 5])
45 sequence = np.array([seq_1_2_5 * (10 ** exp) for exp in range(exp_min - 1, exp_max + 1)])
46 sequence = sequence.flatten()
47 sequence = sequence[(sequence >= min) & (sequence <= max)]
48
49 return list(sequence)
50
51
52 def _boolean_control(identifier, state_index, docs, inverted=False, **kwargs):
53 return Instrument.control(
54 'CST', identifier + '%d', docs,
55 validator=strict_discrete_set,
56 values=[True, False],
57 get_process=lambda x: inverted ^ bool(int(x[state_index][1])),
58 set_process=lambda x: int(inverted ^ x),
59 **kwargs
60 )
61
62
63 class Status(IntFlag):
64 """ IntFlag type for the GPIB status byte which is returned by the :py:attr:`status` property.
65 When the timing_error or programming_error flag is set, a more detailed error description
66 can be obtained by calling :py:method:`check_errors()`.
67 """
68 timing_error = 1 << 0
69 programming_error = 1 << 1
70 syntax_error = 1 << 2
71 system_failure = 1 << 3
72 autovernier_in_progress = 1 << 4
73 sweep_in_progress = 1 << 5
74 service_request = 1 << 6
75 buffer_not_empty = 1 << 7
76
77
78 class HP8116A(Instrument):
79 """ Represents the Hewlett-Packard 8116A 50 MHz Pulse/Function Generator
80 and provides a high-level interface for interacting with the instrument.
81 The resolution for all floating point instrument parameters is 3 digits.
82 """
83
84 def __init__(self, adapter, name="Hewlett-Packard 8116A", **kwargs):
85 kwargs.setdefault('read_termination', '\r\n')
86 kwargs.setdefault('write_termination', '\r\n')
87 kwargs.setdefault('send_end', True)
88 super().__init__(
89 adapter,
90 name,
91 includeSCPI=False,
92 **kwargs
93 )
94 self.has_option_001 = self._check_has_option_001()
95
96 class Digit(Enum):
97 """ Enum of the digits used with the autovernier
98 (see :py:meth:`HP8116A.start_autovernier()`).
99 """
100 MOST_SIGNIFICANT = 'M'
101 SECOND_SIGNIFICANT = 'S'
102 LEAST_SIGNIFICANT = 'L'
103
104 class Direction(Enum):
105 """ Enum of the directions used with the autovernier
106 (see :py:meth:`HP8116A.start_autovernier()`).
107 """
108 UP = 'U'
109 DOWN = 'D'
110
111 OPERATING_MODES = {
112 'normal': 'M1',
113 'triggered': 'M2',
114 'gate': 'M3',
115 'external_width': 'M4',
116
117 # Option 001 only
118 'internal_sweep': 'M5',
119 'external_sweep': 'M6',
120 'internal_burst': 'M7',
121 'external_burst': 'M8',
122 }
123
124 OPERATING_MODES_INV = {v: k for k, v in OPERATING_MODES.items()}
125
126 CONTROL_MODES = {
127 'off': 'CT0',
128 'FM': 'CT1',
129 'AM': 'CT2',
130 'PWM': 'CT3',
131 'VCO': 'CT4',
132 }
133
134 CONTROL_MODES_INV = {v: k for k, v in CONTROL_MODES.items()}
135
136 TRIGGER_SLOPES = {
137 'off': 'T0',
138 'positive': 'T1',
139 'negative': 'T2',
140 }
141
142 TRIGGER_SLOPES_INV = {v: k for k, v in TRIGGER_SLOPES.items()}
143
144 SHAPES = {
145 'dc': 'W0',
146 'sine': 'W1',
147 'triangle': 'W2',
148 'square': 'W3',
149 'pulse': 'W4',
150 }
151
152 SHAPES_INV = {v: k for k, v in SHAPES.items()}
153
154 _units_frequency = {
155 'milli': 'MZ',
156 'no_prefix': 'HZ',
157 'kilo': 'KHZ',
158 'mega': 'MHZ',
159 }
160
161 _units_voltage = {
162 'milli': 'MV',
163 'no_prefix': 'V',
164 }
165
166 _units_time = {
167 'nano': 'NS',
168 'micro': 'US',
169 'milli': 'MS',
170 'no_prefix': 'S',
171 }
172
173 _si_prefixes = {
174 'nano': 1e-9,
175 'micro': 1e-6,
176 'milli': 1e-3,
177 'no_prefix': 1,
178 'kilo': 1e3,
179 'mega': 1e6,
180 }
181
182 @staticmethod
183 def _get_value_with_unit(value, units):
184 """ Convert a floating point value to a string with 3 digits resolution
185 and the appropriate unit.
186
187 :param value: The value to convert.
188 :param units: Dictionary containing a mapping of SI-prefixes to the unit strings
189 the instrument uses, eg. 'milli' -> 'MZ' for millihertz.
190 """
191 if value < 1e-6:
192 value_str = f'{value*1e9:.3g} {units["nano"]}'
193 elif value < 1e-3:
194 value_str = f'{value*1e6:.3g} {units["micro"]}'
195 elif value < 1:
196 value_str = f'{value*1e3:.3g} {units["milli"]}'
197 elif value < 1e3:
198 value_str = f'{value:.3g} {units["no_prefix"]}'
199 elif value < 1e6:
200 value_str = f'{value*1e-3:.3g} {units["kilo"]}'
201 else:
202 value_str = f'{value*1e-6:.3g} {units["mega"]}'
203
204 return value_str
205
206 @staticmethod
207 def _parse_value_with_unit(value_str, units):
208 """ Convert a string with a value and a unit as returned by the HP8116A to a float.
209
210 :param value_str: The string to parse.
211 :param units: Dictionary containing a mapping of SI-prefixes to the unit strings
212 the instrument uses, eg. 'milli' -> 'MZ' for millihertz.
213 """
214
215 # Example value_str: 'FRQ 1.00KHZ'
216 # Digits and unit are always positioned the same for all parameters
217 value_str = value_str.strip()
218 value = float(value_str[3:8].strip())
219 unit = value_str[8:].strip()
220 units_inverse = {v: k for k, v in units.items()}
221 value *= HP8116A._si_prefixes[units_inverse[unit]]
222
223 return value
224
225 # Instrument communication #
226
227 def write(self, command):
228 """ Write a command to the instrument and wait until the 8116A has interpreted it. """
229 super().write(command)
230
231 # We need to read the status byte and wait until the buffer_not_empty bit
232 # is cleared because some older units lock up if we don't.
233 self._wait_for_commands_processed()
234
235 def ask(self, command, num_bytes=None):
236 """ Write a command to the instrument, read the response, and return the response as ASCII text.
237
238 :param command: The command to send to the instrument.
239 :param num_bytes: The number of bytes to read from the instrument. If not specified,
240 the number of bytes is automatically determined by the command.
241 """ # noqa: E501
242 self.write(command)
243
244 if num_bytes is None:
245 if command == 'CST':
246 # We usually only need the first 29 bytes of the state response since they contain
247 # the current boolean parameters. The other parameters all have corresponding
248 # 'interrogate' commands.
249 num_bytes = 29
250 elif command[0] == 'I':
251 num_bytes = 14
252
253 # The first character is always a space or a leftover character from the previous command,
254 # when the number of bytes read was too large or too small.
255 bytes = self.read_bytes(num_bytes)[1:]
256 return bytes.decode('ascii').strip(' ,\r\n')
257
258 operating_mode = Instrument.control(
259 'CST', '%s',
260 """Control the operating mode of the instrument.
261 Possible values (without Option 001) are: 'normal', 'triggered', 'gate', 'external_width'.
262 With Option 001, 'internal_sweep', 'external_sweep', 'external_width', 'external_pulse'
263 are also available.
264 """,
265 validator=strict_discrete_set,
266 values=OPERATING_MODES,
267 map_values=True,
268 get_process=lambda x: HP8116A.OPERATING_MODES_INV[x[0]]
269 )
270
271 control_mode = Instrument.control(
272 'CST', '%s',
273 """Control the control mode of the instrument.
274 Possible values are 'off', 'FM', 'AM', 'PWM', 'VCO'.
275 """,
276 validator=strict_discrete_set,
277 values=CONTROL_MODES,
278 map_values=True,
279 get_process=lambda x: HP8116A.CONTROL_MODES_INV[x[1]]
280 )
281
282 trigger_slope = Instrument.control(
283 'CST', '%s',
284 """Control the slope the trigger triggers on.
285 Possible values are: 'off', 'positive', 'negative'.
286 """,
287 validator=strict_discrete_set,
288 values=TRIGGER_SLOPES,
289 map_values=True,
290 get_process=lambda x: HP8116A.TRIGGER_SLOPES_INV[x[2]]
291 )
292
293 shape = Instrument.control(
294 'CST', '%s',
295 """Control the shape of the output waveform.
296 Possible values are: 'dc', 'sine', 'triangle', 'square', 'pulse'.
297 """,
298 validator=strict_discrete_set,
299 values=SHAPES,
300 map_values=True,
301 get_process=lambda x: HP8116A.SHAPES_INV[x[3]]
302 )
303
304 haversine_enabled = _boolean_control(
305 'H', 4,
306 """Control whether a haversine/havertriangle signal
307 is generated when in 'triggered', 'internal_burst' or 'external_burst' operating mode.
308 """,
309 )
310
311 autovernier_enabled = _boolean_control(
312 'A', 5,
313 """Control whether the autovernier is enabled (bool).""",
314 check_set_errors=True
315 )
316
317 limit_enabled = _boolean_control(
318 'L', 6,
319 """Control whether parameter limiting is enabled (bool).""",
320 )
321
322 complement_enabled = _boolean_control(
323 'C', 7,
324 """Control whether the complement of the signal is generated (bool).""",
325 )
326
327 output_enabled = _boolean_control(
328 'D', 8,
329 """Control whether the output is enabled (bool).""",
330 inverted=True, # The actual command is "Disable output"...
331 )
332
333 frequency = Instrument.control(
334 'IFRQ', 'FRQ %s',
335 """Control the frequency of the output in Hz (strict float from 1e-3 to 52.5e6).
336 """,
337 validator=strict_range,
338 values=[1e-3, 52.5001e6],
339 set_process=lambda x: HP8116A._get_value_with_unit(x, HP8116A._units_frequency),
340 get_process=lambda x: HP8116A._parse_value_with_unit(x, HP8116A._units_frequency)
341 )
342
343 duty_cycle = Instrument.control(
344 'IDTY', 'DTY %s %%',
345 """Control the duty cycle of the output in percent (float).
346 The allowed range generally is 10 % to 90 %, but it also depends on the current frequency.
347 It is valid for all shapes except 'pulse', where :py:attr:`pulse_width` is used instead.
348 """,
349 validator=strict_range,
350 values=[10, 90.0001],
351 cast=int,
352 # get_process=lambda x: int(x[6:8])
353 )
354
355 pulse_width = Instrument.control(
356 'IWID', 'WID %s',
357 """Control the pulse width in s (strict float from 8e-9 to 999e-3).
358 The pulse width may not be larger than the period.
359 """,
360 validator=strict_range,
361 values=[8e-9, 999.001e-3],
362 set_process=lambda x: HP8116A._get_value_with_unit(x, HP8116A._units_time),
363 get_process=lambda x: HP8116A._parse_value_with_unit(x, HP8116A._units_time)
364 )
365
366 amplitude = Instrument.control(
367 'IAMP', 'AMP %s',
368 """Control the amplitude of the output in V (strict float from 10e-3 to 16).
369 The allowed amplitude range is also limited by the current offset.
370 """,
371 validator=strict_range,
372 values=[10e-3, 16.001],
373 set_process=lambda x: HP8116A._get_value_with_unit(x, HP8116A._units_voltage),
374 get_process=lambda x: HP8116A._parse_value_with_unit(x, HP8116A._units_voltage)
375 )
376
377 offset = Instrument.control(
378 'IOFS', 'OFS %s',
379 """Control the offset of the output in V (strit float from -7.95 to 7.95).
380 The allowed offset range is also limited by the amplitude.
381 """,
382 validator=strict_range,
383 values=[-7.95, 7.95001],
384 set_process=lambda x: HP8116A._get_value_with_unit(x, HP8116A._units_voltage),
385 get_process=lambda x: HP8116A._parse_value_with_unit(x, HP8116A._units_voltage)
386 )
387
388 high_level = Instrument.control(
389 'IHIL', 'HIL %s',
390 """Control the high level of the output in V (strict float from -7.9 to 8).
391 The allowed high level range must be at least 10 mV greater than the low level.
392 """,
393 validator=strict_range,
394 values=[-7.9, 8.001],
395 set_process=lambda x: HP8116A._get_value_with_unit(x, HP8116A._units_voltage),
396 get_process=lambda x: HP8116A._parse_value_with_unit(x, HP8116A._units_voltage)
397 )
398
399 low_level = Instrument.control(
400 'ILOL', 'LOL %s',
401 """Control the low level of the output in V (strict float from -8 to 7.9).
402 The allowed low level range must be at least 10 mV less than the high level.
403 """,
404 validator=strict_range,
405 values=[-8, 7.9001],
406 set_process=lambda x: HP8116A._get_value_with_unit(x, HP8116A._units_voltage),
407 get_process=lambda x: HP8116A._parse_value_with_unit(x, HP8116A._units_voltage)
408 )
409
410 burst_number = Instrument.control(
411 'IBUR', 'BUR %s #',
412 """Control the number of periods generated in a burst (strict int from 1 to 1999).
413 It is only valid for units with Option 001 in one of the burst modes.
414 """,
415 validator=strict_range,
416 values=[1, 1999],
417 get_process=lambda x: int(x[4:8])
418 )
419
420 repetition_rate = Instrument.control(
421 'IRPT', 'RPT %s',
422 """Control the repetition rate in s (i.e. the time between bursts)
423 in 'internal_burst' mode (strict float from 20e-9 to 999e-3).
424 """,
425 validator=strict_range,
426 values=[20e-9, 999.001e-3],
427 set_process=lambda x: HP8116A._get_value_with_unit(x, HP8116A._units_time),
428 get_process=lambda x: HP8116A._parse_value_with_unit(x, HP8116A._units_time)
429 )
430
431 sweep_start = Instrument.control(
432 'ISTA', 'STA %s',
433 """Control the start frequency in both sweep modes in Hz
434 (strict float from 1e-3 to 52.5e6).
435 """,
436 validator=strict_range,
437 values=[1e-3, 52.5001e6],
438 set_process=lambda x: HP8116A._get_value_with_unit(x, HP8116A._units_frequency),
439 get_process=lambda x: HP8116A._parse_value_with_unit(x, HP8116A._units_frequency)
440 )
441
442 sweep_stop = Instrument.control(
443 'ISTP', 'STP %s',
444 """Control the stop frequency in both sweep modes in Hz (strict float from 1e-3 to 52.5e6).
445 """,
446 validator=strict_range,
447 values=[1e-3, 52.5001e6],
448 set_process=lambda x: HP8116A._get_value_with_unit(x, HP8116A._units_frequency),
449 get_process=lambda x: HP8116A._parse_value_with_unit(x, HP8116A._units_frequency)
450 )
451
452 sweep_marker_frequency = Instrument.control(
453 'IMRK', 'MRK %s',
454 """Control the frequency marker in both sweep modes in Hz
455 (strict float from 1e-3 to 52.5e6).
456 At this frequency, the marker output switches from low to high.
457 """,
458 validator=strict_range,
459 values=[1e-3, 52.5001e6],
460 set_process=lambda x: HP8116A._get_value_with_unit(x, HP8116A._units_frequency),
461 get_process=lambda x: HP8116A._parse_value_with_unit(x, HP8116A._units_frequency)
462 )
463
464 sweep_time = Instrument.control(
465 'ISWT', 'SWT %s',
466 """Control the sweep time per decade in both sweep modes in s (float).
467 The sweep time is selectable in a 1-2-5 sequence between 10 ms and 500 s.
468 """,
469 validator=truncated_discrete_set,
470 values=_generate_1_2_5_sequence(10e-3, 500),
471 set_process=lambda x: HP8116A._get_value_with_unit(x, HP8116A._units_time),
472 get_process=lambda x: HP8116A._parse_value_with_unit(x, HP8116A._units_time)
473 )
474
475 @property
476 def status(self):
477 """Get the status byte of the 8116A as a :class:`Status` IntFlag-type enum."""
478 return Status(self.adapter.connection.read_stb())
479
480 @property
481 def complete(self):
482 """Get whether the measurement is complete (bool)."""
483 return not (self.status & Status.buffer_not_empty)
484
485 @property
486 def options(self):
487 """Get the device options installed. The only possible option is 001."""
488 if self.has_option_001:
489 return ['001']
490 else:
491 return []
492
493 def start_autovernier(self, control, digit, direction, start_value=None):
494 """ Start the autovernier on the specified control.
495
496 :param control: The control to change, pass as :code:`HP8116A.some_control`. Allowed
497 controls are frequency, amplitude, offset, duty_cycle, and pulse_width
498 :param digit: The digit to change, type: :py:class:`HP8116A.Digit`.
499 :param direction: The direction in which to change the control,
500 type: :py:class:`HP8116A.Direction`.
501 :param start_value: An optional value to start the autovernier at. If not specified,
502 the current value of the control is used.
503 """
504 if not self.autovernier_enabled:
505 raise RuntimeError('Autovernier has to be enabled first.')
506
507 if control not in (HP8116A.frequency, HP8116A.amplitude, HP8116A.offset,
508 HP8116A.duty_cycle, HP8116A.pulse_width):
509 raise ValueError('Control must be one of frequency, amplitude, offset, ' +
510 'duty_cycle, or pulse_width.')
511
512 start_value = control.fget(self) if start_value is None else start_value
513 # The control always has to be set to select it for the autovernier.
514 control.fset(self, start_value)
515
516 self.write(digit.value + direction.value)
517
518 def GPIB_trigger(self):
519 """ Initiate trigger via low-level GPIB-command (aka GET - group execute trigger). """
520 self.adapter.connection.assert_trigger()
521
522 def reset(self):
523 """ Initatiate a reset (like a power-on reset) of the 8116A. """
524 self.adapter.connection.clear()
525 self._wait_for_commands_processed()
526
527 def shutdown(self):
528 """ Gracefully close the connection to the 8116A. """
529 self.adapter.connection.clear()
530 self.adapter.close()
531 super().shutdown()
532
533 def check_errors(self):
534 """ Check for errors in the 8116A.
535
536 :return: list of error entries or empty list if no error occurred.
537 """
538 errors_response = self.ask('IERR', 100).split('\r\n')[0].strip(' ,\r\n')
539 errors = errors_response.split('ERROR')[:-1]
540 errors = [e.strip() + " ERROR" for e in errors]
541
542 if errors[0] == 'NO ERROR':
543 return []
544 else:
545 for error in errors:
546 log.error(f'{self.name}: {error}')
547 return errors
548
549 def _wait_for_commands_processed(self, timeout=1):
550 """ Wait until the commands have been processed by the 8116A. """
551 start = time.time()
552 while not self.complete:
553 time.sleep(0.001)
554 if time.time() - start > timeout:
555 raise RuntimeError('Timeout waiting for commands to be processed.')
556
557 def _check_has_option_001(self):
558 """ Return True if the 8116A has option 001 and False otherwise.
559
560 This is done by checking the length of the response to the CST (current status) command
561 which includes sweep parameters and burst parameters only if the 8116A has option 001.
562 """
563
564 # The longest possible state string is 163 characters long including termination characters
565 state_string = self.ask('CST', 163).split('\r\n')[0].strip(' ,\r\n')
566
567 if len(state_string) == 159:
568 return True
569 elif len(state_string) == 87:
570 return False
571 else:
572 log.warning('Could not determine if 8116A has option 001. Assuming it has.')
573 return True