Debian Codegraph @

pymeasure/instruments/keysight/keysightDSOX1102G.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 import logging
25
26 import numpy as np
27
28 from pymeasure.instruments import Instrument, SCPIUnknownMixin
29 from pymeasure.instruments.validators import strict_discrete_set, strict_range
30
31 log = logging.getLogger(__name__)
32 log.addHandler(logging.NullHandler())
33
34
35 class Channel():
36 """ Implementation of a Keysight DSOX1102G Oscilloscope channel.
37
38 Implementation modeled on Channel object of Tektronix AFG3152C instrument. """
39
40 BOOLS = {True: 1, False: 0}
41
42 bwlimit = Instrument.control(
43 "BWLimit?", "BWLimit %d",
44 """ A boolean parameter that toggles 25 MHz internal low-pass filter.""",
45 validator=strict_discrete_set,
46 values=BOOLS,
47 map_values=True
48 )
49
50 coupling = Instrument.control(
51 "COUPling?", "COUPling %s",
52 """ A string parameter that determines the coupling ("ac" or "dc").""",
53 validator=strict_discrete_set,
54 values={"ac": "AC", "dc": "DC"},
55 map_values=True
56 )
57
58 display = Instrument.control(
59 "DISPlay?", "DISPlay %d",
60 """ A boolean parameter that toggles the display.""",
61 validator=strict_discrete_set,
62 values=BOOLS,
63 map_values=True
64 )
65
66 invert = Instrument.control(
67 "INVert?", "INVert %d",
68 """ A boolean parameter that toggles the inversion of the input signal.""",
69 validator=strict_discrete_set,
70 values=BOOLS,
71 map_values=True
72 )
73
74 label = Instrument.control(
75 "LABel?", 'LABel "%s"',
76 """ A string to label the channel. Labels with more than 10 characters are truncated to 10
77 characters. May contain commonly used ASCII characters. Lower case characters are converted
78 to upper case.""",
79 get_process=lambda v: str(v[1:-1])
80 )
81
82 offset = Instrument.control(
83 "OFFSet?", "OFFSet %f",
84 """ A float parameter to set value that is represented at center of screen in
85 Volts. The range of legal values varies depending on range and scale. If the specified
86 value is outside of the legal range, the offset value is automatically set to the nearest
87 legal value.
88 """
89 )
90
91 probe_attenuation = Instrument.control(
92 "PROBe?", "PROBe %f",
93 """ A float parameter that specifies the probe attenuation. The probe attenuation
94 may be from 0.1 to 10000.""",
95 validator=strict_range,
96 values=[0.1, 10000]
97 )
98
99 range = Instrument.control(
100 "RANGe?", "RANGe %f",
101 """ A float parameter that specifies the full-scale vertical axis in Volts.
102 When using 1:1 probe attenuation, legal values for the range are from 8 mV to 40V."""
103 )
104
105 scale = Instrument.control(
106 "SCALe?", "SCALe %f",
107 """A float parameter that specifies the vertical scale, or units per division, in Volts."""
108 )
109
110 def __init__(self, instrument, number):
111 self.instrument = instrument
112 self.number = number
113
114 def values(self, command, **kwargs):
115 """ Reads a set of values from the instrument through the adapter,
116 passing on any key-word arguments.
117 """
118 return self.instrument.values(":channel%d:%s" % (
119 self.number, command), **kwargs)
120
121 def ask(self, command):
122 self.instrument.ask(":channel%d:%s" % (self.number, command))
123
124 def write(self, command):
125 self.instrument.write(":channel%d:%s" % (self.number, command))
126
127 def setup(self, bwlimit=None, coupling=None, display=None, invert=None, label=None, offset=None,
128 probe_attenuation=None, vertical_range=None, scale=None):
129 """ Setup channel. Unspecified settings are not modified. Modifying values such as
130 probe attenuation will modify offset, range, etc. Refer to oscilloscope documentation and
131 make multiple consecutive calls to setup() if needed.
132
133 :param bwlimit: A boolean, which enables 25 MHz internal low-pass filter.
134 :param coupling: "ac" or "dc".
135 :param display: A boolean, which enables channel display.
136 :param invert: A boolean, which enables input signal inversion.
137 :param label: Label string with max. 10 commonly used ASCII characters.
138 :param offset: Numerical value represented at center of screen, must be inside
139 the legal range.
140 :param probe_attenuation: Probe attenuation values from 0.1 to 1000.
141 :param vertical_range: Full-scale vertical axis of the selected channel. When using 1:1
142 probe attenuation, legal values for the range are from 8mV to 40 V. If the probe
143 attenuation is changed, the range value is multiplied by the probe attenuation factor.
144 :param scale: Units per division. """
145
146 if vertical_range is not None and scale is not None:
147 log.warning(
148 'Both "vertical_range" and "scale" are specified. Specified "scale" has priority.')
149
150 if probe_attenuation is not None:
151 self.probe_attenuation = probe_attenuation
152 if bwlimit is not None:
153 self.bwlimit = bwlimit
154 if coupling is not None:
155 self.coupling = coupling
156 if display is not None:
157 self.display = display
158 if invert is not None:
159 self.invert = invert
160 if label is not None:
161 self.label = label
162 if offset is not None:
163 self.offset = offset
164 if vertical_range is not None:
165 self.range = vertical_range
166 if scale is not None:
167 self.scale = scale
168
169 @property
170 def current_configuration(self):
171 """ Read channel configuration as a dict containing the following keys:
172 - "CHAN": channel number (int)
173 - "OFFS": vertical offset (float)
174 - "RANG": vertical range (float)
175 - "COUP": "dc" or "ac" coupling (str)
176 - "IMP": input impedance (str)
177 - "DISP": currently displayed (bool)
178 - "BWL": bandwidth limiting enabled (bool)
179 - "INV": inverted (bool)
180 - "UNIT": unit (str)
181 - "PROB": probe attenuation (float)
182 - "PROB:SKEW": skew factor (float)
183 - "STYP": probe signal type (str)
184 """
185
186 # Using the instrument's ask method because Channel.ask() adds the prefix ":channelX:", and
187 # to query the configuration details, we actually need to ask ":channelX?", without a
188 # second ":"
189 ch_setup_raw = self.instrument.ask(":channel%d?" % self.number).strip("\n")
190
191 # ch_setup_raw hat the following format:
192 # :CHAN1:RANG +40.0E+00;OFFS +0.00000E+00;COUP DC;IMP ONEM;DISP 1;BWL 0;
193 # INV 0;LAB "1";UNIT VOLT;PROB +10E+00;PROB:SKEW +0.00E+00;STYP SING
194
195 # Cut out the ":CHANx:" at beginning and split string
196 ch_setup_splitted = ch_setup_raw[7:].split(";")
197
198 # Create dict of setup parameters
199 ch_setup_dict = dict(map(lambda v: v.split(" "), ch_setup_splitted))
200
201 # Add "CHAN" key
202 ch_setup_dict["CHAN"] = ch_setup_raw[5]
203
204 # Convert values to specific type
205 to_str = ["COUP", "IMP", "UNIT", "STYP"]
206 to_bool = ["DISP", "BWL", "INV"]
207 to_float = ["OFFS", "PROB", "PROB:SKEW", "RANG"]
208 to_int = ["CHAN"]
209 for key in ch_setup_dict:
210 if key in to_str:
211 ch_setup_dict[key] = str(ch_setup_dict[key])
212 elif key in to_bool:
213 ch_setup_dict[key] = (ch_setup_dict[key] == "1")
214 elif key in to_float:
215 ch_setup_dict[key] = float(ch_setup_dict[key])
216 elif key in to_int:
217 ch_setup_dict[key] = int(ch_setup_dict[key])
218 return ch_setup_dict
219
220
221 class KeysightDSOX1102G(SCPIUnknownMixin, Instrument):
222 """ Represents the Keysight DSOX1102G Oscilloscope interface for interacting
223 with the instrument.
224
225 Refer to the Keysight DSOX1102G Oscilloscope Programmer's Guide for further details about
226 using the lower-level methods to interact directly with the scope.
227
228 .. code-block:: python
229
230 scope = KeysightDSOX1102G(resource)
231 scope.autoscale()
232 ch1_data_array, ch1_preamble = scope.download_data(source="channel1", points=2000)
233 # ...
234 scope.shutdown()
235
236 Known issues:
237
238 - The digitize command will be completed before the operation is. May lead to
239 VI_ERROR_TMO (timeout) occurring when sending commands immediately after digitize.
240 Current fix: if deemed necessary, add delay between digitize and follow-up command
241 to scope.
242 """
243
244 BOOLS = {True: 1, False: 0}
245
246 def __init__(self, adapter, name="Keysight DSOX1102G Oscilloscope", **kwargs):
247 super().__init__(
248 adapter, name, timeout=6000, **kwargs
249 )
250 # Account for setup time for timebase_mode, waveform_points_mode
251 self.ch1 = Channel(self, 1)
252 self.ch2 = Channel(self, 2)
253
254 #################
255 # Channel setup #
256 #################
257
258 def autoscale(self):
259 """ Autoscale displayed channels. """
260 self.write(":autoscale")
261
262 ##################
263 # Timebase Setup #
264 ##################
265
266 @property
267 def timebase(self):
268 """ Read timebase setup as a dict containing the following keys:
269 - "REF": position on screen of timebase reference (str)
270 - "MAIN:RANG": full-scale timebase range (float)
271 - "POS": interval between trigger and reference point (float)
272 - "MODE": mode (str)"""
273 return self._timebase()
274
275 timebase_mode = Instrument.control(
276 ":TIMebase:MODE?", ":TIMebase:MODE %s",
277 """ A string parameter that sets the current time base. Can be "main",
278 "window", "xy", or "roll".""",
279 validator=strict_discrete_set,
280 values={"main": "MAIN", "window": "WIND", "xy": "XY", "roll": "ROLL"},
281 map_values=True
282 )
283
284 timebase_offset = Instrument.control(
285 ":TIMebase:POSition?", ":TIMebase:REFerence CENTer;:TIMebase:POSition %f",
286 """ A float parameter that sets the time interval in seconds between the trigger
287 event and the reference position (at center of screen by default)."""
288 )
289
290 timebase_range = Instrument.control(
291 ":TIMebase:RANGe?", ":TIMebase:RANGe %f",
292 """ A float parameter that sets the full-scale horizontal time in seconds for the
293 main window."""
294 )
295
296 timebase_scale = Instrument.control(
297 ":TIMebase:SCALe?", ":TIMebase:SCALe %f",
298 """ A float parameter that sets the horizontal scale (units per division) in seconds
299 for the main window."""
300 )
301
302 ###############
303 # Acquisition #
304 ###############
305
306 acquisition_type = Instrument.control(
307 ":ACQuire:TYPE?", ":ACQuire:TYPE %s",
308 """ A string parameter that sets the type of data acquisition. Can be "normal", "average",
309 "hresolution", or "peak".""",
310 validator=strict_discrete_set,
311 values={"normal": "NORM", "average": "AVER", "hresolution": "HRES", "peak": "PEAK"},
312 map_values=True
313 )
314
315 acquisition_mode = Instrument.control(
316 ":ACQuire:MODE?", ":ACQuire:MODE %s",
317 """ A string parameter that sets the acquisition mode. Can be "realtime" or "segmented".""",
318 validator=strict_discrete_set,
319 values={"realtime": "RTIM", "segmented": "SEGM"},
320 map_values=True
321 )
322
323 def run(self):
324 """ Starts repetitive acquisitions.
325
326 This is the same as pressing the Run key on the front panel.
327 """
328 self.write(":run")
329
330 def stop(self):
331 """ Stops the acquisition. This is the same as pressing the Stop key on the front panel."""
332 self.write(":stop")
333
334 def single(self):
335 """ Causes the instrument to acquire a single trigger of data.
336 This is the same as pressing the Single key on the front panel. """
337 self.write(":single")
338
339 _digitize = Instrument.setting(
340 ":DIGitize %s",
341 """ Acquire waveforms according to the settings of the :ACQuire commands and specified
342 source, as a string parameter that can take the following values: "channel1", "channel2",
343 "function", "math", "fft", "abus", or "ext". """,
344 validator=strict_discrete_set,
345 values={"channel1": "CHAN1", "channel2": "CHAN2", "function": "FUNC", "math": "MATH",
346 "fft": "FFT", "abus": "ABUS", "ext": "EXT"},
347 map_values=True
348 )
349
350 def digitize(self, source: str):
351 """ Acquire waveforms according to the settings of the :ACQuire commands. Ensure a delay
352 between the digitize operation and further commands, as timeout may be reached before
353 digitize has completed.
354 :param source: "channel1", "channel2", "function", "math", "fft", "abus", or "ext"."""
355 self._digitize = source
356
357 waveform_points_mode = Instrument.control(
358 ":waveform:points:mode?", ":waveform:points:mode %s",
359 """ A string parameter that sets the data record to be transferred with the waveform_data
360 method. Can be "normal", "maximum", or "raw".""",
361 validator=strict_discrete_set,
362 values={"normal": "NORM", "maximum": "MAX", "raw": "RAW"},
363 map_values=True
364 )
365 waveform_points = Instrument.control(
366 ":waveform:points?", ":waveform:points %d",
367 """ An integer parameter that sets the number of waveform points to be transferred with
368 the waveform_data method. Can be any of the following values:
369 100, 250, 500, 1000, 2 000, 5 000, 10 000, 20 000, 50 000, 62 500.
370
371 Note that the oscilloscope may provide less than the specified nb of points. """,
372 validator=strict_discrete_set,
373 values=[100, 250, 500, 1000, 2000, 5000, 10000, 20000, 50000, 62500]
374 )
375 waveform_source = Instrument.control(
376 ":waveform:source?", ":waveform:source %s",
377 """ A string parameter that selects the analog channel, function, or reference waveform
378 to be used as the source for the waveform methods. Can be "channel1", "channel2",
379 "function", "fft", "wmemory1", "wmemory2", or "ext".""",
380 validator=strict_discrete_set,
381 values={"channel1": "CHAN1", "channel2": "CHAN2", "function": "FUNC", "fft": "FFT",
382 "wmemory1": "WMEM1", "wmemory2": "WMEM2", "ext": "EXT"},
383 map_values=True
384 )
385 waveform_format = Instrument.control(
386 ":waveform:format?", ":waveform:format %s",
387 """ A string parameter that controls how the data is formatted when sent from the
388 oscilloscope. Can be "ascii", "word" or "byte". Words are transmitted in big endian by
389 default.""",
390 validator=strict_discrete_set,
391 values={"ascii": "ASC", "word": "WORD", "byte": "BYTE"},
392 map_values=True
393 )
394
395 @property
396 def waveform_preamble(self):
397 """ Get preamble information for the selected waveform source as a dict with the following keys:
398 - "format": byte, word, or ascii (str)
399 - "type": normal, peak detect, or average (str)
400 - "points": nb of data points transferred (int)
401 - "count": always 1 (int)
402 - "xincrement": time difference between data points (float)
403 - "xorigin": first data point in memory (float)
404 - "xreference": data point associated with xorigin (int)
405 - "yincrement": voltage difference between data points (float)
406 - "yorigin": voltage at center of screen (float)
407 - "yreference": data point associated with yorigin (int)""" # noqa: E501
408 return self._waveform_preamble()
409
410 @property
411 def waveform_data(self):
412 """ Get the binary block of sampled data points transmitted using the IEEE 488.2 arbitrary
413 block data format."""
414 # Other waveform formats raise UnicodeDecodeError
415 self.waveform_format = "ascii"
416
417 data = self.values(":waveform:data?")
418 # Strip header from first data element
419 data[0] = float(data[0][10:])
420
421 return data
422
423 ################
424 # System Setup #
425 ################
426
427 @property
428 def system_setup(self):
429 """ A string parameter that sets up the oscilloscope. Must be in IEEE 488.2 format.
430 It is recommended to only set a string previously obtained from this command."""
431 return self.ask(":system:setup?")
432
433 @system_setup.setter
434 def system_setup(self, setup_string):
435 self.write(":system:setup " + setup_string)
436
437 def ch(self, channel_number):
438 if channel_number == 1:
439 return self.ch1
440 elif channel_number == 2:
441 return self.ch2
442 else:
443 raise ValueError("Invalid channel number. Must be 1 or 2.")
444
445 def clear_status(self):
446 """ Clear device status. """
447 self.write("*CLS")
448
449 def factory_reset(self):
450 """ Factory default setup, no user settings remain unchanged. """
451 self.write("*RST")
452
453 def default_setup(self):
454 """ Default setup, some user settings (like preferences) remain unchanged. """
455 self.write(":SYSTem:PRESet")
456
457 def timebase_setup(self, mode=None, offset=None, horizontal_range=None, scale=None):
458 """ Set up timebase. Unspecified parameters are not modified. Modifying a single parameter
459 might impact other parameters. Refer to oscilloscope documentation and make multiple
460 consecutive calls to channel_setup if needed.
461
462 :param mode: Timebase mode, can be "main", "window", "xy", or "roll".
463 :param offset: Offset in seconds between trigger and center of screen.
464 :param horizontal_range: Full-scale range in seconds.
465 :param scale: Units-per-division in seconds."""
466
467 if mode is not None:
468 self.timebase_mode = mode
469 if offset is not None:
470 self.timebase_offset = offset
471 if horizontal_range is not None:
472 self.timebase_range = horizontal_range
473 if scale is not None:
474 self.timebase_scale = scale
475
476 def download_image(self, format_="png", color_palette="color"):
477 """ Get image of oscilloscope screen in bytearray of specified file format.
478
479 :param format_: "bmp", "bmp8bit", or "png"
480 :param color_palette: "color" or "grayscale"
481 """
482 query = f":DISPlay:DATA? {format_}, {color_palette}"
483 # Using binary_values query because default interface does not support binary transfer
484 img = self.binary_values(query, header_bytes=10, dtype=np.uint8)
485 return bytearray(img)
486
487 def download_data(self, source, points=62500):
488 """ Get data from specified source of oscilloscope. Returned objects are a np.ndarray of
489 data values (no temporal axis) and a dict of the waveform preamble, which can be used to
490 build the corresponding time values for all data points.
491
492 Multimeter will be stopped for proper acquisition.
493
494 :param source: measurement source, can be "channel1", "channel2", "function", "fft",
495 "wmemory1", "wmemory2", or "ext".
496 :param points: integer number of points to acquire. Note that oscilloscope may return fewer
497 points than specified, this is not an issue of this library. Can be 100, 250, 500, 1000,
498 2000, 5000, 10000, 20000, 50000, or 62500.
499
500 :return data_ndarray, waveform_preamble_dict: see waveform_preamble property for dict
501 format.
502 """
503 # TODO: Consider downloading from multiple sources at the same time.
504 self.waveform_source = source
505 self.waveform_points_mode = "normal"
506 self.waveform_points = points
507
508 preamble = self.waveform_preamble
509 data_bytes = self.waveform_data
510 return np.array(data_bytes), preamble
511
512 def _timebase(self):
513 """
514 Reads setup data from timebase and converts it to a more convenient dict of values.
515 """
516 tb_setup_raw = self.ask(":timebase?").strip("\n")
517
518 # tb_setup_raw hat the following format:
519 # :TIM:MODE MAIN;REF CENT;MAIN:RANG +1.00E-03;POS +0.0E+00
520
521 # Cut out the ":TIM:" at beginning and split string
522 tb_setup_splitted = tb_setup_raw[5:].split(";")
523
524 # Create dict of setup parameters
525 tb_setup = dict(map(lambda v: v.split(" "), tb_setup_splitted))
526
527 # Convert values to specific type
528 to_str = ["MODE", "REF"]
529 to_float = ["MAIN:RANG", "POS"]
530 for key in tb_setup:
531 if key in to_str:
532 tb_setup[key] = str(tb_setup[key])
533 elif key in to_float:
534 tb_setup[key] = float(tb_setup[key])
535
536 return tb_setup
537
538 def _waveform_preamble(self):
539 """
540 Reads waveform preamble and converts it to a more convenient dict of values.
541 """
542 vals = self.values(":waveform:preamble?")
543 # Get values to dict
544 vals_dict = dict(zip(["format", "type", "points", "count", "xincrement", "xorigin",
545 "xreference", "yincrement", "yorigin", "yreference"], vals))
546 # Map element values
547 format_map = {0: "BYTE", 1: "WORD", 4: "ASCII"}
548 type_map = {0: "NORMAL", 1: "PEAK DETECT", 2: "AVERAGE", 3: "HRES"}
549 vals_dict["format"] = format_map[int(vals_dict["format"])]
550 vals_dict["type"] = type_map[int(vals_dict["type"])]
551
552 # Correct types
553 to_int = ["points", "count", "xreference", "yreference"]
554 to_float = ["xincrement", "xorigin", "yincrement", "yorigin"]
555 for key in vals_dict:
556 if key in to_int:
557 vals_dict[key] = int(vals_dict[key])
558 elif key in to_float:
559 vals_dict[key] = float(vals_dict[key])
560
561 return vals_dict