-
Notifications
You must be signed in to change notification settings - Fork 357
Expand file tree
/
Copy path_Keithley_2600.py
More file actions
1431 lines (1209 loc) · 51.1 KB
/
Copy path_Keithley_2600.py
File metadata and controls
1431 lines (1209 loc) · 51.1 KB
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import logging
import struct
import warnings
from dataclasses import dataclass
from enum import StrEnum
from typing import TYPE_CHECKING, Any, Literal, Protocol, Self, cast
import numpy as np
import numpy.typing as npt
import qcodes.validators as vals
from qcodes.extensions.infer import infer_channel
from qcodes.instrument import (
InstrumentChannel,
VisaInstrument,
VisaInstrumentKWArgs,
)
from qcodes.parameters import (
Parameter,
ParameterBase,
ParameterWithSetpoints,
ParamRawDataType,
create_on_off_val_mapping,
)
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
from typing import Unpack, assert_never
log = logging.getLogger(__name__)
class _LinSweepLike(Protocol):
"""
Protocol for linear sweep objects that can be used with ``setup_fastsweep``.
Any object implementing this protocol can be used to configure fast sweeps.
The canonical example is :class:`qcodes.dataset.LinSweep`.
Required attributes:
param: The parameter being swept (e.g., ``keith.smua.volt``).
delay: Time in seconds to wait after setting each point before measuring.
num_points: Number of sweep points.
Required methods:
get_setpoints: Returns the array of setpoint values for the sweep.
"""
@property
def param(self) -> ParameterBase: ...
@property
def delay(self) -> float: ...
@property
def num_points(self) -> int: ...
def get_setpoints(self) -> npt.NDArray: ...
@dataclass
class _FastSweepConfig:
"""Internal configuration for fastsweep."""
inner_start: float
inner_stop: float
inner_npts: int
inner_delay: float = 0.0
inner_param_name: str = "Voltage"
inner_param_unit: str = "V"
inner_param_full_name: str | None = None # Original parameter's full_name
inner_channel: str = "smua" # Lua channel name for inner sweep
outer_start: float | None = None
outer_stop: float | None = None
outer_npts: int | None = None
outer_delay: float = 0.0
outer_param_name: str = "Voltage"
outer_param_unit: str = "V"
outer_param_full_name: str | None = None # Original parameter's full_name
outer_channel: str = "smub" # Lua channel name for outer sweep
mode: Literal["IV", "VI", "VIfourprobe"] = "IV"
measurement_channel: str = "smua"
@property
def is_2d(self) -> bool:
return self.outer_npts is not None
@property
def total_points(self) -> int:
if self.is_2d:
assert self.outer_npts is not None
return self.inner_npts * self.outer_npts
return self.inner_npts
def get_inner_setpoints(self) -> npt.NDArray:
return np.linspace(self.inner_start, self.inner_stop, self.inner_npts)
def get_outer_setpoints(self) -> npt.NDArray:
if not self.is_2d:
raise RuntimeError("No outer setpoints for 1D sweep")
assert self.outer_start is not None
assert self.outer_stop is not None
assert self.outer_npts is not None
return np.linspace(self.outer_start, self.outer_stop, self.outer_npts)
def _make_setpoint_parameter(
name: str,
label: str,
unit: str,
shape: tuple[int, ...],
get_values: Callable[[], npt.NDArray],
register_name: str | None = None,
) -> Parameter:
"""Create a standalone setpoint parameter for fastsweep.
A fresh parameter is created on each call so that its ``param_spec``
is always consistent with the current sweep configuration.
"""
p: Parameter = Parameter(
name=name,
label=label,
unit=unit,
snapshot_value=False,
vals=vals.Arrays(shape=shape),
set_cmd=False,
get_cmd=get_values,
register_name=register_name,
)
return p
class LuaSweepParameter(ParameterWithSetpoints[npt.NDArray, "Keithley2600Channel"]):
"""
Parameter class to perform fast sweeps using Lua scripts on the Keithley 2600.
Supports both 1D and 2D sweeps. Configure using the channel's
``setup_fastsweep`` method with sweep objects that implement the
``_LinSweepLike`` protocol (e.g., :class:`qcodes.dataset.LinSweep`).
For 1D sweeps, returns a 1D array. For 2D sweeps, returns a 2D array
with shape (outer_npts, inner_npts).
For more information on writing Lua scripts for the Keithley2600, please see
https://www.tek.com/en/documents/application-note/how-to-write-scripts-for-test-script-processing-(tsp)
"""
def _update_metadata(self, config: _FastSweepConfig) -> None:
"""Update parameter metadata based on sweep configuration.
Creates fresh setpoint parameters each time so that their
``param_spec`` is always consistent with the current sweep
configuration — no cache invalidation needed.
"""
# Invalidate our own cached param_spec since unit/label/vals will change
self._param_spec = None
mode = config.mode
match mode:
case "IV":
self.unit = "A"
self.label = "Current"
case "VI" | "VIfourprobe":
self.unit = "V"
self.label = "Voltage"
inner_full_label = config.inner_param_name
if config.inner_param_full_name:
inner_full_label = (
f"{config.inner_param_name} ({config.inner_param_full_name})"
)
if self.instrument is not None:
# Create a fresh inner setpoint parameter
self.instrument.fastsweep_inner_setpoints = _make_setpoint_parameter(
name="fastsweep_inner_setpoints",
label=inner_full_label,
unit=config.inner_param_unit,
shape=(config.inner_npts,),
get_values=config.get_inner_setpoints,
register_name=config.inner_param_full_name,
)
if config.is_2d:
assert config.outer_npts is not None
outer_full_label = config.outer_param_name
if config.outer_param_full_name:
outer_full_label = (
f"{config.outer_param_name} ({config.outer_param_full_name})"
)
# Create a fresh outer setpoint parameter
self.instrument.fastsweep_outer_setpoints = _make_setpoint_parameter(
name="fastsweep_outer_setpoints",
label=outer_full_label,
unit=config.outer_param_unit,
shape=(config.outer_npts,),
get_values=config.get_outer_setpoints,
register_name=config.outer_param_full_name,
)
self.setpoints = (
self.instrument.fastsweep_outer_setpoints,
self.instrument.fastsweep_inner_setpoints,
)
self.setpoint_names = (outer_full_label, inner_full_label)
self.setpoint_units = (config.outer_param_unit, config.inner_param_unit)
self.vals = vals.Arrays(shape=(config.outer_npts, config.inner_npts))
else:
self.setpoints = (self.instrument.fastsweep_inner_setpoints,)
self.setpoint_names = (inner_full_label,) # type: ignore[assignment]
self.setpoint_units = (config.inner_param_unit,) # type: ignore[assignment]
self.vals = vals.Arrays(shape=(config.inner_npts,))
def _build_1d_script(self, config: _FastSweepConfig) -> list[str]:
"""Build Lua script for 1D sweep."""
if self.instrument is None:
raise RuntimeError("No instrument attached to Parameter.")
sweep_channel = config.inner_channel
meas_channel = config.measurement_channel
nplc = self.instrument.nplc()
if config.inner_npts < 1:
raise ValueError(
f"inner_npts must be at least 1 for fast sweep, got {config.inner_npts}"
)
if config.inner_npts == 1:
dX = 0.0
else:
dX = (config.inner_stop - config.inner_start) / (config.inner_npts - 1)
match config.mode:
case "IV":
meas, source, func, sense_mode = "i", "v", "1", "0"
case "VI":
meas, source, func, sense_mode = "v", "i", "0", "0"
case "VIfourprobe":
meas, source, func, sense_mode = "v", "i", "0", "1"
case _:
if TYPE_CHECKING:
assert_never()
raise ValueError(
f"Unsupported fast sweep mode {config.mode!r}. "
"Expected one of 'IV', 'VI', 'VIfourprobe'."
)
script = [
# Configure measurement channel
f"{meas_channel}.measure.nplc = {nplc:.12f}",
f"{meas_channel}.sense = {sense_mode}",
f"{meas_channel}.measure.count = 1",
# Configure sweep/source channel
f"{sweep_channel}.source.func = {func}",
f"{sweep_channel}.source.output = 1",
# Initialize sweep variables
f"startX = {config.inner_start:.12f}",
f"dX = {dX:.12f}",
# Clear measurement buffer
f"{meas_channel}.nvbuffer1.clear()",
f"{meas_channel}.nvbuffer1.appendmode = 1",
# Sweep loop
f"for index = 1, {config.inner_npts} do",
" target = startX + (index-1)*dX",
f" {sweep_channel}.source.level{source} = target",
]
if config.inner_delay > 0:
script.append(f" delay({config.inner_delay})")
script.extend(
[
f" {meas_channel}.measure.{meas}({meas_channel}.nvbuffer1)",
"end",
"format.data = format.REAL32",
"format.byteorder = format.LITTLEENDIAN",
f"printbuffer(1, {config.inner_npts}, {meas_channel}.nvbuffer1.readings)",
]
)
return script
def _build_2d_script(self, config: _FastSweepConfig) -> list[str]:
"""Build Lua script for 2D sweep."""
if self.instrument is None:
raise RuntimeError("No instrument attached to Parameter.")
inner_channel = config.inner_channel
outer_channel = config.outer_channel
meas_channel = config.measurement_channel
nplc = self.instrument.nplc()
assert config.inner_start is not None
assert config.inner_stop is not None
assert config.inner_npts is not None
assert config.outer_start is not None
assert config.outer_stop is not None
assert config.outer_npts is not None
inner_npts = config.inner_npts
outer_npts = config.outer_npts
if inner_npts < 1:
raise ValueError("inner_npts must be at least 1 for 2D fast sweep.")
if outer_npts < 1:
raise ValueError("outer_npts must be at least 1 for 2D fast sweep.")
if inner_npts == 1:
dX_inner = 0.0
else:
dX_inner = (config.inner_stop - config.inner_start) / (
config.inner_npts - 1
)
if outer_npts == 1:
dX_outer = 0.0
else:
dX_outer = (config.outer_stop - config.outer_start) / (
config.outer_npts - 1
)
match config.mode:
case "IV":
meas, source, func, sense_mode = "i", "v", "1", "0"
outer_source, outer_func = "v", "1"
case "VI":
meas, source, func, sense_mode = "v", "i", "0", "0"
outer_source, outer_func = "i", "0"
case "VIfourprobe":
meas, source, func, sense_mode = "v", "i", "0", "1"
outer_source, outer_func = "i", "0"
case _:
if TYPE_CHECKING:
assert_never()
raise ValueError(
f"Unsupported fast sweep mode {config.mode!r}. "
"Expected one of 'IV', 'VI', 'VIfourprobe'."
)
script = [
# Configure measurement channel
f"{meas_channel}.measure.nplc = {nplc:.12f}",
f"{meas_channel}.sense = {sense_mode}",
f"{meas_channel}.measure.count = 1",
# Set up inner channel (fast sweep)
f"{inner_channel}.source.func = {func}",
f"{inner_channel}.source.output = 1",
# Set up outer channel (slow sweep)
f"{outer_channel}.source.func = {outer_func}",
f"{outer_channel}.source.output = 1",
# Initialize sweep variables
f"startX_inner = {config.inner_start:.12f}",
f"dX_inner = {dX_inner:.12f}",
f"startX_outer = {config.outer_start:.12f}",
f"dX_outer = {dX_outer:.12f}",
# Clear measurement buffer
f"{meas_channel}.nvbuffer1.clear()",
f"{meas_channel}.nvbuffer1.appendmode = 1",
# Outer loop (slow axis)
f"for outer_idx = 1, {config.outer_npts} do",
" outer_target = startX_outer + (outer_idx-1)*dX_outer",
f" {outer_channel}.source.level{outer_source} = outer_target",
]
if config.outer_delay > 0:
script.append(f" delay({config.outer_delay})")
script.extend(
[
f" for inner_idx = 1, {config.inner_npts} do",
" inner_target = startX_inner + (inner_idx-1)*dX_inner",
f" {inner_channel}.source.level{source} = inner_target",
]
)
if config.inner_delay > 0:
script.append(f" delay({config.inner_delay})")
script.extend(
[
f" {meas_channel}.measure.{meas}({meas_channel}.nvbuffer1)",
" end",
"end",
"format.data = format.REAL32",
"format.byteorder = format.LITTLEENDIAN",
f"printbuffer(1, {config.total_points}, {meas_channel}.nvbuffer1.readings)",
]
)
return script
def get_raw(self) -> npt.NDArray:
if self.instrument is None:
raise RuntimeError("No instrument attached to Parameter.")
config = self.instrument._fastsweep_config
if config is None:
raise RuntimeError("Fastsweep not configured. Call setup_fastsweep first.")
if config.is_2d:
script = self._build_2d_script(config)
data = self.instrument._execute_lua(script, config.total_points)
assert config.outer_npts is not None
return data.reshape(config.outer_npts, config.inner_npts)
else:
script = self._build_1d_script(config)
return self.instrument._execute_lua(script, config.total_points)
class TimeTrace(ParameterWithSetpoints[npt.NDArray, "Keithley2600Channel"]):
"""
A parameter class that holds the data corresponding to the time dependence of
current and voltage.
"""
def _check_time_trace(self) -> None:
"""
A helper function that compares the integration time with measurement
interval for accurate results.
Raises:
RuntimeError: If no instrument attached to Parameter.
"""
if self.instrument is None:
raise RuntimeError("No instrument attached to Parameter.")
dt = self.instrument.timetrace_dt()
nplc = self.instrument.nplc()
linefreq = self.instrument.linefreq()
plc = 1 / linefreq
if nplc * plc > dt:
warnings.warn(
f"Integration time of {nplc * plc * 1000:.1f} "
f"ms is longer than {dt * 1000:.1f} ms set "
"as measurement interval. Consider lowering "
"NPLC or increasing interval.",
UserWarning,
2,
)
def _set_mode(self, mode: str) -> None:
"""
A helper function to set correct units and labels.
Args:
mode: User defined mode for the timetrace. It can be either
"current" or "voltage".
"""
if mode == "current":
self.unit = "A"
self.label = "Current"
if mode == "voltage":
self.unit = "V"
self.label = "Voltage"
def _time_trace(self) -> npt.NDArray:
"""
The function that prepares a Lua script for timetrace data acquisition.
Raises:
RuntimeError: If no instrument attached to Parameter.
"""
if self.instrument is None:
raise RuntimeError("No instrument attached to Parameter.")
channel = self.instrument.channel
npts = self.instrument.timetrace_npts()
dt = self.instrument.timetrace_dt()
mode = self.instrument.timetrace_mode()
mode_map = {"current": "i", "voltage": "v"}
script = [
f"{channel}.measure.count={npts}",
f"oldint={channel}.measure.interval",
f"{channel}.measure.interval={dt}",
f"{channel}.nvbuffer1.clear()",
f"{channel}.measure.{mode_map[mode]}({channel}.nvbuffer1)",
f"{channel}.measure.interval=oldint",
f"{channel}.measure.count=1",
"format.data = format.REAL32",
"format.byteorder = format.LITTLEENDIAN",
f"printbuffer(1, {npts}, {channel}.nvbuffer1.readings)",
]
return self.instrument._execute_lua(script, npts)
def get_raw(self) -> npt.NDArray:
if self.instrument is None:
raise RuntimeError("No instrument attached to Parameter.")
self._check_time_trace()
data = self._time_trace()
return data
class TimeAxis(Parameter[npt.NDArray, "Keithley2600Channel"]):
"""
A simple :class:`.Parameter` that holds all the times (relative to the
measurement start) at which the points of the time trace were acquired.
"""
def get_raw(self) -> npt.NDArray:
if self.instrument is None:
raise RuntimeError("No instrument attached to Parameter.")
npts = self.instrument.timetrace_npts()
dt = self.instrument.timetrace_dt()
return np.linspace(0, dt * npts, npts, endpoint=False)
class Keithley2600MeasurementStatus(StrEnum):
"""
Keeps track of measurement status.
"""
CURRENT_COMPLIANCE_ERROR = "Reached current compliance limit."
VOLTAGE_COMPLIANCE_ERROR = "Reached voltage compliance limit."
VOLTAGE_AND_CURRENT_COMPLIANCE_ERROR = (
"Reached both voltage and current compliance limits."
)
NORMAL = "No error occured."
COMPLIANCE_ERROR = "Reached compliance limit." # deprecated, dont use it. It exists only for backwards compatibility
MeasurementStatus = Keithley2600MeasurementStatus
"""Alias for backwards compatibility. Will eventually be deprecated and removed"""
_from_bits_tuple_to_status = {
(0, 0): Keithley2600MeasurementStatus.NORMAL,
(1, 0): Keithley2600MeasurementStatus.VOLTAGE_COMPLIANCE_ERROR,
(0, 1): Keithley2600MeasurementStatus.CURRENT_COMPLIANCE_ERROR,
(1, 1): Keithley2600MeasurementStatus.VOLTAGE_AND_CURRENT_COMPLIANCE_ERROR,
}
class _ParameterWithStatus(Parameter):
def __init__(self, *args: Any, **kwargs: Any):
super().__init__(*args, **kwargs)
self._measurement_status: Keithley2600MeasurementStatus | None = None
@property
def measurement_status(self) -> Keithley2600MeasurementStatus | None:
return self._measurement_status
@staticmethod
def _parse_response(data: str) -> tuple[float, Keithley2600MeasurementStatus]:
value, meas_status = data.split("\t")
status_bits = [
int(i)
for i in bin(int(float(meas_status))).replace("0b", "").zfill(16)[::-1]
]
status = _from_bits_tuple_to_status[(status_bits[0], status_bits[1])]
return float(value), status
def snapshot_base(
self,
update: bool | None = True,
params_to_skip_update: Sequence[str] | None = None,
) -> dict[Any, Any]:
snapshot = super().snapshot_base(
update=update, params_to_skip_update=params_to_skip_update
)
if self._snapshot_value:
snapshot["measurement_status"] = self.measurement_status
return snapshot
class _MeasurementCurrentParameter(_ParameterWithStatus):
def set_raw(self, value: ParamRawDataType) -> None:
assert isinstance(self.instrument, Keithley2600Channel)
assert isinstance(self.root_instrument, Keithley2600)
smu_chan = self.instrument
channel = smu_chan.channel
smu_chan.write(f"{channel}.source.leveli={value:.12f}")
smu_chan._reset_measurement_statuses_of_parameters()
def get_raw(self) -> ParamRawDataType:
assert isinstance(self.instrument, Keithley2600Channel)
assert isinstance(self.root_instrument, Keithley2600)
smu = self.instrument
channel = self.instrument.channel
data = smu.ask(
f"{channel}.measure.i(), status.measurement.instrument.{channel}.condition"
)
value, status = self._parse_response(data)
self._measurement_status = status
return value
class _MeasurementVoltageParameter(_ParameterWithStatus):
def set_raw(self, value: ParamRawDataType) -> None:
assert isinstance(self.instrument, Keithley2600Channel)
assert isinstance(self.root_instrument, Keithley2600)
smu_chan = self.instrument
channel = smu_chan.channel
smu_chan.write(f"{channel}.source.levelv={value:.12f}")
smu_chan._reset_measurement_statuses_of_parameters()
def get_raw(self) -> ParamRawDataType:
assert isinstance(self.instrument, Keithley2600Channel)
assert isinstance(self.root_instrument, Keithley2600)
smu = self.instrument
channel = self.instrument.channel
data = smu.ask(
f"{channel}.measure.v(), status.measurement.instrument.{channel}.condition"
)
value, status = self._parse_response(data)
self._measurement_status = status
return value
class Keithley2600Channel(InstrumentChannel["Keithley2600"]):
"""
Class to hold the two Keithley channels, i.e.
SMUA and SMUB.
"""
def __init__(self, parent: Keithley2600, name: str, channel: str) -> None:
"""
Args:
parent: The Instrument instance to which the channel is
to be attached.
name: The 'colloquial' name of the channel
channel: The name used by the Keithley, i.e. either
'smua' or 'smub'
"""
if channel not in ["smua", "smub"]:
raise ValueError('channel must be either "smub" or "smua"')
super().__init__(parent, name)
self.model = self._parent.model
self._extra_visa_timeout = 5000
self._measurement_duration_factor = 2 # Ensures that we are always above
# the expected time.
vranges = self.parent._vranges
iranges = self.parent._iranges
vlimit_minmax = self.parent._vlimit_minmax
ilimit_minmax = self.parent._ilimit_minmax
self.volt: _MeasurementVoltageParameter = self.add_parameter(
"volt",
parameter_class=_MeasurementVoltageParameter,
label="Voltage",
unit="V",
snapshot_get=False,
)
"""Parameter volt"""
self.curr: _MeasurementCurrentParameter = self.add_parameter(
"curr",
parameter_class=_MeasurementCurrentParameter,
label="Current",
unit="A",
snapshot_get=False,
)
"""Parameter curr"""
self.res: Parameter = self.add_parameter(
"res",
get_cmd=f"{channel}.measure.r()",
get_parser=float,
set_cmd=False,
label="Resistance",
unit="Ohm",
)
"""Parameter res"""
self.mode: Parameter = self.add_parameter(
"mode",
get_cmd=f"{channel}.source.func",
get_parser=float,
set_cmd=f"{channel}.source.func={{:d}}",
val_mapping={"current": 0, "voltage": 1},
docstring="Selects the output source type. "
"Can be either voltage or current.",
)
"""Selects the output source type. Can be either voltage or current."""
self.output: Parameter = self.add_parameter(
"output",
get_cmd=f"{channel}.source.output",
get_parser=float,
set_cmd=f"{channel}.source.output={{:d}}",
val_mapping=create_on_off_val_mapping(on_val=1, off_val=0),
)
"""Parameter output"""
self.linefreq: Parameter = self.add_parameter(
"linefreq",
label="Line frequency",
get_cmd="localnode.linefreq",
get_parser=float,
set_cmd=False,
unit="Hz",
)
"""Parameter linefreq"""
self.nplc: Parameter = self.add_parameter(
"nplc",
label="Number of power line cycles",
set_cmd=f"{channel}.measure.nplc={{}}",
get_cmd=f"{channel}.measure.nplc",
get_parser=float,
docstring="Number of power line cycles, used to perform measurements",
vals=vals.Numbers(0.001, 25),
)
"""Number of power line cycles, used to perform measurements"""
self.four_wire_measurement: Parameter[bool, Self] = self.add_parameter(
"four_wire_measurement",
label="Four-wire (remote) sense mode",
get_cmd=f"{channel}.sense",
get_parser=float,
set_cmd=f"{channel}.sense={{}}",
val_mapping=create_on_off_val_mapping(on_val=1, off_val=0),
docstring="Enables or disables four-wire (remote) sense mode. "
"When enabled, voltage is measured at the DUT using "
"separate sense leads, eliminating lead resistance errors.",
)
"""Enable or disables four-wire (remote) sense mode."""
# volt range
# needs get after set (WilliamHPNielsen): why?
self.sourcerange_v: Parameter = self.add_parameter(
"sourcerange_v",
label="voltage source range",
get_cmd=f"{channel}.source.rangev",
get_parser=float,
set_cmd=self._set_sourcerange_v,
unit="V",
docstring="The range used when sourcing voltage "
"This affects the range and the precision "
"of the source.",
vals=vals.Enum(*vranges[self.model]),
)
"""The range used when sourcing voltage This affects the range and the precision of the source."""
self.source_autorange_v_enabled: Parameter = self.add_parameter(
"source_autorange_v_enabled",
label="voltage source autorange",
get_cmd=f"{channel}.source.autorangev",
get_parser=float,
set_cmd=f"{channel}.source.autorangev={{}}",
docstring="Set autorange on/off for source voltage.",
val_mapping=create_on_off_val_mapping(on_val=1, off_val=0),
)
"""Set autorange on/off for source voltage."""
self.measurerange_v: Parameter = self.add_parameter(
"measurerange_v",
label="voltage measure range",
get_cmd=f"{channel}.measure.rangev",
get_parser=float,
set_cmd=self._set_measurerange_v,
unit="V",
docstring="The range to perform voltage "
"measurements in. This affects the range "
"and the precision of the measurement. "
"Note that if you both measure and "
"source current this will have no effect, "
"set `sourcerange_v` instead",
vals=vals.Enum(*vranges[self.model]),
)
"""
The range to perform voltage measurements in. This affects the range and the precision of the measurement.
Note that if you both measure and source current this will have no effect, set `sourcerange_v` instead
"""
self.measure_autorange_v_enabled: Parameter = self.add_parameter(
"measure_autorange_v_enabled",
label="voltage measure autorange",
get_cmd=f"{channel}.measure.autorangev",
get_parser=float,
set_cmd=f"{channel}.measure.autorangev={{}}",
docstring="Set autorange on/off for measure voltage.",
val_mapping=create_on_off_val_mapping(on_val=1, off_val=0),
)
"""Set autorange on/off for measure voltage."""
# current range
# needs get after set
self.sourcerange_i: Parameter = self.add_parameter(
"sourcerange_i",
label="current source range",
get_cmd=f"{channel}.source.rangei",
get_parser=float,
set_cmd=self._set_sourcerange_i,
unit="A",
docstring="The range used when sourcing current "
"This affects the range and the "
"precision of the source.",
vals=vals.Enum(*iranges[self.model]),
)
"""The range used when sourcing current This affects the range and the precision of the source."""
self.source_autorange_i_enabled: Parameter = self.add_parameter(
"source_autorange_i_enabled",
label="current source autorange",
get_cmd=f"{channel}.source.autorangei",
get_parser=float,
set_cmd=f"{channel}.source.autorangei={{}}",
docstring="Set autorange on/off for source current.",
val_mapping=create_on_off_val_mapping(on_val=1, off_val=0),
)
"""Set autorange on/off for source current."""
self.measurerange_i: Parameter = self.add_parameter(
"measurerange_i",
label="current measure range",
get_cmd=f"{channel}.measure.rangei",
get_parser=float,
set_cmd=self._set_measurerange_i,
unit="A",
docstring="The range to perform current "
"measurements in. This affects the range "
"and the precision of the measurement. "
"Note that if you both measure and source "
"current this will have no effect, set "
"`sourcerange_i` instead",
vals=vals.Enum(*iranges[self.model]),
)
"""
The range to perform current measurements in. This affects the range and the precision of the measurement.
Note that if you both measure and source current this will have no effect, set `sourcerange_i` instead"""
self.measure_autorange_i_enabled: Parameter = self.add_parameter(
"measure_autorange_i_enabled",
label="current autorange",
get_cmd=f"{channel}.measure.autorangei",
get_parser=float,
set_cmd=f"{channel}.measure.autorangei={{}}",
docstring="Set autorange on/off for measure current.",
val_mapping=create_on_off_val_mapping(on_val=1, off_val=0),
)
"""Set autorange on/off for measure current."""
# Compliance limit
self.limitv: Parameter = self.add_parameter(
"limitv",
get_cmd=f"{channel}.source.limitv",
get_parser=float,
set_cmd=f"{channel}.source.limitv={{}}",
docstring="Voltage limit e.g. the maximum voltage "
"allowed in current mode. If exceeded "
"the current will be clipped.",
vals=vals.Numbers(
vlimit_minmax[self.model][0], vlimit_minmax[self.model][1]
),
unit="V",
)
"""Voltage limit e.g. the maximum voltage allowed in current mode. If exceeded the current will be clipped."""
# Compliance limit
self.limiti: Parameter = self.add_parameter(
"limiti",
get_cmd=f"{channel}.source.limiti",
get_parser=float,
set_cmd=f"{channel}.source.limiti={{}}",
docstring="Current limit e.g. the maximum current "
"allowed in voltage mode. If exceeded "
"the voltage will be clipped.",
vals=vals.Numbers(
ilimit_minmax[self.model][0], ilimit_minmax[self.model][1]
),
unit="A",
)
"""Current limit e.g. the maximum current allowed in voltage mode. If exceeded the voltage will be clipped."""
# Internal fastsweep configuration - set via setup_fastsweep()
self._fastsweep_config: _FastSweepConfig | None = None
# Setpoint parameters for fastsweep — created fresh by setup_fastsweep()
self.fastsweep_inner_setpoints: Parameter | None = None
self.fastsweep_outer_setpoints: Parameter | None = None
self.fastsweep: LuaSweepParameter = self.add_parameter(
"fastsweep",
vals=vals.Arrays(shape=(1,)), # Placeholder, updated by setup_fastsweep
setpoints=(), # Updated by setup_fastsweep
parameter_class=LuaSweepParameter,
docstring="Performs a fast sweep using on-instrument Lua scripts. "
"Configure using setup_fastsweep() with LinSweep-like object(s). "
"For 1D sweeps, returns a 1D array. "
"For 2D sweeps, returns a 2D array with shape (outer_npts, inner_npts).",
)
"""
Performs a fast sweep. Configure with setup_fastsweep() before use.
Call ``fastsweep`` on the **inner** channel (the one from the first
:class:`~qcodes.dataset.LinSweep`). Calling this parameter (or using
``.get()``) returns the fast sweep data as a NumPy ``ndarray`` with
shape determined by the configured sweep(s).
**Direct usage (returns ndarray)**
Example 1D::
>>> from qcodes.dataset import LinSweep
>>> keith.smua.setup_fastsweep(LinSweep(keith.smua.volt, 0, 1, 100))
>>> data = keith.smua.fastsweep() # or: keith.smua.fastsweep.get()
>>> data.shape
(100,)
Example 2D (inner=smub, outer=smua)::
>>> from qcodes.dataset import LinSweep
>>> keith.smua.setup_fastsweep(
... LinSweep(keith.smub.volt, 0, 1, 100), # inner
... LinSweep(keith.smua.volt, 0, 0.5, 20), # outer
... )
>>> data = keith.smub.fastsweep() # call on inner channel
>>> data.shape
(20, 100)
**Dataset logging with do0d**
To log the fast sweep into a QCoDeS dataset, use :func:`do0d`
with the ``fastsweep`` parameter::
>>> from qcodes.dataset import LinSweep, do0d
>>> keith.smua.setup_fastsweep(LinSweep(keith.smua.volt, 0, 1, 100))
>>> ds, _, _ = do0d(keith.smua.fastsweep)
For a 2D sweep (inner=smub, outer=smua)::
>>> from qcodes.dataset import LinSweep, do0d
>>> keith.smua.setup_fastsweep(
... LinSweep(keith.smub.volt, 0, 1, 100), # inner
... LinSweep(keith.smua.volt, 0, 0.5, 20), # outer
... )
"""
self.timetrace_npts: Parameter = self.add_parameter(
"timetrace_npts",
initial_value=500,
label="Number of points",
get_cmd=None,
set_cmd=None,
)
"""Parameter timetrace_npts"""
self.timetrace_dt: Parameter = self.add_parameter(
"timetrace_dt",
initial_value=1e-3,
label="Time resolution",
unit="s",
get_cmd=None,
set_cmd=None,
)
"""Parameter timetrace_dt"""
self.time_axis: TimeAxis = self.add_parameter(
name="time_axis",
label="Time",
unit="s",
snapshot_value=False,
vals=vals.Arrays(shape=(self.timetrace_npts,)),
parameter_class=TimeAxis,
)
"""Parameter time_axis"""
self.timetrace: TimeTrace = self.add_parameter(
"timetrace",
vals=vals.Arrays(shape=(self.timetrace_npts,)),
setpoints=(self.time_axis,),
parameter_class=TimeTrace,
)
"""Parameter timetrace"""
self.timetrace_mode: Parameter = self.add_parameter(
"timetrace_mode",
initial_value="current",
get_cmd=None,