-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathpicobase.py
1186 lines (983 loc) · 43.9 KB
/
picobase.py
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
# -*- coding: utf-8 -*-
"""
This is the base class that all picoscope modules use.
As much logic as possible is put into this file.
At minimum each instrument file requires you to modify the name of the API
function call (e.g. ps6000xxxx vs ps4000xxxx).
This is to force the authors of the instrument files to actually read the
documentation as opposed to assuming similarities between scopes.
You can find pico-python at github.com/colinoflynn/pico-python .
"""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import inspect
import time
import numpy as np
from .error_codes import ERROR_CODES as _ERROR_CODES
"""
pico-python is Copyright (c) 2013-2014 By:
Colin O'Flynn <coflynn@newae.com>
Mark Harfouche <mark.harfouche@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Inspired by Patrick Carle's code at
http://www.picotech.com/support/topic11239.html
which was adapted from
http://www.picotech.com/support/topic4926.html
"""
class _PicoscopeBase(object):
"""
This class defines a general interface for Picoscope oscilloscopes.
This class should not be called directly since it relies on lower level
functions to communicate with the actual devices.
"""
#########################################################
# You must reimplement this in device specific classes
#########################################################
# Do not include .dll or .so, these will be appended automatically
LIBNAME = "ps6000"
MAX_VALUE = 32764
MIN_VALUE = -32764
EXT_MAX_VALUE = 32767
EXT_MIN_VALUE = -32767
EXT_RANGE_VOLTS = 20
CHANNEL_RANGE = [{"rangeV": 20E-3, "apivalue": 1, "rangeStr": "20 mV"},
{"rangeV": 50E-3, "apivalue": 2, "rangeStr": "50 mV"},
{"rangeV": 100E-3, "apivalue": 3, "rangeStr": "100 mV"},
{"rangeV": 200E-3, "apivalue": 4, "rangeStr": "200 mV"},
{"rangeV": 500E-3, "apivalue": 5, "rangeStr": "500 mV"},
{"rangeV": 1.0, "apivalue": 6, "rangeStr": "1 V"},
{"rangeV": 2.0, "apivalue": 7, "rangeStr": "2 V"},
{"rangeV": 5.0, "apivalue": 8, "rangeStr": "5 V"},
]
NUM_CHANNELS = 2
CHANNELS = {"A": 0, "B": 1}
CHANNEL_COUPLINGS = {"DC50": 2, "DC": 1, "AC": 0}
BW_LIMITS = {"Full": 0, "20MHZ": 1}
############################################################
# End of things you must reimplement (I think).
############################################################
# If we don't get this CaseInsentiveDict working, I would prefer to stick
# with their spelling of archaic C all caps for this. I know it is silly,
# but it removes confusion for certain things like
# DC_VOLTAGE = DCVoltage or DcVoltage or DC_Voltage
# or even better
# SOFT_TRIG = SoftwareTrigger vs SoftTrig
ERROR_CODES = _ERROR_CODES
# For some reason this isn't working with me :S
THRESHOLD_TYPE = {"Above": 0,
"Below": 1,
"Rising": 2,
"Falling": 3,
"RiseOrFall": 4}
# getUnitInfo parameter types
UNIT_INFO_TYPES = {"DriverVersion": 0x0,
"USBVersion": 0x1,
"HardwareVersion": 0x2,
"VariantInfo": 0x3,
"BatchAndSerial": 0x4,
"CalDate": 0x5,
"KernelVersion": 0x6,
"DigitalHardwareVersion": 0x7,
"AnalogueHardwareVersion": 0x8,
"PicoFirmwareVersion1": 0x9,
"PicoFirmwareVersion2": 0xA}
def __init__(self, serialNumber=None, connect=True):
"""
Create a scope object, and by default also connect to it.
Parameters
----------
serialNumber
Set the serial number in order to connect to a specific scope.
Leave it empty for connecting to the next free scope.
connect : bool, default: True
Connect to the scope
"""
# TODO: Make A class for each channel
# that way the settings will make more sense
# These do not correspond to API values, but rather to
# the "true" voltage as seen at the oscilloscope probe
self.CHRange = [5.0] * self.NUM_CHANNELS
self.CHOffset = [0.0] * self.NUM_CHANNELS
self.CHCoupling = [1] * self.NUM_CHANNELS
self.ProbeAttenuation = [1.0] * self.NUM_CHANNELS
self.handle = None
if connect is True:
self.open(serialNumber)
def getUnitInfo(self, info):
"""Return a string containing information about `info`."""
if not isinstance(info, int):
info = self.UNIT_INFO_TYPES[info]
return self._lowLevelGetUnitInfo(info)
def getMaxValue(self):
"""Return the maximum ADC value, used for scaling."""
# TODO: make this more consistent accross versions
# This was a "fix" when we started supported PS5000a
return self.MAX_VALUE
def getMinValue(self):
"""Return the minimum ADC value, used for scaling."""
return self.MIN_VALUE
def getAllUnitInfo(self):
"""Return a string containing all information of the device."""
s = ""
for key in sorted(self.UNIT_INFO_TYPES.keys(),
key=self.UNIT_INFO_TYPES.get):
s += key.ljust(30) + ": " + self.getUnitInfo(key) + "\n"
s = s[:-1]
return s
def setChannel(self, channel='A', coupling="AC", VRange=2.0,
VOffset=0.0, enabled=True, BWLimited=0,
probeAttenuation=1.0):
"""
Set up a specific scope channel with the smallest range possible.
Parameters
-----------
channel
The channel to set up.
coupling
'AC' or 'DC'. Note that if you set a channel to use AC coupling,
you may need to make a "dummy call" to runBlock, or the first batch
of data returned via getData* may be inaccurate.
See https://www.picotech.com/support/topic35401.html
VRange
Measurement range in V.
VOffset
An offset, in volts, to be added to the input signal before it
reaches the input amplifier and digitizer.
enabled
Enable or disable the channel.
BWLimited
Limit the bandwidth.
probeAttenuation
See below.
Return
------
Actual range of the scope as double.
probeAttenuation
----------------
If using a probe (or a sense resitor), the `probeAttenuation` value is
used to find the approriate channel range on the scope to use.
e.g. to use a 10x attenuation probe, you must supply the following
parameters ps.setChannel('A', "DC", 20.0, 5.0, True, False, 10.0)
The scope will then be set to use the +- 2V mode at the scope allowing
you to measure your signal from -25V to +15V.
After this point, you can set everything in terms of units as seen at
the tip of the probe. For example, you can set a trigger of 15V and it
will trigger at the correct value.
When using a sense resistor, lets say R = 1.3 ohm, you obtain the
relation:
V = IR, meaning that your probe as an attenuation of R compared to the
current you are trying to measure.
You should supply probeAttenuation = 1.3
The rest of your units should be specified in amps.
Unfortunately, you still have to supply a `VRange` that is very close
to the allowed values. This will change in furture version where we
will find the next largest range to accomodate the desired range.
If you want to use units of mA, supply a probe attenuation of 1.3E3.
Note, the authors recommend sticking to SI units because it makes it
easier to guess what units each parameter is in.
"""
if enabled:
enabled = 1
else:
enabled = 0
if not isinstance(channel, int):
chNum = self.CHANNELS[channel]
else:
chNum = channel
if not isinstance(coupling, int):
coupling = self.CHANNEL_COUPLINGS[coupling]
# finds the next largest range
VRangeAPI = None
for item in self.CHANNEL_RANGE:
if item["rangeV"] - VRange / probeAttenuation > -1E-4:
if VRangeAPI is None:
VRangeAPI = item
# break
# Don't know if this is necessary assuming that it will iterate
# in order
elif VRangeAPI["rangeV"] > item["rangeV"]:
VRangeAPI = item
if VRangeAPI is None:
raise ValueError(
"Desired range %f is too large. Maximum range is %f." %
(VRange, self.CHANNEL_RANGE[-1]["rangeV"] * probeAttenuation))
# store the actually chosen range of the scope
VRange = VRangeAPI["rangeV"] * probeAttenuation
if not isinstance(BWLimited, int):
BWLimited = self.BW_LIMITS[BWLimited]
if BWLimited == 3:
BWLimited = 3 # 1MHz Bandwidth Limiter for PicoScope 4444
elif BWLimited == 2:
BWLimited = 2 # Bandwidth Limiter for PicoScope 6404,
# 100kHz Bandwidth Limiter for PicoScope 4444
elif BWLimited == 1:
BWLimited = 1 # Bandwidth Limiter for PicoScope 6402/6403,
# 20kHz Bandwidth Limiter for PicoScope 4444
else:
BWLimited = 0
self._lowLevelSetChannel(chNum, enabled, coupling,
VRangeAPI["apivalue"],
VOffset / probeAttenuation, BWLimited)
# if all was successful, save the parameters
self.CHRange[chNum] = VRange
self.CHOffset[chNum] = VOffset
self.CHCoupling[chNum] = coupling
self.ProbeAttenuation[chNum] = probeAttenuation
return VRange
def runBlock(self, pretrig=0.0, segmentIndex=0, callback=None):
"""Run a single block.
Must have already called setSampling for proper setup.
Parameters
----------
pretrig
Fraction of samples before the trigger.
segmentIndex
Index of scope memory segment to save data to.
callback
Function to call once the data acquisition finishes.
"""
# getting max samples is riddiculous.
# 1GS buffer means it will take so long
nSamples = min(self.noSamples, self.maxSamples)
# to return the same No. Samples ( if pretrig != 0.0 ) I'm wrong ?
nSamples_pretrig = int(round(nSamples * pretrig))
self._lowLevelRunBlock(nSamples_pretrig,
nSamples - nSamples_pretrig,
self.timebase, self.oversample, segmentIndex,
callback, None)
def isReady(self):
"""Return whether scope is ready to transfer data."""
return self._lowLevelIsReady()
def waitReady(self, spin_delay=0.01):
"""Block until the scope is ready, retesting every `spin_delay` s."""
while not self.isReady():
time.sleep(spin_delay)
def setSamplingInterval(self, sampleInterval, duration, oversample=0,
segmentIndex=0):
"""
Set the timebase according to a desired sampling interval.
Parameters
----------
sampleInterval
Desired interval in seconds between two samples.
duration
Desired duration of measurement.
oversample
Average over several measurements in the sample interval.
Not many picoscopes are capable of oversampling.
segmentIndex
Index of the memory segment to store data into.
Return
------
actualSampleInterval : float
The sample interval in seconds according to the timebase.
noSamples : int
Number of samples in the measurement duration.
maxSamples : int
Maximum number of samples possible in the memory segment.
"""
self.oversample = oversample
self.timebase = self.getTimeBaseNum(sampleInterval)
timebase_dt = self.getTimestepFromTimebase(self.timebase)
noSamples = int(round(duration / timebase_dt))
(self.sampleInterval, self.maxSamples) = self._lowLevelGetTimebase(
self.timebase, noSamples, oversample, segmentIndex)
self.noSamples = noSamples
self.sampleRate = 1.0 / self.sampleInterval
return (self.sampleInterval, self.noSamples, self.maxSamples)
def setSamplingFrequency(self, sampleFrequency, noSamples, oversample=0,
segmentIndex=0):
"""
Set the timebase according to a desired sampling frequency.
Parameters
----------
sampleFrequency
Desired sample frequency in samples per second.
noSamples
Desired number of samples.
oversample
Average over several measurements in the sample interval.
Not many picoscopes are capable of oversampling
segmentIndex
Index of the memory segment to store data into.
Return
------
sampleRate : float
The sample frequency in samples per second.
maxSamples : int
Maximum number of samples possible in the memory segment.
"""
# TODO: make me more like the functions above
# at least in terms of what I return
sampleInterval = 1.0 / sampleFrequency
duration = noSamples * sampleInterval
self.setSamplingInterval(sampleInterval, duration, oversample,
segmentIndex)
return (self.sampleRate, self.maxSamples)
def setNoOfCaptures(self, noCaptures):
"""
Set the number of captures for one run of rapid block mode.
If you do not call this function before a run, the driver will capture
one waveform.
"""
self._lowLevelSetNoOfCaptures(noCaptures)
def memorySegments(self, noSegments):
"""
Divide the scope memory into `noSegments` segments.
The scope fills the available memory segment for a single capture.
More segments allow several consecutive captures.
The memory is distributed amongst the active channels: the number of
samples available to each channel is the maximum number of samples
divided by 2 (for 2 channels) or 4 (for 3 or 4 channels) or
8 (for 5 to 8 channels).
Returns
Number of samples in the segment.
"""
maxSamples = self._lowLevelMemorySegments(noSegments)
self.maxSamples = maxSamples
self.noSegments = noSegments
return self.maxSamples
def getMaxMemorySegments(self):
"""
Return the maximum number of memory segments allowed by the device.
"""
segments = self._lowLevelGetMaxSegments()
return segments
def setExtTriggerRange(self, VRange=0.5):
"""
Set the range for the EXT trigger channel.
This is only implemented for PS4000 series devices where
the only acceptable values for VRange are 0.5 or 5.0.
"""
VRangeAPI = None
for item in self.CHANNEL_RANGE:
if np.isclose(item["rangeV"], VRange):
VRangeAPI = item
break
if VRangeAPI is None:
raise ValueError('Provided VRange is not valid')
self._lowLevelSetExtTriggerRange(VRangeAPI["apivalue"])
def setSimpleTrigger(self, trigSrc, threshold_V=0, direction="Rising",
delay=0, timeout_ms=100, enabled=True):
"""
Set up a simple trigger.
Parameters
----------
trigSrc
Either a channel number corresponding to the low level
specifications of the scope or a string such as 'A' or 'AUX'.
threshold_V
Threshold at which to trigger in V.
direction
Can be a text string such as "Rising" or "Falling",
or the value of the dict from self.THRESHOLD_TYPE[] corresponding
to your trigger type.
delay
Number of clock cycles to wait from trigger conditions met
until we actually trigger capture.
timeout_ms
Time to wait in ms from calling runBlock() or similar
(e.g. when trigger arms) for the trigger to occur. If no trigger
occurs it gives up & auto-triggers.
enabled
Enable or disable the trigger.
Notes
-----
- Support for offset is currently untested.
- The AUX port (or EXT) only has a range of +- 1V (at least in PS6000).
"""
if not isinstance(trigSrc, int):
trigSrc = self.CHANNELS[trigSrc]
if not isinstance(direction, int):
direction = self.THRESHOLD_TYPE[direction]
if trigSrc >= self.NUM_CHANNELS:
threshold_adc = int((threshold_V / self.EXT_RANGE_VOLTS) *
self.EXT_MAX_VALUE)
# The external port is typically used as a clock. So I don't think
# we should raise errors
threshold_adc = min(threshold_adc, self.EXT_MAX_VALUE)
threshold_adc = max(threshold_adc, self.EXT_MIN_VALUE)
else:
a2v = self.CHRange[trigSrc] / self.getMaxValue()
threshold_adc = int((threshold_V + self.CHOffset[trigSrc]) / a2v)
if (threshold_adc > self.getMaxValue() or
threshold_adc < self.getMinValue()):
raise IOError(
"Trigger Level of %fV outside allowed range (%f, %f)" % (
threshold_V,
-self.CHRange[trigSrc] - self.CHOffset[trigSrc],
+self.CHRange[trigSrc] - self.CHOffset[trigSrc]))
enabled = int(bool(enabled))
self._lowLevelSetSimpleTrigger(enabled, trigSrc, threshold_adc,
direction, delay, timeout_ms)
def getTriggerTimeOffset(self, segmentIndex=0):
"""
Get the trigger time offset in s for a waveform.
Parameter
---------
segmentIndex
Index of the memory segment in question.
"""
return self._lowLevelGetTriggerTimeOffset(segmentIndex)
def flashLed(self, times=5, start=False, stop=False):
"""
Flash the front panel LEDs.
Parameters
----------
times : int
Number of times to flash the LED
start : bool
Start the LED to flash indefinitely. Equals times < 0.
stop : bool
Stop the LED to flash. Equals times == 0
Note that calls to the RunStreaming or RunBlock will stop any flashing.
"""
if start:
times = -1
if stop:
times = 0
self._lowLevelFlashLed(times)
def getScaleAndOffset(self, channel):
"""
Return `channel`s scale and offset used to convert the raw waveform.
To use: first multiply by the scale, then subtract the offset.
Returns a dictionary with keys 'scale' and 'offset'.
"""
if not isinstance(channel, int):
channel = self.CHANNELS[channel]
return {'scale': self.CHRange[channel] / float(self.getMaxValue()),
'offset': self.CHOffset[channel]}
def rawToV(self, channel, dataRaw, dataV=None, dtype=np.float64):
"""
Convert the raw data to voltage units.
Parameters
----------
channel
Scope channel number or name.
dataRaw
Raw data.
dataV
Numpy array to fill with the data. If None, create an empty one.
dtype
Datatype for the numpy array to create.
Return
------
Numpy array with the measurement in V.
"""
if not isinstance(channel, int):
channel = self.CHANNELS[channel]
if dataV is None:
dataV = np.empty(dataRaw.shape, dtype=dtype)
a2v = self.CHRange[channel] / dtype(self.getMaxValue())
np.multiply(dataRaw, a2v, dataV)
np.subtract(dataV, self.CHOffset[channel], dataV)
return dataV
def getDataV(self, channel, numSamples=0, startIndex=0, downSampleRatio=1,
downSampleMode=0, segmentIndex=0, returnOverflow=False,
exceptOverflow=False, dataV=None, dataRaw=None,
dtype=np.float64):
"""
Return the data of a single channel as an array of voltage values.
Paramters
---------
channel
Scope channel number or name.
numSamples
Number of samples to return. If 0, take the calculated number from
set sampling interval/frequency.
startIndex
Index of the sample to start transfer.
downSampleRatio
Downsampling factor that will be applied to the raw data. Multiple
downsampling modes can be bitwise-ORed together, but the
downSampleRatio must be the same for all modes.
downSampleMode
Method of downsampling.
segmentIndex
Index of the memory segment to get data from.
returnOverflow
Return whether the measurement exceeded the range,
additionally to the data.
exceptOverflow
Raise an IOError exception on overflow.
dataV
Numpy array to fill with the data. If None, create an empty one.
dtype
Datatype for the numpy array to create.
dataRaw
Not used
Return
-----
dataV : numpy array
Numpy array with the values in Volts.
overflow : bool, only if returnOverflow is True
Whether the measured value exceeded the measurement range.
"""
(dataRaw, numSamplesReturned, overflow) = self.getDataRaw(
channel, numSamples, startIndex, downSampleRatio, downSampleMode,
segmentIndex, dataRaw)
if dataV is None:
dataV = self.rawToV(channel, dataRaw, dtype=dtype)
dataV = dataV[:numSamplesReturned]
else:
self.rawToV(channel, dataRaw, dataV, dtype=dtype)
dataV[numSamplesReturned:] = np.nan
if returnOverflow:
return (dataV, overflow)
else:
if overflow and exceptOverflow:
raise IOError("Overflow detected in data")
return dataV
def getDataRaw(self, channel='A', numSamples=0, startIndex=0,
downSampleRatio=1, downSampleMode=0, segmentIndex=0,
data=None):
"""
Return the data of a single channel.
Paramters
---------
channel
Scope channel number or name.
numSamples
Number of samples to return. If 0, take the calculated number from
set sampling interval/frequency.
startIndex
Index of the sample to start transfer.
downSampleRatio
Downsampling factor that will be applied to the raw data. Multiple
downsampling modes can be bitwise-ORed together, but the
downSampleRatio must be the same for all modes.
downSampleMode
Method of downsampling.
segmentIndex
Index of the memory segment to get data from.
data
Numpy array to fill with the data. If None, create an empty one.
Return
------
data : numpy array
Array with the digitalized measurement values.
NumSamplesReturned : int
Number of samples returned.
overflow : bool
Whether the measured value exceeded the measurement range.
"""
if not isinstance(channel, int):
channel = self.CHANNELS[channel]
if numSamples == 0:
# maxSamples is probably huge, 1Gig Sample can be HUGE....
numSamples = min(self.maxSamples, self.noSamples)
if data is None:
data = np.empty(numSamples, dtype=np.int16)
else:
if data.dtype != np.int16:
raise TypeError('Provided array must be int16')
if data.size < numSamples:
raise ValueError(
'Provided array must be at least as big as numSamples.')
# see numpy.ndarray.flags
if data.flags['CARRAY'] is False:
raise TypeError('Provided array must be c_contiguous,' +
' aligned and writeable.')
self._lowLevelSetDataBuffer(channel, data, downSampleMode,
segmentIndex)
(numSamplesReturned, overflow) = self._lowLevelGetValues(
numSamples, startIndex, downSampleRatio, downSampleMode,
segmentIndex)
# necessary or else the next call to getValues will try to fill
# this array unless it is a call trying to read the same channel.
self._lowLevelClearDataBuffer(channel, segmentIndex)
# overflow is a bitwise mask
overflow = bool(overflow & (1 << channel))
return (data, numSamplesReturned, overflow)
def getDataRawBulk(self, channel='A', numSamples=0, fromSegment=0,
toSegment=None, downSampleRatio=1, downSampleMode=0,
data=None):
"""
Get one or more waveforms collected in rapid block mode.
Parameters
----------
channel
Scope channel number or name.
numSamples
Number of samples per segment to return.
If 0, take the calculated number from set sampling interval.
fromSegment
Index of the first segment to retrieve data from.
toSegment
Index of the last segment to retrieve data from. If None: the last.
downSampleRatio
Downsampling factor that will be applied to the raw data. Multiple
downsampling modes can be bitwise-ORed together, but the
downSampleRatio must be the same for all modes.
downSampleMode
Method of downsampling.
data
Numpy array to fill with the data. If None, create an empty one.
Return
------
data : numpy array
Array containing the raw data.
numSamples : int
Number of samples retrieved per waveform.
overflow : numpy array
Array containing whether the range was exceeded.
"""
if not isinstance(channel, int):
channel = self.CHANNELS[channel]
if toSegment is None:
toSegment = self.noSegments - 1
if numSamples == 0:
numSamples = min(self.maxSamples, self.noSamples)
numSegmentsToCopy = toSegment - fromSegment + 1
if data is None:
data = np.ascontiguousarray(
np.zeros((numSegmentsToCopy, numSamples), dtype=np.int16))
# set up each row in the data array as a buffer for one of
# the memory segments in the scope
for i, segment in enumerate(range(fromSegment, toSegment + 1)):
self._lowLevelSetDataBufferBulk(channel,
data[i],
segment,
downSampleMode)
overflow = np.ascontiguousarray(
np.zeros(numSegmentsToCopy, dtype=np.int16))
self._lowLevelGetValuesBulk(numSamples, fromSegment, toSegment,
downSampleRatio, downSampleMode, overflow)
# don't leave the API thinking these can be written to later
for i, segment in enumerate(range(fromSegment, toSegment + 1)):
self._lowLevelClearDataBuffer(channel, segment)
return (data, numSamples, overflow)
def setSigGenBuiltInSimple(self,
offsetVoltage=0, pkToPk=2, waveType="Sine",
frequency=1E6, shots=1, triggerType="Rising",
triggerSource="None", stopFrequency=None,
increment=10.0, dwellTime=1E-3, sweepType="Up",
numSweeps=0):
"""
Generate simple signals using the built-in waveforms.
Parameters
----------
offsetVoltage
Voltage offset.
pkToPk
Voltage from peak to peak
waveType
Type of waveform: 'Sine', 'Square', 'Triangle', 'RampUp',
'RampDown', and 'DCVoltage'.
Some hardware also supports these additional waveforms:
'Sinc', 'Gaussian', 'HalfSine', and 'WhiteNoise'.
frequency
Frequency in Hertz to start at.
shots
How often to repeat the waveform. If nonzero, `numSweeps`=0.
triggerType
Type of trigger edge/threshold. See SIGGEN_TRIGGER_TYPES.
triggerSource
Source of the waveform trigger. See SIGGEN_TRIGGER_SOURCES.
stopFrequency
Frequency in Hertz to stop at. If None, do not sweep.
increment
Frequency change in Hertz, if in sweep mode.
dwellTime
Time in seconds between two frequency changes in sweep mode.
sweepType
Type of sweeping the frequency: 'Up', 'Down', 'UpDown', 'DownUp'.
numSweeps
Number of sweeps. If nonzero, `shots` has to be zero.
"""
# I put this here, because the python idiom None is very
# close to the "None" string we expect
if triggerSource is None:
triggerSource = "None"
if not isinstance(waveType, int):
waveType = self.WAVE_TYPES[waveType]
if not isinstance(triggerType, int):
triggerType = self.SIGGEN_TRIGGER_TYPES[triggerType]
if not isinstance(triggerSource, int):
triggerSource = self.SIGGEN_TRIGGER_SOURCES[triggerSource]
if not isinstance(sweepType, int):
sweepType = self.SWEEP_TYPES[sweepType]
self._lowLevelSetSigGenBuiltInSimple(
offsetVoltage, pkToPk, waveType, frequency, shots, triggerType,
triggerSource, stopFrequency, increment, dwellTime, sweepType,
numSweeps)
def setAWGSimple(self, waveform, duration, offsetVoltage=None,
pkToPk=None, indexMode="Single", shots=1,
triggerType="Rising", triggerSource="ScopeTrig"):
"""
Set the AWG to output your desired waveform.
If you require precise control of the timestep increment, you should
use setSigGenAritrarySimpleDeltaPhase instead
Check setSigGenAritrarySimpleDeltaPhase for parameter explanation
Returns:
The actual duration of the waveform.
"""
sampling_interval = duration / len(waveform)
if not isinstance(indexMode, int):
indexMode = self.AWG_INDEX_MODES[indexMode]
if indexMode == self.AWG_INDEX_MODES["Single"]:
pass
elif indexMode == self.AWG_INDEX_MODES["Dual"]:
sampling_interval /= 2
elif indexMode == self.AWG_INDEX_MODES["Quad"]:
sampling_interval /= 4
deltaPhase = self.getAWGDeltaPhase(sampling_interval)
actual_druation = self.setAWGSimpleDeltaPhase(
waveform, deltaPhase, offsetVoltage, pkToPk, indexMode, shots,
triggerType, triggerSource)
return (actual_druation, deltaPhase)
def setAWGSimpleDeltaPhase(self, waveform, deltaPhase, offsetVoltage=None,
pkToPk=None, indexMode="Single", shots=1,
triggerType="Rising",
triggerSource="ScopeTrig"):
"""
Specify deltaPhase between each sample and not the total waveform
duration.
Returns the actual time duration of the waveform
If pkToPk and offset Voltage are both set to None, then their values
are computed as
pkToPk = np.max(waveform) - np.min(waveform)
offset = (np.max(waveform) + np.min(waveform)) / 2
This should in theory minimize the quantization error in the ADC.
else, the waveform should be a numpy int16 type array with the
containing waveform
For the Quad mode, if offset voltage is not provided, then waveform[0]
is assumed to be the offset. In quad mode, the offset voltage is the
point of symmetry
This is function provides a little more control than
setAWGSimple in the sense that you are able to specify deltaPhase
directly. It should only be used when deltaPhase becomes very large.
Warning. Ideally, you would want this to be a power of 2 that way each
sample is given out at exactly the same difference in time otherwise,
if you give it something closer to .75 you would obtain
T | phase accumulator value | sample
0 | 0 | 0
5 | 0.75 | 0
10 | 1.50 | 1
15 | 2.25 | 2
20 | 3.00 | 3
25 | 3.75 | 3
notice how sample 0 and 3 were played twice while others were only
played once.
This is why this low level function is exposed to the user so that he
can control these edge cases
I would suggest using something like this: if you care about obtaining
evenly spaced samples at the expense of the precise duration of the
your waveform
To find the next highest power of 2
always a smaller sampling interval than the one you asked for
math.pow(2, math.ceil(math.log(deltaPhase, 2)))
To find the next smaller power of 2
always a larger sampling interval than the one you asked for
math.pow(2, math.floor(math.log(deltaPhase, 2)))
To find the nearest power of 2
math.pow(2, int(math.log(deltaPhase, 2), + 0.5))
"""
"""
This part of the code is written for the PS6403
(PS6403B if that matters)
I don't really know a good way to differentiate between PS6403 versions
It essentially does some autoscaling for the waveform so that it can be
sent to the Picoscope to allow for maximum resolution from the DDS.
I haven't tested if you can actually obtain more resolution than simply
setting the DDS to output from -2 to +2
I assume they have some type of adjustable gain and offset on their DDS
allowing them to claim that they can get extremely high resolution.
"""
if not isinstance(indexMode, int):
indexMode = self.AWG_INDEX_MODES[indexMode]
if not isinstance(triggerType, int):
triggerType = self.SIGGEN_TRIGGER_TYPES[triggerType]
if not isinstance(triggerSource, int):
triggerSource = self.SIGGEN_TRIGGER_SOURCES[triggerSource]
if waveform.dtype == np.int16:
if offsetVoltage is None:
offsetVoltage = 0.0
if pkToPk is None:
pkToPk = 2.0
# TODO: make this a per scope function assuming 2.0 V AWG
else:
if indexMode == self.AWG_INDEX_MODES["Quad"]:
# Optimize for the Quad mode.
"""
Quad mode. The generator outputs the contents of the buffer,
then on its second pass through the buffer outputs the same
data in reverse order. On the third and fourth passes
it does the same but with a negative version of the data. This
allows you to specify only the first quarter of a waveform with
fourfold symmetry, such as a sine wave, and let the generator
fill in the other three quarters.
"""
if offsetVoltage is None:
offsetVoltage = waveform[0]
else:
# Nothing to do for the dual mode or the single mode
if offsetVoltage is None:
offsetVoltage = (np.max(waveform) + np.min(waveform)) / 2