Debian Codegraph @

pymeasure/instruments/lecroy/lecroyT3DSO1204.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 import re
26
27 from pymeasure.instruments import Instrument
28 from pymeasure.instruments.teledyne.teledyne_oscilloscope import TeledyneOscilloscope,\
29 TeledyneOscilloscopeChannel, sanitize_source
30 from pymeasure.instruments.validators import strict_discrete_set, strict_range
31
32 log = logging.getLogger(__name__)
33 log.addHandler(logging.NullHandler())
34
35
36 def _math_define_validator(value, values):
37 """
38 Validate the input of the math_define property
39 :param value: input parameters as a 3-element tuple
40 :param values: allowed space for each parameter
41 """
42 if not isinstance(value, tuple):
43 raise ValueError('Input value {} of trigger_select should be a tuple'.format(value))
44 if len(value) != 3:
45 raise ValueError('Number of parameters {} different from 3'.format(len(value)))
46 output = (sanitize_source(value[0]), value[1], sanitize_source(value[2]))
47 for i in range(3):
48 strict_discrete_set(output[i], values=values[i])
49 return output
50
51
52 def _measure_delay_validator(value, values):
53 """
54 Validate the input of the measure_delay property
55 :param value: input parameters as a 3-element tuple
56 :param values: allowed space for each parameter
57 """
58 if not isinstance(value, tuple):
59 raise ValueError('Input value {} of trigger_select should be a tuple'.format(value))
60 if len(value) != 3:
61 raise ValueError('Number of parameters {} different from 3'.format(len(value)))
62 output = (value[0], sanitize_source(value[1]), sanitize_source(value[2]))
63 if output[1][0] > output[2][0]:
64 raise ValueError(f'First channel number {output[1]} must be <= than second one {output[2]}')
65 for i in range(3):
66 strict_discrete_set(output[i], values=values[i])
67 return output
68
69
70 class LeCroyT3DSO1204Channel(TeledyneOscilloscopeChannel):
71 """Implementation of a LeCroy T3DSO1204 Oscilloscope channel.
72
73 Implementation modeled on Channel object of Keysight DSOX1102G instrument.
74 """
75
76 TRIGGER_SLOPES = {"negative": "NEG", "positive": "POS", "window": "WINDOW"}
77
78 # Change listed values for existing commands:
79 trigger_slope_values = TRIGGER_SLOPES
80
81 bwlimit = Instrument.control(
82 "BWL?", "BWL %s",
83 """Control the 20 MHz internal low-pass filter (strict bool).
84
85 This oscilloscope only has one frequency available for this filter.
86 """,
87 validator=strict_discrete_set,
88 values=TeledyneOscilloscopeChannel._BOOLS,
89 map_values=True
90 )
91
92 invert = Instrument.control(
93 "INVS?", "INVS %s",
94 """Control the inversion of the input signal (strict bool).""",
95 validator=strict_discrete_set,
96 values=TeledyneOscilloscopeChannel._BOOLS,
97 map_values=True
98 )
99
100 skew_factor = Instrument.control(
101 "SKEW?", "SKEW %.2ES",
102 """Control the channel-to-channel skew factor for the specified channel.
103 Each analog channel can be adjusted + or -100 ns for a total of 200 ns difference
104 between channels. You can use the oscilloscope's skew control to remove cable-delay
105 errors between channels.
106 """,
107 validator=strict_range,
108 values=[-1e-7, 1e-7],
109 preprocess_reply=lambda v: v.rstrip('S')
110 )
111
112 trigger_level2 = Instrument.control(
113 "TRLV2?", "TRLV2 %.2EV",
114 """Control the lower trigger level voltage for the specified source (float).
115 Higher and lower trigger levels are used with runt/slope triggers.
116 When setting the trigger level it must be divided by the probe attenuation. This is
117 not documented in the datasheet and it is probably a bug of the scope firmware.
118 An out-of-range value will be adjusted to the closest legal value.
119 """
120 )
121
122 unit = Instrument.control(
123 "UNIT?", "UNIT %s",
124 """Control the unit of the specified trace. Measurement results, channel sensitivity, and
125 trigger level will reflect the measurement units you select. ("A" for Amperes, "V" for
126 Volts).
127 """,
128 validator=strict_discrete_set,
129 values=["A", "V"]
130 )
131
132
133 class LeCroyT3DSO1204(TeledyneOscilloscope):
134 """Represents the LeCroy T3DSO1204 Oscilloscope interface for interacting with the instrument.
135
136 Refer to the LeCroy T3DSO1204 Oscilloscope Programmer's Guide for further details about
137 using the lower-level methods to interact directly with the scope.
138
139 This implementation is based on the shared base class :class:`TeledyneOscilloscope`.
140
141 Attributes:
142
143 WRITE_INTERVAL_S: minimum time between two commands. If a command is received less than
144 WRITE_INTERVAL_S after the previous one, the code blocks until at least WRITE_INTERVAL_S
145 seconds have passed.
146 Because the oscilloscope takes a non-negligible time to perform some operations, it might
147 be needed for the user to tweak the sleep time between commands.
148 The WRITE_INTERVAL_S is set to 10ms as default however its optimal value heavily depends
149 on the actual commands and on the connection type, so it is impossible to give a unique
150 value to fit all cases. An interval between 10ms and 500ms second proved to be good,
151 depending on the commands and connection latency.
152
153 .. code-block:: python
154
155 scope = LeCroyT3DSO1204(resource)
156 scope.autoscale()
157 ch1_data_array, ch1_preamble = scope.download_waveform(source="C1", points=2000)
158 # ...
159 scope.shutdown()
160 """
161
162 _BOOLS = {True: "ON", False: "OFF"}
163
164 WRITE_INTERVAL_S = 0.02 # seconds
165
166 ch_1 = Instrument.ChannelCreator(LeCroyT3DSO1204Channel, 1)
167
168 ch_2 = Instrument.ChannelCreator(LeCroyT3DSO1204Channel, 2)
169
170 ch_3 = Instrument.ChannelCreator(LeCroyT3DSO1204Channel, 3)
171
172 ch_4 = Instrument.ChannelCreator(LeCroyT3DSO1204Channel, 4)
173
174 def __init__(self, adapter, name="LeCroy T3DSO1204 Oscilloscope", **kwargs):
175 super().__init__(adapter, name, **kwargs)
176
177 ##################
178 # Timebase Setup #
179 ##################
180
181 timebase_hor_magnify = Instrument.control(
182 "HMAG?", "HMAG %.2ES",
183 """Control the zoomed (delayed) window horizontal scale (seconds/div).
184
185 The main sweep scale determines the range for this command.
186 """,
187 validator=strict_range,
188 values=[1e-9, 20e-3]
189 )
190
191 timebase_hor_position = Instrument.control(
192 "HPOS?", "HPOS %.2ES",
193 """Control the horizontal position in the zoomed (delayed) view of the main sweep.
194
195 The main sweep range and the main sweep horizontal position determine
196 the range for this command. The value for this command must keep the zoomed view window
197 within the main sweep range.
198 """,
199 )
200
201 @property
202 def timebase(self):
203 """Get timebase setup as a dict containing the following keys:
204
205 - "timebase_scale": horizontal scale in seconds/div (float)
206 - "timebase_offset": interval in seconds between the trigger and the reference
207 position (float)
208 - "timebase_hor_magnify": horizontal scale in the zoomed window in seconds/div (float)
209 - "timebase_hor_position": horizontal position in the zoomed window in seconds
210 (float)
211
212 """
213 tb_setup = {
214 "timebase_scale": self.timebase_scale,
215 "timebase_offset": self.timebase_offset,
216 "timebase_hor_magnify": self.timebase_hor_magnify,
217 "timebase_hor_position": self.timebase_hor_position
218 }
219 return tb_setup
220
221 def timebase_setup(self, scale=None, offset=None, hor_magnify=None, hor_position=None):
222 """Set up timebase. Unspecified parameters are not modified. Modifying a single parameter
223 might impact other parameters. Refer to oscilloscope documentation and make multiple
224 consecutive calls to timebase_setup if needed.
225
226 :param scale: interval in seconds between the trigger event and the reference position.
227 :param offset: horizontal scale per division in seconds/div.
228 :param hor_magnify: horizontal scale in the zoomed window in seconds/div.
229 :param hor_position: horizontal position in the zoomed window in seconds."""
230
231 if scale is not None:
232 self.timebase_scale = scale
233 if offset is not None:
234 self.timebase_offset = offset
235 if hor_magnify is not None:
236 self.timebase_hor_magnify = hor_magnify
237 if hor_position is not None:
238 self.timebase_hor_position = hor_position
239
240 ###############
241 # Acquisition #
242 ###############
243
244 acquisition_type = Instrument.control(
245 "ACQW?", "ACQW %s",
246 """Control the type of data acquisition.
247
248 Can be 'normal', 'peak', 'average', 'highres'.
249 """,
250 validator=strict_discrete_set,
251 values={"normal": "SAMPLING", "peak": "PEAK_DETECT", "average": "AVERAGE",
252 "highres": "HIGH_RES"},
253 map_values=True,
254 get_process=lambda v: [v[0].lower(), int(v[1])] if len(v) == 2 and v[0] == "AVERAGE" else v
255 )
256
257 acquisition_average = Instrument.control(
258 "AVGA?", "AVGA %d",
259 """Control the averaging times of average acquisition.""",
260 validator=strict_discrete_set,
261 values=[4, 16, 32, 64, 128, 256, 512, 1024]
262 )
263
264 acquisition_status = Instrument.measurement(
265 "SAST?", """Get the acquisition status of the scope.""",
266 values={"stopped": "Stop", "triggered": "Trig'd", "ready": "Ready", "auto": "Auto",
267 "armed": "Arm"},
268 map_values=True
269 )
270
271 acquisition_sampling_rate = Instrument.measurement(
272 "SARA?", """Get the sample rate of the scope."""
273 )
274
275 def acquisition_sample_size(self, source):
276 """Get acquisition sample size for a certain channel. Used mainly for waveform acquisition.
277 If the source is MATH, the SANU? MATH query does not seem to work, so I return the memory
278 size instead.
279
280 :param source: channel number of channel name.
281 :return: acquisition sample size of that channel.
282 """
283 if isinstance(source, str):
284 source = sanitize_source(source)
285 if source in [1, "C1"]:
286 return self.acquisition_sample_size_c1
287 elif source in [2, "C2"]:
288 return self.acquisition_sample_size_c2
289 elif source in [3, "C3"]:
290 return self.acquisition_sample_size_c3
291 elif source in [4, "C4"]:
292 return self.acquisition_sample_size_c4
293 elif source == "MATH":
294 math_define = self.math_define[1]
295 match = re.match(r"'(\w+)[+\-/*](\w+)'", math_define)
296 return min(self.acquisition_sample_size(match.group(1)),
297 self.acquisition_sample_size(match.group(2)))
298 else:
299 raise ValueError("Invalid source: must be 1, 2, 3, 4 or C1, C2, C3, C4, MATH.")
300
301 acquisition_sample_size_c1 = Instrument.measurement(
302 "SANU? C1", """Get the number of data points that the hardware
303 will acquire from the input signal of channel 1.
304 Note.
305 Channel 2 and channel 1 share the same ADC, so the sample is the same too.
306 """
307 )
308
309 acquisition_sample_size_c2 = Instrument.measurement(
310 "SANU? C1", """Get the number of data points that the hardware
311 will acquire from the input signal of channel 2.
312 Note.
313 Channel 2 and channel 1 share the same ADC, so the sample is the same too.
314 """
315 )
316
317 acquisition_sample_size_c3 = Instrument.measurement(
318 "SANU? C3", """Get the number of data points that the hardware
319 will acquire from the input signal of channel 3.
320 Note.
321 Channel 3 and channel 4 share the same ADC, so the sample is the same too.
322 """
323 )
324
325 acquisition_sample_size_c4 = Instrument.measurement(
326 "SANU? C3", """Get the number of data points that the hardware
327 will acquire from the input signal of channel 4.
328 Note.
329 Channel 3 and channel 4 share the same ADC, so the sample is the same too.
330 """
331 )
332
333 ##################
334 # Waveform #
335 ##################
336
337 memory_size = Instrument.control(
338 "MSIZ?", "MSIZ %s",
339 """Control the maximum depth of memory.
340
341 <size>:={7K,70K,700K,7M} for non-interleaved mode. Non-interleaved means a single channel is
342 active per A/D converter. Most oscilloscopes feature two channels per A/D converter.
343
344 <size>:={14K,140K,1.4M,14M} for interleave mode. Interleave mode means multiple active
345 channels per A/D converter.
346 """,
347 validator=strict_discrete_set,
348 values={7e3: "7K", 7e4: "70K", 7e5: "700K", 7e6: "7M",
349 14e3: "14K", 14e4: "140K", 14e5: "1.4M", 14e6: "14M"},
350 map_values=True
351 )
352
353 @property
354 def waveform_preamble(self):
355 """Get preamble information for the selected waveform source as a dict with the
356 following keys:
357
358 - "type": normal, peak detect, average, high resolution (str)
359 - "requested_points": number of data points requested by the user (int)
360 - "sampled_points": number of data points sampled by the oscilloscope (int)
361 - "transmitted_points": number of data points actually transmitted (optional) (int)
362 - "memory_size": size of the oscilloscope internal memory in bytes (int)
363 - "sparsing": sparse point. It defines the interval between data points. (int)
364 - "first_point": address of the first data point to be sent (int)
365 - "source": source of the data : "C1", "C2", "C3", "C4", "MATH".
366 - "unit": Physical units of the Y-axis
367 - "type": type of data acquisition. Can be "normal", "peak", "average", "highres"
368 - "average": average times of average acquisition
369 - "sampling_rate": sampling rate (it is a read-only property)
370 - "grid_number": number of horizontal grids (it is a read-only property)
371 - "status": acquisition status of the scope. Can be "stopped", "triggered", "ready",
372 "auto", "armed"
373 - "xdiv": horizontal scale (units per division) in seconds
374 - "xoffset": time interval in seconds between the trigger event and the reference position
375 - "ydiv": vertical scale (units per division) in Volts
376 - "yoffset": value that is represented at center of screen in Volts
377 """
378 vals = self.values("WFSU?")
379 preamble = {
380 "sparsing": vals[vals.index("SP") + 1],
381 "requested_points": vals[vals.index("NP") + 1],
382 "first_point": vals[vals.index("FP") + 1],
383 "transmitted_points": None,
384 "source": self.waveform_source,
385 "type": self.acquisition_type,
386 "sampling_rate": self.acquisition_sampling_rate,
387 "grid_number": self._grid_number,
388 "status": self.acquisition_status,
389 "memory_size": self.memory_size,
390 "xdiv": self.timebase_scale,
391 "xoffset": self.timebase_offset
392 }
393 preamble["average"] = self.acquisition_average if preamble["type"][0] == "average" else None
394 strict_discrete_set(self.waveform_source, ["C1", "C2", "C3", "C4", "MATH"])
395 preamble["sampled_points"] = self.acquisition_sample_size(self.waveform_source)
396 return self._fill_yaxis_preamble(preamble)
397
398 def _fill_yaxis_preamble(self, preamble=None):
399 """Fill waveform preamble section concerning the Y-axis.
400 :param preamble: waveform preamble to be filled
401 :return: filled preamble
402 """
403 if preamble is None:
404 preamble = {}
405 if self.waveform_source == "MATH":
406 preamble["ydiv"] = self.math_vdiv
407 preamble["yoffset"] = self.math_vpos
408 preamble["unit"] = None
409 else:
410 preamble["ydiv"] = self.ch(self.waveform_source).scale
411 preamble["yoffset"] = self.ch(self.waveform_source).offset
412 preamble["unit"] = self.ch(self.waveform_source).unit
413 return preamble
414
415 ###############
416 # Math #
417 ###############
418
419 math_define = Instrument.control(
420 "DEF?", "DEF EQN,'%s%s%s'",
421 """Control the desired waveform math operation between two channels.
422
423 Three parameters must be passed as a tuple:
424
425 #. source1 : source channel on the left
426 #. operation : operator must be "*", "/", "+", "-"
427 #. source2 : source channel on the right
428
429 """,
430 validator=_math_define_validator,
431 values=[["C1", "C2", "C3", "C4"], ["*", "/", "+", "-"], ["C1", "C2", "C3", "C4"]]
432 )
433
434 math_vdiv = Instrument.control(
435 "MTVD?", "MTVD %.2EV",
436 """Control the vertical scale of the selected math operation.
437
438 This command is only valid in add, subtract, multiply and divide operation.
439 Note: legal values for the scale depend on the selected operation.
440 """,
441 validator=strict_discrete_set,
442 values=[5e-4, 1e-3, 2e-3, 5e-3, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, 100]
443 )
444
445 math_vpos = Instrument.control(
446 "MTVP?", "MTVP %d",
447 """Control the vertical position of the math waveform with specified source.
448
449 Note: the point represents the screen pixels and is related to the screen center. For
450 example, if the point is 50. The math waveform will be displayed 1 grid above the vertical
451 center of the screen. Namely one grid is 50.
452 """,
453 validator=strict_range,
454 values=[-255, 255]
455 )
456
457 ###############
458 # Measure #
459 ###############
460
461 measure_delay = Instrument.control(
462 "MEAD?", "MEAD %s,%s-%s",
463 """Control measurement delay.
464
465 The MEASURE_DELY command places the instrument in the continuous measurement mode and
466 starts a type of delay measurement.
467 The MEASURE_DELY? query returns the measured value of delay type.
468 The command accepts three arguments with the following syntax:
469
470 measure_delay = (<type>,<sourceA>,<sourceB>)
471
472 <type> := {PHA,FRR,FRF,FFR,FFF,LRR,LRF,LFR,LFF,SKEW}
473
474 <sourceA>,<sourceB> := {C1,C2,C3,C4} where if sourceA=CX and sourceB=CY, then X < Y
475
476 ========= ======================================================================
477 Type Description
478 ========= ======================================================================
479 PHA The phase difference between two channels. (rising edge - rising edge)
480 FRR Delay between two channels. (first rising edge - first rising edge)
481 FRF Delay between two channels. (first rising edge - first falling edge)
482 FFR Delay between two channels. (first falling edge - first rising edge)
483 FFF Delay between two channels. (first falling edge - first falling edge)
484 LRR Delay between two channels. (first rising edge - last rising edge)
485 LRF Delay between two channels. (first rising edge - last falling edge)
486 LFR Delay between two channels. (first falling edge - last rising edge)
487 LFF Delay between two channels. (first falling edge - last falling edge)
488 Skew Delay between two channels. (edge – edge of the same type)
489 ========= ======================================================================
490 """,
491 validator=_measure_delay_validator,
492 values=[["PHA", "FRR", "FRF", "FFR", "FFF", "LRR", "LRF", "LFR", "LFF", "Skey"],
493 ["C1", "C2", "C3", "C4"], ["C1", "C2", "C3", "C4"]]
494 )
495
496 ###############
497 # Display #
498 ###############
499
500 menu = Instrument.control(
501 "MENU?", "MENU %s",
502 """Control the bottom menu enabled state (strict bool).""",
503 validator=strict_discrete_set,
504 values=TeledyneOscilloscope._BOOLS,
505 map_values=True
506 )
507
508 grid_display = Instrument.control(
509 "GRDS?", "GRDS %s",
510 """Control the type of the grid which is used to display (FULL, HALF, OFF).""",
511 validator=strict_discrete_set,
512 values={"full": "FULL", "half": "HALF", "off": "OFF"},
513 map_values=True
514 )