-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDataReader.py
More file actions
1607 lines (1199 loc) · 50.3 KB
/
DataReader.py
File metadata and controls
1607 lines (1199 loc) · 50.3 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
#!/usr/bin/python
import os
import glob
import operator
import copy
import numpy as np
from scipy.signal import savgol_filter as savgol
from scipy.signal import find_peaks
from scipy.signal import argrelextrema
from scipy.interpolate import interp1d
from scipy.ndimage import generic_filter, median_filter
from scipy.stats import median_abs_deviation as mad
from scipy.optimize import curve_fit, least_squares, minimize
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
from matplotlib.colors import LinearSegmentedColormap
from matplotlib import cm, colors
from matplotlib.patches import Rectangle
from matplotlib.patches import Circle
from matplotlib.animation import FFMpegWriter
from datetime import datetime
import itertools
def stringisint( s):
try:
val = int(s)
return True
except:
return False
def stringisfloat( s):
try:
val = float(s)
return True
except:
return False
def stringisstring( s):
if stringisfloat(s):
return False
if stringisint(s):
return False
return True
def makeiterable(o):
if hasattr(o,'__iter__'):
return o
return [0]
# ================================
# for third y axis
def make_patch_spines_invisible(ax):
ax.set_frame_on(True)
ax.patch.set_visible(False)
for sp in ax.spines.values():
sp.set_visible(False)
def find_spectral_lines_interpolated(y, window_length=21, polyorder=4, snr_threshold=5):
"""
Finds spectral lines using interpolated 2nd derivative zero-crossings.
"""
# 1. Compute 2nd derivative
y_pp = savgol(y, window_length=window_length, polyorder=polyorder, deriv=2)
# Noise estimation for thresholding
noise_std = np.std(y_pp[:100])
height_threshold = snr_threshold * noise_std
# 2. Find peaks (minima) in the 2nd derivative
peaks, _ = find_peaks(-y_pp, height=height_threshold)
results = []
for p in peaks:
# --- Sub-pixel Zero Crossing: Left Side ---
left_idx = p
while left_idx > 0 and y_pp[left_idx] < 0:
left_idx -= 1
# Linear interpolation: y = mx + b between left_idx and left_idx + 1
# Solve for x where y=0: x = x1 - y1 * (x2 - x1) / (y2 - y1)
y1, y2 = y_pp[left_idx], y_pp[left_idx + 1]
x_left = left_idx - y1 * (1.0) / (y2 - y1)
# --- Sub-pixel Zero Crossing: Right Side ---
right_idx = p
while right_idx < len(y_pp) - 1 and y_pp[right_idx] < 0:
right_idx += 1
y1, y2 = y_pp[right_idx - 1], y_pp[right_idx]
x_right = (right_idx - 1) - y1 * (1.0) / (y2 - y1)
# 3. Calculate Sigma and Amplitude
# Width between interpolated crossings is 2 * sigma
sigma = (x_right - x_left) / 2.0
# Amplitude estimate: A = |f''(center)| * sigma^2
amp_pp = np.abs(y_pp[p])
estimated_amp = amp_pp * (sigma**2)
results.append({
"center": p,
"x_left": x_left,
"x_right": x_right,
"sigma": sigma,
"estimated_amplitude": estimated_amp
})
return results
def find_spectral_lines(y, window_length=21, polyorder=4, snr_threshold=5):
"""
Finds spectral lines using 2nd derivative zero-crossings for width/amplitude.
Parameters:
y: array-like, the spectral data (e.g., from .tcd1304 file).
window_length: int, SavGol window size (must be odd).
polyorder: int, polynomial order for SavGol.
snr_threshold: float, threshold for peak detection in the 2nd derivative.
Returns:
List of dictionaries containing 'center', 'sigma', and 'estimated_amplitude'.
"""
# 1. Compute 2nd derivative using Savitzky-Golay
y_pp = savgol(y, window_length=window_length, polyorder=polyorder, deriv=2)
# Estimate noise floor of the 2nd derivative for SNR thresholding
noise_std = np.std(y_pp[:100]) # Uses first 100 points as baseline noise
height_threshold = snr_threshold * noise_std
# 2. Find peaks (minima) in the 2nd derivative
# We negate y_pp so find_peaks detects the "dips" as local maxima
peaks, _ = find_peaks(-y_pp, height=height_threshold)
results = []
for p in peaks:
# 3. Find Zero Crossings around the peak p
# Look left
left_idx = p
while left_idx > 0 and y_pp[left_idx] < 0:
left_idx -= 1
# Look right
right_idx = p
while right_idx < len(y_pp) - 1 and y_pp[right_idx] < 0:
right_idx += 1
# 4. Calculate Sigma (Width)
# Distance between zero crossings is 2 * sigma
sigma = (right_idx - left_idx) / 2.0
# 5. Estimate Amplitude (A)
# Relationship: f''(center) = -A / sigma^2
# Use absolute value of the 2nd derivative at peak center
amp_pp = np.abs(y_pp[p])
estimated_amp = amp_pp * (sigma**2)
results.append({
"center": p,
"sigma": sigma,
"estimated_amplitude": estimated_amp
})
return results
def select_spectral_lines_results(results,xcoordinates,selection,tolerance=None):
selected=[]
x = np.array([ xcoordinates[r['center']] for r in results ])
for s in selection:
n = np.abs(x - s).argmin()
if tolerance is None:
xtol = results[n]['sigma']
else:
xtol = tolerance
if np.abs(x[n]-s) <= xtol:
selected.append(results[n])
else:
selected.append(None)
results = selected
return results
def format_spectral_lines_results(results,key=None):
#print("formatting", results)
s = ""
if key is None:
for r in results:
#print("processing", r)
if r is None:
s += " NaN NaN NaN"
else:
s += " %.3f %.3f %.5g"%(r['center'],r['sigma'],r['estimated_amplitude'])
#print(s)
else:
for r in results:
#print("processing", r)
if r is None:
s += " NaN"
else:
s += " %.5g "%(r[key])
#print(s)
return s
# ==========================================================
def get_dynamic_integrated_intensity(x, y, center_wave):
# 1. Smooth the data to suppress noise
y_smooth = savgol(y, window_length=11, polyorder=3)
# 2. Compute 2nd derivative (d2y/dx2)
d2y = savgol(y_smooth, window_length=11, polyorder=3, deriv=2)
# 3. Define a broad search area around the expected peak
roi_mask = (x > center_wave - 2.0) & (x < center_wave + 2.0)
# 4. Use the second derivative to identify inflection points (where d2y flips sign)
# The inflection points define where the peak starts and ends
inflection_points = np.where(np.diff(np.sign(d2y[roi_mask])))[0]
if len(inflection_points) >= 2:
# Take the outermost inflection points in our ROI as the integration bounds
start_idx = inflection_points[0]
end_idx = inflection_points[-1]
# Extract the segment between inflection points
peak_segment = y_smooth[roi_mask][start_idx:end_idx]
# 5. Integrate the segment
return np.sum(peak_segment)
# Fallback: if inflection points aren't clear, return a simple slice
return np.sum(y_smooth[roi_mask])
# ==========================================================
def extract_linear_segment(data, xcoord, x1, x2):
idx = np.where( (xcoord >= x1) & (xcoord <= x2) )[0]
return data[idx]
def median_linear_segment(data, xcoord, x1, x2):
segment = extract_linear_segment(data,xcoord,x1,x2)
return np.median(segment)
# ==========================================================
# cleanup spectrum, cosmic ray, errant pixels, etc
def spectrum_median_filter( data, fp=13, passes = 2):
#print( "spectrum_median_filter, fp", fp, "passes", passes )
for n in range(passes):
data = median_filter(data,footprint=fp)
'''
ydata = copy.deepcopy(data)
data = median_filter(ydata,footprint=fp)
'''
return data
def spectrum_excursion_filter( data, span=11, gap=3, threshold=5., passes=2, verbose=False ):
datalen = len(data)
x = np.linspace(0,span,span,endpoint=False)
y = copy.deepcopy(data)
halfspan = int(span/2)
halfgap = int(gap/2)
n1 = int(halfspan-halfgap)
n2 = int(n1 + gap)
idx = list(range(n1)) + list(range(n2,span))
for n, d in enumerate(data):
if n < span:
n1 = 0
n2 = n1 + span;
elif datalen - n < span:
n1 = datalen - span
n2 = datalen
else:
n1 = n - int(span/2)
n2 = n + span
#segment = copy.deepcopy(data[n1:n2])
segment = data[n1:n2]
median_ = np.median(segment[idx])
stdev_ = np.std(segment[idx])
m = passes - 1
while m > 0:
idx = np.where(np.abs(segment-median_)<threshold*stdev_)
signal = np.median(segment[idx])
stdev_ = np.std(segment[idx])
m -= 1
if abs(d - median_) > threshold * stdev_:
y[n] = median_
return y
# ===================================================================================================================
def gaussian(x, amplitude, mean, sigma):
return amplitude * np.exp(-(1./2)*((x - mean) / sigma)**2)
def fit_gaussian(x,data):
popt, pcov = curve_fit(gaussian, x, data)
perr = np.sqrt(np.diag(pcov))
amplitude,mean,stdev, perr
# ===================================================================================================================
class FLEXPWM:
def __init__( self, name, period, onA, offA, invertA, onB, offB, invertB):
self.name = name
self.period = period
self.onA = onA
self.offA = offA
self.invertA = invertA
self.onB = onB
self.offB = offB
self.invertB = invertB
def dump( self ):
s = 'FLEXPWM: ' + self.name
for key, val in self.__dict__.items():
s += ' ' + key + '=' + str(val)
print(s)
return True
def draw(self,ax,stop,yoffset):
def draw_(ax,on,off,stop,invert,yoffset):
x = 0
step1 = on
step2 = off-on
step3 = period-off
if invert:
offstate = 1 + yoffset
onstate = yoffset
else:
onstate = 1 + yoffset
offstate = yoffset
while x < stop:
if step1 > 0:
ax.axhline(offstate,x,x+step1)
x = x+step1
if step2 > 0:
ax.axvline(x,offstate,onstate)
ax.axhline(onstate,x,x+step2)
x = x+step2
ax.axvline(x,offstate,onstate)
if step3 > 0:
ax.axhline(onstate,x,x+step3)
x = x+step3
draw_(ax,self.onA,self.offA,self.period,self.invertA,yoffset)
draw_(ax,self.onB,self.offB,self.period,self.invertB,yoffset)
# ===================================================================================================================
class DATAFrame:
def __init__( self, lines, parentinstance, offsetdigits = 5 ):
self.parent = parentinstance
self.weight = 1
self.isimage = False
# ----------------------------------------------------------------
# Read the file, load data and exec lines with '='
self.isint = False
rows = None
for line in lines:
line = line.strip()
if not len(line):
continue
if '=' in line:
if line[0] == '#':
line = line[1:].strip()
exec( line, self.__dict__ )
elif line.startswith( "# END" ) or line.startswith( "# end" ):
break
elif line.startswith( "# DATA" ) or line.startswith( "# data" ):
rows = []
self.isimage = False
self.isint = ('int64' in line) or ('int32') in line or ('uint16' in line)
elif line.startswith( "# IMAGE" ) or line.startswith( "# image" ):
rows = []
self.isimage = True
self.isint = 'uint16' in line
elif rows is not None:
if self.isint:
rows.append( [ int(r) for r in line.split() ] )
else:
rows.append( [ float(r) for r in line.split() ] )
# ----------------------------------------------------------------
# These are all historical, retained for backwards compatibility
if 'INTERVAL' in self.__dict__:
self.__dict__['interval'] = round( float(self.INTERVAL)*1.E-6, offsetdigits )
if 'SHUTTER' in self.__dict__:
self.__dict__['shutter'] = round( float(self.SHUTTER)*1.E-6, offsetdigits )
if 'CLOCK' in self.__dict__:
self.__dict__['clock'] = round( float(self.CLOCK)*1.E-6, offsetdigits )
if 'TRIGGERELAPSED' in self.__dict__:
self.__dict__['offset'] = round( float(self.TRIGGERELAPSED)*1.E-6, offsetdigits )
self.__dict__['elapsed'] = round( float(self.TRIGGERELAPSED)*1.E-6, offsetdigits )
# added 25/2/11
if 'ELAPSED' in self.__dict__:
self.__dict__['offset'] = round( float(self.ELAPSED)*1.E-6, offsetdigits )
self.__dict__['elapsed'] = round( float(self.ELAPSED)*1.E-6, offsetdigits )
if 'nanotimestamp' in self.__dict__:
self.__dict__['offset'] = round( float(self.nanotimestamp)*1.E-9, offsetdigits )
if 'ACCUMULATE' in self.__dict__:
try:
self.weight = max( self.ACCUMULATE, 1 )
except Exception as e:
print( 'ACCUMULATE', e )
# ======================================================================
# historical, image data support, else from rows to columns
if self.isimage:
self.data = np.array(rows)
else:
self.data = np.array(rows).T
for n,d in enumerate(self.data):
self.__dict__['chan%d'%n] = self.data[n]
if 'LABELS' in self.__dict__:
for n,s in enumerate(self.LABELS):
self.__dict__[s] = self.data[n]
# Data in volts, if read as integers convert to volts and apply baseline
def dataVolts(self,col=0,dark_subtraction=True,offset_subtraction=False, vfs=None, offset=None):
data = self.data[col]
if self.isint:
# --------------------------------------------
if vfs is not None:
bits = self.parent.bits
data = data * vfs/(2.**bits)
if offset is not None:
data = data - offset
# --------------------------------------------
else:
if self.parent.vperbit:
data = data * self.parent.vperbit
if offset_subtraction:
if 'offset' in self.__dict__:
print("offset subtraction", self.offset)
data = data - self.offset
elif 'scale_offset' in self.parent.__dict__:
print("parent scale_offset subtraction", self.parent.scale_offset)
data = data - self.parent.scale_offset
elif 'darkstart' in self.parent.__dict__ and self.parent.darkstart > 0:
offset = np.median(data[::darkstart])
data = data - offset
else:
print("offset_subtraction requested but no offset found in datafile")
# --------------------------------------------
if dark_subtraction and self.parent.darklength:
darkstart = self.parent.darkstart
darklength = self.parent.darklength
darkstop = darkstart + darklength
darkoffset = np.median( data[darkstart:darkstop] )
print("masked pixels (dark) subtraction", darkoffset)
data = data - darkoffset
return data
# data in number of electrons counters (close to 1 per photon)
def dataCounts(self,col=0):
data = self.dataVolts(col)
data *= 37.152*1000.
return data
def get( self, name ):
if name in self.__dict__:
return self.__dict__[name]
return None
def median( self, n=0, idx=None ):
if idx is None:
return np.nanmedian(self.data,axis=1)
else:
return np.nanmedian(self.data[idx],axis=1)
def nanmean( self, n=0, idx=None ):
if idx is None:
return np.nanmean(self.data,axis=1)
else:
return np.nanmean(self.data[idx],axis=1)
def dump( self ):
for key, val in self.__dict__.items():
if type(val) is list and len(val) > 10:
print( key, '=', val[0], '...' )
elif type(val) in [ dict ] :
continue
else:
print( key, type(val), ' =', val )
return True
def weighteddata( self ):
return self.data * self.weight
# ===================================================================================================================
# DATA Class has header and a list of frames, of type class DATAFRAME
class DATA:
def __init__( self, file, offsetdigits=5, verbose=False, debug=False ):
self.associated = None
if type(file) is str:
file = open( file, 'r' )
self.filename = file.name
self.version = file.readline().strip()
if self.version.startswith('#'):
self.version = self.version[1:].strip()
self.datetimestring = file.readline().strip()
if self.datetimestring.startswith('# time:'):
if debug:
print( '*** legacy time' )
self.datetimestring = self.datetimestring[7:].strip()
elif self.datetimestring.startswith('# opened:'):
if debug:
print( '*** original legacy time' )
self.datetimestring = self.datetimestring[9:].strip()
else:
self.datetimestring = self.datetimestring.strip('# ')
self.weightedadd = True
self.frames = []
for line in file:
line = line.strip()
if not len(line):
continue
if line[0] == '#':
line = line[1:].strip()
if line.startswith( 'header end' ):
break
if '=' in line:
line = line.strip()
exec( line, self.__dict__ )
if debug:
for k, v in self.__dict__.items():
if not k.startswith('__'):
print( k, v )
# Now we read the data frames
lines = []
for line in file:
lines.append(line)
if line.startswith( '# END' ):
self.frames.append( DATAFrame( lines, self, offsetdigits ) )
lines = []
file.close()
# added 8/22/2024
self.nframes = len(self.frames)
# And here is a numpy array of all of the frames of data
self.data = []
for frame in self.frames:
self.data.append(frame.data)
self.data = np.array(self.data)
def dump( self ):
for key, val in self.__dict__.items():
if type(val) is list and len(val) > 10:
print( key, '=', val[0], '...' )
elif isinstance(val,FLEXPWM):
print(val,type(val))
val.dump()
elif type(val) in [ dict ] :
continue
else:
print( key, type(val), ' =', val )
for f in self.frames:
print( '---------------------------' )
f.dump()
return True
def get( self, name ):
if name in self.__dict__:
return self.__dict__[name]
return None
def getlist(self, name):
vals = []
for f in self.frames:
vals.append(f.__dict__[name])
return vals
def getset(self,name):
return set(self.getlist(name))
def dataVolts(self,frameindex=None,col=0,dark_subtraction=True,offset_subtraction=True,vfs=None, offset=None, average=False):
if not self.nframes:
return None
if frameindex is None:
frameindex = list(range(self.nframes))
if type(frameindex) is list:
data = []
for n in frameindex:
data.append(self.frames[n].dataVolts(col=col,
dark_subtraction=dark_subtraction,
offset_subtraction=offset_subtraction,
vfs=vfs,offset=offset))
if average and len(frameindex) > 1:
data = np.average(data,axis=0)
return data
return self.frames[frameindex].dataVolts(col=col,
dark_subtraction=dark_subtraction,
offset_subtraction=offset_subtraction,
vfs=vfs,offset=offset)
def dataCounts(self,frameindex=None,col=0,dark_subtraction=True,offset_subtraction=True):
if not self.nframes:
return None
if frameindex is None:
frameindex = list(range(self.nframes))
if type(frameindex) is list:
data = []
for n in frameindex:
data.append(self.frames[n].dataCounts())
return data
return self.frames[frameindex].dataCounts()
# =========================================================================================================
# Load LCCD data
class LCCDDATA( DATA ):
def __init__( self, file, offsetdigits=5, other=None, verbose=False ):
DATA.__init__( self, file, offsetdigits, verbose=verbose )
# other instrument if any, associated with this measurement
self.other = other
# pixels, in millimeters
if 'pixelpitch' in self.__dict__:
self.pixelwidth_ = self.pixelpitch
else:
self.pixelwidth_ = 8.0E-3
self.datalength = len(self.frames[0].data[0])
print("creating xpixels")
self.xpixels = np.linspace( 0, self.datalength, self.datalength )
print("creating defaiult xdata")
self.xdata = self.xpixels * self.pixelwidth_
# Wavelength coefficients specified
if 'coefficients' in self.__dict__:
print("creating xdata from coefficients")
self.xdata = np.polynomial.polynomial.polyval( self.xpixels, self.coefficients )
if 'wavelength_coefficients' in self.__dict__:
print("creating xdata from wavelength_coefficients")
self.coefficients = self.wavelength_coefficients
self.xdata = np.polynomial.polynomial.polyval( self.xpixels, self.coefficients )
# integration intervals
self.exposure = 0.
try:
self.mode = list(self.getset('MODE'))[0]
except Exception as e:
print( 'mode', e )
try:
self.interval = list(self.getset('interval'))[0]
except Exception as e:
print( 'interval', e )
try:
self.shutter = list(self.getset('shutter'))[0]
except Exception as e:
print( 'shutter', e )
try:
self.clock = list(self.getset('clock'))[0]
except Exception as e:
print( 'clock', e )
try:
self.elapsedtimes = self.getlist('elapsed')
except Exception as e:
print( 'elaspedtimes', e )
self.exposure = None
if self.exposure is None:
try:
self.frame_exposures = [ round(f.frame_exposure,6) for f in self.frames ]
s = set(self.frame_exposures)
s = list(s)
print( "set of frame_exposures", s)
if len(s) == 1:
self.exposure = float(s[0])
print( "set exposure from frame_exposure", self.exposure)
except Exception as e:
print( 'frame_exposures', e )
if self.exposure is None:
try:
self.shutter_periods = list(self.getset('sh_period'))
#print( self.shutter_periods)
s = list(set(self.shutter_periods))
if len(s) == 1 and not self.exposure:
self.exposure = float(s[0])*1.E-6
print( "set exposure from shutter period", self.exposure)
except Exception as e:
print( 'shutter_periods', e )
if self.exposure is None:
try:
self.timer_periods = list(self.getset('timer_period'))
print( self.timer_periods)
s = list(set(self.timer_periods))
if len(s) == 1 and s[0] > 0 and not self.exposure:
# timer overrides exposure if present
self.exposure = float(s[0])*1.E-6
print( "set exposure from timer period", self.exposure)
except Exception as e:
print( 'shutter_period', e )
for flexpwm_name in [ 'clk', 'sh', 'icg', 'cnvst', 'timer' ]:
try:
self.__dict__[ 'flexpwm_'+flexpwm_name ] = self.extractflexpwm(flexpwm_name)
print('dict: flexpwm_'+flexpwm_name, self.__dict__['flexpwm_'+flexpwm_name])
except Exception as e:
print( 'extract '+flexpwm_name, e )
def trim( self, left = 0, right = -1 ):
self.xpixels = self.xpixels[left:right]
self.datalength = len(self.xpixels)
self.xdata = self.xdata[left:right]
self.angles = self.angles[left:right]
for n,frame in enumerate(self.frames):
frame.data = frame.data[:,left:right]
if 'xdata' in frame.__dicit__:
frame.__dict__['xdata'] = self.xdata
if 'angles' in frame.__dicit__:
frame.__dict__['angles'] = self.angles
def trim_by_xdata(self, left=None, right=None ):
idx1 = 0
if left is not None:
idx1 = np.argmax( self.xdata>=left )
idx2 = -1
if right is not None:
idx2 = 1 + np.where(self.xdata<=right)[0][-1]
self.trim( idx1, idx2 )
def extractflexpwm(self,name):
timestep = 1./150.E6
try:
key = "flexpwm_" + name+"_period"
print( "key", key, self.__dict__[key] )
if key in self.__dict__:
vals = self.__dict__[key]
vals = vals.split()
divider = int(vals[4])
timestep = float(divider)/150.E6
period = float(vals[0])*timestep
key = "flexpwm_" + name+"_A"
print( "key", key, self.__dict__[key] )
if key in self.__dict__:
vals = self.__dict__[key]
vals = vals.split()
onA = float(vals[5])*timestep
offA = float(vals[7])*timestep
invertA = 'noninverting' not in self.__dict__[key]
key = "flexpwm_" + name+"_B"
print( "key", key, self.__dict__[key] )
if key in self.__dict__:
vals = self.__dict__[key]
vals = vals.split()
onB = float(vals[5])*timestep
offB = float(vals[7])*timestep
invertB = 'noninverting' not in self.__dict__[key]
except Exception as e:
print(name, 'not parsed', e)
return None
return FLEXPWM( name, period, onA, offA, invertA, onB, offB, invertB)
# =============================================================================================
def loaddata( filespec, verbose=False ):
if filespec.endswith('lccd') or filespec.endswith('tcd1304'):
if verbose:
print( 'loaddata', filespec )
print( 'is lccd' )
data = LCCDDATA(filespec, verbose=verbose)
else:
data = DATA(filespec, verbose=verbose)
return data
def loaddataset( filespecs, verbose=False ):
if type(filespecs) is not list:
filespecs = [ filespecs ]
dataset = []
for filespec in filespecs:
for file in glob.glob(filespec):
dataset.append(loaddata(file, verbose=verbose ))
return dataset
def sortdataset( dataset, attr_name ):
dataset.sort( key=operator.attrgetter( attr_name ) )
def set_xaxis( ax, xmin=None, xmax=None, label=None, color=None, ticfontsize=None, labelfontsize=None ):
if xmin is not None:
ax.set_xlim( left = float(xmin) )
if xmax is not None:
ax.set_xlim( right = float(xmax) )
if ticfontsize:
ax.tick_params(axis='x', labelsize=ticfontsize)
if label is not None:
if color is not None and labelfontsize is not None:
ax.set_xlabel( label, color=color, fontsize=labelfontsize )
elif color is not None:
ax.set_xlabel( label, color=color )
elif labelfontsize is not None:
ax.set_xlabel( label, fontsize=labelfontsize )
else:
ax.set_xlabel( label )
def set_yaxis( ax, ymin=None, ymax=None, label=None, color=None, ticfontsize=None, labelfontsize=None ):
if ymin is not None:
ax.set_ylim( bottom = float(ymin) )
if ymax is not None:
ax.set_ylim( top = float(ymax) )
if ticfontsize:
ax.tick_params(axis='y', labelsize=ticfontsize)
if label is not None:
print( "set_yaxis label", label, color)
if color is not None and labelfontsize is not None:
ax.set_ylabel( label, color=color, fontsize=labelfontsize )
elif color is not None:
ax.set_ylabel( label, color=color )
elif labelfontsize is not None:
ax.set_ylabel( label, fontsize=labelfontsize )
else:
ax.set_ylabel( label )
def set_zaxis( ax, zmin=None, zmax=None, label=None, color=None, ticfontsize=None, labelfontsize=None ):
if labelfontsize is None:
labelfontsize = 'medium'
if zmin is not None:
ax.set_zlim( bottom = zmin )
if zmax is not None:
ax.set_zlim( top = zmax )
if ticfontsize:
ax.tick_params(axis='z', labelsize=ticfontsize)
if label is not None:
if color is not None and labelfontsize is not None:
ax.set_zlabel( label, color=color, fontsize=labelfontsize )
elif color is not None:
ax.set_zlabel( label, color=color )