File: FitPeakSelect.py

package info (click to toggle)
pymca 5.8.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 44,392 kB
  • sloc: python: 155,456; ansic: 15,843; makefile: 116; sh: 73; xml: 55
file content (486 lines) | stat: -rw-r--r-- 17,921 bytes parent folder | download
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
#/*##########################################################################
#
# The PyMca X-Ray Fluorescence Toolkit
#
# Copyright (c) 2004-2019 European Synchrotron Radiation Facility
#
# This file is part of the PyMca X-ray Fluorescence Toolkit developed at
# the ESRF by the Software group.
#
# 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 Data Analysis"
__contact__ = "sole@esrf.fr"
__license__ = "MIT"
__copyright__ = "European Synchrotron Radiation Facility, Grenoble, France"

import copy
import logging

from . import EnergyTable
from PyMca5.PyMcaPhysics import Elements
from .QPeriodicTable import QPeriodicTable
from PyMca5.PyMcaGui import PyMcaQt as qt


_logger = logging.getLogger(__name__)

QTVERSION = qt.qVersion()
ElementList = Elements.ElementList
__revision__ = "$Revision: 1.12 $"


class PeakButton(qt.QPushButton):
    sigPeakClicked = qt.pyqtSignal(str)
    def __init__(self, parent, peak):
        qt.QPushButton.__init__(self, parent)
        #, peak)
        self.peak= peak

        font= self.font()
        font.setBold(1)
        self.setText(peak)
        self.setFlat(1)
        if QTVERSION < '4.0.0':
            self.setToggleButton(0)
        self.setSizePolicy(qt.QSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Expanding))

        self.selected= 0
        self.brush= qt.QBrush(qt.QColor(qt.Qt.yellow))

        self.clicked.connect(self.clickedSlot)

    def toggle(self):
        self.selected= not self.selected
        self.update()

    def setSelected(self, b):
        self.selected= b
        if b:
            role = self.backgroundRole()
            palette = self.palette()
            palette.setBrush( role,self.brush)
            self.setPalette(palette)
        else:
            role = self.backgroundRole()
            palette = self.palette()
            palette.setBrush( role, qt.QBrush())
            self.setPalette(palette)
        self.update()

    def isSelected(self):
        return self.selected

    def clickedSlot(self):
        self.toggle()
        self.sigPeakClicked.emit(self.peak)

    def paintEvent(self, pEvent):
        p = qt.QPainter(self)
        wr= self.rect()
        pr= qt.QRect(wr.left()+1, wr.top()+1, wr.width()-2, wr.height()-2)
        if self.selected:
            p.fillRect(pr, self.brush)
        p.setPen(qt.Qt.black)
        if hasattr(p, "drawRoundRect"):
            p.drawRoundRect(pr)
        else:
            p.drawRoundedRect(pr, 1., 1., qt.Qt.RelativeSize)
        p.end()
        qt.QPushButton.paintEvent(self, pEvent)

    def drawButton(self, p):
        wr= self.rect()
        pr= qt.QRect(wr.left()+1, wr.top()+1, wr.width()-2, wr.height()-2)
        if self.selected:
                p.fillRect(pr, self.brush)
        qt.QPushButton.drawButtonLabel(self, p)
        p.setPen(qt.Qt.black)
        p.drawRoundRect(pr)

class PeakButtonList(qt.QWidget):
    # emitted object is a list
    sigSelectionChanged = qt.pyqtSignal(object)
    def __init__(self, parent=None, name="PeakButtonList",
                 peaklist=['K','Ka','Kb','L','L1','L2','L3','M'],
                 fl=0):
        qt.QWidget.__init__(self,parent)
        self.peaklist = peaklist

        if QTVERSION < '4.0.0':
            layout= qt.QHBoxLayout(self, 0, 5)
        else:
            layout= qt.QHBoxLayout(self)
            layout.setContentsMargins(0, 0, 0, 0)
            layout.setSpacing(5)
            #, 0, 5)

        layout.addStretch(2)

        self.buttondict={}
        for key in peaklist:
            self.buttondict[key] = PeakButton(self, key)
            layout.addWidget(self.buttondict[key])
            self.buttondict[key].sigPeakClicked.connect(self.__selection)

        layout.addStretch(1)

        #Reset
        self.resetBut = qt.QPushButton(self)
        self.resetBut.setText("Reset")
        layout.addWidget(self.resetBut)
        self.resetBut.clicked.connect(self.__resetBut)

        layout.addStretch(2)

    def __resetBut(self):
        for key in self.peaklist:
            self.buttondict[key].setSelected(0)
        self.sigSelectionChanged.emit([])

    def __selection(self, peak):
        selection= []
        for key in self.peaklist:
            if self.buttondict[key].isSelected():
                selection.append(key)
        self.sigSelectionChanged.emit(selection)


    def setSelection(self, selection=[]):
        for key in self.peaklist:
            if key in selection:
                self.buttondict[key].setSelected(1)
            else:
                self.buttondict[key].setSelected(0)

    def setDisabled(self,selection=[]):
        for key in self.peaklist:
            if key in selection:
                self.buttondict[key].setEnabled(0)
            else:
                self.buttondict[key].setEnabled(1)


class FitPeakSelect(qt.QWidget):
    sigFitPeakSelect = qt.pyqtSignal(object)
    def __init__(self, parent=None, name="FitPeakSelect", peakdict = {}, energyTable=None):
        qt.QWidget.__init__(self,parent)

        layout=qt.QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(10)
        hbox = qt.QWidget(self)
        hboxLayout = qt.QHBoxLayout(hbox)
        hboxLayout.setContentsMargins(0, 0, 0, 0)
        hboxLayout.setSpacing(20)
        hboxLayout.addWidget(qt.HorizontalSpacer(hbox))
        l1=MyQLabel(hbox, bold=True, color=qt.QColor(0,0,0))
        hboxLayout.addWidget(l1)

        self.energyValue = None
        if energyTable is not None:
            text = '<b><nobr>Excitation Energy (keV)</nobr></b>'
            l1.setFixedWidth(l1.fontMetrics().maxWidth()*len("##"+text+"####"))
            l1.setText(text)
            self.energyTable = energyTable
            add = 0
            self.energy = MyQLabel(hbox)
            hboxLayout.addWidget(self.energy)
            self.energy.setFixedWidth(self.energy.fontMetrics().maxWidth()*len('########.###'))
            self.energy.setAlignment(qt.Qt.AlignLeft)
            #self.energy.setForegroundColor(qt.Qt.red)
        else:
            l1.setText('<b><nobr>Excitation Energy (keV)</nobr></b>')
            self.energyTable = EnergyTable.EnergyTable(self)
            add = 1
            self.energy = qt.QLineEdit(hbox)
            hboxLayout.addWidget(self.energy)
            self.energy.setFixedWidth(self.energy.fontMetrics().maxWidth()*len('########.###'))
            self.energyButton = qt.QPushButton(hbox)
            hboxLayout.addWidget(self.energyButton)
            self.energyButton.setText("Update")
            self.energyButton.clicked.connect(self._energyClicked)

        hboxLayout.addWidget(qt.HorizontalSpacer(hbox))
        layout.addSpacing(20)
        layout.addWidget(hbox)

        self.table = QPeriodicTable(self)
        line= qt.QFrame(self)
        line.setFrameShape(qt.QFrame.HLine)
        line.setFrameShadow(qt.QFrame.Sunken)

        self.peaks = PeakButtonList(self)
        self.peaks.setDisabled(['K','Ka','Kb','L','L1','L2','L3','M'])

        self.energyTable.sigEnergyTableSignal.connect(self._energyTableAction)
        self.table.sigElementClicked.connect(self.elementClicked)
        self.peaks.sigSelectionChanged.connect(self.peakSelectionChanged)

        #Reset All
        self.resetAllButton = qt.QPushButton(self.peaks)
        palette = qt.QPalette(self.resetAllButton.palette())
        role = self.resetAllButton.foregroundRole()
        palette.setColor(role, qt.Qt.red)
        self.resetAllButton.setPalette(palette)
        self.resetAllButton.setText("Reset All")
        self.peaks.layout().addWidget(self.resetAllButton)

        self.resetAllButton.clicked.connect(self.__resetAll)

        layout.addWidget(self.table)
        layout.addWidget(line)
        layout.addWidget(self.peaks)
        if add:layout.addWidget(self.energyTable)
        layout.addStretch(1)

        self.current= None
        self.setSelection(peakdict)

    def __resetAll(self):
        msg=qt.QMessageBox.warning( self, "Clear selection",
                      "Do you want to reset the selection for all elements?",
                      qt.QMessageBox.Yes,qt.QMessageBox.No)
        if msg == qt.QMessageBox.No:
            return

        self.peakdict = {}
        self.table.setSelection(list(self.peakdict.keys()))
        self.peaks.setSelection([])
        self.peakSelectionChanged([])

    def __getZ(self,element):
        return ElementList.index(element) + 1

    def setSelection(self,peakdict):
        self.peakdict = {}
        self.peakdict.update(peakdict)
        for key in list(self.peakdict.keys()):
                if type(self.peakdict[key])!= type([]):
                        self.peakdict[key]= [ self.peakdict[key] ]
        self.table.setSelection(list(self.peakdict.keys()))

    def getSelection(self):
        ddict={}
        for key in list(self.peakdict.keys()):
                if len(self.peakdict[key]):
                        ddict[key]= self.peakdict[key]
        return ddict

    def peakSelectionChanged(self,selection):
        if self.current is None: return
        if type(selection) != type([]):
            selection=selection.list
        self.peakdict[self.current] = selection
        if len(self.peakdict[self.current]):
            self.table.setElementSelected(self.current,1)
        else:
            self.table.setElementSelected(self.current,0)
        sel= self.getSelection()
        sel['current'] = self.current
        self.sigFitPeakSelect.emit((sel))

    def elementClicked(self,symbol):
        if QTVERSION > '4.0.0':symbol = str(symbol)
        if not (symbol in self.peakdict):
            self.peakdict[symbol] = []
        self.current = symbol
        if len(self.peakdict[self.current]):
            self.table.setElementSelected(self.current,1)
        else:
            self.table.setElementSelected(self.current,0)
        for ele in list(self.peakdict.keys()):
            if ele != symbol:
                if not len(self.peakdict[ele]):
                    del self.peakdict[ele]
        sel= self.getSelection()
        sel['current'] = self.current
        self.setPeaksDisabled(symbol)
        self.sigFitPeakSelect.emit((sel))
        self.peaks.setSelection(self.peakdict[symbol])

    def setPeaksDisabled(self,symbol):
        z = self.__getZ(symbol)
        if (z > 47) and (Elements.getomegam5('Cd') > 0.0):
            #we have data available to support that
            disabled = []
        elif z > 66:
            #self.peaks.setDisabled(['Ka','Kb'])
            #disabled = ['Ka','Kb']
            disabled = []
        elif z > 17:
            #self.peaks.setDisabled(['Ka','Kb','M'])
            #disabled = ['Ka','Kb','M']
            disabled = ['M']
        elif z > 2:
            #self.peaks.setDisabled(['Ka','Kb','L','L1','L2','L3','M'])
            #disabled = ['Ka','Kb','L','L1','L2','L3','M']
            disabled = ['L','L1','L2','L3','M']
        else:
            #self.peaks.setDisabled(['K','Ka','Kb','L','L1','L2','L3','M'])
            #disabled = ['Ka','Kb','L','L1','L2','L3','M']
            disabled = ['Ka', 'Kb','L','L1','L2','L3','M']

        ele = symbol
        if self.energyValue is not None:
            for peak in ['K', 'Ka', 'Kb', 'L','L1','L2','L3','M']:
                if peak not in disabled:
                    if peak == 'L':
                        if Elements.Element[ele]['binding']['L3'] > self.energyValue:
                            disabled.append(peak)
                    elif peak == 'M':
                        if Elements.Element[ele]['binding']['M5'] > self.energyValue:
                            disabled.append(peak)
                    elif peak == 'Ka':
                        if Elements.Element[ele]['binding']['K'] > self.energyValue:
                            disabled.append(peak)
                    elif peak == 'Kb':
                        if Elements.Element[ele]['binding']['K'] > self.energyValue:
                            disabled.append(peak)
                    elif Elements.Element[ele]['binding'][peak] > self.energyValue:
                            disabled.append(peak)
                    else:
                        pass
        self.peaks.setDisabled(disabled)

    def setEnergy(self, energy):
        if (energy is None) or (energy == []):
            self.energyValue = energy
            self.energy.setText("None")
        elif energy == "None":
            self.energyValue = None
            self.energy.setText("None")
        elif type(energy) == type([]):
            self.energyValue = max(energy)
        else:
            self.energyValue = energy
            self.energy.setText("%.4f" % energy)
        self._energyClicked()

    def _energyTableAction(self, ddict):
        _logger.debug("_energyTableAction called, ddict = %s" % ddict)
        elist, wlist, flist, slist= self.energyTable.getParameters()
        maxenergy = 0.0
        for i in range(len(flist)):
            if flist[i]:
                if elist[i] is not None:
                    if wlist[i] > 0.0:
                        if elist[i] > maxenergy:
                            maxenergy = elist[i]
        if maxenergy == 0.0:maxenergy = None
        self.setEnergy(maxenergy)

    def _energyClicked(self):
        string = str(self.energy.text())
        string.replace(" ","")
        if (string != "None") and len(string):
            try:
                value = float(string)
                self.energyValue = value
                if False:
                    self.energyButton.setFocus()
            except:
                msg=qt.QMessageBox(self.energy)
                msg.setIcon(qt.QMessageBox.Critical)
                msg.setText("Invalid Float")
                msg.exec_loop()
                self.energy.setFocus()
        else:
            self.energyValue = None
            if False:
                self.energyButton.setFocus()
        self.__updateSelection()

    def __updateSelection(self):
        if self.energyValue is not None:
            for ele in list(self.peakdict.keys()):
                for peak in self.peakdict[ele]:
                    if   peak in self.peakdict[ele]:
                        index = self.peakdict[ele].index(peak)
                    if   peak == 'L':
                        if Elements.Element[ele]['binding']['L3'] > self.energyValue:
                            del self.peakdict[ele][index]
                    elif peak == 'M':
                        if Elements.Element[ele]['binding']['M5'] > self.energyValue:
                            del self.peakdict[ele][index]
                    elif peak == "Ka":
                        if Elements.Element[ele]['binding']['K'] > self.energyValue:
                            del self.peakdict[ele][index]
                    elif peak == "Kb":
                        if Elements.Element[ele]['binding']['K'] > self.energyValue:
                            del self.peakdict[ele][index]
                    elif Elements.Element[ele]['binding'][peak] > self.energyValue:
                        del self.peakdict[ele][index]
                    else:
                        pass
                if ele == self.current:
                    self.peaks.setSelection(self.peakdict[ele])
                    self.peakSelectionChanged(self.peakdict[ele])
                    self.elementClicked(ele)
                if not len(self.peakdict[ele]): del self.peakdict[ele]
        dict = copy.deepcopy(self.peakdict)
        self.setSelection(dict)


class MyQLineEdit(qt.QLineEdit):
    def __init__(self,parent=None,name=None):
        qt.QLineEdit.__init__(self,parent,name)

    def focusInEvent(self,event):
        self.setPaletteBackgroundColor(qt.QColor('yellow'))

    def focusOutEvent(self,event):
        self.setPaletteBackgroundColor(qt.QColor('white'))

class MyQLabel(qt.QLabel):
    def __init__(self, parent=None, bold=True, color= qt.Qt.red):
        qt.QLabel.__init__(self,parent)
        palette = self.palette()
        role = self.foregroundRole()
        palette.setColor(role,color)
        self.setPalette(palette)
        self.font().setBold(bold)


    if QTVERSION < '4.0.0':
        def drawContents(self, painter):
            painter.font().setBold(self.bold)
            pal =self.palette()
            pal.setColor(qt.QColorGroup.Foreground,self.color)
            self.setPalette(pal)
            qt.QLabel.drawContents(self,painter)
            painter.font().setBold(0)

if __name__ == "__main__":
    import sys
    def change(ddict):
        print("New selection:",)
        print(ddict)
    a = qt.QApplication([])
    a.lastWindowClosed.connect(a.quit)

    w = qt.QTabWidget()

    f = FitPeakSelect()
    w.addTab(f, "QPeriodicTable")
    f.sigFitPeakSelect.connect(change)
    w.show()
    a.exec()
    a = None