Debian Codegraph @

pymeasure/instruments/teledyne/teledyne_oscilloscope.py

raw
1 #
2 # This file is part of the PyMeasure package.
3 #
4 # Copyright (c) 2013-2022 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 from abc import ABCMeta
26 import re
27 import sys
28 import time
29 from decimal import Decimal
30 import numpy as np
31
32 from pymeasure.instruments import Instrument, Channel, SCPIUnknownMixin
33 from pymeasure.instruments.validators import strict_discrete_set, strict_range, \
34 strict_discrete_range
35
36
37 def sanitize_source(source):
38 """Parse source string.
39
40 :param source: can be "cX", "ch X", "chan X", "channel X", "math" or "line", where X is
41 a single digit integer. The parser is case and white space insensitive.
42 :return: can be "C1", "C2", "C3", "C4", "MATH" or "LINE.
43 """
44
45 match = re.match(r"^\s*(C|CH|CHAN|CHANNEL)\s*(?P<number>\d)\s*$|"
46 r"^\s*(?P<name_only>MATH|LINE)\s*$", source, re.IGNORECASE)
47 if match:
48 if match.group("number") is not None:
49 source = "C" + match.group("number")
50 else:
51 source = match.group("name_only")
52 source = source.upper()
53 else:
54 raise ValueError(f"source {source} not recognized")
55 return source
56
57
58 def _trigger_select_num_pars(value):
59 """Find the expected number of parameters for the trigger_select property.
60
61 :param value: input parameters as a tuple
62 """
63 value = tuple(map(lambda v: v.upper() if isinstance(v, str) else v, value))
64 num_expected_pars = 0
65 if 3 <= len(value) <= 5:
66 if value[0] == "EDGE":
67 num_expected_pars = 3 if value[2] == "OFF" else 4
68 elif value[0] in ["SLEW", "INTV"]:
69 num_expected_pars = 4 if value[2] in ["IS", "IL"] else 5
70 elif value[0] in ["GLIT", "RUNT"]:
71 num_expected_pars = 4 if value[2] in ["PS", "PL"] else 5
72 elif value[0] == "DROP":
73 num_expected_pars = 4
74 else:
75 raise ValueError('Number of parameters {} can only be 3, 4, 5'.format(len(value)))
76 return num_expected_pars
77
78
79 def _trigger_select_validator(value, values, num_pars_finder=_trigger_select_num_pars):
80 """Validate the input of the trigger_select property.
81
82 :param value: input parameters as a tuple
83 :param values: allowed space for each parameter
84 :param num_pars_finder: function to find the number of expected parameters
85 """
86 if not isinstance(value, tuple):
87 raise ValueError('Input value {} of trigger_select should be a tuple'.format(value))
88 if len(value) < 3 or len(value) > 5:
89 raise ValueError('Number of parameters {} can only be 3, 4, 5'.format(len(value)))
90 value = tuple(map(lambda v: v.upper() if isinstance(v, str) else v, value))
91 value = list(value)
92 value[1] = sanitize_source(value[1])
93 value = tuple(value)
94 if value[0] not in values.keys():
95 raise ValueError('Value {} not in the discrete set {}'.format(value[0], values.keys()))
96 num_expected_pars = num_pars_finder(value)
97 if len(value) != num_expected_pars:
98 raise ValueError('Number of parameters {} != {}'.format(len(value), num_expected_pars))
99 for i, element in enumerate(value[1:], start=1):
100 if i < 3:
101 strict_discrete_set(element, values=values[value[0]][i - 1])
102 else:
103 strict_range(element, values=values[value[0]][i - 1])
104 return value
105
106
107 def _trigger_select_get_process(value):
108 """Process the output of the trigger_select property.
109
110 The format of the input list is
111
112 <trig_type>, SR, <source>, HT, <hold_type>[, HV, <hold_value1>S][, HV2, <hold_value2>S]
113
114 The format of the output list is
115
116 <trig_type>, <source>, <hold_type>[, <hold_value1>][, <hold_value2>]
117
118 :param value: output parameters as a list
119 """
120 output = []
121 if len(value) > 0:
122 output.append(value[0].lower())
123 if "SR" in value:
124 output.append(value[value.index("SR") + 1].lower())
125 if "HT" in value:
126 output.append(value[value.index("HT") + 1].lower())
127 if "HV" in value:
128 output.append(float(value[value.index("HV") + 1][:-1]))
129 if "HV2" in value:
130 output.append(float(value[value.index("HV2") + 1][:-1]))
131 return output
132
133
134 def _results_list_to_dict(results):
135 """Turn a list into a dict, using the uneven indices as keys.
136
137 E.g. turn ['C1', 'OFF', 'C2', 'OFF'] into {'C1': 'OFF', 'C2': 'OFF'}
138 """
139 keys = results[::2]
140 values = results[1::2]
141 return dict(zip(keys, values))
142
143
144 def _remove_unit(value):
145 """Remove a unit from the returned string and cast to float."""
146 if isinstance(value, float):
147 return value
148
149 if value.endswith(" V"):
150 value = value[:-2]
151
152 return float(value)
153
154
155 def _intensity_validator(value, values):
156 """Validate the input of the intensity property (grid intensity and trace intensity).
157
158 :param value: input parameters as a 2-element tuple
159 :param values: allowed space for each parameter
160 """
161 if not isinstance(value, tuple):
162 raise ValueError('Input value {} of trigger_select should be a tuple'.format(value))
163 if len(value) != 2:
164 raise ValueError('Number of parameters {} different from 2'.format(len(value)))
165 for i in range(2):
166 strict_discrete_range(value=value[i], values=values[i], step=1)
167 return value
168
169
170 class _ChunkResizer:
171 """The only purpose of this class is to resize the chunk size of the instrument adapter.
172
173 This is necessary when reading a big chunk of data from the oscilloscope like image dumps and
174 waveforms.
175
176 .. Note::
177 Only if the new chunk size is bigger than the current chunk size, it is resized.
178
179 """
180
181 def __init__(self, adapter, chunk_size):
182 """Just initialize the object attributes.
183
184 :param adapter: Adapter of the instrument. This is usually accessed through the
185 Instrument::adapter attribute.
186 :param chunk_size: new chunk size (int).
187 """
188 self.adapter = adapter
189 self.old_chunk_size = None
190 self.new_chunk_size = int(chunk_size) if chunk_size else 0
191
192 def __enter__(self):
193 """Only resize the chunk size if the adapter support this feature."""
194 if (self.adapter.connection is not None
195 and hasattr(self.adapter.connection, "chunk_size")):
196 if self.new_chunk_size > self.adapter.connection.chunk_size:
197 self.old_chunk_size = self.adapter.connection.chunk_size
198 self.adapter.connection.chunk_size = self.new_chunk_size
199
200 def __exit__(self, exc_type, exc_val, exc_tb):
201 if self.old_chunk_size is not None:
202 self.adapter.connection.chunk_size = self.old_chunk_size
203
204
205 class TeledyneOscilloscopeChannel(Channel, metaclass=ABCMeta):
206 """A base abstract class for channel on a :class:`TeledyneOscilloscope` device."""
207
208 _BOOLS = {True: "ON", False: "OFF"}
209
210 BANDWIDTH_LIMITS = ["OFF", "ON"]
211
212 TRIGGER_SLOPES = {"negative": "NEG", "positive": "POS"}
213
214 # Capture and split a reply like "RMS,281E-6" and "RMS,281E-6,OK"
215 # The third response item ("state"), is not present in all oscilloscopes
216 # For compatibility it is captured if it can, but ignored otherwise
217 _re_pava_response = re.compile(r"^\s*"
218 r"(?P<parameter>\w+),\s*"
219 r"(?P<value>[^,]*)\s*"
220 r"(?:,(?P<state>\w+)\s*)?$")
221
222 bwlimit = Instrument.control(
223 "BWL?", "BWL %s",
224 """Control the internal low-pass filter for this channel.
225
226 The current bandwidths can only be read back for all channels at once!
227 """,
228 validator=strict_discrete_set,
229 values=BANDWIDTH_LIMITS,
230 get_process=_results_list_to_dict,
231 dynamic=True,
232 )
233
234 coupling = Instrument.control(
235 "CPL?", "CPL %s",
236 """Control the coupling with a string parameter ("ac 1M", "dc 1M", "ground").""",
237 validator=strict_discrete_set,
238 values={"ac 1M": "A1M", "dc 1M": "D1M", "ground": "GND"},
239 map_values=True
240 )
241
242 display = Instrument.control(
243 "TRA?", "TRA %s",
244 """Control the display enabled state. (strict bool)""",
245 validator=strict_discrete_set,
246 values=_BOOLS,
247 map_values=True
248 )
249
250 offset = Instrument.control(
251 "OFST?", "OFST %.2EV",
252 """Control the center of the screen in Volts by a a float parameter.
253 The range of legal values varies depending on range and scale. If the specified
254 value is outside of the legal range, the offset value is automatically set to the nearest
255 legal value.
256 """
257 )
258
259 probe_attenuation = Instrument.control(
260 "ATTN?", "ATTN %g",
261 """Control the probe attenuation. The probe attenuation may be from 0.1 to 10000.""",
262 validator=strict_discrete_set,
263 values={0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000}
264 )
265
266 scale = Instrument.control(
267 "VDIV?", "VDIV %.2EV",
268 """Control the vertical scale (units per division) in Volts."""
269 )
270
271 trigger_coupling = Instrument.control(
272 "TRCP?", "TRCP %s",
273 """Control the input coupling for the selected trigger sources (string).
274
275 - ac: AC coupling block DC component in the trigger path, removing dc offset
276 voltage from the trigger waveform. Use AC coupling to get a stable edge trigger when
277 your waveform has a large dc offset.
278 - dc: DC coupling allows dc and ac signals into the trigger path.
279 - lowpass: HFREJ coupling places a lowpass filter in the trigger path.
280 - highpass: LFREJ coupling places a highpass filter in the trigger path.
281
282 """,
283 validator=strict_discrete_set,
284 values={"ac": "AC", "dc": "DC", "lowpass": "HFREJ", "highpass": "LFREJ"},
285 map_values=True
286 )
287
288 trigger_level = Instrument.control(
289 "TRLV?", "TRLV %.2EV",
290 """Control the trigger level voltage for the active trigger source (float).
291
292 When there are two trigger levels to set, this command is used to set the higher
293 trigger level voltage for the specified source. :attr:`trigger_level2` is used to set
294 the lower trigger level voltage.
295
296 When setting the trigger level it must be divided by the probe attenuation. This is
297 not documented in the datasheet and it is probably a bug of the scope firmware.
298 An out-of-range value will be adjusted to the closest legal value.
299 """,
300 get_process=_remove_unit,
301 )
302
303 trigger_slope = Instrument.control(
304 "TRSL?", "TRSL %s",
305 """Control the trigger slope of the specified trigger source (string).
306
307 <trig_slope>:={NEG,POS,WINDOW} for edge trigger
308 <trig_slope>:={NEG,POS} for other trigger
309
310 +------------+--------------------------------------------------+
311 | parameter | trigger slope |
312 +------------+--------------------------------------------------+
313 | negative | Negative slope for edge trigger or other trigger |
314 +------------+--------------------------------------------------+
315 | positive | Positive slope for edge trigger or other trigger |
316 +------------+--------------------------------------------------+
317 | window | Window slope for edge trigger |
318 +------------+--------------------------------------------------+
319
320 """,
321 validator=strict_discrete_set,
322 values=TRIGGER_SLOPES,
323 map_values=True,
324 dynamic=True,
325 )
326
327 _measurable_parameters = ["PKPK", "MAX", "MIN", "AMPL", "TOP", "BASE", "CMEAN", "MEAN", "RMS",
328 "CRMS", "OVSN", "FPRE", "OVSP", "RPRE", "PER", "FREQ", "PWID",
329 "NWID", "RISE", "FALL", "WID", "DUTY", "NDUTY", "ALL"]
330
331 display_parameter = Instrument.setting(
332 "PACU %s",
333 """Set the waveform processing of this channel with the specified algorithm and the result
334 is displayed on the front panel.
335
336 The command accepts the following parameters:
337
338 ========= ===================================
339 Parameter Description
340 ========= ===================================
341 PKPK vertical peak-to-peak
342 MAX maximum vertical value
343 MIN minimum vertical value
344 AMPL vertical amplitude
345 TOP waveform top value
346 BASE waveform base value
347 CMEAN average value in the first cycle
348 MEAN average value
349 RMS RMS value
350 CRMS RMS value in the first cycle
351 OVSN overshoot of a falling edge
352 FPRE preshoot of a falling edge
353 OVSP overshoot of a rising edge
354 RPRE preshoot of a rising edge
355 PER period
356 FREQ frequency
357 PWID positive pulse width
358 NWID negative pulse width
359 RISE rise-time
360 FALL fall-time
361 WID Burst width
362 DUTY positive duty cycle
363 NDUTY negative duty cycle
364 ALL All measurement
365 ========= ===================================
366 """,
367 validator=strict_discrete_set,
368 values=_measurable_parameters
369 )
370
371 def measure_parameter(self, parameter: str):
372 """Process a waveform with the selected algorithm and returns the specified measurement.
373
374 :param parameter: same as the display_parameter property
375 """
376 parameter = strict_discrete_set(value=parameter, values=self._measurable_parameters)
377 output = self.ask("PAVA? %s" % parameter)
378 match = self._re_pava_response.match(output)
379 if match:
380 if match.group('parameter') != parameter:
381 raise ValueError(f"Parameter {match.group('parameter')} different from {parameter}")
382 if match.group('state') and match.group('state') == 'IV':
383 raise ValueError(f"Parameter state for {parameter} is invalid")
384 return float(match.group('value'))
385 else:
386 raise ValueError(f"Cannot extract value from output {output}")
387
388 def insert_id(self, command):
389 # only in case of the BWL and PACU commands the syntax is different. Why? SIGLENT Why?
390 if command[0:4] == "BWL ":
391 return "BWL C%d,%s" % (self.id, command[4:])
392 elif command[0:5] == "PACU ":
393 return "PACU %s,C%d" % (command[5:], self.id)
394 else:
395 return "C%d:%s" % (self.id, command)
396
397 # noinspection PyIncorrectDocstring
398 def setup(self, **kwargs):
399 """Setup channel. Unspecified settings are not modified.
400
401 Modifying values such as probe attenuation will modify offset, range, etc. Refer to
402 oscilloscope documentation and make multiple consecutive calls to setup() if needed.
403 See property descriptions for more information.
404
405 :param bwlimit:
406 :param coupling:
407 :param display:
408 :param invert:
409 :param offset:
410 :param skew_factor:
411 :param probe_attenuation:
412 :param scale:
413 :param unit:
414 :param trigger_coupling:
415 :param trigger_level:
416 :param trigger_level2:
417 :param trigger_slope:
418 """
419 for key, value in kwargs.items():
420 setattr(self, key, value)
421
422 @property
423 def current_configuration(self):
424 """Get channel configuration as a dict containing the following keys:
425
426 - "channel": channel number (int)
427 - "attenuation": probe attenuation (float)
428 - "bandwidth_limit": bandwidth limiting enabled (bool)
429 - "coupling": "ac 1M", "dc 1M", "ground" coupling (str)
430 - "offset": vertical offset (float)
431 - "skew_factor": channel-tochannel skew factor (float)
432 - "display": currently displayed (bool)
433 - "unit": "A" or "V" units (str)
434 - "volts_div": vertical divisions (float)
435 - "inverted": inverted (bool)
436 - "trigger_coupling": trigger coupling can be "dc" "ac" "highpass" "lowpass" (str)
437 - "trigger_level": trigger level (float)
438 - "trigger_level2": trigger lower level for SLEW or RUNT trigger (float)
439 - "trigger_slope": trigger slope can be "negative" "positive" "window" (str)
440 """
441
442 ch_setup = {
443 "channel": self.id,
444 "attenuation": self.probe_attenuation,
445 "bandwidth_limit": self.bwlimit,
446 "coupling": self.coupling,
447 "offset": self.offset,
448 "skew_factor": self.skew_factor,
449 "display": self.display,
450 "unit": self.unit,
451 "volts_div": self.scale,
452 "inverted": self.invert,
453 "trigger_coupling": self.trigger_coupling,
454 "trigger_level": self.trigger_level,
455 "trigger_level2": self.trigger_level2,
456 "trigger_slope": self.trigger_slope
457 }
458 return ch_setup
459
460
461 class TeledyneOscilloscope(SCPIUnknownMixin, Instrument, metaclass=ABCMeta):
462 """A base abstract class for any Teledyne Lecroy oscilloscope.
463
464 All Teledyne oscilloscopes have a very similar interface, hence this base class to combine
465 them. Note that specific models will likely have conflicts in their interface.
466
467 Attributes:
468 WRITE_INTERVAL_S: minimum time between two commands. If a command is received less than
469 WRITE_INTERVAL_S after the previous one, the code blocks until at least WRITE_INTERVAL_S
470 seconds have passed.
471 Because the oscilloscope takes a non neglibile time to perform some operations, it might
472 be needed for the user to tweak the sleep time between commands.
473 The WRITE_INTERVAL_S is set to 10ms as default however its optimal value heavily depends
474 on the actual commands and on the connection type, so it is impossible to give a unique
475 value to fit all cases. An interval between 10ms and 500ms second proved to be good,
476 depending on the commands and connection latency.
477 """
478
479 _BOOLS = TeledyneOscilloscopeChannel._BOOLS
480
481 WRITE_INTERVAL_S = 0.02 # seconds
482
483 ch_1 = Instrument.ChannelCreator(TeledyneOscilloscopeChannel, 1)
484
485 ch_2 = Instrument.ChannelCreator(TeledyneOscilloscopeChannel, 2)
486
487 ch_3 = Instrument.ChannelCreator(TeledyneOscilloscopeChannel, 3)
488
489 ch_4 = Instrument.ChannelCreator(TeledyneOscilloscopeChannel, 4)
490
491 def __init__(self, adapter, name="Teledyne Oscilloscope", **kwargs):
492 super().__init__(adapter, name=name, **kwargs)
493 if self.adapter.connection is not None:
494 self.adapter.connection.timeout = 3000
495 self._grid_number = 14 # Number of grids in the horizontal direction
496 self._seconds_since_last_write = 0 # Timestamp of the last command
497 self._header_size = 16 # bytes
498 self._footer_size = 2 # bytes
499 self.waveform_source = "C1"
500 self.default_setup()
501
502 ################
503 # System Setup #
504 ################
505
506 def default_setup(self):
507 """ Set up the oscilloscope for remote operation.
508
509 The COMM_HEADER command controls the
510 way the oscilloscope formats response to queries. This command does not affect the
511 interpretation of messages sent to the oscilloscope. Headers can be sent in their long or
512 short form regardless of the CHDR setting.
513 By setting the COMM_HEADER to OFF, the instrument is going to reply with minimal
514 information, and this makes the response message much easier to parse.
515 The user should not be fiddling with the COMM_HEADER during operation, because
516 if the communication header is anything other than OFF, the whole driver breaks down.
517 """
518 self._comm_header = "OFF"
519
520 def ch(self, source):
521 """ Get channel object from its index or its name. Or if source is "math", just return the
522 scope object.
523
524 :param source: can be 1, 2, 3, 4 or C1, C2, C3, C4, MATH
525 :return: handle to the selected source.
526 """
527 if isinstance(source, str):
528 source = sanitize_source(source)
529 if source == "MATH":
530 return self
531 elif source == "LINE":
532 raise ValueError("LINE is not a valid channel")
533 else:
534 return getattr(self, f"ch_{source if isinstance(source, int) else source[-1]}")
535
536 def autoscale(self):
537 """ Autoscale displayed channels."""
538 self.write("ASET")
539
540 def write(self, command, **kwargs):
541 """Write the command to the instrument through the adapter.
542
543 Note: if the last command was sent less than WRITE_INTERVAL_S before, this method blocks for
544 the remaining time so that commands are never sent with rate more than 1/WRITE_INTERVAL_S
545 Hz.
546
547 :param command: command string to be sent to the instrument
548 """
549 seconds_since_last_write = time.monotonic() - self._seconds_since_last_write
550 if seconds_since_last_write < self.WRITE_INTERVAL_S:
551 time.sleep(self.WRITE_INTERVAL_S - seconds_since_last_write)
552 self._seconds_since_last_write = seconds_since_last_write
553 super().write(command, **kwargs)
554
555 _comm_header = Instrument.control(
556 "CHDR?", "CHDR %s",
557 """Control the way the oscilloscope formats response to queries.
558 The user should not be fiddling with the COMM_HEADER during operation, because
559 if the communication header is anything other than OFF, the whole driver breaks down.
560 • SHORT — response starts with the short form of the header word.
561 • LONG — response starts with the long form of the header word.
562 • OFF — header is omitted from the response and units in numbers are suppressed.""",
563 validator=strict_discrete_set,
564 values=["OFF", "SHORT", "LONG"],
565 )
566
567 ###########
568 # General #
569 ###########
570
571 bwlimit = Instrument.control(
572 "BWL?", "BWL %s",
573 """Set the internal low-pass filter for all channels.""",
574 validator=strict_discrete_set,
575 values=TeledyneOscilloscopeChannel.BANDWIDTH_LIMITS,
576 get_process=_results_list_to_dict,
577 dynamic=True,
578 )
579
580 ##################
581 # Timebase Setup #
582 ##################
583
584 timebase_offset = Instrument.control(
585 "TRDL?", "TRDL %.2ES",
586 """Control the time interval in seconds between the trigger event and the reference
587 position (at center of screen by default)."""
588 )
589
590 timebase_scale = Instrument.control(
591 "TDIV?", "TDIV %.2ES",
592 """Control the horizontal scale (units per division) in seconds for the main
593 window (float).""",
594 validator=strict_range,
595 values=[1e-9, 100]
596 )
597
598 @property
599 def timebase(self):
600 """Get timebase setup as a dict containing the following keys:
601
602 - "timebase_scale": horizontal scale in seconds/div (float)
603 - "timebase_offset": interval in seconds between the trigger and the reference
604 position (float)
605 """
606 tb_setup = {
607 "timebase_scale": self.timebase_scale,
608 "timebase_offset": self.timebase_offset,
609 }
610 return tb_setup
611
612 def timebase_setup(self, scale=None, offset=None):
613 """Set up timebase. Unspecified parameters are not modified. Modifying a single parameter
614 might impact other parameters. Refer to oscilloscope documentation and make multiple
615 consecutive calls to timebase_setup if needed.
616
617 :param scale: interval in seconds between the trigger event and the reference position.
618 :param offset: horizontal scale per division in seconds/div.
619 """
620
621 if scale is not None:
622 self.timebase_scale = scale
623 if offset is not None:
624 self.timebase_offset = offset
625
626 ###############
627 # Acquisition #
628 ###############
629
630 def run(self):
631 """Starts repetitive acquisitions.
632
633 This is the same as pressing the Run key on the front panel.
634 """
635 self.trigger_mode = "normal"
636
637 def stop(self):
638 """ Stops the acquisition. This is the same as pressing the Stop key on the front panel."""
639 self.write("STOP")
640
641 def single(self):
642 """Causes the instrument to acquire a single trigger of data.
643
644 This is the same as pressing the Single key on the front panel.
645 """
646 self.write("ARM")
647
648 ##################
649 # Waveform #
650 ##################
651
652 waveform_points = Instrument.control(
653 "WFSU?", "WFSU NP,%d",
654 """Control the number of waveform points to be transferred with
655 the digitize method (int). NP = 0 sends all data points.
656
657 Note that the oscilloscope may provide less than the specified nb of points.
658 """,
659 validator=strict_range,
660 get_process=lambda vals: vals[vals.index("NP") + 1],
661 values=[0, sys.maxsize]
662 )
663
664 waveform_sparsing = Instrument.control(
665 "WFSU?", "WFSU SP,%d",
666 """Control the interval between data points (integer). For example:
667
668 SP = 0 sends all data points.
669 SP = 4 sends 1 point every 4 data points.
670 """,
671 validator=strict_range,
672 get_process=lambda vals: vals[vals.index("SP") + 1],
673 values=[0, sys.maxsize]
674 )
675
676 waveform_first_point = Instrument.control(
677 "WFSU?", "WFSU FP,%d",
678 """Control the address of the first data point to be sent (int).
679 For waveforms acquired in sequence mode, this refers to the relative address in the
680 given segment. The first data point starts at zero and is strictly positive.""",
681 validator=strict_range,
682 get_process=lambda vals: vals[vals.index("FP") + 1],
683 values=[0, sys.maxsize]
684 )
685
686 ##################
687 # Waveform #
688 ##################
689
690 memory_size = Instrument.control(
691 "MSIZ?", "MSIZ %s",
692 """Control the maximum depth of memory (float or string).
693 Assign for example 500, 100e6, "100K", "25MA".
694
695 The reply will always be a float.
696 """
697 )
698
699 @property
700 def waveform_preamble(self):
701 """Get preamble information for the selected waveform source as a dict with the
702 following keys:
703
704 - "requested_points": number of data points requested by the user (int)
705 - "sampled_points": number of data points sampled by the oscilloscope (int)
706 - "transmitted_points": number of data points actually transmitted (optional) (int)
707 - "memory_size": size of the oscilloscope internal memory in bytes (int)
708 - "sparsing": sparse point. It defines the interval between data points. (int)
709 - "first_point": address of the first data point to be sent (int)
710 - "source": source of the data : "C1", "C2", "C3", "C4", "MATH".
711 - "grid_number": number of horizontal grids (it is a read-only property)
712 - "xdiv": horizontal scale (units per division) in seconds
713 - "xoffset": time interval in seconds between the trigger event and the reference position
714 - "ydiv": vertical scale (units per division) in Volts
715 - "yoffset": value that is represented at center of screen in Volts
716
717 """
718 vals = self.values("WFSU?")
719 preamble = {
720 "sparsing": vals[vals.index("SP") + 1],
721 "requested_points": vals[vals.index("NP") + 1],
722 "first_point": vals[vals.index("FP") + 1],
723 "transmitted_points": None,
724 "source": self.waveform_source,
725 "grid_number": self._grid_number,
726 "memory_size": self.memory_size,
727 "xdiv": self.timebase_scale,
728 "xoffset": self.timebase_offset
729 }
730 return self._fill_yaxis_preamble(preamble)
731
732 def _fill_yaxis_preamble(self, preamble=None):
733 """Fill waveform preamble section concerning the Y-axis.
734 :param preamble: waveform preamble to be filled
735 :return: filled preamble
736 """
737 if preamble is None:
738 preamble = {}
739 if self.waveform_source == "MATH":
740 preamble["ydiv"] = self.math_vdiv
741 preamble["yoffset"] = self.math_vpos
742 else:
743 preamble["ydiv"] = self.ch(self.waveform_source).scale
744 preamble["yoffset"] = self.ch(self.waveform_source).offset
745 return preamble
746
747 def _digitize(self, src, num_bytes=None):
748 """Acquire waveforms according to the settings of the acquire commands.
749 Note.
750 If the requested number of bytes is not specified, the default chunk size is used,
751 but in such a case it cannot be quaranteed that the message is received in its entirety.
752
753 :param src: source of data: "C1", "C2", "C3", "C4", "MATH".
754 :param: num_bytes: number of bytes expected from the scope (including the header and
755 footer).
756 :return: bytearray with raw data.
757 """
758 with _ChunkResizer(self.adapter, num_bytes):
759 binary_values = self.binary_values(f"{src}:WF? DAT2", dtype=np.uint8)
760 if num_bytes is not None and len(binary_values) != num_bytes:
761 raise BufferError(f"read bytes ({len(binary_values)}) != requested bytes ({num_bytes})")
762 return binary_values
763
764 def _header_footer_sanity_checks(self, message):
765 """Check that the header follows the predefined format.
766 The format of the header is DAT2,#9XXXXXXX where XXXXXXX is the number of acquired
767 points, and it is zero padded.
768 Then check that the footer is present. The footer is a double line-carriage \n\n
769 :param message: raw bytes received from the scope """
770 message_header = bytes(message[0:self._header_size]).decode("ascii")
771 # Sanity check on header and footer
772 if message_header[0:7] != "DAT2,#9":
773 raise ValueError(f"Waveform data in invalid : header is {message_header}")
774 message_footer = bytes(message[-self._footer_size:]).decode("ascii")
775 if message_footer != "\n\n":
776 raise ValueError(f"Waveform data in invalid : footer is {message_footer}")
777
778 def _npoints_sanity_checks(self, message):
779 """Check that the number of transmitted points is consistent with the message length.
780 :param message: raw bytes received from the scope """
781 message_header = bytes(message[0:self._header_size]).decode("ascii")
782 transmitted_points = int(message_header[-9:])
783 received_points = len(message) - self._header_size - self._footer_size
784 if transmitted_points != received_points:
785 raise ValueError(f"Number of transmitted points ({transmitted_points}) != "
786 f"number of received points ({received_points})")
787
788 def _acquire_data(self, requested_points=0, sparsing=1):
789 """Acquire raw data points from the scope. The header, footer and number of points are
790 sanity-checked, but they are not processed otherwise. For a description of the input
791 arguments refer to the download_waveform method.
792 If the number of expected points is big enough, the transmission is split in smaller
793 chunks of 20k points and read one chunk at a time. I do not know the reason why,
794 but if the chunk size is big enough the transmission does not complete successfully.
795 :return: raw data points as numpy array and waveform preamble
796 """
797 # Setup waveform acquisition parameters
798 self.waveform_sparsing = sparsing
799 self.waveform_points = requested_points
800 self.waveform_first_point = 0
801
802 # Calculate how many points are to be expected
803 sample_points = self.acquisition_sample_size(self.waveform_source)
804 if requested_points > 0:
805 expected_points = min(requested_points, int(sample_points / sparsing))
806 else:
807 expected_points = int(sample_points / sparsing)
808
809 # If the number of points is big enough, split the data in small chunks and read it one
810 # chunk at a time. For less than a certain amount of points we do not bother splitting them.
811 chunk_bytes = 20000
812 chunk_points = chunk_bytes - self._header_size - self._footer_size
813 iterations = -(expected_points // -chunk_points)
814 i = 0
815 data = []
816 while i < iterations:
817 # number of points already read
818 read_points = i * chunk_points
819 # number of points still to read
820 remaining_points = expected_points - read_points
821 # number of points requested in a single chunk
822 requested_points = chunk_points if remaining_points > chunk_points else remaining_points
823 self.waveform_points = requested_points
824 # number of bytes requested in a single chunk
825 requested_bytes = requested_points + self._header_size + self._footer_size
826 # read the next chunk starting from this points
827 first_point = read_points * sparsing
828 self.waveform_first_point = first_point
829 # read chunk of points
830 values = self._digitize(src=self.waveform_source, num_bytes=requested_bytes)
831 # perform many sanity checks on the received data
832 self._header_footer_sanity_checks(values)
833 self._npoints_sanity_checks(values)
834 # append the points without the header and footer
835 data.append(values[self._header_size:-self._footer_size])
836 i += 1
837 data = np.concatenate(data)
838 preamble = self.waveform_preamble
839 return data, preamble
840
841 #################
842 # Download data #
843 #################
844
845 def download_image(self):
846 """Get a BMP image of oscilloscope screen in bytearray of specified file format.
847 """
848 # Using binary_values query because default interface does not support binary transfer
849 with _ChunkResizer(self.adapter, 20 * 1024 * 1024):
850 img = self.binary_values("SCDP", dtype=np.uint8)
851 return bytearray(img)
852
853 def _process_data(self, ydata, preamble):
854 """Apply scale and offset to the data points acquired from the scope.
855 - Y axis : the scale is ydiv / 25 and the offset -yoffset. the
856 offset is not applied for the MATH source.
857 - X axis : the scale is sparsing / sampling_rate and the offset is -xdiv * 7. The
858 7 = 14 / 2 factor comes from the fact that there are 14 vertical grid lines and the data
859 starts from the left half of the screen.
860
861 :return: tuple of (numpy array of Y points, numpy array of X points, waveform preamble) """
862
863 def _scale_data(y):
864 if preamble["source"] == "MATH":
865 value = int.from_bytes([y], byteorder='big', signed=False) * preamble["ydiv"] / 25.
866 value -= preamble["ydiv"] * (preamble["yoffset"] + 255) / 50.
867 else:
868 value = int.from_bytes([y], byteorder='big', signed=True) * preamble["ydiv"] / 25.
869 value -= preamble["yoffset"]
870 return value
871
872 def _scale_time(x):
873 return float(Decimal(-preamble["xdiv"] * self._grid_number / 2.) +
874 Decimal(float(x * preamble["sparsing"])) /
875 Decimal(preamble["sampling_rate"]))
876
877 data_points = np.vectorize(_scale_data)(ydata)
878 time_points = np.vectorize(_scale_time)(np.arange(len(data_points)))
879 return data_points, time_points, preamble
880
881 def download_waveform(self, source, requested_points=None, sparsing=None):
882 """Get data points from the specified source of the oscilloscope.
883
884 The returned objects are two np.ndarray of data and time points and a dict with the
885 waveform preamble, that contains metadata about the waveform.
886
887 :param source: measurement source. It can be "C1", "C2", "C3", "C4", "MATH".
888 :param requested_points: number of points to acquire. If None the number of points
889 requested in the previous call will be assumed, i.e. the value of the number of
890 points stored in the oscilloscope memory. If 0 the maximum number of points will
891 be returned.
892 :param sparsing: interval between data points. For example if sparsing = 4, only one
893 point every 4 points is read. If 0 or None the sparsing of the previous call is
894 assumed, i.e. the value of the sparsing stored in the oscilloscope memory.
895 :return: data_ndarray, time_ndarray, waveform_preamble_dict: see waveform_preamble
896 property for dict format.
897 """
898 # Sanitize the input arguments
899 if not sparsing:
900 sparsing = self.waveform_sparsing
901 if requested_points is None:
902 requested_points = self.waveform_points
903 self.waveform_source = sanitize_source(source)
904 # Acquire the Y data and the preable
905 ydata, preamble = self._acquire_data(requested_points, sparsing)
906 # Update the preamble with info about actually acquired data
907 preamble["transmitted_points"] = len(ydata)
908 preamble["requested_points"] = requested_points
909 preamble["sparsing"] = sparsing
910 preamble["first_point"] = 0
911 # Scale the Y-data and create the X-data
912 return self._process_data(ydata, preamble)
913
914 ###############
915 # Trigger #
916 ###############
917
918 trigger_mode = Instrument.control(
919 "TRMD?", "TRMD %s",
920 """Control the trigger sweep mode (string).
921
922 <mode>:= {AUTO,NORM,SINGLE,STOP}
923
924 - auto : When AUTO sweep mode is selected, the oscilloscope begins to search for the
925 trigger signal that meets the conditions.
926 If the trigger signal is satisfied, the running state on the top left corner of
927 the user interface shows Trig'd, and the interface shows stable waveform.
928 Otherwise, the running state always shows Auto, and the interface shows unstable
929 waveform.
930 - normal : When NORMAL sweep mode is selected, the oscilloscope enters the wait trigger
931 state and begins to search for trigger signals that meet the conditions.
932 If the trigger signal is satisfied, the running state shows Trig'd, and the interface
933 shows stable waveform.
934 Otherwise, the running state shows Ready, and the interface displays the last
935 triggered waveform (previous trigger) or does not display the waveform (no
936 previous trigger).
937 - single : When SINGLE sweep mode is selected, the backlight of SINGLE key lights up,
938 the oscilloscope enters the waiting trigger state and begins to search for the
939 trigger signal that meets the conditions.
940 If the trigger signal is satisfied, the running state shows Trig'd, and the interface
941 shows stable waveform.
942 Then, the oscilloscope stops scanning, the RUN/STOP key is red light,
943 and the running status shows Stop.
944 Otherwise, the running state shows Ready, and the interface does not display the waveform.
945 - stopped : STOP is a part of the option of this command, but not a trigger mode of the
946 oscilloscope.
947 """,
948 validator=strict_discrete_set,
949 values={"stopped": "STOP", "normal": "NORM", "single": "SINGLE", "auto": "AUTO"},
950 map_values=True
951 )
952
953 _trigger_select_vals = {
954 "EDGE": [["C1", "C2", "C3", "C4", "LINE"], ["TI", "OFF"], [80e-9, 1.5]],
955 "DROP": [["C1", "C2", "C3", "C4"], ["TI"], [2e-9, 4.2]],
956 "GLIT": [["C1", "C2", "C3", "C4"], ["PS", "PL", "P2", "P1"], [2e-9, 4.2], [2e-9, 4.2]],
957 "RUNT": [["C1", "C2", "C3", "C4"], ["PS", "PL", "P2", "P1"], [2e-9, 4.2]],
958 "SLEW": [["C1", "C2", "C3", "C4"], ["IS", "IL", "I2", "I1"], [2e-9, 4.2]],
959 "INTV": [["C1", "C2", "C3", "C4"], ["IS", "IL", "I2", "I1"], [2e-9, 4.2]]
960 }
961
962 _trigger_select_short_command = "TRSE %s,SR,%s,HT,%s"
963 _trigger_select_normal_command = "TRSE %s,SR,%s,HT,%s,HV,%.2E"
964 _trigger_select_extended_command = "TRSE %s,SR,%s,HT,%s,HV,%.2E,HV2,%.2E"
965
966 _trigger_select = Instrument.control(
967 "TRSE?", _trigger_select_normal_command,
968 """Control the trigger, see :meth:`~trigger_select()` documentation.""",
969 get_process=_trigger_select_get_process,
970 validator=_trigger_select_validator,
971 values=_trigger_select_vals,
972 dynamic=True
973 )
974
975 def center_trigger(self):
976 """Set the trigger levels to center of the trigger source waveform."""
977 self.write("SET50")
978
979 @property
980 def trigger_select(self):
981 """Control the condition that will trigger the acquisition of waveforms (string).
982
983 Depending on the trigger type, additional parameters must be specified. These additional
984 parameters are grouped in pairs. The first in the pair names the variable to be modified,
985 while the second gives the new value to be assigned. Pairs may be given in any order and
986 restricted to those variables to be changed.
987
988 There are five parameters that can be specified. Parameters 1. 2. 3. are always mandatory.
989 Parameters 4. 5. are required only for certain combinations of the previous parameters.
990
991 1. <trig_type>:={edge, slew, glit, intv, runt, drop}
992 2. <source>:={c1, c2, c3, c4, line}
993 3. <hold_type>:=
994
995 * {ti, off} for edge trigger.
996 * {ti} for drop trigger.
997 * {ps, pl, p2, p1} for glit/runt trigger.
998 * {is, il, i2, i1} for slew/intv trigger.
999
1000 4. <hold_value1>:= a time value with unit.
1001 5. <hold_value2>:= a time value with unit.
1002
1003 Note:
1004
1005 - "line" can only be selected when the trigger type is "edge".
1006 - All time arguments should be given in multiples of seconds. Use the scientific notation
1007 if necessary.
1008 - The range of hold_values varies from trigger types. [80nS, 1.5S] for "edge" trigger,
1009 and [2nS, 4.2S] for others.
1010 - The trigger_select command is switched automatically between the short, normal and
1011 extended version depending on the number of expected parameters.
1012 """
1013 return self._trigger_select
1014
1015 # noinspection PyAttributeOutsideInit
1016 @trigger_select.setter
1017 def trigger_select(self, value):
1018 num_expected_pars = _trigger_select_num_pars(value)
1019 if num_expected_pars == 3:
1020 self._trigger_select_set_command = self._trigger_select_short_command
1021 elif num_expected_pars == 4:
1022 self._trigger_select_set_command = self._trigger_select_normal_command
1023 elif num_expected_pars == 5:
1024 self._trigger_select_set_command = self._trigger_select_extended_command
1025 self._trigger_select = value
1026
1027 def trigger_setup(self, mode=None, source=None, trigger_type=None, hold_type=None,
1028 hold_value1=None, hold_value2=None, coupling=None, level=None, level2=None,
1029 slope=None):
1030 """Set up trigger.
1031
1032 Unspecified parameters are not modified. Modifying a single parameter
1033 might impact other parameters. Refer to oscilloscope documentation and make multiple
1034 consecutive calls to trigger_setup and channel_setup if needed.
1035
1036 :param mode: trigger sweep mode [auto, normal, single, stop]
1037 :param source: trigger source [c1, c2, c3, c4, line]
1038 :param trigger_type: condition that will trigger the acquisition of waveforms
1039 [edge,slew,glit,intv,runt,drop]
1040 :param hold_type: hold type (refer to page 172 of programing guide)
1041 :param hold_value1: hold value1 (refer to page 172 of programing guide)
1042 :param hold_value2: hold value2 (refer to page 172 of programing guide)
1043 :param coupling: input coupling for the selected trigger sources
1044 :param level: trigger level voltage for the active trigger source
1045 :param level2: trigger lower level voltage for the active trigger source (only slew/runt
1046 trigger)
1047 :param slope: trigger slope of the specified trigger source
1048 """
1049 if mode is not None:
1050 self.trigger_mode = mode
1051 if all(i is not None for i in [source, trigger_type, hold_type]):
1052 args = [trigger_type, source, hold_type]
1053 if hold_value1 is not None:
1054 args.append(hold_value1)
1055 if hold_value2 is not None:
1056 args.append(hold_value2)
1057 self.trigger_select = tuple(args)
1058 elif any(i is not None for i in [source, trigger_type, hold_type]):
1059 raise ValueError("Need to specify all of source, trigger_type and hold_type arguments")
1060 if source is not None:
1061 source = sanitize_source(source)
1062 strict_discrete_set(source, ["C1", "C2", "C3", "C4", "LINE"])
1063 ch = self.ch(source)
1064 if coupling is not None:
1065 ch.trigger_coupling = coupling
1066 if level is not None:
1067 ch.trigger_level = level
1068 if level2 is not None:
1069 ch.trigger_level2 = level2
1070 if slope is not None:
1071 ch.trigger_slope = slope
1072
1073 @property
1074 def trigger(self):
1075 """Get trigger setup as a dict containing the following keys:
1076
1077 - "mode": trigger sweep mode [auto, normal, single, stop]
1078 - "trigger_type": condition that will trigger the acquisition of waveforms [edge,
1079 slew,glit,intv,runt,drop]
1080 - "source": trigger source [c1,c2,c3,c4]
1081 - "hold_type": hold type (refer to page 172 of programing guide)
1082 - "hold_value1": hold value1 (refer to page 172 of programing guide)
1083 - "hold_value2": hold value2 (refer to page 172 of programing guide)
1084 - "coupling": input coupling for the selected trigger sources
1085 - "level": trigger level voltage for the active trigger source
1086 - "level2": trigger lower level voltage for the active trigger source (only slew/runt
1087 trigger)
1088 - "slope": trigger slope of the specified trigger source
1089
1090 """
1091 trigger_select = self.trigger_select
1092 ch = self.ch(trigger_select[1])
1093 tb_setup = {
1094 "mode": self.trigger_mode,
1095 "trigger_type": trigger_select[0],
1096 "source": trigger_select[1],
1097 "hold_type": trigger_select[2],
1098 "hold_value1": trigger_select[3] if len(trigger_select) >= 4 else None,
1099 "hold_value2": trigger_select[4] if len(trigger_select) >= 5 else None,
1100 "coupling": ch.trigger_coupling,
1101 "level": ch.trigger_level,
1102 "level2": ch.trigger_level2,
1103 "slope": ch.trigger_slope
1104 }
1105 return tb_setup
1106
1107 ###############
1108 # Math #
1109 ###############
1110
1111 ###############
1112 # Measure #
1113 ###############
1114
1115 def display_parameter(self, parameter, channel):
1116 """Same as the display_parameter method in the Channel subclass."""
1117 self.ch(channel).display_parameter = parameter
1118
1119 def measure_parameter(self, parameter, channel):
1120 """
1121 Same as the measure_parameter method in the Channel subclass
1122 """
1123 # noinspection PyArgumentList
1124 return self.ch(channel).measure_parameter(parameter)
1125
1126 ###############
1127 # Display #
1128 ###############
1129
1130 intensity = Instrument.control(
1131 "INTS?", "INTS GRID,%d,TRACE,%d",
1132 """Set the intensity level of the grid or the trace in percent """,
1133 validator=_intensity_validator,
1134 values=[[0, 100], [0, 100]],
1135 get_process=lambda v: {v[0]: v[1], v[2]: v[3]}
1136 )