Debian Codegraph @

pymeasure/instruments/srs/sr830.py

raw
1 #
2 # This file is part of the PyMeasure package.
3 #
4 # Copyright (c) 2013-2024 PyMeasure Developers
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a copy
7 # of this software and associated documentation files (the "Software"), to deal
8 # in the Software without restriction, including without limitation the rights
9 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 # copies of the Software, and to permit persons to whom the Software is
11 # furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 # THE SOFTWARE.
23 #
24
25 import re
26 import time
27 import numpy as np
28 from enum import IntFlag
29 from pymeasure.instruments import Instrument
30 from pymeasure.instruments.validators import strict_discrete_set, \
31 truncated_discrete_set, truncated_range, discreteTruncate
32
33
34 class LIAStatus(IntFlag):
35 """ IntFlag type that is returned by the lia_status property.
36 """
37 NO_ERROR = 0
38 INPUT_OVERLOAD = 1
39 FILTER_OVERLOAD = 2
40 OUTPUT_OVERLOAD = 4
41 REF_UNLOCK = 8
42 FREQ_RANGE_CHANGE = 16
43 TC_CHANGE = 32
44 TRIGGER = 64
45 UNUSED = 128
46
47
48 class ERRStatus(IntFlag):
49 """ IntFlag type that is returned by the err_status property.
50 """
51 NO_ERROR = 0
52 BACKUP_ERR = 2
53 RAM_ERR = 4
54 ROM_ERR = 16
55 GPIB_ERR = 32
56 DSP_ERR = 64
57 MATH_ERR = 128
58
59
60 class SR830(Instrument):
61 SAMPLE_FREQUENCIES = [
62 62.5e-3, 125e-3, 250e-3, 500e-3, 1, 2, 4, 8, 16,
63 32, 64, 128, 256, 512
64 ]
65 SENSITIVITIES = [
66 2e-9, 5e-9, 10e-9, 20e-9, 50e-9, 100e-9, 200e-9,
67 500e-9, 1e-6, 2e-6, 5e-6, 10e-6, 20e-6, 50e-6, 100e-6,
68 200e-6, 500e-6, 1e-3, 2e-3, 5e-3, 10e-3, 20e-3,
69 50e-3, 100e-3, 200e-3, 500e-3, 1
70 ]
71 TIME_CONSTANTS = [
72 10e-6, 30e-6, 100e-6, 300e-6, 1e-3, 3e-3, 10e-3,
73 30e-3, 100e-3, 300e-3, 1, 3, 10, 30, 100, 300, 1e3,
74 3e3, 10e3, 30e3
75 ]
76 FILTER_SLOPES = [6, 12, 18, 24]
77 EXPANSION_VALUES = [1, 10, 100]
78 RESERVE_VALUES = ['High Reserve', 'Normal', 'Low Noise']
79 CHANNELS = ['X', 'Y', 'R']
80 INPUT_CONFIGS = ['A', 'A - B', 'I (1 MOhm)', 'I (100 MOhm)']
81 INPUT_GROUNDINGS = ['Float', 'Ground']
82 INPUT_COUPLINGS = ['AC', 'DC']
83 INPUT_NOTCH_CONFIGS = ['None', 'Line', '2 x Line', 'Both']
84 REFERENCE_SOURCES = ['External', 'Internal']
85 SNAP_ENUMERATION = {"x": 1, "y": 2, "r": 3, "theta": 4,
86 "aux in 1": 5, "aux in 2": 6, "aux in 3": 7, "aux in 4": 8,
87 "frequency": 9, "ch1": 10, "ch2": 11}
88 REFERENCE_SOURCE_TRIGGER = ['SINE', 'POS EDGE', 'NEG EDGE']
89 INPUT_FILTER = ['Off', 'On']
90
91 status = Instrument.measurement(
92 "*STB?",
93 """Get the status byte and Master Summary Status bit.""",
94 cast=str,
95 )
96
97 id = Instrument.measurement(
98 "*IDN?",
99 """Get the identification of the instrument.""",
100 cast=str,
101 maxsplit=0,
102 )
103
104 def clear(self):
105 """Clear the instrument status byte."""
106 self.write("*CLS")
107
108 def reset(self):
109 """Reset the instrument."""
110 self.write("*RST")
111
112 sine_voltage = Instrument.control(
113 "SLVL?", "SLVL%0.3f",
114 """ A floating point property that represents the reference sine-wave
115 voltage in Volts. This property can be set. """,
116 validator=truncated_range,
117 values=[0.004, 5.0]
118 )
119 frequency = Instrument.control(
120 "FREQ?", "FREQ%0.5e",
121 """ A floating point property that represents the lock-in frequency
122 in Hz. This property can be set. """,
123 validator=truncated_range,
124 values=[0.001, 102000]
125 )
126 phase = Instrument.control(
127 "PHAS?", "PHAS%0.2f",
128 """ A floating point property that represents the lock-in phase
129 in degrees. This property can be set. """,
130 validator=truncated_range,
131 values=[-360, 729.99]
132 )
133 x = Instrument.measurement("OUTP?1",
134 """ Reads the X value in Volts. """
135 )
136 y = Instrument.measurement("OUTP?2",
137 """ Reads the Y value in Volts. """
138 )
139
140 lia_status = Instrument.measurement(
141 "LIAS?",
142 """ Reads the value of the lockin amplifier (LIA) status byte. Returns a binary string with
143 positions within the string corresponding to different status flags:
144
145 +----+--------------------------------------+
146 |Bit | Status |
147 +====+======================================+
148 | 0 | Input/Amplifier overload |
149 +----+--------------------------------------+
150 | 1 | Time constant filter overload |
151 +----+--------------------------------------+
152 | 2 | Output overload |
153 +----+--------------------------------------+
154 | 3 | Reference unlock |
155 +----+--------------------------------------+
156 | 4 | Detection frequency range switched |
157 +----+--------------------------------------+
158 | 5 | Time constant changed indirectly |
159 +----+--------------------------------------+
160 | 6 | Data storage triggered |
161 +----+--------------------------------------+
162 | 7 | unused |
163 +----+--------------------------------------+
164 """,
165 get_process=lambda s: LIAStatus(int(s)),
166 )
167
168 err_status = Instrument.measurement(
169 "ERRS?",
170 """Reads the value of the lockin error (ERR) status byte. Returns an IntFlag type with
171 positions within the string corresponding to different error flags:
172
173 +----+--------------------------------------+
174 |Bit | Status |
175 +====+======================================+
176 | 0 | unused |
177 +----+--------------------------------------+
178 | 1 | backup error |
179 +----+--------------------------------------+
180 | 2 | RAM error |
181 +----+--------------------------------------+
182 | 3 | unused |
183 +----+--------------------------------------+
184 | 4 | ROM error |
185 +----+--------------------------------------+
186 | 5 | GPIB error |
187 +----+--------------------------------------+
188 | 6 | DSP error |
189 +----+--------------------------------------+
190 | 7 | DSP error |
191 +----+--------------------------------------+
192 """,
193 get_process=lambda s: ERRStatus(int(s)),
194 )
195
196 @property
197 def xy(self):
198 """ Reads the X and Y values in Volts. """
199 return self.snap()
200
201 magnitude = Instrument.measurement("OUTP?3",
202 """ Reads the magnitude in Volts. """
203 )
204 theta = Instrument.measurement("OUTP?4",
205 """ Reads the theta value in degrees. """
206 )
207 channel1 = Instrument.control(
208 "DDEF?1;", "DDEF1,%d,0",
209 """ A string property that represents the type of Channel 1,
210 taking the values X, R, X Noise, Aux In 1, or Aux In 2.
211 This property can be set.""",
212 validator=strict_discrete_set,
213 values=['X', 'R', 'X Noise', 'Aux In 1', 'Aux In 2'],
214 map_values=True
215 )
216 channel2 = Instrument.control(
217 "DDEF?2;", "DDEF2,%d,0",
218 """ A string property that represents the type of Channel 2,
219 taking the values Y, Theta, Y Noise, Aux In 3, or Aux In 4.
220 This property can be set.""",
221 validator=strict_discrete_set,
222 values=['Y', 'Theta', 'Y Noise', 'Aux In 3', 'Aux In 4'],
223 map_values=True
224 )
225 sensitivity = Instrument.control(
226 "SENS?", "SENS%d",
227 """ A floating point property that controls the sensitivity in Volts,
228 which can take discrete values from 2 nV to 1 V. Values are truncated
229 to the next highest level if they are not exact. """,
230 validator=truncated_discrete_set,
231 values=SENSITIVITIES,
232 map_values=True
233 )
234 time_constant = Instrument.control(
235 "OFLT?", "OFLT%d",
236 """ A floating point property that controls the time constant
237 in seconds, which can take discrete values from 10 microseconds
238 to 30,000 seconds. Values are truncated to the next highest
239 level if they are not exact. """,
240 validator=truncated_discrete_set,
241 values=TIME_CONSTANTS,
242 map_values=True
243 )
244 filter_slope = Instrument.control(
245 "OFSL?", "OFSL%d",
246 """ An integer property that controls the filter slope, which
247 can take on the values 6, 12, 18, and 24 dB/octave. Values are
248 truncated to the next highest level if they are not exact. """,
249 validator=truncated_discrete_set,
250 values=FILTER_SLOPES,
251 map_values=True
252 )
253 filter_synchronous = Instrument.control(
254 "SYNC?", "SYNC %d",
255 """A boolean property that controls the synchronous filter.
256 This property can be set. Allowed values are: True or False """,
257 validator=strict_discrete_set,
258 values={True: 1, False: 0},
259 map_values=True
260 )
261 harmonic = Instrument.control(
262 "HARM?", "HARM%d",
263 """ An integer property that controls the harmonic that is measured.
264 Allowed values are 1 to 19999. Can be set. """,
265 validator=strict_discrete_set,
266 values=range(1, 19999),
267 )
268 input_config = Instrument.control(
269 "ISRC?", "ISRC %d",
270 """ An string property that controls the input configuration. Allowed
271 values are: {}""".format(INPUT_CONFIGS),
272 validator=strict_discrete_set,
273 values=INPUT_CONFIGS,
274 map_values=True
275 )
276 input_grounding = Instrument.control(
277 "IGND?", "IGND %d",
278 """ An string property that controls the input shield grounding. Allowed
279 values are: {}""".format(INPUT_GROUNDINGS),
280 validator=strict_discrete_set,
281 values=INPUT_GROUNDINGS,
282 map_values=True
283 )
284 input_coupling = Instrument.control(
285 "ICPL?", "ICPL %d",
286 """ An string property that controls the input coupling. Allowed
287 values are: {}""".format(INPUT_COUPLINGS),
288 validator=strict_discrete_set,
289 values=INPUT_COUPLINGS,
290 map_values=True
291 )
292 input_notch_config = Instrument.control(
293 "ILIN?", "ILIN %d",
294 """ An string property that controls the input line notch filter
295 status. Allowed values are: {}""".format(INPUT_NOTCH_CONFIGS),
296 validator=strict_discrete_set,
297 values=INPUT_NOTCH_CONFIGS,
298 map_values=True
299 )
300 reference_source = Instrument.control(
301 "FMOD?", "FMOD %d",
302 """ An string property that controls the reference source. Allowed
303 values are: {}""".format(REFERENCE_SOURCES),
304 validator=strict_discrete_set,
305 values=REFERENCE_SOURCES,
306 map_values=True
307 )
308 reference_source_trigger = Instrument.control(
309 "RSLP?", "RSLP %d",
310 """ A string property that controls the reference source triggering. Allowed
311 values are: {}""".format(REFERENCE_SOURCE_TRIGGER),
312 validator=strict_discrete_set,
313 values=REFERENCE_SOURCE_TRIGGER,
314 map_values=True
315 )
316
317 aux_out_1 = Instrument.control(
318 "AUXV?1;", "AUXV1,%f;",
319 """ A floating point property that controls the output of Aux output 1 in
320 Volts, taking values between -10.5 V and +10.5 V.
321 This property can be set.""",
322 validator=truncated_range,
323 values=[-10.5, 10.5]
324 )
325 # For consistency with other lock-in instrument classes
326 dac1 = aux_out_1
327
328 aux_out_2 = Instrument.control(
329 "AUXV?2;", "AUXV2,%f;",
330 """ A floating point property that controls the output of Aux output 2 in
331 Volts, taking values between -10.5 V and +10.5 V.
332 This property can be set.""",
333 validator=truncated_range,
334 values=[-10.5, 10.5]
335 )
336 # For consistency with other lock-in instrument classes
337 dac2 = aux_out_2
338
339 aux_out_3 = Instrument.control(
340 "AUXV?3;", "AUXV3,%f;",
341 """ A floating point property that controls the output of Aux output 3 in
342 Volts, taking values between -10.5 V and +10.5 V.
343 This property can be set.""",
344 validator=truncated_range,
345 values=[-10.5, 10.5]
346 )
347 # For consistency with other lock-in instrument classes
348 dac3 = aux_out_3
349
350 aux_out_4 = Instrument.control(
351 "AUXV?4;", "AUXV4,%f;",
352 """ A floating point property that controls the output of Aux output 4 in
353 Volts, taking values between -10.5 V and +10.5 V.
354 This property can be set.""",
355 validator=truncated_range,
356 values=[-10.5, 10.5]
357 )
358 # For consistency with other lock-in instrument classes
359 dac4 = aux_out_4
360
361 aux_in_1 = Instrument.measurement(
362 "OAUX?1;",
363 """ Reads the Aux input 1 value in Volts with 1/3 mV resolution. """
364 )
365 # For consistency with other lock-in instrument classes
366 adc1 = aux_in_1
367
368 aux_in_2 = Instrument.measurement(
369 "OAUX?2;",
370 """ Reads the Aux input 2 value in Volts with 1/3 mV resolution. """
371 )
372 # For consistency with other lock-in instrument classes
373 adc2 = aux_in_2
374
375 aux_in_3 = Instrument.measurement(
376 "OAUX?3;",
377 """ Reads the Aux input 3 value in Volts with 1/3 mV resolution. """
378 )
379 # For consistency with other lock-in instrument classes
380 adc3 = aux_in_3
381
382 aux_in_4 = Instrument.measurement(
383 "OAUX?4;",
384 """ Reads the Aux input 4 value in Volts with 1/3 mV resolution. """
385 )
386 # For consistency with other lock-in instrument classes
387 adc4 = aux_in_4
388
389 def __init__(self, adapter, name="Stanford Research Systems SR830 Lock-in amplifier",
390 **kwargs):
391 super().__init__(
392 adapter,
393 name,
394 includeSCPI=False,
395 **kwargs
396 )
397
398 def auto_gain(self):
399 self.write("AGAN")
400
401 def auto_reserve(self):
402 self.write("ARSV")
403
404 def auto_phase(self):
405 self.write("APHS")
406
407 def auto_offset(self, channel):
408 """ Offsets the channel (X, Y, or R) to zero """
409 if channel not in self.CHANNELS:
410 raise ValueError('SR830 channel is invalid')
411 channel = self.CHANNELS.index(channel) + 1
412 self.write("AOFF %d" % channel)
413
414 def get_scaling(self, channel):
415 """ Returns the offset percent and the expansion term
416 that are used to scale the channel in question
417 """
418 if channel not in self.CHANNELS:
419 raise ValueError('SR830 channel is invalid')
420 channel = self.CHANNELS.index(channel) + 1
421 offset, expand = self.ask("OEXP? %d" % channel).split(',')
422 return float(offset), self.EXPANSION_VALUES[int(expand)]
423
424 def set_scaling(self, channel, precent, expand=0):
425 """ Sets the offset of a channel (X=1, Y=2, R=3) to a
426 certain percent (-105% to 105%) of the signal, with
427 an optional expansion term (0, 10=1, 100=2)
428 """
429 if channel not in self.CHANNELS:
430 raise ValueError('SR830 channel is invalid')
431 channel = self.CHANNELS.index(channel) + 1
432 expand = discreteTruncate(expand, self.EXPANSION_VALUES)
433 self.write("OEXP %i,%.2f,%i" % (channel, precent, expand))
434
435 def output_conversion(self, channel):
436 """ Returns a function that can be used to determine
437 the signal from the channel output (X, Y, or R)
438 """
439 offset, _ = self.get_scaling(channel)
440 sensitivity = self.sensitivity
441 return lambda x: x + offset / 100 * sensitivity
442
443 @property
444 def sample_frequency(self):
445 """ Gets the sample frequency in Hz """
446 index = int(self.ask("SRAT?"))
447 if index == 14:
448 return None # Trigger
449 else:
450 return SR830.SAMPLE_FREQUENCIES[index]
451
452 @sample_frequency.setter
453 def sample_frequency(self, frequency):
454 """Sets the sample frequency in Hz (None is Trigger)"""
455 assert type(frequency) in [float, int, type(None)]
456 if frequency is None:
457 index = 14 # Trigger
458 else:
459 frequency = discreteTruncate(frequency, SR830.SAMPLE_FREQUENCIES)
460 index = SR830.SAMPLE_FREQUENCIES.index(frequency)
461 self.write("SRAT%f" % index)
462
463 def aquireOnTrigger(self, enable=True):
464 self.write("TSTR%d" % enable)
465
466 @property
467 def reserve(self):
468 return SR830.RESERVE_VALUES[int(self.ask("RMOD?"))]
469
470 @reserve.setter
471 def reserve(self, reserve):
472 if reserve not in SR830.RESERVE_VALUES:
473 index = 1
474 else:
475 index = SR830.RESERVE_VALUES.index(reserve)
476 self.write("RMOD%d" % index)
477
478 def is_out_of_range(self):
479 """ Returns True if the magnitude is out of range
480 """
481 return int(self.ask("LIAS?2")) == 1
482
483 def quick_range(self):
484 """ While the magnitude is out of range, increase
485 the sensitivity by one setting
486 """
487 self.write('LIAE 2,1')
488 while self.is_out_of_range():
489 self.write("SENS%d" % (int(self.ask("SENS?")) + 1))
490 time.sleep(5.0 * self.time_constant)
491 self.write("*CLS")
492 # Set the range as low as possible
493 newsensitivity = 1.15 * abs(self.magnitude)
494 if self.input_config in ('I (1 MOhm)', 'I (100 MOhm)'):
495 newsensitivity = newsensitivity * 1e6
496 self.sensitivity = newsensitivity
497
498 @property
499 def buffer_count(self):
500 query = self.ask("SPTS?")
501 if query.count("\n") > 1:
502 return int(re.match(r"\d+\n$", query, re.MULTILINE).group(0))
503 else:
504 return int(query)
505
506 def fill_buffer(self, count: int, has_aborted=lambda: False, delay=0.001):
507 """ Fill two numpy arrays with the content of the instrument buffer
508
509 Eventually waiting until the specified number of recording is done
510 """
511 ch1 = np.empty(count, np.float32)
512 ch2 = np.empty(count, np.float32)
513 currentCount = self.buffer_count
514 index = 0
515 while currentCount < count:
516 if currentCount > index:
517 ch1[index:currentCount] = self.get_buffer(1, index, currentCount)
518 ch2[index:currentCount] = self.get_buffer(2, index, currentCount)
519 index = currentCount
520 time.sleep(delay)
521 currentCount = self.buffer_count
522 if has_aborted():
523 self.pause_buffer()
524 return ch1, ch2
525 self.pause_buffer()
526 ch1[index: count + 1] = self.get_buffer(1, index, count) # noqa: E203
527 ch2[index: count + 1] = self.get_buffer(2, index, count) # noqa: E203
528 return ch1, ch2
529
530 def buffer_measure(self, count, stopRequest=None, delay=1e-3):
531 """ Start a fast measurement mode and transfers data from buffer to extract mean
532 and std measurements
533
534 Return the mean and std from both channels
535 """
536 self.write("FAST2;STRD")
537 ch1 = np.empty(count, np.float64)
538 ch2 = np.empty(count, np.float64)
539 currentCount = self.buffer_count
540 index = 0
541 while currentCount < count:
542 if currentCount > index:
543 ch1[index:currentCount] = self.get_buffer(1, index, currentCount)
544 ch2[index:currentCount] = self.get_buffer(2, index, currentCount)
545 index = currentCount
546 time.sleep(delay)
547 currentCount = self.buffer_count
548 if stopRequest is not None and stopRequest.isSet():
549 self.pause_buffer()
550 return (0, 0, 0, 0)
551 self.pause_buffer()
552 ch1[index:count] = self.get_buffer(1, index, count)
553 ch2[index:count] = self.get_buffer(2, index, count)
554 return (ch1.mean(), ch1.std(), ch2.mean(), ch2.std())
555
556 def pause_buffer(self):
557 self.write("PAUS")
558
559 def start_buffer(self, fast=True):
560 if fast:
561 self.write("FAST2;STRD")
562 else:
563 self.write("FAST0")
564
565 def wait_for_buffer(self, count, has_aborted=lambda: False,
566 timeout=60, timestep=0.01):
567 """ Wait for the buffer to fill a certain count
568 """
569 i = 0
570 while not self.buffer_count >= count and i < (timeout / timestep):
571 time.sleep(timestep)
572 i += 1
573 if has_aborted():
574 return False
575 self.pause_buffer()
576
577 def get_buffer(self, channel=1, start=0, end=None):
578 """ Acquires the 32 bit floating point data through binary transfer
579 """
580 if end is None:
581 end = self.buffer_count
582 return self.binary_values("TRCB?%d,%d,%d" % (
583 channel, start, end - start))
584
585 def reset_buffer(self):
586 self.write("REST")
587
588 def trigger(self):
589 self.write("TRIG")
590
591 def snap(self, val1="X", val2="Y", *vals):
592 """ Method that records and retrieves 2 to 6 parameters at a single
593 instant. The parameters can be one of: X, Y, R, Theta, Aux In 1,
594 Aux In 2, Aux In 3, Aux In 4, Frequency, CH1, CH2.
595 Default is "X" and "Y".
596
597 :param val1: first parameter to retrieve
598 :param val2: second parameter to retrieve
599 :param vals: other parameters to retrieve (optional)
600 """
601 if len(vals) > 4:
602 raise ValueError("No more that 6 values (in total) can be captured"
603 "simultaneously.")
604
605 # check if additional parameters are given as a list
606 if len(vals) == 1 and isinstance(vals[0], (list, tuple)):
607 vals = vals[0]
608
609 # make a list of all vals
610 vals = [val1, val2] + list(vals)
611
612 vals_idx = [str(self.SNAP_ENUMERATION[val.lower()]) for val in vals]
613
614 command = "SNAP? " + ",".join(vals_idx)
615 return self.values(command)
616
617 def save_setup(self, setup_number: int):
618 """Save the current instrument configuration (all parameters) in a memory
619 referred to by an integer
620
621 :param setup_number: the integer referring to the memory (between 1 and 9 (included))
622 """
623 if 1 <= setup_number <= 9:
624 self.write(f'SSET{setup_number:d};')
625
626 def load_setup(self, setup_number: int):
627 """ Load a previously saved instrument configuration from the memory referred
628 to by an integer
629
630 :param setup_number: the integer referring to the memory (between 1 and 9 (included))
631 """
632 if 1 <= setup_number <= 9:
633 self.write(f'RSET{setup_number:d};')
634
635 def start_scan(self):
636 """ Start the data recording into the buffer
637 """
638 self.write('STRT')
639
640 def pause_scan(self):
641 """ Pause the data recording
642 """
643 self.write('PAUS')