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