File: McaAdvancedTable.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 (315 lines) | stat: -rw-r--r-- 12,965 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
#/*##########################################################################
#
# 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 logging
from PyMca5.PyMcaGui import PyMcaQt as qt
if hasattr(qt, "QString"):
    QString = qt.QString
else:
    QString = str
QTVERSION = qt.qVersion()
_logger = logging.getLogger(__name__)

try:
    from PyMca5.PyMcaGui.misc.TableWidget import TableWidget
    QTable = TableWidget
except:
    _logger.warning("Cannot import clipboard enabled table")
    QTable = qt.QTableWidget

class McaTable(QTable):
    sigMcaTableSignal = qt.pyqtSignal(object)
    sigClosed = qt.pyqtSignal(object)
    def __init__(self, *args,**kw):
        QTable.__init__(self, *args)
        if 'labels' in kw:
            self.labels=[]
            for label in kw['labels']:
                self.labels.append(label)
        else:
            #self.labels=['Element','Group','Energy','Ratio','Fit Area','MCA Area','Sigma','Fwhm','Chisq']
            self.labels=['Element','Group','Fit Area','Sigma','Energy','Ratio','FWHM','Chi square']
        self.setColumnCount(len(self.labels))

        for i in range(len(self.labels)):
            item = self.horizontalHeaderItem(i)
            if item is None:
                item = qt.QTableWidgetItem(self.labels[i],
                                           qt.QTableWidgetItem.Type)
            item.setText(self.labels[i])
            self.setHorizontalHeaderItem(i,item)

        self.regionlist=[]
        self.regiondict={}
        verticalHeader = self.verticalHeader() 
        if hasattr(verticalHeader, "setSectionsClickable"):
            self.verticalHeader().setSectionsClickable(True)
        else:
            self.verticalHeader().setClickable(True)
        self.verticalHeader().sectionClicked.connect(self.__myslot)

        self.itemSelectionChanged.connect(self.__myslot)
        #self.connect(self,qt.SIGNAL("selectionChanged()"),self.__myslot)
        #self.setSelectionMode(qttable.QTable.SingleRow)


    def fillfrommca(self,result,diag=1):
        line=0
        #calculate the number of rows
        nrows = 0
        for group in result['groups']:
            nrows += 1
            for peak in result[group]['peaks']:
                nrows += 1
            for peak0 in result[group]['escapepeaks']:
                peak  = peak0+"esc"
                if result[group][peak]['ratio'] > 0.0:
                    nrows += 1
        self.setRowCount(nrows)
        for group in result['groups']:
            ele,group0 = group.split()
            fitarea    = QString("%.4e" % (result[group]['fitarea']))
            sigmaarea  = QString("%.2e" % (result[group]['sigmaarea']))
            fields = [ele,group0,fitarea,sigmaarea]
            col = 0
            color = qt.QColor('white')
            nlines = self.rowCount()
            if (line+1) > nlines:
                self.setRowCount(line+1)
            for i in range(len(self.labels)):
                if i < len(fields):
                    item = self.item(line, col)
                    text = fields[i]
                    if item is None:
                        item = qt.QTableWidgetItem(text,
                                                   qt.QTableWidgetItem.Type)
                        self.setItem(line, col, item)
                    else:
                        item.setText(text)
                        if hasattr(item, "setBackground"):
                            item.setBackground(color)
                        else:
                            item.setBackgroundColor(color)
                        item.setFlags(qt.Qt.ItemIsSelectable|
                                      qt.Qt.ItemIsEnabled)
                else:
                    item = self.item(line, col)
                    if item is not None:
                        item.setText("")
                    #self.setItem(line, col, item)
                col=col+1
            line += 1
            #Lemon Chiffon = (255,250,205)
            color = qt.QColor(255,250,205)
            for peak in result[group]['peaks']:
                name  = peak
                energy = QString("%.3f" % (result[group][peak]['energy']))
                ratio  = QString("%.5f" % (result[group][peak]['ratio']))
                area   = QString("%.4e" % (result[group][peak]['fitarea']))
                sigma  = QString("%.2e" % (result[group][peak]['sigmaarea']))
                fwhm   = QString("%.3f" % (result[group][peak]['fwhm']))
                chisq  = QString("%.2f" % (result[group][peak]['chisq']))
                if (line+1) > nlines:
                    self.setRowCount(line+1)
                fields = [name,area,sigma,energy,ratio,fwhm,chisq]
                col = 1
                for field in fields:
                    item = self.item(line, col)
                    text = field
                    if item is None:
                        item = qt.QTableWidgetItem(text,
                                                   qt.QTableWidgetItem.Type)
                        self.setItem(line, col, item)
                    else:
                        item.setText(text)
                    if hasattr(item, "setBackground"):
                        item.setBackground(color)
                    else:
                        item.setBackgroundColor(color)
                    item.setFlags(qt.Qt.ItemIsSelectable|
                                  qt.Qt.ItemIsEnabled)
                    col=col+1
                line+=1
            for peak0 in result[group]['escapepeaks']:
                peak  = peak0+"esc"
                if result[group][peak]['ratio'] > 0.0:
                    energy = QString("%.3f" % (result[group][peak]['energy']))
                    ratio  = QString("%.5f" % (result[group][peak]['ratio']))
                    area   = QString("%.4e" % (result[group][peak]['fitarea']))
                    sigma  = QString("%.2e" % (result[group][peak]['sigmaarea']))
                    fwhm   = QString("%.3f" % (result[group][peak]['fwhm']))
                    chisq  = QString("%.2f" % (result[group][peak]['chisq']))
                    if (line+1) > nlines:
                        self.setRowCount(line+1)
                    fields = [peak,area,sigma,energy,ratio,fwhm,chisq]
                    col = 1
                    for field in fields:
                        item = self.item(line, col)
                        if item is None:
                            item = qt.QTableWidgetItem(field,
                                                       qt.QTableWidgetItem.Type)
                            self.setItem(line, col, item)
                        else:
                            item.setText(field)
                        if hasattr(item, "setBackground"):
                            item.setBackground(color)
                        else:
                            item.setBackgroundColor(color)
                        item.setFlags(qt.Qt.ItemIsSelectable|
                                      qt.Qt.ItemIsEnabled)
                        col=col+1
                    line+=1
        for i in range(self.columnCount()):
            if i>-1:
                self.resizeColumnToContents(i)

    def __getfitpar(self,result):
        if  result['fitconfig']['fittheory'].find("Area") != -1:
            fitlabel='Area'
        elif result['fitconfig']['fittheory'].find("Hypermet") != -1:
            fitlabel='Area'
        else:
            fitlabel='Height'
        values = []
        sigmavalues = []
        for param in result['paramlist']:
            if param['name'].find('ST_Area') != -1:
                # value and sigmavalue defined via fitlabel
                values[-1]      = value * (1.0 + param['fitresult'])
                #just an approximation
                sigmavalues[-1] = sigmavalue * (1.0 + param['fitresult'])
            elif param['name'].find('LT_Area')!= -1:
                pass
            elif param['name'].find(fitlabel) != -1:
                value      = param['fitresult']
                sigmavalue = param['sigma']
                values.append(value)
                sigmavalues.append(sigmavalue)
        return fitlabel, values, sigmavalues


    def __myslot(self,*var):
        ddict={}
        if len(var) == 0:
            #selection changed event
            #get the current selection
            ddict['event'] = 'McaTableClicked'
            row = self.currentRow()
        else:
            #Header click
            ddict['event'] = 'McaTableRowHeaderClicked'
            row = var[0]
        ccol = self.currentColumn()
        ddict['row'  ]       = row
        ddict['col']         = ccol
        ddict['labelslist']  = self.labels
        if row >= 0:
            col = 0
            for label in self.labels:
                item = self.item(row, col)
                if item is not None:
                    text = item.text()
                    try:
                        ddict[label] = float(str(text))
                    except:
                        ddict[label] = str(text)
                col +=1
        self.sigMcaTableSignal.emit(ddict)

    def gettext(self):
        lemon= ("#%x%x%x" % (255,250,205)).upper()
        if QTVERSION < '4.0.0':
            hb = self.horizontalHeader().paletteBackgroundColor()
            hcolor = ("#%x%x%x" % (hb.red(),hb.green(),hb.blue())).upper()
        else:
            _logger.debug("color background to implement")
            hcolor = ("#%x%x%x" % (230,240,249)).upper()
        text = ""
        text += ("<nobr>")
        text += ("<table>")
        text += ("<tr>")
        ncols = self.columnCount()
        for l in range(ncols):
            text+=('<td align="left" bgcolor="%s"><b>' % hcolor)
            text+=(str(self.horizontalHeaderItem(l).text()))
            text+=("</b></td>")
        text+=("</tr>")
        #text+=( str(QString("</br>"))
        nrows = self.rowCount()
        for r in range(nrows):
            text+=("<tr>")
            moretext = ""
            item = self.item(r, 0)
            if item is not None:
                moretext = str(item.text())
            if len(moretext):
                color = "white"
                b="<b>"
            else:
                b=""
                color = lemon
            for c in range(ncols):
                moretext = ""
                item = self.item(r, c)
                if item is not None:
                    moretext = str(item.text())
                if len(moretext):
                    finalcolor = color
                else:
                    finalcolor = "white"
                if c<2:
                    text+=('<td align="left" bgcolor="%s">%s' % (finalcolor,b))
                else:
                    text+=('<td align="right" bgcolor="%s">%s' % (finalcolor,b))
                text+= moretext
                if len(b):
                    text+=("</td>")
                else:
                    text+=("</b></td>")
            moretext = ""
            item = self.item(r, 0)
            if item is not None:
                moretext = str(item.text())
            if len(moretext):
                text+=("</b>")
            text+=("</tr>")
            #text+=( str(QString("<br>"))
            text+=("\n")
        text+=("</table>")
        text+=("</nobr>")
        return text

    def closeEvent(self, event):
        QTable.closeEvent(self, event)
        ddict={}
        ddict['event']= 'closed'
        self.sigClosed.emit(ddict)