forked from vasole/pymca
-
Notifications
You must be signed in to change notification settings - Fork 1
/
McaAdvancedFit.py
2825 lines (2617 loc) · 116 KB
/
McaAdvancedFit.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
#/*##########################################################################
#
# The PyMca X-Ray Fluorescence Toolkit
#
# Copyright (c) 2004-2023 European Synchrotron Radiation Facility
#
# This file is part of the PyMca X-ray Fluorescence Toolkit developed at
# the ESRF.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
#############################################################################*/
__author__ = "V. Armando Sole - ESRF"
__contact__ = "[email protected]"
__license__ = "MIT"
__copyright__ = "European Synchrotron Radiation Facility, Grenoble, France"
import sys
import os
import numpy
import time
import copy
import logging
import tempfile
import shutil
import traceback
from PyMca5.PyMcaGui import PyMcaQt as qt
if hasattr(qt, "QString"):
QString = qt.QString
else:
QString = qt.safe_str
QTVERSION = qt.qVersion()
from PyMca5.PyMcaGui.pymca import QPyMcaMatplotlibSave1D
MATPLOTLIB = True
#force understanding of utf-8 encoding
#otherways it cannot generate svg output
try:
import encodings.utf_8
except Exception:
#not a big problem
pass
from PyMca5.PyMcaPhysics.xrf import ClassMcaTheory
FISX = ClassMcaTheory.FISX
if FISX:
FisxHelper = ClassMcaTheory.FisxHelper
from PyMca5.PyMcaGui.physics.xrf import FitParam
from PyMca5.PyMcaGui.physics.xrf import McaAdvancedTable
from PyMca5.PyMcaGui.physics.xrf import QtMcaAdvancedFitReport
from PyMca5.PyMcaGui.physics.xrf import ConcentrationsWidget
from PyMca5.PyMcaPhysics.xrf import ConcentrationsTool
from PyMca5.PyMcaGui.plotting import PlotWindow
from PyMca5.PyMcaGui.plotting import PyMca_Icons
IconDict = PyMca_Icons.IconDict
from PyMca5.PyMcaGui.physics.xrf import McaCalWidget
from PyMca5.PyMcaGui.physics.xrf import PeakIdentifier
from PyMca5.PyMcaGui.misc import SubprocessLogWidget
from PyMca5.PyMcaGui.physics.xrf import ElementsInfo
Elements = ElementsInfo.Elements
#import McaROIWidget
from PyMca5.PyMcaGui.plotting import PyMcaPrintPreview
from PyMca5.PyMcaCore import PyMcaDirs
from PyMca5.PyMcaIO import ConfigDict
from PyMca5.PyMcaGui.misc import CalculationThread
from PyMca5.PyMcaGui.io import PyMcaFileDialogs
_logger = logging.getLogger(__name__)
_logger.debug("############################################\n"
"# McaAdvancedFit is in DEBUG mode #\n"
"############################################")
XRFMC_FLAG = False
try:
from PyMca5.PyMcaPhysics.xrf.XRFMC import XRFMCHelper
XRFMC_FLAG = True
except ImportError:
_logger.warning("Cannot import XRFMCHelper module")
if _logger.getEffectiveLevel() == logging.DEBUG:
raise
USE_BOLD_FONT = True
class McaAdvancedFit(qt.QWidget):
"""
This class inherits QWidget.
It provides all the functionality required to perform an interactive fit
and to generate a configuration file.
It is the simplest way to embed PyMca's fitting functionality into other
PyQt application.
It can be used from the interactive prompt of ipython provided ipython is
started with the -q4thread flag.
**Usage**
>>> from PyMca5 import McaAdvancedFit
>>> w = McaAdvancedFit.McaAdvancedFit()
>>> w.setData(x=x, y=y) # x is your channel array and y the counts array
>>> w.show()
"""
sigMcaAdvancedFitSignal = qt.pyqtSignal(object)
def __init__(self, parent=None, name="PyMca - McaAdvancedFit",fl=0,
sections=None, top=True, margin=11, spacing=6):
qt.QWidget.__init__(self, parent)
self.setWindowTitle(name)
self.setWindowIcon(qt.QIcon(qt.QPixmap(IconDict['gioconda16'])))
self.lastInputDir = None
self.configDialog = None
self.matplotlibDialog = None
self.mainLayout = qt.QVBoxLayout(self)
self.mainLayout.setContentsMargins(margin, margin, margin, margin)
self.mainLayout.setSpacing(0)
if sections is None:
sections=["TABLE"]
self.headerLabel = qt.QLabel(self)
self.mainLayout.addWidget(self.headerLabel)
self.headerLabel.setAlignment(qt.Qt.AlignHCenter)
font = self.font()
font.setBold(USE_BOLD_FONT)
self.headerLabel.setFont(font)
self.setHeader('Fit of XXXXXXXXXX from Channel XXXXX to XXXX')
self.top = Top(self)
self.mainLayout.addWidget(self.top)
self.sthread = None
self.elementsInfo = None
self.identifier = None
self.logWidget = None
if False and len(sections) == 1:
w = self
self.mcatable = McaAdvancedTable.McaTable(w)
self.concentrationsWidget = None
else:
self.mainTab = qt.QTabWidget(self)
self.mainLayout.addWidget(self.mainTab)
#graph
self.tabGraph = qt.QWidget()
tabGraphLayout = qt.QVBoxLayout(self.tabGraph)
tabGraphLayout.setContentsMargins(margin, margin, margin, margin)
tabGraphLayout.setSpacing(spacing)
#self.graphToolbar = qt.QHBox(self.tabGraph)
self.graphWindow = McaGraphWindow(self.tabGraph)
tabGraphLayout.addWidget(self.graphWindow)
self.graph = self.graphWindow
self.graph.setGraphXLabel('Channel')
self.graph.setGraphYLabel('Counts')
self.mainTab.addTab(self.tabGraph, "GRAPH")
self.graphWindow.sigPlotSignal.connect(self._mcaGraphSignalSlot)
#table
self.tabMca = qt.QWidget()
tabMcaLayout = qt.QVBoxLayout(self.tabMca)
tabMcaLayout.setContentsMargins(margin, margin, margin, margin)
tabMcaLayout.setSpacing(spacing)
w = self.tabMca
line = Line(w, info="TABLE")
tabMcaLayout.addWidget(line)
line.setToolTip("DoubleClick toggles floating window mode")
self.mcatable = McaAdvancedTable.McaTable(w)
tabMcaLayout.addWidget(self.mcatable)
self.mainTab.addTab(w,"TABLE")
line.sigLineDoubleClickEvent.connect(self._tabReparent)
self.mcatable.sigClosed.connect(self._mcatableClose)
#concentrations
self.tabConcentrations = qt.QWidget()
tabConcentrationsLayout = qt.QVBoxLayout(self.tabConcentrations)
tabConcentrationsLayout.setContentsMargins(margin,
margin,
margin,
margin)
tabConcentrationsLayout.setSpacing(0)
line2 = Line(self.tabConcentrations, info="CONCENTRATIONS")
self.concentrationsWidget = ConcentrationsWidget.Concentrations(self.tabConcentrations)
tabConcentrationsLayout.addWidget(line2)
tabConcentrationsLayout.addWidget(self.concentrationsWidget)
self.mainTab.addTab(self.tabConcentrations,"CONCENTRATIONS")
line2.setToolTip("DoubleClick toggles floating window mode")
self.concentrationsWidget.sigConcentrationsSignal.connect( \
self.__configureFromConcentrations)
line2.sigLineDoubleClickEvent.connect(self._tabReparent)
self.concentrationsWidget.sigClosed.connect( \
self._concentrationsWidgetClose)
#diagnostics
self.tabDiagnostics = qt.QWidget()
tabDiagnosticsLayout = qt.QVBoxLayout(self.tabDiagnostics)
tabDiagnosticsLayout.setContentsMargins(margin, margin, margin, margin)
tabDiagnosticsLayout.setSpacing(spacing)
w = self.tabDiagnostics
self.diagnosticsWidget = qt.QTextEdit(w)
self.diagnosticsWidget.setReadOnly(1)
tabDiagnosticsLayout.addWidget(self.diagnosticsWidget)
self.mainTab.addTab(w, "DIAGNOSTICS")
self.mainTab.currentChanged[int].connect(self._tabChanged)
self._energyAxis = False
self.__printmenu = qt.QMenu()
self.__printmenu.addAction(QString("Calibrate"), self._calibrate)
self.__printmenu.addAction(QString("Identify Peaks"),self.__peakIdentifier)
self.__printmenu.addAction(QString("Elements Info"), self.__elementsInfo)
self.outdir = None
self.configDir = None
self.__lastreport= None
self.browser = None
self.info = {}
self.__fitdone = 0
self._concentrationsDict = None
self._concentrationsInfo = None
self._xrfmcMatrixSpectra = None
#self.graph.hide()
#self.guiconfig = FitParam.Fitparam()
"""
self.specfitGUI.guiconfig.MCACheckBox.setEnabled(0)
palette = self.specfitGUI.guiconfig.MCACheckBox.palette()
palette.setDisabled(palette.active())
"""
##############
hbox=qt.QWidget(self)
self.bottom = hbox
hboxLayout = qt.QHBoxLayout(hbox)
hboxLayout.setContentsMargins(0, 0, 0, 0)
hboxLayout.setSpacing(4)
if not top:
self.configureButton = qt.QPushButton(hbox)
self.configureButton.setText("Configure")
self.toolsButton = qt.QPushButton(hbox)
self.toolsButton.setText("Tools")
hboxLayout.addWidget(self.configureButton)
hboxLayout.addWidget(self.toolsButton)
hboxLayout.addWidget(qt.HorizontalSpacer(hbox))
self.fitButton = qt.QPushButton(hbox)
hboxLayout.addWidget(self.fitButton)
#font = self.fitButton.font()
#font.setBold(True)
#self.fitButton.setFont(font)
self.fitButton.setText("Fit Again!")
self.printButton = qt.QPushButton(hbox)
hboxLayout.addWidget(self.printButton)
self.printButton.setText("Print")
self.htmlReportButton = qt.QPushButton(hbox)
hboxLayout.addWidget(self.htmlReportButton)
self.htmlReportButton.setText("HTML Report")
self.matrixSpectrumButton = qt.QPushButton(hbox)
hboxLayout.addWidget(self.matrixSpectrumButton)
self.matrixSpectrumButton.setText("Matrix Spectrum")
self.matrixXRFMCSpectrumButton = qt.QPushButton(hbox)
self.matrixXRFMCSpectrumButton.setText("MC Matrix Spectrum")
hboxLayout.addWidget(self.matrixXRFMCSpectrumButton)
self.matrixXRFMCSpectrumButton.hide()
self.peaksSpectrumButton = qt.QPushButton(hbox)
hboxLayout.addWidget(self.peaksSpectrumButton)
self.peaksSpectrumButton.setText("Peaks Spectrum")
self.matrixSpectrumButton.setCheckable(1)
self.peaksSpectrumButton.setCheckable(1)
hboxLayout.addWidget(qt.HorizontalSpacer(hbox))
self.dismissButton = qt.QPushButton(hbox)
hboxLayout.addWidget(self.dismissButton)
self.dismissButton.setText("Dismiss")
hboxLayout.addWidget(qt.HorizontalSpacer(hbox))
self.mainLayout.addWidget(hbox)
self.printButton.setToolTip('Print Active Tab')
self.htmlReportButton.setToolTip('Generate Browser Compatible Output\nin Chosen Directory')
self.matrixSpectrumButton.setToolTip('Toggle Matrix Spectrum Calculation On/Off')
self.matrixXRFMCSpectrumButton.setToolTip('Calculate Matrix Spectrum Using Monte Carlo')
self.peaksSpectrumButton.setToolTip('Toggle Individual Peaks Spectrum Calculation On/Off')
self.mcafit = ClassMcaTheory.McaTheory()
self.fitButton.clicked.connect(self.fit)
self.printButton.clicked.connect(self.printActiveTab)
self.htmlReportButton.clicked.connect(self.htmlReport)
self.matrixSpectrumButton.clicked.connect(self.__toggleMatrixSpectrum)
if self.matrixXRFMCSpectrumButton is not None:
self.matrixXRFMCSpectrumButton.clicked.connect(self.xrfmcSpectrum)
self.peaksSpectrumButton.clicked.connect(self.__togglePeaksSpectrum)
self.dismissButton.clicked.connect(self.dismiss)
self.top.configureButton.clicked.connect(self.__configure)
self.top.printButton.clicked.connect(self.__printps)
if top:
self.top.sigTopSignal.connect(self.__updatefromtop)
else:
self.top.hide()
self.configureButton.clicked.connect(self.__configure)
self.toolsButton.clicked.connect(self.__printps)
self._updateTop()
def __mainTabPatch(self, index):
return self.mainTabLabels[index]
def _fitdone(self):
if self.__fitdone:
return True
else:
return False
def refreshWidgets(self):
"""
This method just forces the graphical widgets to get updated.
It should be called if somehow you have modified the fit and/
or concentrations parameters by other means than the graphical
interface.
"""
self.__configure(justupdate=True)
def configure(self, ddict=None):
"""
This methods configures the fitting parameters and updates the
graphical interface.
It returns the current configuration.
"""
if ddict is None:
return self.mcafit.configure(ddict)
#configure and get the new configuration
newConfig = self.mcafit.configure(ddict)
#refresh the interface
self.refreshWidgets()
#return the current configuration
return newConfig
def __configure(self, justupdate=False):
config = {}
config.update(self.mcafit.config)
#config['fit']['use_limit'] = 1
if not justupdate:
if self.configDialog is None:
if self.__fitdone:
dialog = FitParam.FitParamDialog(modal=1,
fl=0,
initdir=self.configDir,
fitresult=self.dict['result'])
else:
dialog = FitParam.FitParamDialog(modal=1,
fl=0,
initdir=self.configDir,
fitresult=None)
dialog.fitparam.peakTable.sigFitPeakSelect.connect( \
self.__elementclicked)
self.configDialog = dialog
else:
dialog = self.configDialog
if self.__fitdone:
dialog.setFitResult(self.dict['result'])
else:
dialog.setFitResult(None)
if self.__fitdone:
# a direct fit without loading the file can lead to errors
lastTime = self.mcafit.getLastTime()
self.info["time"] = lastTime
dialog.setParameters(self.mcafit.getStartingConfiguration())
dialog.setData(self.mcafit.xdata * 1.0,
self.mcafit.ydata * 1.0,
info=copy.deepcopy(self.info))
#dialog.fitparam.regionCheck.setDisabled(True)
#dialog.fitparam.minSpin.setDisabled(True)
#dialog.fitparam.maxSpin.setDisabled(True)
ret = dialog.exec()
if dialog.initDir is not None:
self.configDir = 1 * dialog.initDir
else:
self.configDir = None
if ret != qt.QDialog.Accepted:
dialog.close()
#del dialog
return
try:
#this may crash in qt 2.3.0
npar = dialog.getParameters()
except Exception:
msg = qt.QMessageBox(self)
msg.setIcon(qt.QMessageBox.Critical)
msg.setText("Error occured getting parameters:")
msg.setInformativeText(str(sys.exc_info()[1]))
msg.setDetailedText(traceback.format_exc())
msg.exec()
return
config.update(npar)
dialog.close()
#del dialog
self.graph.clearMarkers()
self.graph.replot()
self.__fitdone = False
self._concentrationsDict = None
self._concentrationsInfo = None
self._xrfmcMatrixSpectra = None
if self.concentrationsWidget is not None:
self.concentrationsWidget.concentrationsTable.setRowCount(0)
if self.mcatable is not None:
self.mcatable.setRowCount(0)
self.diagnosticsWidget.clear()
#make sure newly or redefined materials are added to the
#materials in the fit configuration
for material in Elements.Material.keys():
self.mcafit.config['materials'][material] =copy.deepcopy(Elements.Material[material])
hideButton = True
if 'xrfmc' in config:
programFile = config['xrfmc'].get('program', None)
if programFile is not None:
if os.path.exists(programFile):
if os.path.isfile(config['xrfmc']['program']):
hideButton = False
if hideButton:
self.matrixXRFMCSpectrumButton.hide()
else:
self.matrixXRFMCSpectrumButton.show()
if _logger.getEffectiveLevel() == logging.DEBUG:
self.mcafit.configure(config)
else:
try:
thread = CalculationThread.CalculationThread( \
calculation_method = self.mcafit.configure,
calculation_vars = config,
expand_vars=False,
expand_kw=False)
thread.start()
CalculationThread.waitingMessageDialog(thread,
message = "Configuring, please wait",
parent=self,
modal=True,
update_callback=None,
frameless=True)
threadResult = thread.getResult()
if type(threadResult) == type((1,)):
if len(threadResult):
if threadResult[0] == "Exception":
raise Exception(threadResult[1], threadResult[2])
except Exception:
msg = qt.QMessageBox(self)
msg.setIcon(qt.QMessageBox.Critical)
msg.setWindowTitle("Configuration error")
msg.setText("Error configuring fit:")
msg.setInformativeText(str(sys.exc_info()[1]))
msg.setDetailedText(traceback.format_exc())
msg.exec()
return
#update graph
delcurves = []
curveList = self.graph.getAllCurves(just_legend=True)
for key in curveList:
if key not in ["Data"]:
delcurves.append(key)
for key in delcurves:
self.graph.removeCurve(key)
if not justupdate:
self.plot()
self._updateTop()
if self.concentrationsWidget is not None:
try:
app = qt.QApplication.instance()
app.processEvents()
self.concentrationsWidget.setParameters(config['concentrations'], signal=False)
except Exception:
if str(self.mainTab.tabText(self.mainTab.currentIndex())).upper() == "CONCENTRATIONS":
self.mainTab.setCurrentIndex(0)
def __configureFromConcentrations(self,ddict):
_logger.debug("McaAdvancedFit.__configureFromConcentrations %s", ddict)
config = self.concentrationsWidget.getParameters()
self.mcafit.config['concentrations'].update(config)
if ddict['event'] == 'updated':
if 'concentrations' in ddict:
self._concentrationsDict = ddict['concentrations']
self._concentrationsInfo = None
self._xrfmcMatrixSpectra = None
def __elementclicked(self,ddict):
ddict['event'] = 'McaAdvancedFitElementClicked'
self.__showElementMarker(ddict)
self.__anasignal(ddict)
def __showElementMarker(self, dict):
self.graph.clearMarkers()
ele = dict['current']
items = []
if not (ele in dict):
self.graph.replot()
return
for rays in dict[ele]:
for transition in Elements.Element[ele][rays +" xrays"]:
items.append([transition,
Elements.Element[ele][transition]['energy'],
Elements.Element[ele][transition]['rate']])
config = self.mcafit.configure()
xdata = self.mcafit.xdata * 1.0
xmin = xdata[0]
xmax = xdata[-1]
ymin,ymax = self.graph.getGraphYLimits()
calib = [config['detector'] ['zero'], config['detector'] ['gain']]
for transition,energy,rate in items:
marker = ""
x = (energy - calib[0])/calib[1]
if (x < xmin) or (x > xmax):continue
if not self._energyAxis:
if abs(calib[1]) > 0.0000001:
marker=self.graph.insertXMarker(x,
legend=transition,
text=transition,
color='orange',
replot=False)
else:
marker=self.graph.insertXMarker(energy,
legend=transition,
text=transition,
color='orange',
replot=False)
self.graph.replot()
def _updateTop(self):
config = {}
if 0:
config.update(self.mcafit.config['fit'])
else:
config['stripflag'] = self.mcafit.config['fit'].get('stripflag',0)
config['fitfunction'] = self.mcafit.config['fit'].get('fitfunction',0)
config['hypermetflag'] = self.mcafit.config['fit'].get('hypermetflag',1)
config['sumflag'] = self.mcafit.config['fit'].get('sumflag',0)
config['escapeflag'] = self.mcafit.config['fit'].get('escapeflag',0)
config['continuum'] = self.mcafit.config['fit'].get('continuum',0)
self.top.setParameters(config)
def __updatefromtop(self,ndict):
config = self.mcafit.configure()
for key in ndict.keys():
if key not in ['stripflag', 'hypermetflag',
'sumflag', 'escapeflag',
'fitfunction', 'continuum']:
_logger.debug("UNKNOWN key %s", key)
config['fit'][key] = ndict[key]
self.__fitdone = False
#erase table
if self.mcatable is not None:
self.mcatable.setRowCount(0)
#erase concentrations
if self.concentrationsWidget is not None:
self.concentrationsWidget.concentrationsTable.setRowCount(0)
#erase diagnostics
self.diagnosticsWidget.clear()
#update graph
curveList = self.graph.getAllCurves(just_legend=True)
delcurves = []
for key in curveList:
if key not in ["Data"]:
delcurves.append(key)
for key in delcurves:
self.graph.removeCurve(key)
self.plot()
if _logger.getEffectiveLevel() == logging.DEBUG:
self.mcafit.configure(config)
else:
try:
thread = CalculationThread.CalculationThread( \
calculation_method = self.mcafit.configure,
calculation_vars = config,
expand_vars=False,
expand_kw=False)
thread.start()
CalculationThread.waitingMessageDialog(thread,
message = "Configuring, please wait",
parent=self,
modal=True,
update_callback=None)
threadResult = thread.getResult()
if type(threadResult) == type((1,)):
if len(threadResult):
if threadResult[0] == "Exception":
raise Exception(threadResult[1], threadResult[2])
except Exception:
msg = qt.QMessageBox(self)
msg.setIcon(qt.QMessageBox.Critical)
msg.setWindowTitle("Configuration error")
msg.setText("Error configuring fit:")
msg.setInformativeText(str(sys.exc_info()[1]))
msg.setDetailedText(traceback.format_exc())
msg.exec()
return
def _tabChanged(self, value):
_logger.debug("_tabChanged(self, value) called")
if str(self.mainTab.tabText(self.mainTab.currentIndex())).upper() == "CONCENTRATIONS":
self.printButton.setEnabled(False)
w = self.concentrationsWidget
if w.parent() is None:
if w.isHidden():
w.show()
w.raise_()
self.printButton.setEnabled(True)
#do not calculate again. It should be already updated
return
try:
self.concentrations()
self.printButton.setEnabled(True)
except Exception:
if _logger.getEffectiveLevel() == logging.DEBUG:
raise
#print "try to set"
self.printButton.setEnabled(False)
msg = qt.QMessageBox(self)
msg.setIcon(qt.QMessageBox.Critical)
msg.setText("Concentrations error: %s" % sys.exc_info()[1])
msg.exec()
self.mainTab.setCurrentIndex(0)
elif str(self.mainTab.tabText(self.mainTab.currentIndex())).upper() == "TABLE":
self.printButton.setEnabled(True)
w = self.mcatable
if w.parent() is None:
if w.isHidden():
w.show()
w.raise_()
elif str(self.mainTab.tabText(self.mainTab.currentIndex())).upper() == "DIAGNOSTICS":
self.printButton.setEnabled(False)
self.diagnostics()
else:
self.printButton.setEnabled(True)
def _concentrationsWidgetClose(self, ddict):
ddict['info'] = "CONCENTRATIONS"
self._tabReparent(ddict)
def _mcatableClose(self, ddict):
ddict['info'] = "TABLE"
self._tabReparent(ddict)
def _tabReparent(self, ddict):
if ddict['info'] == "CONCENTRATIONS":
w = self.concentrationsWidget
parent = self.tabConcentrations
elif ddict['info'] == "TABLE":
w = self.mcatable
parent = self.tabMca
if w.parent() is not None:
parent.layout().removeWidget(w)
w.setParent(None)
w.show()
else:
w.setParent(parent)
parent.layout().addWidget(w)
def _calibrate(self):
config = self.mcafit.configure()
x = self.mcafit.xdata0[:]
y = self.mcafit.ydata0[:]
legend = "Calibration for " + qt.safe_str(self.headerLabel.text())
ndict={}
ndict[legend] = {'A':config['detector']['zero'],
'B':config['detector']['gain'],
'C': 0.0}
caldialog = McaCalWidget.McaCalWidget(legend=legend,
x=x,
y=y,
modal=1,
caldict=ndict,
fl=0)
caldialog.calpar.orderbox.setEnabled(0)
caldialog.calpar.CText.setEnabled(0)
caldialog.calpar.savebox.setEnabled(0)
ret = caldialog.exec()
if ret == qt.QDialog.Accepted:
ddict = caldialog.getDict()
config['detector']['zero'] = ddict[legend]['A']
config['detector']['gain'] = ddict[legend]['B']
#self.mcafit.configure(config)
self.mcafit.config['detector']['zero'] = 1. * ddict[legend]['A']
self.mcafit.config['detector']['gain'] = 1. * ddict[legend]['B']
self.__fitdone = 0
self.plot()
del caldialog
def __elementsInfo(self):
if self.elementsInfo is None:
self.elementsInfo = ElementsInfo.ElementsInfo(None, "Elements Info")
if self.elementsInfo.isHidden():
self.elementsInfo.show()
self.elementsInfo.raise_()
def __peakIdentifier(self, energy = None):
if energy is None:
energy = 5.9
if self.identifier is None:
self.identifier=PeakIdentifier.PeakIdentifier(energy=energy,
threshold=0.040,
useviewer=1)
self.identifier.mySlot()
self.identifier.setEnergy(energy)
if self.identifier.isHidden():
self.identifier.show()
self.identifier.raise_()
def printActiveTab(self):
txt = str(self.mainTab.tabText(self.mainTab.currentIndex())).upper()
if txt == "GRAPH":
self.graphWindow.printGraph()
elif txt == "TABLE":
self.printps(True)
elif txt == "CONCENTRATIONS":
self.printConcentrations(True)
elif txt == "DIAGNOSTICS":
pass
else:
pass
def diagnostics(self):
self.diagnosticsWidget.clear()
if not self.__fitdone:
msg = qt.QMessageBox(self)
msg.setIcon(qt.QMessageBox.Critical)
text = "Sorry. You need to perform a fit first.\n"
msg.setText(text)
msg.exec()
if str(self.mainTab.tabText(self.mainTab.currentIndex())).upper() == "DIAGNOSTICS":
self.mainTab.setCurrentIndex(0)
return
fitresult = self.dict
x = fitresult['result']['xdata']
energy = fitresult['result']['energy']
y = fitresult['result']['ydata']
yfit = fitresult['result']['yfit']
param = fitresult['result']['fittedpar']
i = fitresult['result']['parameters'].index('Noise')
noise= param[i] * param[i]
i = fitresult['result']['parameters'].index('Fano')
fano = param[i] * 2.3548*2.3548*0.00385
meanfwhm = numpy.sqrt(noise + 0.5 * (energy[0] + energy[-1]) * fano)
i = fitresult['result']['parameters'].index('Gain')
gain = fitresult['result']['fittedpar'][i]
meanfwhm = int(meanfwhm/gain) + 1
missed = self.mcafit.detectMissingPeaks(y, yfit, meanfwhm)
hcolor = 'white'
finalcolor = 'white'
text=""
if len(missed):
text+="<br><b><font color=blue size=4>Possibly Missing or Underestimated Peaks</font></b>"
text+="<nobr><table><tr>"
text+='<td align="right" bgcolor="%s"><b>' % hcolor
text+='Channel'
text+="</b></td>"
text+='<td align="right" bgcolor="%s"><b>' % hcolor
text+='Energy'
text+="</b></td>"
text+="</tr>"
for peak in missed:
text+="<tr>"
text+='<td align="right" bgcolor="%s">' % finalcolor
text+="<b><font size=3>%d </font></b>" % x[int(peak)]
text+="</td>"
text+='<td align="right" bgcolor="%s">' % finalcolor
text+="<b><font size=3>%.3f </font></b>" % energy[int(peak)]
text+="</td>"
text+="</tr>"
text+="<tr>"
text+="</table>"
missed = self.mcafit.detectMissingPeaks(yfit, y, meanfwhm)
if len(missed):
text+="<br><b><font color=blue size=4>Possibly Overestimated Peaks</font></b>"
text+="<nobr><table><tr>"
text+='<td align="right" bgcolor="%s"><b>' % hcolor
text+='Channel'
text+="</b></td>"
text+='<td align="right" bgcolor="%s"><b>' % hcolor
text+='Energy'
text+="</b></td>"
text+="</tr>"
for peak in missed:
text+="<tr>"
text+='<td align="right" bgcolor="%s">' % finalcolor
text+="<b><font size=3>%d </font></b>" % x[int(peak)]
text+="</td>"
text+='<td align="right" bgcolor="%s">' % finalcolor
text+="<b><font size=3>%.3f </font></b>" % energy[int(peak)]
text+="</td>"
text+="</tr>"
text+="<tr>"
text+="</table>"
# check for secondary effects
useMatrix = False
for attenuator in fitresult['result']['config']['attenuators']:
if attenuator.upper() == "MATRIX":
if fitresult['result']['config']['attenuators'][attenuator][0]:
useMatrix = True
break
if useMatrix and FISX and \
(not fitresult['result']['config']['concentrations']['usemultilayersecondary']):
doIt = False
corrections = None
if 'fisx' in fitresult['result']['config']:
corrections = fitresult['result']['config']['fisx'].get('corrections',
None)
if corrections is None:
# calculate the corrections
corrections = FisxHelper.getFisxCorrectionFactorsFromFitConfiguration( \
fitresult['result']['config'],
elementsFromMatrix=False)
# to put it into config is misleading because it was not made at
# configuration time.
if 'fisx' not in fitresult['result']['config']:
fitresult['result']['config']['fisx'] = {}
fitresult['result']['config']['fisx']['secondary'] = 2
fitresult['result']['config']['fisx']['corrections'] = corrections
tertiary = False
bodyText = ""
for element in corrections:
for family in corrections[element]:
correction = corrections[element][family]['correction_factor']
if correction[-1] > 1.02:
doIt = True
bodyText += "<tr>"
bodyText += '<td align="right" bgcolor="%s">' % finalcolor
bodyText += "<b><font size=3>%s </font></b>" % \
(element + " " + family)
bodyText += "</td>"
bodyText += '<td align="right" bgcolor="%s">' % finalcolor
bodyText += "<b><font size=3>"
bodyText += "%.3f</font></b>" % correction[1]
bodyText += " "
if len(corrections[element][family]['correction_factor']) > 2:
tertiary = True
bodyText+= "</td>"
bodyText += '<td align="right" bgcolor="%s">' % finalcolor
bodyText += "<b><font size=3>"
bodyText+= "%.3f </font></b>" % correction[2]
bodyText += " "
bodyText+= "</td>"
bodyText+= "</tr>"
if doIt:
bodyText += "<tr>"
bodyText += "</table>"
warningText = "<br><b><font color=blue size=4>"
warningText += "Neglected higher order excitation correction</font></b>"
warningText += "<nobr><table>"
warningText += "<tr>"
warningText += '<td align="right" bgcolor="%s"><b>' % hcolor
warningText += 'Peak Family'
warningText += "</b></td>"
warningText += '<td align="right" bgcolor="%s"><b>' % hcolor
warningText += (' ' * 10)
warningText += '2nd Order'
warningText += "</b></td>"
if tertiary:
warningText += '<td align="right" bgcolor="%s"><b>' % hcolor
warningText += (' ' * 10)
warningText += '3rd Order'
warningText += "</b></td>"
warningText += "</tr>"
text += (warningText + bodyText)
self.diagnosticsWidget.insertHtml(text)
def concentrations(self):
self._concentrationsDict = None
self._concentrationsInfo = None
self._xrfmcMatrixSpectra = None
if not self.__fitdone:
msg = qt.QMessageBox(self)
msg.setIcon(qt.QMessageBox.Critical)
text = "Sorry, You need to perform a fit first.\n"
msg.setText(text)
msg.exec()
if str(self.mainTab.tabText(self.mainTab.currentIndex())).upper() == "CONCENTRATIONS":
self.mainTab.setCurrentIndex(0)
return
fitresult = self.dict
if False:
#from the fit, it misses any update from concentrations
config = fitresult['result']['config']
else:
#from current, it should be up to date
config = self.mcafit.configure()
#tool = ConcentrationsWidget.Concentrations(fl=qt.Qt.WDestructiveClose)
if self.concentrationsWidget is None:
self.concentrationsWidget = ConcentrationsWidget.Concentrations()
self.concentrationsWidget.sigConcentrationsSignal.connect( \
self.__configureFromConcentrations)
self.concentrationsWidget.setTimeFactor(self.mcafit.getLastTime(), signal=False)
tool = self.concentrationsWidget
#this forces update
tool.getParameters()
ddict = {}
ddict.update(config['concentrations'])
tool.setParameters(ddict, signal=False)
try:
ddict, info = tool.processFitResult(config=ddict, fitresult=fitresult,
elementsfrommatrix=False,
fluorates=self.mcafit._fluoRates,
addinfo=True)
except Exception:
if _logger.getEffectiveLevel() == logging.DEBUG:
raise
msg = qt.QMessageBox(self)
msg.setIcon(qt.QMessageBox.Critical)
msg.setText("Error processing fit result: %s" % (sys.exc_info()[1]))
msg.exec()
if str(self.mainTab.tabText(self.mainTab.currentIndex())).upper() == 'CONCENTRATIONS':
self.mainTab.setCurrentIndex(0)
return
self._concentrationsDict = ddict
self._concentrationsInfo = info
tool.show()
tool.setFocus()
tool.raise_()
def __toggleMatrixSpectrum(self):
if self.matrixSpectrumButton.isChecked():
self.matrixSpectrum()
self.plot()
else:
if "Matrix" in self.graph.getAllCurves(just_legend=True):
self.graph.removeCurve("Matrix", replot=False)
self.plot()
def __togglePeaksSpectrum(self):
if self.peaksSpectrumButton.isChecked():
self.peaksSpectrum()
else:
self.__clearPeaksSpectrum()
self.plot()
def __clearPeaksSpectrum(self):
delcurves = []
for key in self.graph.getAllCurves(just_legend=True):
if key not in ["Data", "Fit", "Continuum", "Pile-up", "Matrix"]:
if key.startswith('MC Matrix'):
if self._xrfmcMatrixSpectra in [None, []]:
delcurves.append(key)
else:
delcurves.append(key)
for key in delcurves:
self.graph.removeCurve(key, replot=False)
def matrixSpectrum(self):
if not self.__fitdone:
msg = qt.QMessageBox(self)
msg.setIcon(qt.QMessageBox.Critical)
text = "Sorry, for the time being you need to perform a fit first\n"
text+= "in order to calculate the spectrum derived from the matrix.\n"
text+= "Background and detector parameters are taken from last fit"
msg.setText(text)
msg.exec()
return
#fitresult = self.dict['result']
fitresult = self.dict
config = self.mcafit.configure()
self._concentrationsInfo = None
tool = ConcentrationsTool.ConcentrationsTool()
#this forces update
tool.configure()
ddict = {}
ddict.update(config['concentrations'])
tool.configure(ddict)
if _logger.getEffectiveLevel() == logging.DEBUG:
ddict, info = tool.processFitResult(fitresult=fitresult,
elementsfrommatrix=True,
addinfo=True)
else:
try:
thread = CalculationThread.CalculationThread(
calculation_method=tool.processFitResult,
calculation_kw={'fitresult': fitresult,