-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathgammaGUI-qt
3396 lines (3071 loc) · 128 KB
/
gammaGUI-qt
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/env python3
"""
Usage:
gammaGUI-qt <file_name> [options]
gammaGUI-qt [options]
options:
-o open a blank window
--fwhm_at_0=<fwhm0> fwhm value at x=0
--min_snr=<msnr> min SNR
--ref_x=<xref> x reference for fwhm_ref
--ref_fwhm=<ref_fwhm> fwhm ref corresponding to x_ref
--cebr detector type (cerium bromide)
--labr detector type (lanthanum bromide)
--hpge detector type (HPGe)
Reads a csv file with the following column format: counts | energy_EUNITS,
where EUNITS can be for examle keV or MeV. It can also read a CSV file with a
single column named "counts". No need to have channels because
they are automatically infered starting from channel = 0.
If detector type is defined e.g. --cebr then the code guesses the x_ref and
fwhm_ref based on the known detector characteristics.
Note that the detector type input parameters must be changed depending on the
particular electronic gain used. The examples here are for our specific
detector configurations.
"""
import docopt
import random
import pandas as pd
import numpy as np
import datetime
from scipy import ndimage
import re
import sys
import time
from copy import deepcopy
from PyQt5.QtWidgets import *
from PyQt5.uic import loadUi
from PyQt5 import QtCore, QtWidgets, QtGui, QtWebEngineWidgets
from PyQt5.QtCore import Qt, QUrl
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.widgets import SpanSelector, RectangleSelector
from nasagamma import param_handle
from nasagamma import peakfit as pf
from nasagamma import peaksearch as ps
from nasagamma import spectrum as sp
from nasagamma import advanced_fit as adv
from nasagamma import tlist
from nasagamma import energy_calibration as ecal
from nasagamma import efficiency
from nasagamma import resolution
from nasagamma import file_reader
from nasagamma import read_parquet_api
from nasagamma import helper_api
from nasagamma import parse_NIST
from nasagamma import diagnostics
from nasagamma import apicalc
from nasagamma import decay_exponential as decay
import pkg_resources
import plotly.graph_objs as go
import plotly.io as pio
import tempfile
class Dialog_from_UI(QDialog):
"""Create a dialog from a UI file with a given window title."""
def __init__(self):
super().__init__()
self.define_ui_vars()
ui_file = pkg_resources.resource_filename("nasagamma", self.ui_name)
loadUi(ui_file, self)
self.setWindowTitle(self.window_title)
class WindowMainInfo(Dialog_from_UI):
def define_ui_vars(self):
self.setWindowFlag(Qt.WindowMinimizeButtonHint, True)
self.setWindowFlag(Qt.WindowMaximizeButtonHint, True)
self.ui_name = "win_info_main.ui"
self.window_title = "Spectrum info"
class WindowCust(Dialog_from_UI):
def define_ui_vars(self):
self.setWindowFlag(Qt.WindowMinimizeButtonHint, True)
self.setWindowFlag(Qt.WindowMaximizeButtonHint, True)
self.ui_name = "win_customize.ui"
self.window_title = "Customize plot"
class WindowCustInfo(Dialog_from_UI):
def define_ui_vars(self):
self.ui_name = "win_info_customize.ui"
self.window_title = "Customize info"
class WindowAddSubtract(Dialog_from_UI):
def define_ui_vars(self):
# self.setWindowFlags(Qt.WindowStaysOnTopHint)
self.setWindowFlag(Qt.WindowMinimizeButtonHint, True)
self.setWindowFlag(Qt.WindowMaximizeButtonHint, True)
self.ui_name = "win_add_subtract.ui"
self.window_title = "Add/Subtract Spectra"
class WindowAddSubtractInfo(Dialog_from_UI):
def define_ui_vars(self):
# self.setWindowFlags(Qt.WindowStaysOnTopHint)
self.setWindowFlag(Qt.WindowMinimizeButtonHint, True)
self.setWindowFlag(Qt.WindowMaximizeButtonHint, True)
self.ui_name = "win_info_add_subt.ui"
self.window_title = "Add/Subtract Info"
class WindowPeakFinder(Dialog_from_UI):
def define_ui_vars(self):
self.setWindowFlag(Qt.WindowMinimizeButtonHint, True)
self.setWindowFlag(Qt.WindowMaximizeButtonHint, True)
self.ui_name = "win_peak_find.ui"
self.window_title = "Peak finder"
class WindowPeakFinderInfo(Dialog_from_UI):
def define_ui_vars(self):
self.ui_name = "win_info_peak_find.ui"
self.window_title = "Peak finder info"
class WindowCal(Dialog_from_UI):
def define_ui_vars(self):
self.ui_name = "win_erg_cal.ui"
self.window_title = "Energy calibration"
class WindowCalInfo(Dialog_from_UI):
def define_ui_vars(self):
self.ui_name = "win_info_ecal.ui"
self.window_title = "Energy calibration information"
class WindowCalEqns(Dialog_from_UI):
def define_ui_vars(self):
self.ui_name = "win_erg_cal_eqns.ui"
self.window_title = "Energy calibration: set equations"
class WindowCalAddPoint(Dialog_from_UI):
def define_ui_vars(self):
self.ui_name = "win_erg_cal_add_point.ui"
self.window_title = "Energy calibration: add point"
class WindowEff(Dialog_from_UI):
def define_ui_vars(self):
self.ui_name = "win_eff.ui"
self.window_title = "Efficiency calibration"
class WindowEffInfo(Dialog_from_UI):
def define_ui_vars(self):
self.ui_name = "win_info_eff.ui"
self.window_title = "Efficiency calibration information"
class WindowInfoFile(Dialog_from_UI):
def define_ui_vars(self):
self.ui_name = "win_info_file.ui"
self.window_title = "File information"
class WindowIsotID(Dialog_from_UI):
def define_ui_vars(self):
self.setWindowFlag(Qt.WindowMinimizeButtonHint, True)
self.setWindowFlag(Qt.WindowMaximizeButtonHint, True)
self.ui_name = "win_isot_id.ui"
self.window_title = "Isotope ID"
class WindowIsotIDInfo(Dialog_from_UI):
def define_ui_vars(self):
self.ui_name = "win_info_isot_id.ui"
self.window_title = "Isotope ID info"
class WindowAdvFit(Dialog_from_UI):
def define_ui_vars(self):
self.ui_name = "win_adv_fit.ui"
self.window_title = "Advanced Fitting"
class WindowAPImca(Dialog_from_UI):
def define_ui_vars(self):
self.ui_name = "win_api_mca.ui"
self.window_title = "API MCA"
class WindowAPI3D(Dialog_from_UI):
def define_ui_vars(self):
self.ui_name = "win_api_3D.ui"
self.window_title = "API 3D plot"
class WindowAPIfilters(Dialog_from_UI):
def define_ui_vars(self):
self.ui_name = "win_api_filters.ui"
self.window_title = "Apply API filters"
class WindowPNGInfo(Dialog_from_UI):
def define_ui_vars(self):
self.ui_name = "win_info_png.ui"
self.window_title = "PNG information"
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, data):
super(TableModel, self).__init__()
self._data = data
self.highlighted_rows = []
def data(self, index, role):
row = index.row()
column = index.column()
if role == Qt.DisplayRole:
value = self._data.iloc[row, column]
return str(value)
elif role == Qt.BackgroundRole and row in self.highlighted_rows:
return QtGui.QColor(Qt.yellow) # Set the desired background color
# return QtGui.QColor(91, 115, 200)
def set_highlighted_rows(self, rows):
self.highlighted_rows = rows
self.dataChanged.emit(
self.index(0, 0), self.index(self.rowCount(0), self.columnCount(0))
)
def rowCount(self, index):
return self._data.shape[0]
def columnCount(self, index):
return self._data.shape[1]
def headerData(self, section, orientation, role):
# section is the index of the column/row.
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
return str(self._data.columns[section])
if orientation == Qt.Vertical:
return str(self._data.index[section])
def sort(self, Ncol, order):
"""Sort table by given column number."""
try:
self.layoutAboutToBeChanged.emit()
self._data = self._data.sort_values(
self._data.columns[Ncol], ascending=not order
)
self.layoutChanged.emit()
except Exception as e:
print(e)
class NasaGammaApp(QMainWindow):
def __init__(self, commands):
print(super())
super().__init__()
ui_file = pkg_resources.resource_filename("nasagamma", "qt_gui.ui")
loadUi(ui_file, self)
self.setWindowFlag(Qt.WindowMaximizeButtonHint, True)
# self.setMinimumSize(1800, 900)
# pixmap = QPixmap("figs/nasa-logo.jpg")
# self.label_nasa.setPixmap(pixmap)
# self.resize(600, 600)
self.setWindowTitle("NASA-gamma")
self.setWindowIcon(QtGui.QIcon("figs/NASA-gamma-logo.png"))
self.scale = "linear"
self.snr_state = "off"
self.pushButton_scale.clicked.connect(self.update_scale)
self.pushButton_scale.setStyleSheet("background-color : lightgoldenrodyellow")
self.button_add_peak.setStyleSheet("background-color : silver")
self.button_add_peak.setCheckable(True)
self.button_add_peak.clicked.connect(self.add_peak)
# push buttons
self.enable_fitButtons(False)
self.bg = "poly1"
self.e_units = None
self.pushButton_poly1.setStyleSheet("background-color : lightgreen")
self.pushButton_poly1.setCheckable(True)
self.pushButton_poly1.setChecked(True)
self.pushButton_poly2.setStyleSheet("background-color : lightgreen")
self.pushButton_poly2.setCheckable(True)
self.pushButton_poly3.setStyleSheet("background-color : lightgreen")
self.pushButton_poly3.setCheckable(True)
self.pushButton_poly4.setStyleSheet("background-color : lightgreen")
self.pushButton_poly4.setCheckable(True)
self.pushButton_poly5.setStyleSheet("background-color : lightgreen")
self.pushButton_poly5.setCheckable(True)
self.pushButton_exp.setStyleSheet("background-color : lightgreen")
self.pushButton_exp.setCheckable(True)
self.btn_grp = QButtonGroup()
self.btn_grp.setExclusive(True)
self.btn_grp.addButton(self.pushButton_poly1)
self.btn_grp.addButton(self.pushButton_poly2)
self.btn_grp.addButton(self.pushButton_poly3)
self.btn_grp.addButton(self.pushButton_poly4)
self.btn_grp.addButton(self.pushButton_poly5)
self.btn_grp.addButton(self.pushButton_exp)
self.btn_grp.buttonClicked.connect(self.update_poly)
# info button (main window)
self.w_info_main = WindowMainInfo()
self.button_info_main.clicked.connect(self.main_info_activate)
# reset main figure
self.button_reset.clicked.connect(self.reset_spectrum)
# Gaussian or skewed Gaussian?
self.sk_gauss = False
self.pushButton_gauss.setStyleSheet("background-color : silver")
self.pushButton_gauss.setCheckable(True)
self.pushButton_gauss.setChecked(True)
self.pushButton_gauss2.setStyleSheet("background-color : silver")
self.pushButton_gauss2.setCheckable(True)
self.btn_grp_gauss = QButtonGroup()
self.btn_grp_gauss.setExclusive(True)
self.btn_grp_gauss.addButton(self.pushButton_gauss)
self.btn_grp_gauss.addButton(self.pushButton_gauss2)
self.btn_grp_gauss.buttonClicked.connect(self.update_gauss)
self.button_remove_cal.setStyleSheet("background-color : lightcoral")
# customize
self.w_cust = WindowCust()
self.button_customize.setStyleSheet("background-color : lightsteelblue")
self.button_customize.clicked.connect(self.new_window_custom)
self.w_cust_info = WindowCustInfo()
self.w_cust.button_info.clicked.connect(self.customize_info_activate)
self.w_cust.button_apply_lab.clicked.connect(self.try_cust_labels)
self.w_cust.button_apply_smooth.clicked.connect(self.try_cust_smooth)
self.w_cust.button_apply_CR.clicked.connect(self.try_cust_countRate)
self.w_cust.button_apply_shift.clicked.connect(self.try_cust_shift)
# add/subtract spectra
self.button_add_subtract.clicked.connect(self.activate_window_add_subtract)
self.w_add_sub = WindowAddSubtract()
self.w_add_sub.button_load1.clicked.connect(self.load_file1)
self.w_add_sub.button_load2.clicked.connect(self.load_file2)
self.w_add_sub.button_plot.clicked.connect(self.add_sub_plot)
self.w_add_sub_info = WindowAddSubtractInfo()
self.w_add_sub.button_info.clicked.connect(self.add_sub_info_activate)
# navigation toolbars
self.toolbars = []
for tb in [
self.main_plot,
self.cal_plot,
self.efficiency_plot,
self.resolution_plot,
self.api_plot,
self.diag_plot00,
self.plot_dt_png,
]:
tmp = NavigationToolbar(tb.canvas, self)
tmp.setVisible(False)
tmp.setStyleSheet("font-size: 24px; background-color : wheat")
self.addToolBar(tmp)
self.toolbars.append(tmp)
self.toolbars[0].setVisible(True)
self.tabWidget.currentChanged.connect(self.switch_toolbar)
self.tabWidget.setStyleSheet("background-color : whitesmoke")
# menu bar
self.saveFitReport.triggered.connect(self.saveReport)
self.openFile.triggered.connect(self.load_spe_file)
self.saveSpect.triggered.connect(self.save_spect)
self.saveIDpeaks.triggered.connect(self.save_ID_peaks)
self.info_file.triggered.connect(self.try_display_info_file)
self.clearSpectrum.triggered.connect(self.clear_spectrum)
self.initialize_main_figure()
self.reset_main_figure()
self.reset_spect_params()
# remove ticks
self.remove_ticks_fit()
self.list_xrange = []
self.commands = commands
self.search = 0 # initialize dummy search object
# peak fitting
get_input = param_handle.get_spect_search(self.commands)
if get_input is not None:
(
self.spect,
self.search,
self.ref_x,
self.fwhm_at_0,
self.ref_fwhm,
) = get_input
self.e_units = self.spect.e_units
self.fileName = self.commands["<file_name>"]
self.create_graph(fit=True, reset=True)
try:
self.min_snr = float(self.commands["--min_snr"])
except:
print("Opening a blank GUI")
self.button_remove_cal.clicked.connect(self.remove_cal)
# peak search range
self.x0 = None
self.x1 = None
# advanced fitting
# TODO
self.parea = None
self.w_adv_fit = WindowAdvFit()
self.button_adv_fit.clicked.connect(self.open_adv_fit)
self.w_adv_fit.button_perform_fit.clicked.connect(self.calculate_peak_area)
## energy calibration
self.mean_vals = [0]
self.e_vals = [0]
self.e_sigs = [0]
self.pred_erg = 0
self.mean_vals_not_fit = []
self.e_vals_not_fit = []
self.selected_rows_ecal = []
self.cal_e_units = None
self.df_ecal = None
self.df_ecal_not_fit = None
self.df_ecal_fit = None
self.flag_check_e_units = 0
self.flag_e_legend = 0
self.ecal_eqn = None
self.w_info_cal = WindowCalInfo()
self.button_info_cal.clicked.connect(self.cal_info_activate)
# push butons
self.button_add_cal.setStyleSheet("background-color : lightblue")
self.button_origin.setStyleSheet("background-color : lightgoldenrodyellow")
self.button_apply_cal.setStyleSheet("background-color : sandybrown")
self.button_reset_cal.setStyleSheet("background-color : lightcoral")
self.button_cal1.setStyleSheet("background-color : lightgreen")
self.button_cal2.setStyleSheet("background-color : lightgreen")
self.button_cal3.setStyleSheet("background-color : lightgreen")
self.button_cal_eqns.setStyleSheet("background-color : silver")
self.button_origin.clicked.connect(self.set_origin)
self.button_remove_selected.clicked.connect(self.ecal_remove_selected)
self.button_cal1.setCheckable(True)
self.button_cal2.setCheckable(True)
self.button_cal3.setCheckable(True)
self.btn_grp2 = QButtonGroup()
self.btn_grp2.setExclusive(True)
self.btn_grp2.addButton(self.button_cal1)
self.btn_grp2.addButton(self.button_cal2)
self.btn_grp2.addButton(self.button_cal3)
self.btn_grp2.buttonClicked.connect(self.update_cal)
self.n = 1
self.reset_cal_figure()
# energy textbox
# self.button_add_cal.clicked.connect(self.add_cal)
self.button_add_cal.clicked.connect(self.new_window_cal)
# reset calibration
self.button_reset_cal.clicked.connect(self.reset_cal)
# apply calibration
self.button_apply_cal.clicked.connect(self.apply_cal)
# set calibration equation
self.button_cal_eqns.clicked.connect(self.new_window_cal_eqns)
# Add calibration point
self.button_cal_add_point.clicked.connect(self.new_window_cal_add_point)
## Resolution
# push butons
self.button_fwhm1.setStyleSheet("background-color : lightblue")
self.button_fwhm2.setStyleSheet("background-color : lightblue")
self.button_add_fwhm.setStyleSheet("background-color : khaki")
self.button_origin_fwhm.setStyleSheet("background-color : lightgoldenrodyellow")
self.button_reset_fwhm.setStyleSheet("background-color : lightcoral")
self.button_extrapolate.setStyleSheet("background-color : lightgreen")
self.button_fwhm1.setCheckable(True)
self.button_fwhm2.setCheckable(True)
self.button_extrapolate.setCheckable(True)
self.btn_grp3 = QButtonGroup()
self.btn_grp3.setExclusive(True)
self.btn_grp3.addButton(self.button_fwhm1)
self.btn_grp3.addButton(self.button_fwhm2)
self.btn_grp3.buttonClicked.connect(self.update_fwhm_figure)
self.reset_fwhm_figure()
self.fit_lst = []
self.button_add_fwhm.clicked.connect(self.add_fwhm)
self.button_origin_fwhm.clicked.connect(self.set_origin_fwhm)
self.button_reset_fwhm.clicked.connect(self.reset_fwhm)
self.button_extrapolate.clicked.connect(self.extrapolate_fwhm)
self.fwhm_x = [0]
self.fwhm = [0]
## Efficiency
self.eff_vals = []
self.selected_rows_eff = []
self.eff_scale = "log"
self.df_eff = None
# push butons
self.w_info_eff = WindowEffInfo()
self.button_info_eff.clicked.connect(self.eff_info_activate)
self.button_yscale_eff.setStyleSheet("background-color : lightgoldenrodyellow")
self.button_yscale_eff.clicked.connect(self.eff_yscale)
self.button_reset_eff.setStyleSheet("background-color : lightcoral")
self.button_reset_eff.clicked.connect(self.reset_eff_all)
self.button_fit1_eff.setStyleSheet("background-color : lightgreen")
self.button_fit1_eff.clicked.connect(self.eff_fit1)
self.button_fit2_eff.setStyleSheet("background-color : lightgreen")
self.button_fit2_eff.clicked.connect(self.eff_fit2)
self.button_add_eff.setStyleSheet("background-color : sandybrown")
self.button_add_eff.clicked.connect(self.new_window_eff)
self.button_remove_selected_eff.clicked.connect(self.eff_remove_selected)
self.reset_eff_figure()
## Diagnostics
self.folder_path = None
self.button_cts_cr.setEnabled(False)
self.button_cts_cr_fit.setEnabled(False)
self.button_centroid_max.setEnabled(False)
self.button_combine_send.setEnabled(False)
self.button_diag_save.setEnabled(False)
self.button_load_folder.clicked.connect(self.open_folder)
self.button_fit_diag.clicked.connect(
lambda: self.try_fit_peaks_diagnostics(integral=False)
)
self.button_integral_diag.clicked.connect(
lambda: self.try_fit_peaks_diagnostics(integral=True)
)
self.button_diag_clear.clicked.connect(self.initialize_plots_diagnostics)
self.button_cts_cr.clicked.connect(self.change_cts_cr_diag)
self.button_cts_cr_fit.clicked.connect(self.change_cts_cr_fit_diag)
self.button_centroid_max.clicked.connect(self.change_centroid_max_diag)
self.button_combine_send.clicked.connect(self.combine_and_send_to_spect)
self.button_diag_save.clicked.connect(self.save_multiple_spectra)
## API
self.api_spect_scale = "linear"
self.api_xy_scale = "linear"
self.api_yscale.clicked.connect(self.api_spect_yscale)
self.api_button_logxy.setCheckable(True)
self.api_button_logxy.clicked.connect(self.api_xylog)
self.api_vmax_txt.returnPressed.connect(self.api_on_returnXY)
self.api_send_to_spect.clicked.connect(self.send_to_spect_api)
self.api_load_file.clicked.connect(self.activate_load_api_file)
self.api_reset.clicked.connect(self.reset_button_api)
self.api_button_filters.clicked.connect(self.api_window_filters)
# API 3D
self.button_api_3D.clicked.connect(self.open_api_3D)
# self.button_api_plot3D.clicked.connect(self.create_plot_api3D)
# API MCA
self.w_api_mca = WindowAPImca()
self.button_api_mca.clicked.connect(self.open_api_mca)
self.w_api_mca.button_apply_all.clicked.connect(self.activate_api_mca)
self.w_api_mca.button_apply_select.clicked.connect(self.activate_api_mca_select)
self.w_api_mca.button_reset.clicked.connect(self.reset_mca_plots)
self.w_api_mca.button_send_to_spect.clicked.connect(self.send_to_spect_mca)
# self.w_adv_fit.button_perform_fit.clicked.connect(self.calculate_peak_area)
## Find peaks
self.button_find_peaks.setStyleSheet("background-color : mediumaquamarine")
self.button_find_peaks.clicked.connect(self.activate_peak_finder)
self.w_peak_find = WindowPeakFinder()
# self.check_peak_find_groups()
self.w_peak_find.button_kernel_apply.clicked.connect(self.peakFind_kernel_apply)
self.w_peak_find.radioButton_hpge.clicked.connect(self.peakFind_check_hpge)
self.w_peak_find.radioButton_labr.clicked.connect(self.peakFind_check_labr)
self.w_peak_find.radioButton_nai.clicked.connect(self.peakFind_check_nai)
self.w_peak_find.radioButton_plastic.clicked.connect(self.peakFind_check_plastic)
self.w_peak_find_info = WindowPeakFinderInfo()
self.w_peak_find.button_info.clicked.connect(self.peakFind_info_activate)
## Isotope ID
self.df_isotID_selected = pd.DataFrame()
self.df_isotID = []
self.isotID_vlines = []
self.button_identify_peaks.setStyleSheet("background-color : navajowhite")
self.button_identify_peaks.clicked.connect(self.activate_isotope_id)
self.w_isot_id = WindowIsotID()
self.w_isot_id.isotID_button_apply.setStyleSheet("background-color : lightblue")
self.w_isot_id.isotID_button_clear.setStyleSheet("background-color : lightcoral")
self.w_isot_id.isotID_button_apply.clicked.connect(self.isotID_apply)
self.w_isot_id.isotID_button_clear.clicked.connect(self.isotID_clear)
self.w_isot_id.button_remove_vlines.setStyleSheet("background-color : lightcoral")
self.w_isot_id.button_plot_vlines.clicked.connect(self.isotID_plot_vlines)
self.w_isot_id.button_remove_vlines.clicked.connect(self.isotID_remove_vlines)
self.w_isot_id.edit_element_search.returnPressed.connect(self.isotID_textSearch)
self.w_isotID_info = WindowIsotIDInfo()
self.w_isot_id.button_info.clicked.connect(self.isotID_info_activate)
## PNG
self.w_info_png = WindowPNGInfo()
self.button_info_png.clicked.connect(self.png_info_activate)
self.png_spect_scale = "linear"
self.button_yscale_png.clicked.connect(self.png_spect_yscale)
# self.pushButton_keep_png.setCheckable(True)
self.button_loadFile_png.clicked.connect(self.load_file_png)
self.button_reset_png.clicked.connect(self.reset_png)
self.pushButton_apply_tbins_png.clicked.connect(self.change_tbins_png)
self.pushButton_apply_ebins_png.clicked.connect(self.change_ebins_png)
self.pushButton_apply_t_png.clicked.connect(self.apply_trange_png)
self.pushButton_apply_e_png.clicked.connect(self.apply_erange_png)
self.pushButton_apply_dieaway_png.clicked.connect(self.apply_die_away)
self.pushButton_apply_fit_png.clicked.connect(self.apply_die_away_fit)
self.button_send_to_spec_png.clicked.connect(self.send_to_spect_png)
self.initialize_plots_png()
def main_info_activate(self):
self.w_info_main.activateWindow()
self.w_info_main.show()
def switch_toolbar(self):
current = self.tabWidget.currentIndex()
for i, tb in enumerate(self.toolbars):
tb.setVisible(i == current)
def create_graph(self, fit=True, reset=True):
# txt = f"Xrange (optional) [{self.e_units}]:"
# self.w_peak_find.label_units.setText(txt)
if reset:
self.reset_main_figure()
self.remove_ticks_fit()
self.reset_span()
if fit:
self.search.plot_peaks(
yscale=self.scale, snrs=self.snr_state, ax=self.ax_main
)
self.span_select()
else:
self.spect.plot(ax=self.ax_main, scale=self.scale)
self.ax_main.set_yscale(self.scale)
self.fig.canvas.draw_idle()
def initialize_main_figure(self):
self.fig = self.main_plot.canvas.figure # spectrum
self.fig_fit = self.fit_plot.canvas.figure # residual
self.fig.clear()
self.fig_fit.clear()
self.fig.set_constrained_layout(True)
self.fig_fit.set_constrained_layout(True)
gs = self.fig_fit.add_gridspec(2, 1, height_ratios=[0.3, 1.5])
self.fig.patch.set_alpha(0)
# axes
self.ax_main = self.fig.add_subplot()
self.ax_res = self.fig_fit.add_subplot(gs[0, 0])
self.ax_fit = self.fig_fit.add_subplot(gs[1, 0])
self.fig.canvas.draw_idle()
self.fig_fit.canvas.draw_idle()
def reset_spect_params(self):
self.spect = 0
self.search = 0
self.fit = 0
self.span = None
def reset_main_figure(self):
# clear axes
# self.ax_main.clear()
# self.ax_res.clear()
# self.ax_fit.clear()
if self.button_add_peak.isChecked():
self.fig.canvas.mpl_disconnect(self.cid)
self.button_add_peak.setChecked(False)
self.initialize_main_figure()
self.fig.canvas.draw_idle()
self.fig_fit.canvas.draw_idle()
def clear_spectrum(self):
self.reset_spect_params()
self.reset_main_figure()
self.remove_ticks_fit()
def remove_ticks_fit(self):
self.ax_fit.set_xticks([])
self.ax_fit.set_yticks([])
self.ax_res.set_xticks([])
self.ax_res.set_yticks([])
def reset_span(self):
if self.span is not None:
self.span.set_active(False)
self.span.set_visible(False)
def update_scale(self):
if self.scale == "log":
self.ax_main.set_yscale("linear")
self.scale = "linear"
elif self.scale == "linear":
self.ax_main.set_yscale("log")
self.scale = "log"
self.fig.canvas.draw_idle()
def add_peak(self):
if self.button_add_peak.isChecked():
print("Waiting to add a new peak...")
self.cid = self.fig.canvas.mpl_connect("button_press_event", self.onclick)
if self.span is not None:
self.span.set_active(False)
else:
self.fig.canvas.mpl_disconnect(self.cid)
def onclick(self, event):
xnew = event.xdata
if self.spect.energies is not None:
xnew = np.where(self.spect.energies >= xnew)[0][0]
else:
xnew = np.where(self.spect.channels >= xnew)[0][0]
print(xnew)
# if no search object initialized, initialize a dummy one
if self.search == 0:
self.search = ps.PeakSearch(self.spect, 420, 3, min_snr=1e6, method="scipy")
self.span_select()
x_idx = np.searchsorted(self.search.peaks_idx, xnew)
self.search.peaks_idx = np.insert(self.search.peaks_idx, x_idx, xnew)
fwhm_guess_new = self.search.fwhm(xnew)
self.search.fwhm_guess = np.insert(self.search.fwhm_guess, x_idx, fwhm_guess_new)
if self.spect.energies is not None:
self.ax_main.axvline(
x=self.spect.energies[xnew], color="red", linestyle="--", alpha=0.2
)
else:
self.ax_main.axvline(
x=self.spect.channels[xnew], color="red", linestyle="--", alpha=0.2
)
self.fig.canvas.draw_idle()
self.fig.canvas.mpl_disconnect(self.cid)
self.button_add_peak.setChecked(False)
self.span.set_active(True)
## Advanced fitting
## TODO
def open_adv_fit(self):
self.w_adv_fit.activateWindow()
self.parea = adv.PeakAreaLinearBkg(
spectrum=self.spect, x1=self.fit.xrange[0], x2=self.fit.xrange[1]
)
self.w_adv_fit.show()
self.reset_plot_adv_fit()
self.plot_adv_fit(bool_area=False)
def reset_plot_adv_fit(self):
self.fig_adv_fit = self.w_adv_fit.plot_adv_fit.canvas.figure
self.fig_adv_fit.clear()
self.fig_adv_fit.set_constrained_layout(True)
self.fig_adv_fit.patch.set_alpha(0)
self.ax_area = self.fig_adv_fit.add_subplot()
def plot_adv_fit(self, bool_area=False):
self.parea.plot(ax=self.ax_area, areas=bool_area)
self.fig_adv_fit.canvas.draw_idle()
def calculate_peak_area(self):
x1 = self.w_adv_fit.edit_x1.text()
x2 = self.w_adv_fit.edit_x2.text()
if self.isevaluable(x1) and self.isevaluable(x2) and self.parea is not None:
peak_range = [eval(x1), eval(x2)]
self.parea.calculate_peak_area(prange=peak_range)
self.reset_plot_area()
self.plot_area(bool_area=True)
## Customize plots
def customize_info_activate(self):
self.w_cust_info.activateWindow()
self.w_cust_info.show()
def new_window_custom(self):
self.w_cust.activateWindow()
self.w_cust.show()
# self.w_cust.accepted.connect(self.try_customize_plot)
def try_cust_labels(self):
try:
self.cust_labels()
except Exception as e:
print("Invalid label/constant values")
print("An unknown error occurred:", str(e))
def try_cust_smooth(self):
# try:
self.cust_smooth()
# except:
# print("Invalid smoothing/rebinning values")
def try_cust_countRate(self):
try:
self.cust_countRate()
except Exception as e:
print("Invalid count rate values")
print("An unknown error occurred:", str(e))
def try_cust_shift(self):
try:
self.cust_shift()
except Exception as e:
print("Invalid gain shift values")
print("An unknown error occurred:", str(e))
def cust_labels(self):
description = self.w_cust.descript_txt.text()
xlabel = self.w_cust.x_label_txt.text()
ylabel = self.w_cust.y_label_txt.text()
legend = self.w_cust.legend_txt.text().split(",")
yconst = self.w_cust.yconst_txt.text()
xconst = self.w_cust.xconst_txt.text()
xunits = self.w_cust.xunits_txt.text()
if description != "":
self.spect.description = description
if xlabel != "":
self.ax_main.set_xlabel(xlabel)
self.spect.x_units = xlabel
self.fig.canvas.draw_idle()
if ylabel != "":
self.ax_main.set_ylabel(ylabel)
self.spect.y_label = ylabel
self.fig.canvas.draw_idle()
if legend != [""]:
legend = [x.strip() for x in legend]
self.ax_main.legend(self.ax_main.get_legend_handles_labels()[0], legend)
self.spect.label = legend[-1]
self.fig.canvas.draw_idle()
if yconst != "":
self.spect.counts = self.spect.counts * eval(yconst)
self.create_graph(fit=False, reset=True)
self.search = 0
if xconst != "":
if self.spect.e_units is None:
new_x = self.spect.channels * eval(xconst)
self.e_units = f"Channels * {xconst}"
self.spect = sp.Spectrum(
counts=self.spect.counts, energies=new_x, e_units=self.e_units
)
else:
new_x = self.spect.energies * eval(xconst)
self.spect = sp.Spectrum(
counts=self.spect.counts, energies=new_x, e_units=self.e_units
)
self.create_graph(fit=False, reset=True)
self.search = 0
if xunits != "":
self.e_units = xunits
self.spect.e_units = xunits
self.spect.x_units = f"Energy ({self.e_units})"
self.create_graph(fit=False, reset=True)
self.search = 0
def cust_smooth(self):
rebin = self.w_cust.rebin_txt.text()
moving_avg = self.w_cust.smooth_txt.text()
if rebin != "":
nbins = eval(rebin)
self.spect.rebin(by=nbins)
self.create_graph(fit=False, reset=True)
self.search = 0
if moving_avg != "":
n = int(eval(moving_avg))
self.spect.smooth(num=n)
self.create_graph(fit=False, reset=True)
self.search = 0
def cust_countRate(self):
livetime = self.w_cust.livetime_txt.text()
if self.w_cust.checkBox_CR.isChecked():
yl = "CPS"
self.ax_main.set_ylabel(yl)
self.spect.y_label = yl
self.spect.cps = True
self.fig.canvas.draw_idle()
if livetime != "" and self.isevaluable(livetime) and self.spect.cps:
self.spect.livetime = eval(livetime)
self.create_graph(fit=False, reset=True)
self.search = 0
def cust_shift(self):
gain_shift = self.w_cust.shiftBy_txt.text()
if self.w_cust.checkBox_erg.isChecked():
bool_erg = True
else:
bool_erg = False
if gain_shift != "":
gs = eval(gain_shift)
self.spect.gain_shift(by=gs, energy=bool_erg)
self.create_graph(fit=False, reset=True)
self.search = 0
## Add/subtract spectra
def add_sub_info_activate(self):
self.w_add_sub_info.activateWindow()
self.w_add_sub_info.show()
def activate_window_add_subtract(self):
self.w_add_sub.activateWindow()
self.w_add_sub.show()
def load_file1(self):
try:
self.file1, self.e_units1, self.spect1 = self.open_file()
except Exception as e:
self.file1 = "**ERROR loading file**"
print("An unknown error occurred:", str(e))
disp1 = self.file1.split("/")[-1]
self.w_add_sub.filename1.setText(disp1)
def load_file2(self):
try:
self.file2, self.e_units2, self.spect2 = self.open_file()
except Exception as e:
self.file2 = "**ERROR loading file**"
print("An unknown error occurred:", str(e))
disp2 = self.file2.split("/")[-1]
self.w_add_sub.filename2.setText(disp2)
def add_sub_plot(self):
try:
if self.w_add_sub.checkBox_add.isChecked():
cts = self.spect1.counts + self.spect2.counts
elif self.w_add_sub.checkBox_sub.isChecked():
cts = self.spect1.counts - self.spect2.counts
if self.spect1.energies is not None:
x = self.spect1.energies
self.spect = sp.Spectrum(counts=cts, energies=x, e_units=self.e_units1)
self.e_units = self.e_units1
else:
self.spect = sp.Spectrum(counts=cts, e_units=self.e_units1)
self.create_graph(fit=False, reset=True)
self.search = 0
except Exception as e:
print("Could not perform operation")
print("An unknown error occurred:", str(e))
## Fitting
def which_button(self):
if self.pushButton_poly1.isChecked():
self.bg = "poly1"
elif self.pushButton_poly2.isChecked():
self.bg = "poly2"
elif self.pushButton_poly3.isChecked():
self.bg = "poly3"
elif self.pushButton_poly4.isChecked():
self.bg = "poly4"
elif self.pushButton_poly5.isChecked():
self.bg = "poly5"
elif self.pushButton_exp.isChecked():
self.bg = "exponential"
def which_button_gauss(self):
if self.pushButton_gauss2.isChecked():
self.sk_gauss = True
else:
self.sk_gauss = False
def update_poly(self):
if len(self.list_xrange) != 0:
self.which_button()
try:
self.fit = pf.PeakFit(
self.search, self.list_xrange[-1], bkg=self.bg, skew=self.sk_gauss
)
self.ax_res.clear()
self.ax_fit.clear()
self.fit.plot(
plot_type="simple",
fig=self.fig_fit,
ax_res=self.ax_res,
ax_fit=self.ax_fit,
)
data = self.get_values_table_fit()
self.activate_fit_table(data)
except Exception as e:
print("update_poly: could not perform fit")
print("An unknown error occurred:", str(e))
self.fig_fit.canvas.draw_idle()
def update_gauss(self):
if len(self.list_xrange) != 0:
self.which_button_gauss()
try:
self.fit = pf.PeakFit(
self.search, self.list_xrange[-1], bkg=self.bg, skew=self.sk_gauss