Debian Codegraph @

pymeasure/instruments/activetechnologies/AWG401x.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 """This module implements an interface for Active Technologies AWG-401x, both
26 for the Arbitrary Waveform Generator (AWG) mode and the Arbitrary Function
27 Generator (AFG) mode. The module has been developed from the official
28 documentation available on https://www.activetechnologies.it"""
29
30 from collections import abc, namedtuple
31
32 import pprint
33
34 from pymeasure.instruments import Instrument, Channel, SCPIUnknownMixin
35 from pymeasure.instruments.validators import strict_discrete_set, \
36 strict_range
37
38
39 class ChannelBase(Channel):
40 """Implementation of a base Active Technologies AWG-4000 channel."""
41
42 def __init__(self, instrument, id):
43 super().__init__(instrument, id)
44
45 self.delay_values = [self.delay_min, self.delay_max]
46
47 enabled = Instrument.control(
48 "OUTPut{ch}:STATe?", "OUTPut{ch}:STATe %d",
49 """A boolean property that enables or disables the output for the
50 specified channel.""",
51 validator=strict_discrete_set,
52 values={True: 1, False: 0},
53 map_values=True
54 )
55
56 polarity = Instrument.control(
57 "OUTPut{ch}:POLarity?", "OUTPut{ch}:POLarity %s",
58 """This property inverts the output waveform relative to its average
59 value: (High Level – Low Level)/2. NORM for normal, INV for inverted
60 """,
61 validator=strict_discrete_set,
62 values=["NORMAL", "NORM", "INVERTED", "INV"],
63 get_process=lambda v: "NORM" if v == 0 else ("INV" if v == 1 else v)
64 )
65
66 delay = Instrument.control(
67 None, None,
68 """This property sets or queries the initial delay, set 0 for disable
69 it. When you send this command in AFG mode, if the instrument is
70 running, it will be stopped.""",
71 dynamic=True
72 )
73
74 delay_max = Instrument.measurement(
75 None,
76 """This property queries the maximum delay that can be set to the
77 output waveform.""",
78 dynamic=True
79 )
80
81 delay_min = Instrument.measurement(
82 None,
83 """This property queries the minimum delay that can be set to the
84 output waveform.""",
85 dynamic=True
86 )
87
88
89 class ChannelAFG(ChannelBase):
90 """Implementation of a Active Technologies AWG-4000 channel in AFG mode."""
91
92 def __init__(self, instrument, id):
93 super().__init__(instrument, id)
94
95 self.calculate_voltage_range()
96 self.frequency_values = [self.frequency_min, self.frequency_max]
97
98 self.phase_values = [self.phase_min, self.phase_max]
99
100 load_impedance = Instrument.control(
101 "OUTPut{ch}:IMPedance?", "OUTPut{ch}:IMPedance %d",
102 """This property sets the output load impedance for the specified
103 channel. The specified value is used for amplitude, offset, and
104 high/low level settings. You can set the impedance to any value from
105 1 Ω to 1 MΩ. The default value is 50 Ω.""",
106 validator=strict_range,
107 values=[1, 1000000]
108 )
109
110 output_impedance = Instrument.control(
111 "OUTPut{ch}:LOW:IMPedance?", "OUTPut{ch}:LOW:IMPedance %d",
112 """This property sets the instrument output impedance, the possible
113 values are: 5 Ohm or 50 Ohm (default).""",
114 validator=strict_discrete_set,
115 values={5: 1, 50: 0},
116 map_values=True
117 )
118
119 shape = Instrument.control(
120 "SOURce{ch}:FUNCtion:SHAPe?", "SOURce{ch}:FUNCtion:SHAPe %s",
121 """This property sets or queries the shape of the carrier waveform.
122 Allowed choices depends on the choosen modality, please refer on
123 instrument manual. When you set this property with a different value,
124 if the instrument is running it will be stopped.
125 Can be set to: SIN<USOID>, SQU<ARE>, PULS<E>, RAMP, PRN<OISE>, DC,
126 SINC, GAUS<SIAN>, LOR<ENTZ>, ERIS<E>, EDEC<AY>, HAV<ERSINE>, ARBB,
127 EFIL<E>, DOUBLEPUL<SE>""",
128 validator=strict_discrete_set,
129 values=["SINUSOID", "SIN", "SQUARE", "SQU", "PULSE", "PULS", "RAMP",
130 "PRNOISE", "PRN", "DC", "SINC", "GAUSSIAN", "GAUS", "LORENTZ",
131 "LOR", "ERISE", "ERIS", "EDECAY", "EDEC", "HAVERSINE", "HAV",
132 "ARBB", "EFILE", "EFIL", "DOUBLEPULSE", "DOUBLEPUL"]
133 )
134
135 # Default delay override
136 delay_get_command = "SOURce{ch}:INITDELay?"
137 delay_set_command = "SOURce{ch}:INITDELay %s"
138 delay_max_get_command = "SOURce{ch}:INITDELay? MAXimum"
139 delay_min_get_command = "SOURce{ch}:INITDELay? MINimum"
140
141 frequency = Instrument.control(
142 "SOURce{ch}:FREQuency?", "SOURce{ch}:FREQuency %s",
143 """This property sets or queries the frequency of the output waveform.
144 This command is available when the Run Mode is set to any setting other
145 than Sweep. The output frequency range setting depends on the type of
146 output waveform. If you change the type of output waveform, it may
147 change the output frequency because changing waveform types affects the
148 setting range of the output frequency. The output frequency range
149 setting depends also on the amplitude parameter.""",
150 validator=strict_range,
151 dynamic=True
152 )
153
154 frequency_max = Instrument.measurement(
155 "SOURce{ch}:FREQuency? MAXimum",
156 """This property queries the maximum frequency that can be set to the
157 output waveform."""
158 )
159
160 frequency_min = Instrument.measurement(
161 "SOURce{ch}:FREQuency? MINimum",
162 """This property queries the minimum frequency that can be set to the
163 output waveform."""
164 )
165
166 phase = Instrument.control(
167 "SOURce{ch}:PHASe:ADJust?", "SOURce{ch}:PHASe:ADJust %s",
168 """This property sets or queries the phase of the output waveform for
169 the specified channel. The value is in degrees.""",
170 validator=strict_range,
171 dynamic=True
172 )
173
174 phase_max = Instrument.measurement(
175 "SOURce{ch}:PHASe:ADJust? MAXimum",
176 """This property queries the maximum phase that can be set to the
177 output waveform."""
178 )
179
180 phase_min = Instrument.measurement(
181 "SOURce{ch}:PHASe:ADJust? MINimum",
182 """This property queries the minimum phase that can be set to the
183 output waveform."""
184 )
185
186 voltage_unit = Instrument.control(
187 "OUTPut{ch}:VOLTage:UNIT?", "OUTPut{ch}:VOLTage:UNIT %s",
188 """This property sets or queries the units of output amplitude, the
189 possible choices are: VPP, VRMS, DBM. This command does not affect the
190 offset, high level, or low level of output.""",
191 validator=strict_discrete_set,
192 values=["VPP", "VRMS", "DBM"]
193 )
194
195 voltage_low = Instrument.control(
196 "SOURce{ch}:VOLTage:LEVel:IMMediate:LOW?",
197 "SOURce{ch}:VOLTage:LEVel:IMMediate:LOW %s",
198 """This property sets or queries the low level of the waveform. The
199 low level could be limited by noise level to not exceed the maximum
200 amplitude. If the carrier is Noise or DC level, this command and this
201 query cause an error.""",
202 validator=strict_range,
203 dynamic=True
204 )
205
206 voltage_low_max = Instrument.measurement(
207 "SOURce{ch}:VOLTage:LEVel:IMMediate:LOW? MAXimum",
208 """This property queries the maximum low voltage level that can be set
209 to the output waveform."""
210 )
211
212 voltage_low_min = Instrument.measurement(
213 "SOURce{ch}:VOLTage:LEVel:IMMediate:LOW? MINimum",
214 """This property queries the minimum low voltage level that can be set
215 to the output waveform."""
216 )
217
218 voltage_high = Instrument.control(
219 "SOURce{ch}:VOLTage:LEVel:IMMediate:HIGH?",
220 "SOURce{ch}:VOLTage:LEVel:IMMediate:HIGH %s",
221 """This property sets or queries the high level of the waveform. The
222 high level could be limited by noise level to not exceed the maximum
223 amplitude. If the carrier is Noise or DC level, this command and this
224 query cause an error.""",
225 validator=strict_range,
226 dynamic=True
227 )
228
229 voltage_high_max = Instrument.measurement(
230 "SOURce{ch}:VOLTage:LEVel:IMMediate:HIGH? MAXimum",
231 """This property queries the maximum high voltage level that can be set
232 to the output waveform."""
233 )
234
235 voltage_high_min = Instrument.measurement(
236 "SOURce{ch}:VOLTage:LEVel:IMMediate:HIGH? MINimum",
237 """This property queries the minimum high voltage level that can be set
238 to the output waveform."""
239 )
240
241 voltage_amplitude = Instrument.control(
242 "SOURce{ch}:VOLTage:LEVel:IMMediate:AMPLitude?",
243 "SOURce{ch}:VOLTage:LEVel:IMMediate:AMPLitude %s",
244 """This property sets or queries the output amplitude for the specified
245 channel. The measurement unit of amplitude depends on the selection
246 operated using the voltage_unit property. If the carrier is Noise the
247 amplitude is Vpk instead of Vpp. If the carrier is DC level this
248 command causes an error. The range of the amplitude setting could be
249 limited by the frequency and offset parameter of the carrier waveform.
250 """,
251 validator=strict_range,
252 dynamic=True
253 )
254
255 voltage_amplitude_max = Instrument.measurement(
256 "SOURce{ch}:VOLTage:LEVel:IMMediate:AMPLitude? MAXimum",
257 """This property queries the maximum amplitude voltage level that can
258 be set to the output waveform.""",
259 get_process=lambda value: float(value.replace("VPP", ""))
260 )
261
262 voltage_amplitude_min = Instrument.measurement(
263 "SOURce{ch}:VOLTage:LEVel:IMMediate:AMPLitude? MINimum",
264 """This property queries the minimum amplitude voltage level that can
265 be set to the output waveform.""",
266 get_process=lambda value: float(value.replace("VPP", ""))
267 )
268
269 voltage_offset = Instrument.control(
270 "SOURce{ch}:VOLTage:LEVel:IMMediate:OFFSet?",
271 "SOURce{ch}:VOLTage:LEVel:IMMediate:OFFSet %s",
272 """This property sets or queries the offset level for the specified
273 channel. The offset range setting depends on the amplitude parameter.
274 """,
275 validator=strict_range,
276 dynamic=True
277 )
278
279 voltage_offset_max = Instrument.measurement(
280 "SOURce{ch}:VOLTage:LEVel:IMMediate:OFFSet? MAXimum",
281 """This property queries the maximum offset voltage level that can be
282 set to the output waveform."""
283 )
284
285 voltage_offset_min = Instrument.measurement(
286 "SOURce{ch}:VOLTage:LEVel:IMMediate:OFFSet? MINimum",
287 """This property queries the minimum offset voltage level that can be
288 set to the output waveform."""
289 )
290
291 baseline_offset = Instrument.control(
292 "SOURce{ch}:VOLTage:BASELINE:OFFSET?",
293 "SOURce{ch}:VOLTage:BASELINE:OFFSET %s",
294 """This property sets or queries the offset level for the specified
295 channel. The offset range setting depends on the amplitude parameter.
296 """,
297 validator=strict_range,
298 dynamic=True
299 )
300
301 baseline_offset_max = Instrument.measurement(
302 "SOURce{ch}:VOLTage:BASELINE:OFFSET? MAXimum",
303 """This property queries the maximum offset voltage level that can be
304 set to the output waveform."""
305 )
306
307 baseline_offset_min = Instrument.measurement(
308 "SOURce{ch}:VOLTage:BASELINE:OFFSET? MINimum",
309 """This property queries the minimum offset voltage level that can be
310 set to the output waveform."""
311 )
312
313 def calculate_voltage_range(self):
314 self.voltage_low_values = [self.voltage_low_min, self.voltage_low_max]
315
316 self.voltage_high_values = [self.voltage_high_min,
317 self.voltage_high_max]
318
319 self.voltage_amplitude_values = [self.voltage_amplitude_min,
320 self.voltage_amplitude_max]
321
322 self.voltage_offset_values = [self.voltage_offset_min,
323 self.voltage_offset_max]
324
325 self.baseline_offset_values = [self.baseline_offset_min,
326 self.baseline_offset_max]
327
328
329 class ChannelAWG(ChannelBase):
330 """Implementation of a Active Technologies AWG-4000 channel in AWG mode."""
331
332 # Default delay override
333 delay_get_command = "OUTPut{ch}:DELay?"
334 delay_set_command = "OUTPut{ch}:DELay %s"
335 delay_max_get_command = "OUTPut{ch}:DELay? MAXimum"
336 delay_min_get_command = "OUTPut{ch}:DELay? MINimum"
337
338 scale = Instrument.control(
339 "OUTPut{ch}:SCALe?",
340 "OUTPut{ch}:SCALe %f",
341 """This property sets or returns the Amplitude Scale parameter of the
342 analog channel “n”. This property can be modified at run-time to adjust
343 the waveform amplitude while the instrument is running and it is
344 applied to all the waveforms contained in the sequencer. It is
345 expressed in % and it has a range of 0% to 100%. 100% means that the
346 waveform keeps its original amplitude.""",
347 validator=strict_range,
348 values=[0, 100]
349 )
350
351
352 class AWG401x_base(SCPIUnknownMixin, Instrument):
353 """AWG-401x base class"""
354
355 def __init__(self, adapter,
356 name="Active Technologies AWG-4014 1.2GS/s Arbitrary Waveform Generator",
357 **kwargs):
358
359 # Insert an higher timeout because, often, when starting the
360 # instrument, can pass some time and the adapted goes in timeout
361 kwargs.setdefault('timeout', 7500)
362
363 super().__init__(
364 adapter,
365 name,
366 **kwargs
367 )
368
369 def beep(self):
370 """Causes a system beep."""
371 self.write("SYST:BEEP")
372
373 def save(self, position):
374 """Save the actual configuration in memory.
375
376 :param int position: Instrument save position [0,4]
377
378 :raises ValueError: If position is outside permitted limit [0,4].
379 """
380
381 if position >= 0 or position <= 4:
382 self.write(f"*SAV {position}")
383 else:
384 raise ValueError("position value outside permitted range [0,4]")
385
386 def load(self, position):
387 """Load the actual configuration in memory.
388
389 :param int position: Instrument load position [0,4]
390
391 :raises ValueError: If position is outside permitted limit [0,4].
392 """
393
394 if position >= 0 or position <= 4:
395 self.write(f"*RCL {position}")
396 else:
397 raise ValueError("position value outside permitted range [0,4]")
398
399 def wait_last(self):
400 """Wait for last operation completition"""
401
402 self.write("*WAI")
403
404
405 class AWG401x_AFG(AWG401x_base):
406 """Represents the Active Technologies AWG-401x Arbitrary Waveform Generator
407 in AFG mode.
408
409 .. code-block:: python
410
411 wfg = AWG401x_AFG("TCPIP::192.168.0.123::INSTR")
412
413 wfg.reset() # Reset the instrument at default state
414
415 wfg.channels[1].shape = "SINUSOID" # Sets a sine waveform on CH1
416 wfg.channels[1].frequency = 4.7e3 # Sets the frequency to 4.7 kHz on CH1
417 wfg.channels[1].amplitude = 1 # Set amplitude of 1 V on CH1
418 wfg.channels[1].offset = 0 # Set the amplitude to 0 V on CH1
419 wfg.channels[1].enabled = True # Enables the CH1
420
421 wfg.channels[2].shape = "SQUARE" # Sets a square waveform on CH2
422 wfg.channels[2].frequency = 100e6 # Sets the frequency to 100 MHz on CH2
423 wfg.channels[2].amplitude = 0.5 # Set amplitude of 0.5 V on CH2
424 wfg.channels[2].offset = 0 # Set the amplitude to 0 V on CH2
425 wfg.channels[2].enabled = True # Enables the CH2
426
427 wfg.enabled = True # Enable output of waveform generator
428 wfg.beep() # "beep"
429
430 print(wfg.check_errors()) # Get the error queue
431
432 """
433 ch_1 = Instrument.ChannelCreator(ChannelAFG, 1)
434 ch_2 = Instrument.ChannelCreator(ChannelAFG, 2)
435
436 enabled = Instrument.control(
437 "AFGControl:STATus?", "AFGControl:%s",
438 """A boolean property that enables the generation of signals.""",
439 validator=strict_discrete_set,
440 values={True: "START", False: "STOP"},
441 map_values=True,
442 get_process=lambda v: "START" if v == 1 else ("STOP" if v == 0 else v)
443 )
444
445 def __init__(self, adapter, **kwargs):
446 super().__init__(adapter, **kwargs)
447
448 model = self.id.split(",")[1]
449 if model == "AWG4012":
450 num_ch = 2
451 elif model == "AWG4014":
452 num_ch = 4
453 elif model == "AWG4018":
454 num_ch = 8
455 else:
456 raise NotImplementedError(f"Instrument {model} not implemented in"
457 "class AWG401x")
458
459 for i in range(3, num_ch + 1):
460 child = self.add_child(ChannelAFG, i)
461 child._protected = True
462
463
464 class AWG401x_AWG(AWG401x_base):
465 """Represents the Active Technologies AWG-401x Arbitrary Waveform Generator
466 in AWG mode.
467
468 .. code-block:: python
469
470 wfg = AWG401x_AWG("TCPIP::192.168.0.123::INSTR")
471
472 wfg.reset() # Reset the instrument at default state
473
474 # Set a oscillating waveform
475 wfg.waveforms["MyWaveform"] = [1, 0] * 8
476
477 for i in range(1, wfg.num_ch + 1):
478 wfg.entries[1].channels[i].voltage_high = 1 # Sets high voltage = 1
479 wfg.entries[1].channels[i].voltage_low = 0 # Sets low voltage = 1
480 wfg.entries[1].channels[i].waveform = "SQUARE" # Sets a square wave
481 wfg.setting_ch[i].enabled = True # Enable channel
482
483 wfg.entries.resize(2) # Resize the number of entries to 2
484
485 wfg.entries[2].channels[1].waveform = "MyWaveform" # Set custom waveform
486
487 wfg.enabled = True # Enable output of waveform generator
488 wfg.beep() # "beep"
489
490 print(wfg.check_errors()) # Get the error queue
491
492 """
493
494 def __init__(self, adapter, **kwargs):
495 super().__init__(adapter, **kwargs)
496
497 for i in range(1, self.num_ch + 1):
498 self.add_child(ChannelAWG, i, collection="setting_ch")
499
500 self.entries = self.DummyEntriesElements(self, self.num_ch)
501 self.burst_count_values = [self.burst_count_min, self.burst_count_max]
502
503 self.sampling_rate_values = [self.sampling_rate_min,
504 self.sampling_rate_max]
505
506 self._waveforms = self.WaveformsLazyDict(self)
507
508 num_ch = Instrument.measurement(
509 "AWGControl:CONFigure:CNUMber?",
510 """This property queries the number of analog channels.""",
511 cast=int
512 )
513
514 num_dch = Instrument.measurement(
515 "AWGControl:CONFigure:DNUMber?",
516 """This property queries the number of digital channels.""",
517 cast=int
518 )
519
520 sample_decreasing_strategy = Instrument.control(
521 "AWGControl:DECreasing?", "AWGControl:DECreasing %s",
522 """This property sets or returns the Sample Decreasing Strategy. The
523 “Sample decreasing strategy” parameter defines the strategy used to
524 adapt the waveform length to the sequencer entry length in the case
525 where the original waveform length is longer than the sequencer entry
526 length. Can be set to: DECIM<ATION>, CUTT<AIL>, CUTH<EAD>""",
527 validator=strict_discrete_set,
528 values=["DECIMATION", "DECIM", "CUTTAIL", "CUTT", "CUTHEAD", "CUTH"]
529 )
530
531 sample_increasing_strategy = Instrument.control(
532 "AWGControl:INCreasing?", "AWGControl:INCreasing %s",
533 """This property sets or or returns the Sample Increasing Strategy. The
534 “Sample increasing strategy” parameter defines the strategy used to
535 adapt the waveform length to the sequencer entry length in the case
536 where the original waveform length is shorter than the sequencer entry
537 length. Can be set to: INTER<POLATION>, RETURN<ZERO>, HOLD<LAST>,
538 SAMPLESM<ULTIPLICATION>""",
539 validator=strict_discrete_set,
540 values=["INTERPOLATION", "INTER", "RETURNZERO", "RETURN", "HOLDLAST",
541 "HOLD", "SAMPLESMULTIPLICATION", "SAMPLESM"]
542 )
543
544 entry_level_strategy = Instrument.control(
545 "AWGControl:LENGth:MODE?", "AWGControl:LENGth:MODE %s",
546 """This property sets or or returns the Entry Length Strategy. This
547 strategy manages the length of the sequencer entries in relationship
548 with the length of the channel waveforms defined for each entry. The
549 possible values are:
550
551 * ADAPTL<ONGER>: the length of an entry of the sequencer by default
552 will be equal to the length of the longer channel waveform, among all
553 analog channels, assigned to the entry.
554 * ADAPTS<HORTER>: the length of an entry of the sequencer by default
555 will be equal to the length of the shorter channel waveform, among
556 all analog channels, assigned to the entry.
557 * DEF<AULT>:the length of an entry of the sequencer by default will be
558 equal to the value specified in the Sequencer Item Default Length [N]
559 parameter""",
560 validator=strict_discrete_set,
561 values=["ADAPTLONGER", "ADAPTL", "ADAPTSHORTER", "ADAPTS", "DEFAULT",
562 "DEF"]
563 )
564
565 run_mode = Instrument.control(
566 "AWGControl:RMODe?", "AWGControl:RMODe %s",
567 """This property sets or returns the AWG run mode. The possible values
568 are:
569
570 * CONT<INUOUS>: each waveform will loop as written in the entry
571 repetition parameter and the entire sequence is repeated circularly
572 * BURS<T>: the AWG waits for a trigger event. When the trigger event
573 occurs each waveform will loop as written in the entry repetition
574 parameter and the entire sequence will be repeated circularly many
575 times as written in the Burst Count[N] parameter. If you set Burst
576 Count[N]=1 the instrument is in Single mode and the sequence will be
577 repeated only once.
578 * TCON<TINUOUS>: the AWG waits for a trigger event. When the trigger
579 event occurs each waveform will loop as written in the entry
580 repetition parameter and the entire sequence will be repeated
581 circularly.
582 * STEP<PED>: the AWG, for each entry, waits for a trigger event before
583 the execution of the sequencer entry. The waveform of the entry will
584 loop as written in the entry repetition parameter. After the
585 generation of an entry has completed, the last sample of the current
586 entry or the first sample of the next entry is held until the next
587 trigger is received. At the end of the entire sequence the execution
588 will restart from the first entry.
589 * ADVA<NCED>: it enables the “Advanced” mode. In this mode the
590 execution of the sequence can be changed by using conditional and
591 unconditional jumps (JUMPTO and GOTO commands) and dynamic jumps
592 (PATTERN JUMP commands).
593
594 The \\*RST command sets this parameter to CONTinuous.""",
595 validator=strict_discrete_set,
596 values=["CONTINUOUS", "CONT", "BURST", "BURS", "TCONTINUOUS",
597 "TCON", "STEPPED", "STEP", "ADVANCED", "ADVA"]
598 )
599
600 burst_count = Instrument.control(
601 "AWGControl:BURST?",
602 "AWGControl:BURST %d",
603 """This property sets or queries the burst count parameter.""",
604 validator=strict_range,
605 dynamic=True
606 )
607
608 burst_count_max = Instrument.measurement(
609 "AWGControl:BURST? MAXimum",
610 """This property queries the maximum burst count parameter.""",
611 cast=int
612 )
613
614 burst_count_min = Instrument.measurement(
615 "AWGControl:BURST? MINimum",
616 """This property queries the minimum burst count parameter.""",
617 cast=int
618 )
619
620 sampling_rate = Instrument.control(
621 "AWGControl:SRATe?",
622 "AWGControl:SRATe %f",
623 """This property sets or queries the sample rate for the Sampling
624 Clock.""",
625 validator=strict_range,
626 dynamic=True
627 )
628
629 sampling_rate_max = Instrument.measurement(
630 "AWGControl:SRATe? MAXimum",
631 """This property queries the maximum sample rate for the Sampling
632 Clock."""
633 )
634
635 sampling_rate_min = Instrument.measurement(
636 "AWGControl:SRATe? MINimum",
637 """This property queries the minimum sample rate for the Sampling
638 Clock."""
639 )
640
641 run_status = Instrument.measurement(
642 "AWGControl:RSTATe?",
643 """This property returns the run state of the AWG. The possible values
644 are: STOPPED, WAITING_TRIGGER, RUNNING""",
645 values={"STOPPED": 0, "WAITING_TRIGGER": 1, "RUNNING": 2},
646 map_values=True
647 )
648
649 enabled = Instrument.control(
650 "AWGControl:RSTATe?", "AWGControl:%s",
651 """A boolean property that enables the generation of signals.""",
652 validator=strict_discrete_set,
653 values={True: "RUN", False: "STOP"},
654 map_values=True,
655 get_process=lambda v: "STOP" if v == 0 else "RUN"
656 )
657
658 trigger_source = Instrument.control(
659 "TRIGger:SEQuence:SOURce?", "TRIGger:SEQuence:SOURce %s",
660 """This property sets or returns the instrument trigger source. The
661 possible values are:
662
663 * TIM<ER>: the trigger is sent at regular intervals.
664 * EXT<ERNAL>: the trigger come from the external BNC connector.
665 * MAN<UAL>: the trigger is sent via software or using the trigger
666 button on front panel.""",
667 validator=strict_discrete_set,
668 values=["TIMER", "TIM", "EXTERNAL", "EXT", "MANUAL", "MAN"]
669 )
670
671 waveforms = property(
672 lambda self: self._waveforms,
673 doc="""This property returns a dict with all the waveform present
674 in the instrument system (Wave. List). It is possible to modify the
675 values, delete them or create new waveforms""")
676
677 def trigger(self):
678 """Force a trigger event to occour."""
679 self.write("TRIGger:SEQuence:IMMediate")
680
681 def save_file(self,
682 file_name,
683 data,
684 path=None,
685 override_existing=False):
686 """Write a string in a file in the instrument"""
687
688 if path is not None:
689 raise NotImplementedError("Specify path is not implemented")
690
691 if file_name in [file.name
692 for file in self.list_files(path=path)
693 if file.type == '']:
694 if override_existing:
695 self.remove_file(file_name, path=path)
696 else:
697 raise ValueError("File already exist and override is disabled")
698
699 self.adapter.write_binary_values(
700 'MMEM:DATA "' + file_name + '", 0, ',
701 data.encode("ASCII"),
702 datatype='s')
703 # HACK: Send an unuseful command to ensure the last command was
704 # executed because if it is more than 1024 bytes it doesn't work
705 self.wait_last()
706
707 def remove_file(self, file_name, path=None):
708 """Remove a specified file"""
709
710 if path is not None:
711 raise NotImplementedError("Specify path is not implemented")
712
713 if file_name not in [file.name
714 for file in self.list_files(path=path)
715 if file.type == '']:
716 raise ValueError("File do not exist")
717
718 self.write('MMEMORY:DELETE "' + file_name + '"')
719
720 def list_files(self, path=None):
721 """Return a List of tuples with all file found in a directory. If the
722 path is not specified the current directory will be used"""
723
724 if path is not None:
725 raise NotImplementedError("Specify path is not implemented")
726
727 catalog = self.values("MMEMory:CATalog?")
728 catalog = catalog[1:]
729
730 FS_Element = namedtuple("FS_Element", "name type dimension")
731
732 elements = []
733 for i in range(int(len(catalog) / 3)):
734 elements.append(FS_Element(catalog[i * 3 + 0],
735 catalog[i * 3 + 1],
736 catalog[i * 3 + 2]))
737
738 return elements
739
740 class WaveformsLazyDict(abc.MutableMapping):
741 """This class inherit from MutableMapping in order to create a custom
742 dict to lazy load, modify, delete and create instrument waveform."""
743
744 def __init__(self, parent):
745 self.parent = parent
746 self.reset()
747
748 def __getitem__(self, key):
749 """Load data from instrument if not present"""
750 if self._data[key] is None:
751 self._data[key] = self._get_waveform(key)
752 return self._data[key]
753
754 def __setitem__(self, key, value):
755 """Create a new waveform from key and value"""
756
757 if len(value) < 16:
758 raise ValueError("The minimum waveform length is 16 samples")
759 elif len(value) < 384 and len(value) % 16 != 0:
760 raise ValueError("From 16 to 384 samples the granularity of"
761 "the waveform is 16")
762
763 class VoltageOutOfRangeError(Exception):
764 pass
765
766 if max(value) > self.parent.entries[1].channels[1].voltage_high_max:
767 raise VoltageOutOfRangeError(
768 f"{max(value)}V is higher than maximum possible voltage, "
769 f"which is "
770 f"{self.instrument.entries[1].channels[1].voltage_high_max}V")
771 if min(value) < self.parent.entries[1].channels[1].voltage_low_min:
772 raise VoltageOutOfRangeError(
773 f"{min(value)}V is lower than minimum possible voltage, "
774 f"which is "
775 f"{self.instrument.entries[1].channels[1].voltage_low_min}V")
776
777 self.parent.save_file(f"{key}.txt",
778 "\n".join(map(str, value)),
779 override_existing=True)
780
781 try:
782 del self[key]
783 except KeyError:
784 pass
785
786 self.parent.write(f'WLISt:WAVeform:IMPort "{key}",'
787 f'"{key}.txt",ANAlog')
788
789 self.parent.wait_last()
790
791 self.parent.remove_file(f"{key}.txt")
792
793 self._data[key] = None
794 return
795
796 def __delitem__(self, key):
797 """When removing an element this method removes also the
798 corresponding waveform in the instrument"""
799 del self._data[key]
800 self.parent.write(f'WLISt:WAVeform:DELete "{key}"')
801 return
802
803 def __iter__(self):
804 try:
805 for el in self._data:
806 yield el
807 except KeyError:
808 return
809
810 def __len__(self):
811 return len(self._data)
812
813 def __str__(self):
814 """Return a str without the waveforms points because it is useless
815 and loads all waveforms uselessy"""
816 return pprint.pformat({el: "Waveform Points" for el in self._data})
817
818 def reset(self):
819 """Reset the class reloading the waveforms from instrument"""
820 waveforms_name = self.parent.values("WLISt:LIST?")
821 self._data = {v: None for v in waveforms_name}
822
823 def _get_waveform(self, waveform_name):
824 """Get the waveform point of a specified waveform"""
825
826 bin_value = self.parent.adapter.connection.query_binary_values(
827 'WLISt:WAVeform:DATA? "' + waveform_name + '"',
828 header_fmt='ieee',
829 datatype='h')
830
831 return bin_value
832
833 class DummyEntriesElements(abc.Sequence):
834 """Dummy List Class to list every sequencer entry. The content is
835 loaded in real-time."""
836
837 def __init__(self, parent, number_of_channel):
838 self.parent = parent
839 self.num_ch = number_of_channel
840
841 def resize(self, new_size):
842 self.parent.write(f"SEQuence:LENGth {new_size}")
843
844 def __getitem__(self, key):
845 if key <= 0:
846 raise IndexError("Entry numeration start from 1")
847 if key > int(self.parent.values("SEQuence:LENGth?")[0]):
848 raise IndexError("Index out of range")
849 return SequenceEntry(self.parent, self.num_ch, key)
850
851 def __len__(self):
852 return int(self.parent.values("SEQuence:LENGth?")[0])
853
854
855 class SequenceEntry(Channel):
856 """Implementation of sequencer entry."""
857
858 def __init__(self, parent, number_of_channels, sequence_number):
859 super().__init__(parent, sequence_number)
860 self.number_of_channels = number_of_channels
861
862 self.length_values = [self.length_min, self.length_max]
863 self.loop_count_values = [self.loop_count_min, self.loop_count_max]
864
865 for i in range(1, self.number_of_channels + 1):
866 self.add_child(self.AnalogChannel, i,
867 sequence_number=sequence_number)
868
869 def insert_id(self, command):
870 return command.format(ent=self.id)
871
872 length = Instrument.control(
873 "SEQuence:ELEM{ent}:LENGth?",
874 "SEQuence:ELEM{ent}:LENGth %s",
875 """This property sets or returns the number of samples of the entry.
876 """,
877 validator=strict_range,
878 dynamic=True
879 )
880
881 length_max = Instrument.measurement(
882 "SEQuence:ELEM{ent}:LENGth? MAXimum",
883 """This property queries the maximum entry samples length.""",
884 get_process=lambda v: int(v)
885 )
886
887 length_min = Instrument.measurement(
888 "SEQuence:ELEM{ent}:LENGth? MINimum",
889 """This property queries the minimum entry samples length.""",
890 get_process=lambda v: int(v)
891 )
892
893 loop_count = Instrument.control(
894 "SEQuence:ELEM{ent}:LOOP:COUNt?",
895 "SEQuence:ELEM{ent}:LOOP:COUNt %s",
896 """This property sets or returns the number of waveform repetitions for
897 the entry.
898 """,
899 validator=strict_range,
900 dynamic=True
901 )
902
903 loop_count_max = Instrument.measurement(
904 "SEQuence:ELEM{ent}:LOOP:COUNt? MAXimum",
905 """This property queries the maximum number of waveform repetitions for
906 the entry.""",
907 get_process=lambda v: int(v)
908 )
909
910 loop_count_min = Instrument.measurement(
911 "SEQuence:ELEM{ent}:LOOP:COUNt? MINimum",
912 """This property queries the minimum number of waveform repetitions for
913 the entry.""",
914 get_process=lambda v: int(v)
915 )
916
917 class AnalogChannel(Channel):
918 """Implementation of an analog channel for a single sequencer entry."""
919
920 def __init__(self, parent, id, sequence_number):
921 super().__init__(parent, id)
922 self.seq_num = sequence_number
923
924 self.waveform_values = list(self.parent.parent.waveforms.keys())
925 self.calculate_voltage_range()
926
927 def insert_id(self, command):
928 return command.format(ent=self.seq_num, ch=self.id)
929
930 voltage_amplitude = Instrument.control(
931 "SEQuence:ELEM{ent}:AMPlitude{ch}?",
932 "SEQuence:ELEM{ent}:AMPlitude{ch} %s",
933 """This property sets or returns the voltage peak-to-peak
934 amplitude.""",
935 validator=strict_range,
936 dynamic=True
937 )
938
939 voltage_amplitude_max = Instrument.measurement(
940 "SEQuence:ELEM{ent}:AMPlitude{ch}? MAXimum",
941 """This property queries the maximum amplitude voltage level that
942 can be set."""
943 )
944
945 voltage_amplitude_min = Instrument.measurement(
946 "SEQuence:ELEM{ent}:AMPlitude{ch}? MINimum",
947 """This property queries the minimum amplitude voltage level that
948 can be set."""
949 )
950
951 voltage_offset = Instrument.control(
952 "SEQuence:ELEM{ent}:OFFset{ch}?",
953 "SEQuence:ELEM{ent}:OFFset{ch} %s",
954 """This property sets or returns the voltage offset.""",
955 validator=strict_range,
956 dynamic=True
957 )
958
959 voltage_offset_max = Instrument.measurement(
960 "SEQuence:ELEM{ent}:OFFset{ch}? MAXimum",
961 """This property queries the maximum voltage offset that can be
962 set."""
963 )
964
965 voltage_offset_min = Instrument.measurement(
966 "SEQuence:ELEM{ent}:OFFset{ch}? MINimum",
967 """This property queries the minimum voltage offset that can be
968 set."""
969 )
970
971 voltage_high = Instrument.control(
972 "SEQuence:ELEM{ent}:VOLTage:HIGH{ch}?",
973 "SEQuence:ELEM{ent}:VOLTage:HIGH{ch} %s",
974 """This property sets or returns the high voltage level of the
975 waveform.""",
976 validator=strict_range,
977 dynamic=True
978 )
979
980 voltage_high_max = Instrument.measurement(
981 "SEQuence:ELEM{ent}:VOLTage:HIGH{ch}? MAXimum",
982 """This property queries the maximum high voltage level of the
983 waveform that can be set to the output waveform."""
984 )
985
986 voltage_high_min = Instrument.measurement(
987 "SEQuence:ELEM{ent}:VOLTage:HIGH{ch}? MINimum",
988 """This property queries the minimum high voltage level of the
989 waveform that can be set to the output waveform."""
990 )
991
992 voltage_low = Instrument.control(
993 "SEQuence:ELEM{ent}:VOLTage:LOW{ch}?",
994 "SEQuence:ELEM{ent}:VOLTage:LOW{ch} %s",
995 """This property sets or returns the low voltage level of the
996 waveform.""",
997 validator=strict_range,
998 dynamic=True
999 )
1000
1001 voltage_low_max = Instrument.measurement(
1002 "SEQuence:ELEM{ent}:VOLTage:LOW{ch}? MAXimum",
1003 """This property queries the maximum low voltage level of the
1004 waveform that can be set to the output waveform."""
1005 )
1006
1007 voltage_low_min = Instrument.measurement(
1008 "SEQuence:ELEM{ent}:VOLTage:LOW{ch}? MINimum",
1009 """This property queries the minimum low voltage level of the
1010 waveform that can be set to the output waveform."""
1011 )
1012
1013 waveform = Instrument.control(
1014 "SEQuence:ELEM{ent}:WAVeform{ch}?",
1015 "SEQuence:ELEM{ent}:WAVeform{ch} %s",
1016 """This property sets or returns the waveform. It’s possible select
1017 a waveform only from those in the waveform list. In waveform list
1018 are already present 10 predefined waveform: Sine, Ramp, Square,
1019 Sync, DC, Gaussian, Lorentz, Haversine, Exp_Rise and Exp_Decay but
1020 user can import in the list others customized waveforms.""",
1021 validator=strict_discrete_set,
1022 set_process=lambda v: f"\"{v}\"",
1023 dynamic=True
1024 )
1025
1026 def calculate_voltage_range(self):
1027 self.voltage_amplitude_values = [self.voltage_amplitude_min,
1028 self.voltage_amplitude_max]
1029
1030 self.voltage_offset_values = [self.voltage_offset_min,
1031 self.voltage_offset_max]
1032
1033 self.voltage_high_values = [self.voltage_high_min,
1034 self.voltage_high_max]
1035
1036 self.voltage_low_values = [self.voltage_low_min,
1037 self.voltage_low_max]