-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathopt_lib.py
1989 lines (1651 loc) · 71.4 KB
/
opt_lib.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
"""
Created on Tue Mar 14 14:01:46 2017
@author: Svitozar Serkez
"""
from copy import deepcopy
import matplotlib
matplotlib.use('Qt5Agg')
from matplotlib import pyplot as plt
from matplotlib import rcParams
import matplotlib.colors as colors
from scipy import signal
import scipy
import glob
import h5py
import numpy
import sys
import time
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.figure import Figure
# Import numba if available
try:
import numba as nb
from numba import jit
numba_avail = True
except ImportError:
print("math_op.py: module Numba is not installed. Install it if you want speed up correlation calculations.")
numba_avail = False
# # Import ocelot if available
# try:
# import ocelot
# from ocelot.utils.xfel_utils import *
# from ocelot.optics.wave import imitate_1d_sase
# ocelot_avail = True
# except ImportError:
# print("ocelot is not imported.")
ocelot_avail = False
# Configure some plotting parameters.
rcParams['image.cmap'] = 'viridis'
#rcParams['figure.dpi'] = 100
# rcParams['figure.figsize'] = [8, 6]
# rcParams['font.size'] = 15.0
# Physical constants.
from scipy.constants import e, hbar, c, h
from math import pi
# Some useful conversions (### move to separate library?)
h_eV_s = h/e # = 4.135667516e-15 eV s
hr_eV_s = h_eV_s / 2. / pi
speed_of_light = c # = 299792458.0 m/s
def find_nearest_idx(array, value):
if value == -numpy.inf:
value = numpy.amin(array)
if value == numpy.inf:
value = numpy.amax(array)
return (numpy.abs(array-value)).argmin()
def find_nearest(array, value):
return array[find_nearest_idx(array, value)]
def n_moment(x, counts, c, n):
x = numpy.squeeze(x)
if x.ndim != 1:
raise ValueError("scale of x should be 1-dimensional")
if x.size not in counts.shape:
raise ValueError("operands could not be broadcast together with shapes %s %s" %(str(x.shape), str(counts.shape)))
if numpy.sum(counts)==0:
return 0
else:
if x.ndim == 1 and counts.ndim == 1:
return (numpy.sum((x-c)**n*counts) / numpy.sum(counts))**(1./n)
else:
if x.size in counts.shape:
dim_ = [i for i, v in enumerate(counts.shape) if v == x.size]
counts = numpy.moveaxis(counts, dim_, -1)
return (numpy.sum((x-c)**n*counts, axis=-1) / numpy.sum(counts, axis=-1))**(1./n)
def std_moment(x, counts):
mean=n_moment(x, counts, 0, 1)
return n_moment(x, counts, mean, 2)
def fwhm3(valuelist, height=0.5, peakpos=-1, total=1):
### comments:
### handle exception if valuelist not proper input (e.g. not a list or array)
### rename peakpos to peak_index
### None as default for peakpos
### Rename total to start_search_from_edges
### Type of parameter "total" should be bool (default=True)
"""
Calculates the full width at half maximum (fwhm) of some curve.
The function will return the fwhm with sub-pixel interpolation.
It will start at the maximum position and 'walk' left and right
until it approaches the half values.
if total==1, it will start at the edges and 'walk' towards peak
until it approaches the half values.
:param valuelist: Values to analyse (e.g. temporal shape of a pulse).
:type valuelist: iterable (list, array, numpy.ndarray)
:param height: Fraction of maximum value used to evaluate the width. Default=0.5 (corresponding to FWHM).
:type height: float
:param peakpos: List index of the peak to examine. Default = -1 (use global maximum).
:type peakpos: int
:param total: Flag to force searching the half maximum starting from edges (instead of from maximum). Default=1 (True).
:type total: int
:return: Peak index, width, [lower index of width interval, upper index of width interval].
:rtype: tuple
"""
if peakpos == -1: # no peakpos given -> take maximum
peak = numpy.max(valuelist)
peakpos = numpy.min(numpy.nonzero(valuelist == peak))
peakvalue = valuelist[peakpos]
phalf = peakvalue * height
if total == 0:
# go left and right, starting from peakpos
ind1 = peakpos
ind2 = peakpos
while ind1 > 2 and valuelist[ind1] > phalf:
ind1 = ind1 - 1
while ind2 < len(valuelist) - 1 and valuelist[ind2] > phalf:
ind2 = ind2 + 1
grad1 = valuelist[ind1 + 1] - valuelist[ind1]
grad2 = valuelist[ind2] - valuelist[ind2 - 1]
if grad1 == 0 or grad2 == 0:
width = None
else:
# calculate the linear interpolations
# print(ind1,ind2)
p1interp = ind1 + (phalf - valuelist[ind1]) / grad1
p2interp = ind2 + (phalf - valuelist[ind2]) / grad2
# calculate the width
width = p2interp - p1interp
else:
# go to center from edges
ind1 = 1
ind2 = valuelist.size-2
# print(peakvalue,phalf)
# print(ind1,ind2,valuelist[ind1],valuelist[ind2])
while ind1 < peakpos and valuelist[ind1] < phalf:
ind1 = ind1 + 1
while ind2 > peakpos and valuelist[ind2] < phalf:
ind2 = ind2 - 1
# print(ind1,ind2)
# ind1 and 2 are now just above phalf
grad1 = valuelist[ind1] - valuelist[ind1 - 1]
grad2 = valuelist[ind2 + 1] - valuelist[ind2]
if grad1 == 0 or grad2 == 0:
width = None
else:
# calculate the linear interpolations
p1interp = ind1 + (phalf - valuelist[ind1]) / grad1
p2interp = ind2 + (phalf - valuelist[ind2]) / grad2
# calculate the width
width = p2interp - p1interp
# print(p1interp, p2interp)
return (peakpos, width, numpy.array([ind1, ind2]))
def mode(ndarray, axis=0):
### Complete docstring
'''
by Devin Cairns
'''
# Check inputs
ndarray = numpy.asarray(ndarray)
ndim = ndarray.ndim
if ndarray.size == 1:
return (ndarray[0], 1)
elif ndarray.size == 0:
raise Exception('Cannot compute mode on empty array')
try:
axis = range(ndarray.ndim)[axis]
except:
raise Exception('Axis "{}" incompatible with the {}-dimension array'.format(axis, ndim))
# If array is 1-D and numpy version is > 1.9 numpy.unique will suffice
if all([ndim == 1,
int(numpy.__version__.split('.')[0]) >= 1,
int(numpy.__version__.split('.')[1]) >= 9]):
modals, counts = numpy.unique(ndarray, return_counts=True)
index = numpy.argmax(counts)
return modals[index], counts[index]
# Sort array
sort = numpy.sort(ndarray, axis=axis)
# Create array to transpose along the axis and get padding shape
transpose = numpy.roll(numpy.arange(ndim)[::-1], axis)
shape = list(sort.shape)
shape[axis] = 1
# Create a boolean array along strides of unique values
strides = numpy.concatenate([numpy.zeros(shape=shape, dtype='bool'),
numpy.diff(sort, axis=axis) == 0,
numpy.zeros(shape=shape, dtype='bool')],
axis=axis).transpose(transpose).ravel()
# Count the stride lengths
counts = numpy.cumsum(strides)
counts[~strides] = numpy.concatenate([[0], numpy.diff(counts[~strides])])
counts[strides] = 0
# Get shape of padded counts and slice to return to the original shape
shape = numpy.array(sort.shape)
shape[axis] += 1
shape = shape[transpose]
slices = [slice(None)] * ndim
slices[axis] = slice(1, None)
# Reshape and compute final counts
counts = counts.reshape(shape).transpose(transpose)[slices] + 1
# Find maximum counts and return modals/counts
slices = [slice(None, i) for i in sort.shape]
del slices[axis]
index = numpy.ogrid[slices]
index.insert(axis, numpy.argmax(counts, axis=axis))
return sort[index], counts[index]
class ImageArray():
"""
:class ImageArray: Container class for a stack of images.
"""
def __init__(self,
image_stack=None,
train_id=None,
):
'''
Constructor of the ImageArray class.
:param image_stack: Stack of images to process. Default: None (will be set by caller).
:type image_stack: numpy.array (3D).
:param train_id: Sequence of train IDs corresponding to images in the stack. Default: None (will be set by caller).
:type train_id: 1D iterable
'''
if image_stack is None:
self.im = numpy.zeros((1,1,1)) # event, y, x
self.x = None #x pixel number array
self.y = None #y pixel number array
else:
self.im = image_stack
self.x = numpy.arange(self.im.shape[2])
self.y = numpy.arange(self.im.shape[1])
self.pixsize_x = None
self.pixsize_y = None
self.train_id = train_id
self.hdf5 = None
self.file_path = None
self.phen = None
### Could expose members in constructor.
def integr(self):
return numpy.sum(self.im, axis=(1, 2))
def remove_zero_trains(self):
'''
Remove trains with train id 0
'''
idx = numpy.where(self.train_id != 0)[0]
self.im = self.im[idx,:,:]
self.train_id = self.train_id[idx]
def remove_zero_images(self):
'''
Removes images with 0 total count.
'''
integr = self.integr()
idx = numpy.where(integr != 0)[0]
self.im = self.im[idx,:,:]
self.train_id = self.train_id[idx]
def add_spec_scale(self, E_center=9350, dE=0.1):
'''
Allows to add photon energy scale.
:param E_center: Photon energy at the central pixel of the dispersive direction [eV].
:param dE: Energy resolution per pixel [eV]
'''
linsp = numpy.arange(self.im.shape[1])
linsp = linsp - numpy.mean(linsp)
self.phen = linsp * dE + E_center
def yield_spectrum_old(self, slice_min=-numpy.inf, slice_max=numpy.inf, E_center=9350, dE=0.1, spec_direction='y'):
'''
Calculates line-out between slice_min and slice_max
to obtain 2d data matrix of single-shot spectra
returns SpectrumArray() object.
:param slice_min: Minimum spectral energy [eV].
:param slice_max: Maximum spectral energy [eV].
:param E_center: Central energy [eV]. Default: E_center=9350.
:param dE: Energy increment [eV]. Default: dE=0.1.
:param spec_direction: Dispersive direction in the 2D image. Default: disp_dir='y'.
:type spec_direction: str
:return: Array of single-shot spectra.
:rtype: SpectrumArray
'''
spar = SpectrumArray()
linsp = self.y - numpy.mean(self.y)
spar.omega = (linsp * dE + E_center) / hr_eV_s
idx = numpy.logical_and(self.x >= slice_min, self.x <= slice_max)
spar.train_id = self.train_id
spar.path = self.file_path
if self.im.squeeze().ndim == 3:
if sum(idx) == 1:
spar.spec = self.im[:,:,idx].T
else:
spar.spec = numpy.mean(self.im[:,:,idx],2).T
return spar
else:
spar.spec = self.im[:,:].squeeze().T
return spar
def yield_spectrum(self, slc=slice(None,None,1), E_center=9350, dE=0.1, disp_dir='y'):
'''
Calculates line-out over a given slice
to obtain 2d data matrix of single-shot spectra.
Returns SpectrumArray() object
:param slc: Slice over which to extract the spectra.
:type slc: slice
:param E_center: Central energy for spectral axis [eV]. Default: E_center=9350
:param dE: Energy increment for spectral axis [eV]. Default: dE=0.1
:param disp_dir: Dispersive direction in the 2D image. Default: disp_dir='y'.
:type disp_dir: str
:return: Array of single-shot spectra.
:rtype: SpectrumArray
'''
spar = SpectrumArray()
if disp_dir == 'y':
linsp = self.y - numpy.mean(self.y)
elif disp_dir == 'x':
linsp = self.x - numpy.mean(self.x)
else:
raise ValueError('disp_dir should be "x" or "y"')
spar.omega = (linsp * dE + E_center) / hr_eV_s
# idx = numpy.logical_and(self.x >= slice_min, self.x <= slice_max)
spar.train_id = self.train_id
spar.path = self.file_path
if self.im.squeeze().ndim == 3:
if disp_dir == 'y':
spar.spec = numpy.mean(self.im[:,:,slc],2).T
elif disp_dir == 'x':
spar.spec = numpy.mean(self.im[:,slc,:],1).T
else:
raise ValueError('disp_dir should be "x" or "y"')
# if sum(idx) == 1:
# spar.spec = self.im[:,:,idx].T
# else:
# spar.spec = numpy.mean(self.im[:,:,idx],2).T
# return spar
else:
spar.spec = self.im[:,:].squeeze().T
return spar
def remove_background_camx(self, sl=slice(1, 10), averaged=1):
'''
Removes background individually for each x position
(useful when the image has characteristic noise equal at all 'y'-dispersive positions)
:param sl: Slice object with range to calculate background. Default: sl=slice(1,10).
:type sl: slice
:param averaged: Flag to control wheather to treat each event individually. Default: averaged=1 (treat each event individually). Set to averaged=0 to turn this behaviour off.
:type averaged: int
'''
if averaged:
bkg = numpy.mean(self.im[:, sl, :], axis=(0, 1))[numpy.newaxis,numpy.newaxis,:].astype(self.im.dtype)
#bkg = numpy.mean(self.im[:, :, sl], axis=(0, 2))[numpy.newaxis,:,numpy.newaxis].astype(self.im.dtype)
else:
bkg = numpy.mean(self.im[:, sl, :], axis=1)[:,numpy.newaxis,:].astype(self.im.dtype)
#bkg = numpy.mean(self.im[:, :, sl], axis=2)[:, :, numpy.newaxis].astype(self.im.dtype)
import ipdb; ipdb.set_trace()
self.im = (self.im - bkg)
def remove_background_camy(self, sl=slice(1, 10), averaged=1):
'''
Removes background individually for each y position
(useful when the image has characteristic noise equal at all 'x'-dispersive positions)
:param sl: Slice object with range to calculate background. Default: sl=slice(1,10).
:type sl: slice
:param averaged: Flag to control wheather to treat each event individually. Default: averaged=1 (treat each event individually). Set to averaged=0 to turn this behaviour off.
:type averaged: int
'''
if averaged:
bkg = numpy.mean(self.im[:, :, sl], axis=(0, 2))[numpy.newaxis,:,numpy.newaxis].astype(self.im.dtype)
else:
bkg = numpy.mean(self.im[:, :, sl], axis=1)[numpy.newaxis,numpy.newaxis,:].astype(self.im.dtype)
self.im = (self.im - bkg)
def remove_background_spec(self, sl=slice(1, 10), averaged=1):
'''
Removes background individually for each x position
(useful when the image has characteristic noise equal at all 'y'-dispersive positions)
:param sl: Slice object with range to calculate background. Default: sl=slice(1,10).
:type sl: slice
:param averaged: Flag to control wheather to treat each event individually. Default: averaged=1 (treat each event individually). Set to averaged=0 to turn this behaviour off.
:type averaged: int
'''
if averaged:
bkg = numpy.mean(self.im[:, sl, :]).astype(self.im.dtype)
self.im = (self.im - bkg)
else:
bkg = numpy.mean(self.im[:, sl, :], axis=(1, 2))[:,numpy.newaxis,numpy.newaxis].astype(self.im.dtype)
self.im = (self.im - bkg)
def remove_background_imar(self, imar, turn_integer=0):
'''
Removes average background level from each image.
:param sl: Slice object with range to calculate background. Default: sl=slice(1,10).
:type sl: slice
:param turn_integer: Flag to control wheather to convert array elements to integers. Default: turn_integer=0 (no conversion).
:type turn_integer: int
'''
if self.im.ndim == imar.im.ndim == 3:
im_av = numpy.mean(imar.im, axis=0)
else:
im_av = imar.im
if turn_integer:
im_av = int(im_av)
self.im -= im_av
else:
self.im = self.im - im_av
def subtract_event(self, idx):
""" Subtract a given event from all other events.
:param idx: The subtracted event's index.
"""
self.im = self.im - self.im[idx,:,:][numpy.newaxis,:,:]
#self.im = numpy.delete(self.im, idx, axis=0)
#self.train_id = numpy.delete(self.im, idx, axis=0)
def find_darkest_event(self):
""" Find the event with the lowest total intensity.
:return: Index of the darkest event.
:rtype: int
"""
integr = self.integr()
idx = numpy.where(integr == numpy.amin(integr))[0][0]
return idx
def subtract_darkest_event(self):
""" Subtract the darkest event from all other events."""
self.subtract_event(self.find_darkest_event())
def remove_low_intensity_events(self, thresh=0.5, relative=1):
'''
Delete events with sum per image below a threshold.
:param thresh: The total intensity threshold (if relative==0) or scaling factor to determine threshold via threshold = thresh * average_value from all events. Default: thresh=0.5
:param relative: Flag to control the meaning of thresh (absolute threshold or relative to average value).j
'''
integr = numpy.sum(self.im, axis=(1,2))
if relative:
idx = numpy.where(integr > numpy.mean(integr) * thresh)[0]
else:
idx = numpy.where(integr > thresh)[0]
self.im = self.im[idx,:,:]
if self.train_id is not None:
self.train_id = self.train_id[idx]
def fix_negative_values(self):
""" Set negative exposures to 0.0 """
self.im[self.im < 0] = 0
def plot_event(self, event_n, fignum=None):
'''
Plot single camera image.
:param event_n: Index of event to plot.
:type event_n: int
:param fignum: Number of figure to pass to matplotlib.pyplot.figure().
:type fignum: int
'''
if self.pixsize_x != None:
x = self.x * self.pixsize_x * 1000
xlabel_txt = 'x [mm]'
else:
x = self.x
xlabel_txt = 'x direction'
if self.pixsize_y != None:
y = self.y * self.pixsize_y * 1000
ylabel_txt = 'y [mm]'
else:
y = self.y
ylabel_txt = 'x direction'
plt.figure(fignum)
plt.clf()
if self.im[event_n,:,:].squeeze().ndim == 2:
# print(self.im[1,:,:].T.shape)
# print(self.x.shape)
# print(self.y.shape)
plt.pcolormesh(x, y, self.im[event_n,:,:])
plt.axis('tight')
plt.ylabel(ylabel_txt)
plt.xlabel(xlabel_txt)
plt.colorbar()
else:
plt.plot(self.im[event_n,:,:].T)
plt.show()
#def cut(self, xsl=slice(None,None,1), ysl=slice(None,None,1), event=slice(None,None,1)):
#imar = ImageArray()
#imar.x = self.x[xsl]
#imar.y = self.y[ysl]
#imar.train_id = self.train_id[event]
#imar.im = self.im[event, ysl, xsl]
#return imar
def projections(self):
'''
Calculate 3 projections of the image array and return in ImageProjections() object (plottable)
useful to analyze the evolution of the spot position and intensity.
:return: Projections of the image stack in x,y, and event.
:rtype: ImageProjections
'''
proj = ImageProjections()
proj.proj_cam = numpy.sum(self.im, axis=0)
proj.proj_y = numpy.sum(self.im, axis=2) # spec_av -> proj_y
proj.proj_x = numpy.sum(self.im, axis=1) # pos_av -> proj_x
proj.integr = numpy.mean(self.im, axis=(1, 2))
proj.train_id = self.train_id
proj.path = self.file_path
proj.hdf5 = self.hdf5
proj.x = self.x
proj.y = self.y
proj.pixsize_x = self.pixsize_x
proj.pixsize_y = self.pixsize_y
proj_x_fix = proj.proj_x# - numpy.amin(proj.proj_x)
proj_y_fix = proj.proj_y# - numpy.amin(proj.proj_y)
xint = numpy.sum(proj_x_fix, 1)
yint = numpy.sum(proj_y_fix, 1)
# Calculate center of mass"
# Sum up x-coordinates x projected values and divide by sum of projected values. This must be secured against division by 0, using where xint!=0.
proj.x_centmass_pos = numpy.divide(numpy.dot(proj.x , proj_x_fix.T), xint, out=xint.astype(numpy.float), where=xint!=0).astype(numpy.int)
proj.y_centmass_pos = numpy.divide(numpy.dot(proj.y , proj_y_fix.T), yint, out=yint.astype(numpy.float), where=yint!=0).astype(numpy.int)
max_pos = [numpy.unravel_index(numpy.argmax(im, axis=None), im.shape) for im in self.im]
proj.x_max_pos = numpy.array([i[0] for i in max_pos])
proj.y_max_pos = numpy.array([i[1] for i in max_pos])
return proj
class ImageProjections():
'''
:class ImageProjections: Container class to store 3 cartesian projections of the Image Array object.
'''
def __init__(self):
self.proj_cam = None
self.proj_y = None
self.proj_x = None
self.integr = None
self.train_id = None
self.path = None
self.hdf5 = None
self.x = None
self.y = None
self.y_max_pos = None
self.y_max_pos = None
self.x_centmass_pos = None
self.y_centmass_pos = None
pass
def plot(self, plot_pos=1, plot_text=1, fignum=None, figsize=(15,10)):
""" Plot the projections in matplotlib subplots.
:param plot_pos: Flag to control whether to plot the position. Default: plot_pos=1 (True).
:param fignum: Figure number to pass to matplotlib.pyplot.figure().
:param figsize: Size of figure in cm. Default: figsize=(15,10)
"""
events = self.proj_y.shape[0]
xscale = self.x
yscale = self.y
if self.pixsize_x != None:
mult_x = self.pixsize_x * 1000
xlabel_txt = 'x [mm]'
else:
mult_x = 1
xlabel_txt = 'x direction'
if self.pixsize_y != None:
mult_y = self.pixsize_y * 1000
ylabel_txt = 'y [mm]'
else:
mult_y = 1
ylabel_txt = 'x direction'
xscale = xscale * mult_x
yscale = yscale * mult_y
#yscale = numpy.arange(self.proj_cam.shape[0])
#xscale = numpy.arange(self.proj_cam.shape[1])
#if self.train_id.size == events and numpy.nansum(self.train_id)>0:
if self.train_id is not None:
eventscale = self.train_id
else:
eventscale = numpy.arange(events)
plt.figure(fignum, figsize=figsize)
plt.clf()
plt.subplots_adjust(wspace=.2, hspace=.2)
ax_xy = plt.subplot(2,2,1)
if self.proj_cam.squeeze().ndim == 2:
plt.pcolormesh(xscale, yscale, self.proj_cam)
plt.xlabel(xlabel_txt)
plt.ylabel(ylabel_txt)
plt.axis('tight')
#ax_xy = plt.gca()
if plot_text:
plt.text(0.98, 0.98, '[{:.1f} : {:.1f}]'.format(numpy.amin(self.proj_cam), numpy.amax(self.proj_cam)),
horizontalalignment='right', verticalalignment='top',
transform=ax_xy.transAxes, color='white')
plt.text(0.98, 0.02, '[{:.1f} : {:.1f}]'.format(numpy.amin(self.proj_cam), numpy.amax(self.proj_cam)),
horizontalalignment='right', verticalalignment='bottom',
transform=ax_xy.transAxes, color='black')
ax_ty = plt.subplot(2,2,2, sharey=ax_xy)
if self.proj_y.squeeze().ndim == 2:
plt.pcolormesh(eventscale, yscale, self.proj_y.T)
if plot_pos:
if hasattr(self,'y_centmass_pos'):
plt.plot(eventscale, self.y_centmass_pos * mult_y, color='red', linewidth=0.5)
if hasattr(self,'y_max_pos'):
plt.plot(eventscale, self.y_max_pos * mult_y, color='green', linewidth=0.5)
plt.xlabel('event')
plt.ylabel(ylabel_txt)
plt.axis('tight')
if plot_text:
plt.text(0.98, 0.98, '[{:.1f} : {:.1f}]'.format(numpy.amin(self.proj_y), numpy.amax(self.proj_y)),
horizontalalignment='right', verticalalignment='top',
transform=ax_ty.transAxes, color='white')
plt.text(0.98, 0.02, '[{:.1f} : {:.1f}]'.format(numpy.amin(self.proj_y), numpy.amax(self.proj_y)),
horizontalalignment='right', verticalalignment='bottom',
transform=ax_ty.transAxes, color='black')
ax_xt = plt.subplot(2,2,3, sharex=ax_xy)
if self.proj_x.squeeze().ndim == 2:
plt.pcolormesh(xscale, eventscale, self.proj_x)
if plot_pos:
if hasattr(self,'x_centmass_pos'):
plt.plot(self.x_centmass_pos * mult_x, eventscale, color='red', linewidth=0.5)
if hasattr(self,'x_max_pos'):
plt.plot(self.x_max_pos * mult_x, eventscale, color='green', linewidth=0.5)
plt.ylabel('event')
plt.xlabel(xlabel_txt)
plt.axis('tight')
if plot_text:
plt.text(0.98, 0.98, '[{:.1f} : {:.1f}]'.format(numpy.amin(self.proj_x), numpy.amax(self.proj_x)),
horizontalalignment='right', verticalalignment='top',
transform=ax_xt.transAxes, color='white')
plt.text(0.98, 0.02, '[{:.1f} : {:.1f}]'.format(numpy.amin(self.proj_x), numpy.amax(self.proj_x)),
horizontalalignment='right', verticalalignment='bottom',
transform=ax_xt.transAxes, color='black')
ax_ti = plt.subplot(2,2,4, sharex=ax_ty)
plt.plot(eventscale, self.integr)
plt.axis('tight')
#plt.ylim(bottom=0)
plt.xlabel('event')
plt.ylabel('flux [a.u]')
try:
ax_xy.set_xlim([numpy.amin(xscale), numpy.amax(xscale)])
ax_xy.set_ylim([numpy.amin(yscale), numpy.amax(yscale)])
except:
pass
plt.show()
def read_im_arr_hdf5(
file_path,
dtype=numpy.int32,
source='bragg',
xsl=slice(None,None,1),
ysl=slice(None,None,1),
event=slice(None,None,1),
rotate=0,
):
""" Function to read (a stack of) images and relevant metadata from hdf5.
:param file_path: The path to the file to be read.
:type file_path: str
:param dtype: The type in which the images to read is stored. Default: dtype=numpy.int32.
:param source: The data source (camera or detector) from which to read the images. Default: camera=bragg. Possible values: 'bragg' || gotthard' || path to hdf5 dataset, e.g. "INSTRUMENT/SA1_XTD_HIREX/CAM/BRAGG:daqOutput/data/image/pixels"
:type source: str
:param xsl: Slice of indices on third axis (x) to read. Default: xsl=slice(None, None, 1) [-> read all x values]
:type xsl: slice
:param ysl: Slice of indices on second axis (y) to read. Default: ysl=slice(None, None, 1) [-> read all y values]
:type ysl: slice
:param event: Slice of indices on first axis (time/events) to read. Default: event=slice(None, None, 1) [-> read all events]
:type event: slice
"""
# Construct the image array.
imar = ImageArray()
with h5py.File(file_path, 'r') as f:
if source == 'bragg':
pixels = f['INSTRUMENT/SA1_XTD9_HIREX/CAM/BRAGG:daqOutput/data/image/pixels']
elif source == 'gotthard':
pixels = f['INSTRUMENT/SA1_XTD9_HIREX/DAQ/GOTTHARD:daqOutput/data/adc']
else:
pixels = f[source]
# Take out the numpy array and close file safely.
pixels = pixels.value
# Attempt to read the trainIDs.
try:
train_id = f['INSTRUMENT/SA1_XTD9_HIREX/CAM/BRAGG:daqOutput/data/trainId'].value
imar.train_id = train_id[event]
except:
# raise
pass
# Convert to requested type and shape.
imar.im = (pixels[event,ysl,xsl]).astype(dtype)
shape_orig = imar.im.shape
if rotate == 90:
imar.im = numpy.reshape(imar.im, (shape_orig[0], shape_orig[2], shape_orig[1])) #temporary fix for improperly recorded rotated images
if source == 'gotthard':
imar.im = numpy.rollaxis(imar.im,2,1)
imar.x = numpy.arange(imar.im.shape[1])
imar.y = numpy.arange(imar.im.shape[2])
else:
imar.x = numpy.arange(imar.im.shape[2])
imar.y = numpy.arange(imar.im.shape[1])
imar.file_path = file_path
print(' done')
return imar
def read_im_arr_raw(
file_path_mask,
dtype=numpy.int32,
resolution=(1080,1920),
xsl=slice(None,None,1),
ysl=slice(None,None,1),
event=slice(None,None,1),
):
""" """
""" undocumented """
print('reading')
filenames = glob.glob(file_path_mask)
d = []
for filename in filenames:
#print(filename)
l0 = numpy.fromfile(filename, dtype=numpy.uint16)
l = l0.reshape(resolution)
d.append(l)
imar = ImageArray()
im = numpy.rollaxis(numpy.array(d),0)
if dtype is None:
dtype=numpy.uint16
imar.x = numpy.arange(im.shape[2])[xsl]
imar.y = numpy.arange(im.shape[1])[ysl]
imar.train_id = numpy.arange(im.shape[0])[event]
imar.im = im[event,ysl,xsl].astype(dtype)
imar.file_path = file_path_mask
print(' done, processed {:d} files'.format(len(d)))
return imar
def read_im_arr_hdf5_LCLS(file_path, xsl=slice(None,None,1), ysl=slice(None,None,1), event=slice(None,None,1), dtype=numpy.int32, cryst='C'):
""" """
""" undocumented """
print('reading')
f = h5py.File(file_path, 'r')
if cryst == 'C':
pixels = f['/Configure:0000/Run:0000/CalibCycle:0000/Camera::FrameV1/XcsEndstation.1:Opal1000.2/image']
elif cryst == 'Si':
pixels = f['/Configure:0000/Run:0000/CalibCycle:0000/Camera::FrameV1/XcsEndstation.1:Opal1000.1/image']
else:
pixels = f[cryst]
# raise ValueError('cryst should be "Si" or "C"')
# train_id = f['INSTRUMENT/SA1_XTD9_HIREX/CAM/BRAGG:daqOutput/data/trainId']
imar = ImageArray()
im = pixels[event]
if im.ndim==2:
im = im[numpy.newaxis, :,:]
# imar.x = numpy.arange(im.shape[1])[xsl]
# imar.y = numpy.arange(im.shape[2])[ysl]
im = im[:,ysl,xsl]
# imar.train_id = train_id[event]
imar.im = im.astype(dtype)
imar.x = numpy.arange(imar.im.shape[2])
imar.y = numpy.arange(imar.im.shape[1])
# imar.im = numpy.rollaxis(imar.im,2,1)
imar.file_path = file_path
print(' done')
return imar
def read_spec_arr_hdf5_FLASH(file_path, wav0=None, dwav = None, remove_empty=False):
""" """
""" undocumented """
f = h5py.File(file_path, 'r')
pixels = f['/Photon Diagnostic/Wavelength/PG2 spectrometer/photon wavelength']
if dwav is None:
dwav = f['/Photon Diagnostic/Wavelength/PG2 spectrometer/photon wavelength increment']
if wav0 is None:
wav0 = f['/Photon Diagnostic/Wavelength/PG2 spectrometer/photon wavelength start value']
wav = (numpy.nanmean(wav0) + numpy.arange(pixels.shape[1]) * numpy.nanmean(dwav)) * 1e-9
spar = SpectrumArray()
spar.spec = numpy.array(pixels).T
spar.phen = h_eV_s * speed_of_light / wav
spar.train_id = None#numpy.arange(pixels.shape[0])
spar.path = file_path
spar.spec[numpy.isnan(spar.spec)] = 0
if remove_empty:
idx_nonzero = numpy.where(spar.integral() != 0)[0]
spar.spec = spar.spec[:,idx_nonzero]
spar.train_id = spar.train_id[idx_nonzero]
return spar
# x = f['/Photon Diagnostic/GMD/Beam position/position BDA x'][idx_nonzero, 0]
# y = f['/Photon Diagnostic/GMD/Beam position/position BDA y'][idx_nonzero, 0]
# e_el = f['/Electron Diagnostic/Electron energy/pulse resolved energy'][idx_nonzero, 0]
def read_spec_arr_hdf5_FLASH_online(file_path, wav0=None, dwav = None, remove_empty=False):
""" """
""" Read hdf5 files yielded by PG2 spectrometer in FLASH """
f = h5py.File(file_path, 'r')
pixels = f['/Photon Diagnostic/Wavelength/PG2 spectrometer/photon wavelength']
if dwav is None:
dwav = pixels.attrs['inc']
if wav0 is None:
wav0 = pixels.attrs['start']
wav = (numpy.nanmean(wav0) + numpy.arange(pixels.shape[1]) * numpy.nanmean(dwav)) * 1e-9
spar = SpectrumArray()
spar.spec = numpy.array(pixels).T
spar.phen = h_eV_s * speed_of_light / wav
spar.train_id = None#numpy.arange(pixels.shape[0])
spar.path = file_path
spar.spec[numpy.isnan(spar.spec)] = 0
if remove_empty:
spar.remove_zero_int()
return spar
def read_spec_arr_hdf5_SA3(file_path, phen_channel='/INSTRUMENT/SA3_XTD10_SPECT/MDL/FEL_BEAM_SPECTROMETER:output/data/photonEnergy', spec_channel='/INSTRUMENT/SA3_XTD10_SPECT/MDL/FEL_BEAM_SPECTROMETER:output/data/intensityDistribution', train_id_channel='/INSTRUMENT/SA3_XTD10_SPECT/MDL/FEL_BEAM_SPECTROMETER:output/data/trainId'):
print('reading')
f = h5py.File(file_path, 'r')
spar = SpectrumArray()
phen = f[phen_channel]
spec = f[spec_channel]
train_id = f[train_id_channel]
# spar.phen[0,:]
idx = phen[0,:] != 1
spar.phen = phen[0, idx]
spar.spec = spec[:, idx].T
# spar.phen = phen * dE + E_center
spar.train_id = train_id[:]
spar.path = file_path
print(' done')
return spar
def simulate_spar_random(n_events=5,
spec_center=9350,
spec_width=20,
spec_res=0.1,
pulse_length=1,
flattop=0,
spec_extend=3
):
"""
Simulate an array ot FEL spectra (interface function to ocelot.optics.wave.imitate_1d_sase).
:param spec_center: Central energy [eV]. Default: spec_center=9350.
:type spec_center: numeric
:param spec_width: Spetral width (full width at half maximum) [eV]. Default: spec_width=20.
:type spec_width: numeric
:param spec_res: Spectral resolution [eV]. Default: spec_res=0.1.
:type spec_res: numeric
:param pulse_length: Pulse duration [fs]. Default: pulse_length=1.
:type pulse_length: numeric
:param flattop: Flag to control whether pulse shape is flat-top (rectangular). Default: flattop=0 (-> not rectangular).
:type flattop: int
:param spec_extend: ???
"""
t, td, phen,fd = imitate_1d_sase(n_events=n_events, spec_center=spec_center, spec_width=spec_width, spec_res=spec_res, pulse_length=pulse_length, flattop=flattop, spec_extend=spec_extend)
# del(_)
spar = SpectrumArray()
spar.spec = abs(fd)**2
# power = abs(td)**2
spar.omega = phen / hr_eV_s
spar.pow = abs(td)**2
spar.t = t
return spar
class SpectrumArray():
""" :class SpectrumArray: Container class for FEL spectra (intensity vs. energy).
"""
def __init__(self,