-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSpecMath.py
1721 lines (1425 loc) · 62.5 KB
/
SpecMath.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
#################################################################
# #
# SPEC MATHEMATICS #
# version: 1.3.2 - Jan - 2021 #
# @author: Sergio Lins sergio.lins@roma3.infn.it #
#################################################################
TESTFNC = False
#############
# Utilities #
#############
import logging
logger = logging.getLogger("logfile")
import threading
import os, time
import sys
import gc
import numpy as np
import pickle
import random
#############
#################
# Local imports #
#################
import Elements
from Engine.SpecRead import (getdata,
getdimension,
getcalibration,
getfirstfile,
calibrate,
updatespectra)
from Engine.ImgMath import LEVELS
from Engine.Mapping import getdensitymap
from GUI.ProgressBar import Busy
import Constants
import cy_funcs
#################
####################
# External modules #
####################
import matplotlib.pyplot as plt
try:
from numba import jit
except:
print("Failed to load numba")
import math
from tkinter import *
from tkinter import ttk
####################
iterator = 0
lock = threading.Lock()
class datacube:
""" Cube class. Comprises all data read from spectra, elemental maps created,
background extracted (as a separate xy matrix), derived spectra, image size, image
dimension, datacube configuration, calibrated energy axis """
ndim = 0
def __init__(__self__,dtypes,configuration,mode="",name=""):
__self__.version = Constants.VERSION
if mode == "merge":
__self__.name = name
__self__.path = name
__self__.config = {}
__self__.config["directory"] = name
for key in configuration:
if key != "directory": __self__.config[key] = configuration[key]
else:
from Constants import SAMPLE_PATH
__self__.name = configuration["directory"]
__self__.path = SAMPLE_PATH
logger.debug("Initializing cube file")
__self__.datatypes = np.array(["{0}".format(
dtypes[type]) for type in range(len(dtypes))])
try: specsize = getdata(getfirstfile())
except:
if any("h5" in x for x in __self__.datatypes):
specsize = Constants.MY_DATACUBE.shape[2]
__self__.path = ""
else:
specsize = 0
if mode != "merge" and "mca" in __self__.datatypes:
__self__.dimension = getdimension()
__self__.img_size = __self__.dimension[0]*__self__.dimension[1]
__self__.matrix = np.zeros([__self__.dimension[0],__self__.dimension[1],
specsize.shape[0]],dtype="int32",order='C')
__self__.config = configuration
__self__.calibration = getcalibration()
__self__.mps = np.zeros([specsize.shape[0]],dtype="int32")
elif any("h5" in x for x in __self__.datatypes):
__self__.matrix = Constants.MY_DATACUBE
__self__.dimension = (__self__.matrix.shape[0],__self__.matrix.shape[1],True)
__self__.img_size = __self__.dimension[0]*__self__.dimension[1]
__self__.config = configuration
__self__.calibration = getcalibration()
__self__.mps = np.zeros(specsize,dtype="int32")
gc.collect()
__self__.ROI = {}
__self__.hist = {}
__self__.max_counts = {}
def MPS(__self__,mps):
""" Read all data in datacube.matrix and returns a spectrum where each index
is the maximum value found in the matrix for that same index.
MPS stands for Maximum Pixel Spectrum """
size = int(len(mps))
shape = np.asarray(__self__.matrix.shape)
cy_funcs.cy_MPS(__self__.matrix, shape, mps, size)
def stacksum(__self__):
""" Reall all data in datacube.matrix and return the summation derived spectrum """
__self__.sum = np.zeros([__self__.matrix.shape[2]],dtype="int32")
for x in range(__self__.matrix.shape[0]):
for y in range(__self__.matrix.shape[1]):
__self__.sum += __self__.matrix[x,y]
def fit_fano_and_noise(__self__):
__self__.FN = FN_fit_gaus(__self__.sum,
__self__.sum_bg,
__self__.energyaxis,
__self__.gain)
def flush_spectra(__self__,path):
print("Flushing data to {}".format(path))
try: os.makedirs(path)
except:
print("Path {} exists.".format(path))
print("Do you want to overwrite the data? (Y/N)")
proceed = input()
if proceed == "Y" or proceed == "y":
shutil.rmtree(path)
try: os.makedirs(path)
except:
print("Failed to create new directory. Aborting...")
sys.exit(1)
else:
print("Aborted by user.")
sys.exit(1)
iterator = 1
name = "Spec_"
for i in range(__self__.matrix.shape[0]):
for j in range(__self__.matrix.shape[1]):
spec = open(os.path.join(path,name+str(iterator)+".txt"),"+w")
spec.write(
"<<PMCA SPECTRUM>>\nTAG - TAG\nDESCRIPTION - Piratininga SM Sum Spectrum\n")
spec.write("GAIN - 2\nTHRESHOLD - 0\nLIVE_MODE - 0\nPRESET_TIME - OFF\n")
spec.write("LIVE_TIME - 0\nREAL_TIME - 0\nSTART_TIME - {}\n".format(
time.strftime("%Y-%m-%d %H:%M:%S",
time.gmtime())))
spec.write("SERIAL_NUMBER - 00001\n<<CALIBRATION>>\nLABEL - Channel\n")
for pair in __self__.calibration:
spec.write("{0} {1}\n".format(pair[0],pair[1]))
spec.write("<<DATA>>\n")
for c in __self__.matrix[i][j]:
spec.write("{}\n".format(int(c)))
spec.write("<<END>>")
spec.close()
iterator += 1
percent = iterator/__self__.img_size*100
print("{:0.2f} percent complete...".format(percent),end="\r")
def write_sum(__self__):
""" Saves the summation derived spectrum as an mca file to disk """
# import internal variables.
# they must be imported here in order to be the most recent ones (they are constantly
# updated by the GUI).
from Engine.SpecRead import output_path, cube_path
try: os.mkdir(output_path)
except: pass
sum_file = open(os.path.join(output_path,"stacksum.mca"),'w+')
#writes header
sum_file.write("<<PMCA SPECTRUM>>\nTAG - TAG\nDESCRIPTION - {} Sum Spectrum\n".format(
__self__.name))
sum_file.write("GAIN - 2\nTHRESHOLD - 0\nLIVE_MODE - 0\nPRESET_TIME - OFF\n")
sum_file.write("LIVE_TIME - 0\nREAL_TIME - 0\nSTART_TIME - {}\n".format(
time.strftime("%Y-%m-%d %H:%M:%S",
time.gmtime())))
sum_file.write("SERIAL_NUMBER - 00001\n<<CALIBRATION>>\nLABEL - Channel\n")
for pair in __self__.calibration:
sum_file.write("{0} {1}\n".format(pair[0],pair[1]))
sum_file.write("<<DATA>>\n")
###############
for counts in __self__.sum:
sum_file.write("{}\n".format(int(counts)))
sum_file.write("<<END>>")
sum_file.close()
ANSII_file = open(os.path.join(output_path,"ANSII_SUM.txt"),'w+')
ANSII_file.write("counts\tenergy (KeV)\n")
for index in range(__self__.sum.shape[0]):
ANSII_file.write("{0}\t{1}\n".format(
int(__self__.sum[index]),
__self__.energyaxis[index]))
ANSII_file.close()
def strip_background(__self__,
bgstrip=None,
recalculating=False,
progressbar=None):
""" Calculates the background contribution to each invidual spectrum.
The calculated data is saved into the datacube object.
bgstrip; a string """
if recalculating == True:
bgstrip = bgstrip
progressbar = progressbar
progressbar.progress["maximum"] = __self__.img_size
progressbar.updatebar(0)
else:
bgstrip = __self__.config['bgstrip']
try:
progressbar = __self__.progressbar
progressbar.progress["maximum"] = __self__.img_size
except: progressbar = progressbar
counter = 0
##########################
# initialize empty array #
##########################
__self__.background = np.zeros([__self__.dimension[0],__self__.dimension[1],
__self__.matrix.shape[2]],dtype="float32",order='C')
__self__.sum_bg = np.zeros([__self__.matrix.shape[2]])
##########################
if bgstrip == "SNIPBG":
progressbar.update_text("Calculating SNIPBG")
try: cycles, window,savgol,order= __self__.config["bg_settings"]
except: cycles, window, savgol, order = 24,5,5,3
for x in range(__self__.matrix.shape[0]):
for y in range(__self__.matrix.shape[1]):
# default cycle and sampling window = 24,5
stripped = peakstrip(__self__.matrix[x,y],cycles,window,savgol,order)
__self__.background[x,y] = stripped
counter = counter + 1
progressbar.updatebar(counter)
__self__.sum_bg = peakstrip(__self__.sum,cycles,window,savgol,order)
elif bgstrip == "Polynomial":
try: ndegree_global, ndegree_single, r_fact, = __self__.config["bg_settings"]
except: ndegree_global, ndegree_single, r_fact = 6,0,2
matrix_flatten = __self__.matrix.reshape(-1,__self__.matrix.shape[-1])
y_cont, attempt = np.zeros([__self__.matrix.shape[2]]), 0
progressbar.update_text(
"Preparing to fit continuum.".format(attempt))
while y_cont.sum()==0:
attempt += 1
y_cont = polfit_batch(
matrix_flatten,
ndegree_global=ndegree_global,
ndegree_single=ndegree_single,
r=r_fact)
progressbar.update_text(
"Fitting continuum. Trial: {}".format(attempt))
logger.warning(
"Attempt {} to fit continuum. Too slow, increasing R factor".format(
attempt))
r_fact+=1
__self__.sum_bg = y_cont[0]
progressbar.updatebar(0)
for x in range(__self__.matrix.shape[0]):
for y in range(__self__.matrix.shape[1]):
counter += 1 #ignores first continuum which is the global one
__self__.background[x][y] = y_cont[counter]
progressbar.updatebar(counter)
del y_cont
return
def create_densemap(__self__):
""" Calls getdensitymap and attributes the 2D-array output to the object """
__self__.densitymap = getdensitymap(__self__)
def save_cube(__self__):
""" Writes (pickle) the datacube object to memory, if the cube already exists, it is
replaced (updated) """
from Engine.SpecRead import output_path, cube_path
__self__.self_path = cube_path
try:
if not os.path.exists(output_path):
logger.info("Creating outputh path {0}".forma(output_path))
os.mkdir(output_path)
else: logger.debug("Output path exists")
except:
logger.warning("Could not create output folder {}".format(output_path))
pass
p_output = open(cube_path,'wb')
pickle.dump(__self__,p_output)
p_output.close()
def digest_merge(__self__,bar=None):
if bar != None:
time.sleep(0.5)
bar.update_text("6/11 Calculating MPS...")
bar.updatebar(6)
mps = np.zeros([__self__.matrix.shape[2]],dtype="int32")
__self__.MPS(mps)
__self__.mps = mps
if bar != None:
bar.update_text("7/11 Calculating Stacksum...")
bar.updatebar(7)
__self__.stacksum()
__self__.write_sum()
if bar != None:
bar.update_text("8/11 Creating densemap...")
bar.updatebar(8)
__self__.create_densemap()
if bar != None:
bar.update_text("9/11 Calculating continuum...")
bar.updatebar(9)
__self__.strip_background(
recalculating=True,
bgstrip=__self__.config["bgstrip"],
progressbar=bar)
if bar != None:
bar.progress["maximum"] = 11
bar.update_text("10/11 Fitting F & N...")
bar.updatebar(10)
__self__.fit_fano_and_noise()
if bar != None:
bar.update_text("11/11 Writing to disk...")
bar.updatebar(11)
# Mosaic saves the cube. There are few operations left
#__self__.save_cube()
def compile_cube(__self__):
""" Iterate over the spectra dataset, reading each spectrum file saving it to the
proper xy matrix indexes and calculating the background contribution as well.
This method saves all derived spectra, writes summation mca to disk and calculates
the density map. """
if "h5" in __self__.datatypes:
__self__.progressbar = Busy(__self__.img_size,0)
pass
else:
######################
# PACK ALL MCA FILES #
######################
global iterator
iterator = 0
logger.debug("Started mca compilation")
timer = time.time()
__self__.progressbar = Busy(__self__.img_size,0)
x,y,scan = 0,0,(0,0)
if not isinstance(Constants.FILE_POOL,tuple):
build_pool(__self__.img_size)
else: pass
chunks, bite, leftovers = get_chunks(__self__.dimension)
if Constants.CPUS > 1 and bite > 4:
running_chunks = []
for chunk in range(chunks):
############################
# matrix iteration indexes #
############################
start = (chunk*bite)
end = start+bite
############################
################
# pool indexes #
################
a = (bite*__self__.dimension[1])*chunk
b = a+(bite*__self__.dimension[1])
################
pool_chunk = Constants.FILE_POOL[a:b]
t = threading.Thread(target=read_pool,
args=(start,
end,
pool_chunk,
__self__.dimension,
__self__.matrix,))
running_chunks.append(t)
logger.info("Polling chunk {}. Leftovers: {}".format(chunk,leftovers))
if leftovers > 0:
start = (__self__.dimension[0]-leftovers)
end = __self__.dimension[0]
a = (__self__.img_size - (leftovers*__self__.dimension[1]))
pool_chunk = Constants.FILE_POOL[a:]
t = threading.Thread(target=read_pool,
args=(start,
end,
pool_chunk,
__self__.dimension,
__self__.matrix,))
running_chunks.append(t)
logger.info("Polling Leftovers")
for thread in running_chunks:
thread.start()
__self__.periodic_check()
for thread in running_chunks:
thread.join()
else:
for spec in Constants.FILE_POOL:
try: specdata = getdata(spec)
except:
__self__.progressbar.destroybar()
return 1, spec
if isinstance(specdata,np.ndarray) == False:
__self__.progressbar.interrupt(specdata,5)
__self__.progressbar.destroybar()
return 1,specdata
__self__.matrix[x][y] = specdata
scan = refresh_position(scan[0],scan[1],__self__.dimension)
x,y = scan[0],scan[1]
__self__.progressbar.updatebar(iterator)
iterator += 1
logger.info("Packed spectra in {} seconds".format(time.time()-timer))
######################
logger.debug("Calculating MPS...")
__self__.progressbar.progress["maximum"] = 6
__self__.progressbar.update_text("1/6 Calculating MPS...")
__self__.progressbar.updatebar(1)
mps = np.zeros([__self__.matrix.shape[2]],dtype="int32")
datacube.MPS(__self__,mps)
__self__.mps = mps
logger.debug("Calculating summation spectrum...")
__self__.progressbar.update_text("2/6 Calculating sum spec...")
__self__.progressbar.updatebar(2)
datacube.stacksum(__self__)
#datacube.cut_zeros(__self__)
__self__.energyaxis, __self__.gain, __self__.zero = calibrate(
specsize=__self__.matrix.shape[2])
__self__.config["gain"] = __self__.gain
logger.debug("Stripping background...")
__self__.progressbar.update_text("3/6 Stripping background...")
__self__.progressbar.updatebar(3)
__self__.strip_background()
__self__.progressbar.progress["maximum"] = 6
logger.debug("Calculating sum map...")
__self__.progressbar.update_text("4/6 Calculating sum map...")
__self__.progressbar.updatebar(4)
datacube.create_densemap(__self__)
logger.debug("Writing summation mca and ANSII files...")
datacube.write_sum(__self__)
__self__.progressbar.update_text("5/6 Finding Noise and Fano...")
__self__.progressbar.updatebar(5)
datacube.fit_fano_and_noise(__self__)
logger.debug("Saving cube file to disk...")
__self__.progressbar.update_text("6/6 Writing to disk...")
__self__.progressbar.updatebar(6)
__self__.progressbar.destroybar()
del __self__.progressbar
datacube.save_cube(__self__)
logger.debug("Finished packing.")
return 0,None
def periodic_check(__self__):
__self__.check()
def check(__self__):
global iterator
__self__.progressbar.update_text("Packing spectra...")
while iterator < __self__.img_size:
__self__.progressbar.updatebar(iterator)
return 0
def cut_zeros(__self__):
""" Sliced the data cutting off the necessary lead and tail zeros.
Lead and tail are verified through the sum spectrum to avoid data loss """
lead_zeros, tail_zeros = 0,__self__.matrix.shape[2]
for i in range(__self__.sum.shape[0]):
if __self__.sum[i] < __self__.img_size:
lead_zeros = i
else: break
for i in range(1,__self__.sum.shape[0]):
if __self__.sum[-i] < __self__.img_size:
tail_zeros = __self__.matrix.shape[2]-i
else: break
print("lead",lead_zeros,"tail",tail_zeros)
__self__.energyaxis, __self__.gain, __self__.zero = calibrate(
lead=lead_zeros,tail=__self__.matrix.shape[2]-tail_zeros)
__self__.config["gain"] = __self__.gain
__self__.matrix = __self__.matrix[:,:,lead_zeros:tail_zeros]
__self__.background = __self__.background[:,:,lead_zeros:tail_zeros]
__self__.sum = __self__.sum[lead_zeros:tail_zeros]
__self__.sum_bg = __self__.sum_bg[lead_zeros:tail_zeros]
__self__.mps = __self__.mps[lead_zeros:tail_zeros]
print(len(__self__.sum),"sum")
print(len(__self__.sum_bg),"sum_bg")
print(len(__self__.mps),"mps")
print(len(__self__.energyaxis),"energy")
return lead_zeros, tail_zeros
def pack_element(__self__,image,element,line):
""" Saves elemental distribution image to datacibe object
image; a 2d-array
element; a string
line; a string """
from Engine.SpecRead import output_path, cube_path
__self__.__dict__[element+"_"+line] = image
logger.info("Packed {0} map to datacube {1}".format(element,cube_path))
def pack_hist(__self__,hist,bins,element):
""" Saves the histogram of the last calculated elemental distribution map.
This method is called by ImgMath.py while saving the maps """
from Engine.SpecRead import output_path, cube_path
histfile = open(output_path+"\\"+element+"_hist.txt",'w')
histfile.write("<<START>>\n")
histfile.write("hist\n")
for i in range(len(hist)):
histfile.write("{0}\n".format(hist[i]))
histfile.write("<<END>>")
histfile.close()
__self__.hist[element] = [hist,bins]
def unpack_element(__self__,element,line):
""" Retrieves a 2d-array elemental distribution map from the datacube.
element; a string
line; a string """
from Engine.SpecRead import output_path, cube_path
try:
unpacked = __self__.__dict__[element+"_"+line]
logger.info("Unpacked {0} map from datacube {1}".format(element,cube_path))
return unpacked
except KeyError as exception:
logger.info("Failed to unpack {}{} map from {}".format(element,line,__self__.name))
return np.zeros([__self__.dimension[0],
__self__.dimension[1]],dtype="float32")
def check_packed_elements(__self__):
""" Returns a list with all elemental distribution maps packed into the
datacube object """
packed = []
for element in Elements.ElementList:
if hasattr(__self__,element+"_a"):
if hasattr(__self__,element+"_b"):
if __self__.__dict__[element+"_a"].max() > 0:
packed.append(element+"_a")
if __self__.__dict__[element+"_b"].max() > 0:
packed.append(element+"_b")
else:
if __self__.__dict__[element+"_a"].max() > 0:
packed.append(element+"_a")
else: pass
if hasattr(__self__,"custom_a"): packed.append("custom_a")
return packed
def prepack_elements(__self__,element_list,wipe=False):
""" Allocates keys in the datacube object to store the elemental distribution maps """
for element in set(element_list):
if wipe == False:
__self__.__dict__[element+"_a"] = np.zeros([__self__.dimension[0],
__self__.dimension[1]],dtype="float32")
__self__.__dict__[element+"_b"] = np.zeros([__self__.dimension[0],
__self__.dimension[1]],dtype="float32")
__self__.ROI[element] = np.zeros([__self__.energyaxis.shape[0]],
dtype="float32")
__self__.max_counts[element+"_a"] = 0
__self__.max_counts[element+"_b"] = 0
__self__.hist[element] = [np.zeros([__self__.img_size]),np.zeros([LEVELS])]
__self__.__dict__["custom"] = np.zeros(
[__self__.dimension[0],__self__.dimension[1]],dtype="float32")
if wipe == True:
try: del __self__.__dict__[element+"_a"]
except KeyError: print("No alpha map for {}".format(element))
try: del __self__.__dict__[element+"_b"]
except KeyError: print("No beta map for {}".format(element))
if wipe == True:
__self__.max_counts = {}
__self__.hist = {}
__self__.ROI = {}
try: del __self__.__dict__["custom"]
except KeyError: pass
def wipe_maps(__self__):
element_list = [i.split("_")[0] for i in __self__.check_packed_elements()]
__self__.prepack_elements(element_list,wipe=True)
__self__.save_cube()
def replace_map(__self__,image,element):
__self__.__dict__[element] = image
__self__.hist[element] = 0
__self__.ROI[element.split("_")[0]] = np.zeros([__self__.energyaxis.shape[0]],
dtype="float32")
__self__.max_counts[element.split("_")[0]] = image.max()
__self__.save_cube()
def FN_reset():
Constants.FANO = 0.114
Constants.NOISE = 80
def FN_set(F, N):
Constants.FANO = F
Constants.NOISE = N
def converth5():
cube = datacube(["h5-temp"],Constants.CONFIG)
progressbar = Busy(5,0)
logger.debug("Calculating MPS...")
progressbar.update_text("1/5 Calculating MPS...")
progressbar.updatebar(1)
mps = np.zeros([cube.matrix.shape[2]],dtype="int32")
cube.MPS(mps)
cube.mps = mps
logger.debug("Calculating summation spectrum...")
progressbar.update_text("2/5 Calculating sum spec...")
progressbar.updatebar(2)
cube.stacksum()
cube.energyaxis, cube.gain, cube.zero = calibrate(specsize=cube.matrix.shape[2])
cube.config["gain"] = cube.gain
logger.debug("Stripping background...")
progressbar.update_text("3/5 Stripping background...")
progressbar.updatebar(3)
progressbar.progress["maximum"] = cube.img_size
cube.strip_background(progressbar=progressbar)
logger.debug("Calculating sum map...")
progressbar.update_text("4/5 Calculating sum map...")
progressbar.progress["maximum"] = 5
progressbar.updatebar(4)
cube.create_densemap()
progressbar.update_text("5/5 Finding Noise and Fano...")
progressbar.updatebar(5)
cube.fit_fano_and_noise()
progressbar.destroybar()
del progressbar
return cube
def build_pool(size):
Constants.FILE_POOL = []
spec = getfirstfile()
name=str(spec)
specfile_name = name.split("\\")[-1]
name = specfile_name.split(".")[0]
extension = specfile_name.split(".")[-1]
for i in range(len(name)):
if not name[-i-1].isdigit():
prefix = name[:-i]
index = name[-i:]
break
index = int(index)+1
Constants.FILE_POOL.append(spec)
for idx in range(index,size+index-1,1):
spec = os.path.join(Constants.SAMPLE_PATH,
str(Constants.NAME_STRUCT[0]+str(idx)+"."+Constants.NAME_STRUCT[2]))
Constants.FILE_POOL.append(spec)
def read_pool(start,end,pool,dimension,m):
""" INPUT:
- start: int; starting row
- end: int; lower boundary row
- pool: list; contains the spectra to be read
- dimension: int; row length
- m: np.array (int); spectra matrix """
global iterator
scan = (start,0)
x, y = scan[0], scan[1]
for spec in pool:
logger.debug("Coordinates: x {}, y {}. Spectra: {}".format(x,y,spec))
with lock: m[x][y] = getdata(spec)
scan = refresh_position(scan[0],scan[1],dimension)
x,y = scan[0],scan[1]
with lock: iterator += 1
def get_chunks(size):
max_chunks = Constants.CPUS*2
bites = int(((size[0]*size[1])/max_chunks)/size[1])
###################################################################
# missing lines at the end (cannot fit into more chunks or bites) #
###################################################################
leftovers = size[0]-(bites*max_chunks)
###################################################################
return max_chunks, bites, leftovers
def digest_psdinv(y,energies):
""" -- y is an array with the measured FWHM.
-- energies is an array with the corresponding energies for the corresponding
FWHM peaks
This function performs a pseudo inverse regression to equation 1 (see OSP article)
with singular value decomposition (numpy.pinv()) to find FANO and NOISE values
that satisfies the equation """
x = [(2.3548**2)*3.85*en for en in energies]
Y = np.asarray([i**2 for i in y], dtype="float32")
X = np.array([np.ones(len(x)), x], dtype="float32")
C = np.dot(Y,np.linalg.pinv(X))
return abs(C)
def digest_lstsq(y,energies):
""" -- y is an array with the measured FWHM.
-- energies is an array with the corresponding energies for the corresponding
FWHM peaks
This function performs a least-squares fitting to equation 1 (see OSP article)
to find FANO and NOISE values that satisfies it """
x = [(2.3548**2)*3.85*en for en in energies]
Y = np.asarray([i**2 for i in y], dtype="float32")
X = np.vstack([np.ones(len(x)), x]).T
C = np.linalg.lstsq(X,Y,rcond=None)[0]
return abs(C)
def FN_fit_pseudoinv(specdata,gain):
""" Finds suitable FANO and NOISE factors to the input spectrum using only
the gain and no background.
--------------------------------------------------------------------------
INPUT:
specdata; <1D-array> - spectrum to be used
gain; <float> - calibration gain (eV)
OUTPUT:
1D-tuple (F, N)
--------------------------------------------------------
The fit is performed by changing the tophat filter parameters
(window and tolerance to the variance) iteratively. This is
performed to automate the function to any input spectrum, since
different parameters work differently for each spectrum profile.
The output is the averaged value, unless a reasonable value
(between 0.040 and 0.240) is found for the FANO factor. """
F, N = 0, 0
i, x = 0, 80
avg_F, avg_N = 0,0
data = savgol_filter(specdata,5,3)
w, r = 9,2
v = (w/2)+1
while i < x:
F, N = FN_iter(data,gain,v,w,r)
if 0.114-(2*0.0114) <= F <= 0.114+(2*0.0114):
logger.warning("Fano and Noise matched: F:{} N:{}".format(F,N))
return F,N
avg_F += F
avg_N += N
r += 1
if r > 12:
r = 4
w += 2
v = int(w/2)+1
if w >= 13:
w = 2
v = int(w/2)+1
i += 1
N = avg_N/i
F = avg_F/i
return F, N
def FN_iter(data,gain,v,w,r):
""" Verifies if the peak detected is greater than the
variance. r is a tolerance factor that multiplies the variance coef. """
th, delt, pks = tophat(data,v,w)
widths = []
energies = []
for i in pks:
if th[i]>r*delt[i]:
try: lw, up, width = fwhm(data,i,r)
except: break
widths.append(width*gain*1000)
energies.append(gain*i*1000)
N, F = digest_psdinv(widths,energies)
return F, N**.5
def tophat(y,v,w):
""" Applies a tophat filter to a 1D-array following the recipe
given reference below:
[1] Van Grieken, R.E.; Markowicz, A.A. Handbook of X-ray spectrometry,
Marcel Dekker, Inc., 2002.
--------------------------------------------------------------------
INPUT:
y; 1D-array
v; side window width (int)
w; central window width (int)
OUTPUT:
new_y; filtered pectrum (1D-array)
delta; variance (1D-array)
peaks; identified peaks indexes (1D-list)
"""
def hk_(k,v,w):
if -v-(w/2) <= k < -w/2: return -1/(2*v)
elif -w/2 <= k <= w/2: return 1/w
elif w/2 < k <= v+(w/2): return -1/(2*v)
else: return 0
new_y = np.zeros([y.shape[0]])
delta = np.zeros([y.shape[0]])
peaks = []
for i in range(y.shape[0]-(int(v+w/2))):
y_star = 0
y_delta = 0
for k in range(int(-v-w/2),int(v+w/2)):
hk = hk_(k,v,w)
y_star += hk*y[i+k]
y_delta += abs((hk**2)*y[i+k])
new_y[i] = y_star
delta[i] = y_delta**.5
for j in range(1,y.shape[0]-1):
if new_y[j-1] <= new_y[j] and new_y[j] > new_y[j+1]:
peaks.append(j)
return new_y, delta, peaks
def fwhm(data,i,win):
""" Finds the indexes where half the peaks' height is
found for peak located at index i
INPUT:
data; 1D-array
i; peak index
win; tolearnce window
OUTPUT:
lw; lower index
up; upper index
up-lw; peak width """
half = data[i]/2
lw, up = 0, 0
for j in range(i-win,i):
if data[j]>=half:
lw = j-1
break
j=0
for j in range(i,i+win):
if data[j]<=half:
up = j-1
break
if lw >= up: return 0,0,0
return lw, up, up-lw
def FN_fit_gaus(spec,spec_bg,e_axis,gain):
""" Finds a series of relevant peaks between 2100 and 30000 eV and fits them
with a gaussian fuction to obtain the global Fano and Noise factors.
----------------------------------------------------------------------------
INPUT:
spec; <1D-array> - global spectrum to be used in the peak sampling and fit
spec_bg; <1D-array> - continuum of the above spectrum
e_axis; <1D-array> - calibrated energy axis in KeV
gain; <float> - calibration gain in KeV
OUTPUT:
Fano; <float> - Fano factor of the input spectrum
Noise; <float> - Noise factor of the input spectrum """
from scipy.optimize import curve_fit
import copy
####################################
Fano = 0.114
Noise = 80
gain = gain*1000
energyaxis = e_axis*1000
zero = energyaxis[0]
y_array, y_cont = spec, spec_bg
####################################
#########################
# perform deconvolution #
#########################
w = Constants.PEAK_TOLERANCE
v = int(w/2)+1
r = 2
peaks = []
y_conv, y_delta, pre_peaks = tophat(y_array,v,w)
for i in pre_peaks:
if y_conv[i-1]<=y_conv[i]>=y_conv[i+1]:
if y_conv[i]>(r*y_delta[i]) and \
y_conv[i]>y_cont[i]*Constants.CONTINUUM_SUPPRESSION:
peaks.append(i)
#########################
######################################
# filters peaks and exclude outliers #
######################################
filtered_peaks, E_peaks, y_peaks = [],[],[]
for i in peaks:
if 2100<=energyaxis[i]<=30000:
E_peaks.append(energyaxis[i])
filtered_peaks.append(i)
y_peaks.append(y_array[i])
peaks = np.asarray(filtered_peaks)
E_peaks = np.asarray(E_peaks)
y_peaks = np.asarray(y_peaks)
######################################
guess = y_peaks*np.sqrt(
((Noise/2.3548)**2)+(3.85*Noise*E_peaks))*np.sqrt(2*np.pi)/gain
guess = np.insert(guess,0,[Noise,Fano],axis=0)
uncertainty = np.sqrt(y_array).clip(1)
try:
popt_gaus, pcov_gaus = curve_fit(lambda x,Noise,Fano,*A: gaus(
energyaxis,E_peaks,gain,Noise,Fano,
*A) + y_cont,
energyaxis,
y_array,
p0=guess,
sigma=uncertainty,
maxfev=Constants.FIT_CYCLES)
except:
logger.warning("Failed to fit fano and noise. Continuiung with default")
return Fano, Noise
#print(popt_gaus.shape)
#print("NOISE",popt_gaus[0])
#print("FANO",popt_gaus[1])
#y_gaus = np.asarray(
# [gaus(energyaxis,E_peaks[i],gain,*popt_gaus[[0,1,2+i]]) \
# for i in range(E_peaks.size)])+ y_cont
#for i in y_gaus:
# plt.semilogy(energyaxis,i,label="Fit")
#plt.semilogy(energyaxis,y_array,label="Data")
#plt.semilogy(energyaxis,y_cont,label="Continuum")
#plt.legend()
#plt.show()
return popt_gaus[1], popt_gaus[0]
def refresh_position(a,b,length):
""" Returns the next pixel position """
imagex = length[0]
imagey = length[1]
imagedimension = imagex*imagey
currentx = a
currenty = b