File: MultiParameters.py

package info (click to toggle)
pymca 5.1.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 40,004 kB
  • ctags: 17,800
  • sloc: python: 132,302; ansic: 20,016; cpp: 827; makefile: 48; sh: 30; xml: 24
file content (370 lines) | stat: -rw-r--r-- 13,153 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
#/*##########################################################################
# Copyright (C) 2004-2014 V.A. Sole, 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.A. Sole - ESRF Data Analysis"
__contact__ = "sole@esrf.fr"
__license__ = "MIT"
__copyright__ = "European Synchrotron Radiation Facility, Grenoble, France"
import os
import sys
from PyMca5.PyMcaGui import PyMcaQt as qt
from . import Parameters
QTVERSION = qt.qVersion()
from . import McaTable

DEBUG = 0

class ParametersTab(qt.QTabWidget):
    sigMultiParametersSignal = qt.pyqtSignal(object)
    def __init__(self,parent = None, name = "FitParameters"):
        qt.QTabWidget.__init__(self, parent)
        self.setWindowTitle(name)

        #geometry
        #self.resize(570,300)
        #self.setCaption(self.trUtf8(name))

        #initialize the numer of tabs to 1
        #self.TabWidget=QTabWidget(self,"ParametersTab")
        #self.TabWidget.setGeometry(QRect(25,25,450,350))
        #the widgets in the notebook
        self.views={}
        #the names of the widgets (to have them in order)
        self.tabs=[]
        #the widgets/tables themselves
        self.tables={}
        self.mcatable=None
        self.setContentsMargins(10, 10, 10, 10)
        self.setview(name="Region 1")

    def setview(self,name=None,fitparameterslist=None):
        if name is None:
            name = self.current
        if name in self.tables.keys():
            table=self.tables[name]
        else:
            #create the parameters instance
            self.tables[name]=Parameters.Parameters(self)
            table=self.tables[name]
            self.tabs.append(name)
            self.views[name]=table
            #if qVersion() >= '3.0.0':
            #    self.addTab(table,self.trUtf8(name))
            #else:
            #    self.addTab(table,self.tr(name))
            self.addTab(table,str(name))
        if fitparameterslist is not None:
            table.fillfromfit(fitparameterslist)
        #print "SHowing page ",name
        if QTVERSION < '4.0.0':
            self.showPage(self.views[name])
        else:
            self.setCurrentWidget(self.views[name])
        self.current=name

    def renameview(self,oldname=None,newname=None):
        error = 1
        if newname is not None:
            if newname not in self.views.keys():
                if oldname in self.views.keys():
                    parameterlist=self.tables[oldname].fillfitfromtable()
                    self.setview(name=newname,fitparameterslist=parameterlist)
                    self.removeview(oldname)
                    error = 0
        return error

    def fillfromfit(self,fitparameterslist,current=None):
        if current is None:
            current=self.current
        #for view in self.tables.keys():
        #    self.removeview(view)
        self.setview(fitparameterslist=fitparameterslist,name=current)

    def fillfitfromtable(self,*vars,**kw):
        if len(vars) > 0:
            name=vars[0]
        elif 'view' in kw:
            name=kw['view']
        elif 'name' in kw:
            name=kw['name']
        else:
            name=self.current
        if hasattr(self.tables[name],'fillfitfromtable'):
            return self.tables[name].fillfitfromtable()
        else:
            return None

    def removeview(self,*vars,**kw):
        error = 1
        if len(vars) > 0:
            view=vars[0]
        elif 'view' in kw:
            view=kw['view']
        elif 'name' in kw:
            view=kw['name']
        else:
            return error
        if view == self.current:
            return error
        if view in self.views.keys():
                self.tabs.remove(view)
                if QTVERSION < '4.0.0':
                    self.removePage(self.tables[view])
                    self.removePage(self.views[view])
                else:
                    index = self.indexOf(self.tables[view])
                    self.removeTab(index)
                    index = self.indexOf(self.views[view])
                    self.removeTab(index)
                del self.tables[view]
                del self.views[view]
                error =0
        return error

    def removeallviews(self,keep='Fit'):
        for view in list(self.tables.keys()):
            if view != keep:
                self.removeview(view)

    def fillfrommca(self,mcaresult):
        #for view in self.tables.keys():
        #    self.removeview(view)
        self.removeallviews()
        region = 0
        for result in mcaresult:
             #if result['chisq'] is not None:
                region=region+1
                self.fillfromfit(result['paramlist'],current='Region '+\
                                 "%d" % region)
        name='MCA'
        if name in self.tables:
           table=self.tables[name]
        else:
           self.tables[name]=McaTable.McaTable(self)
           table=self.tables[name]
           self.tabs.append(name)
           self.views[name]=table
           #self.addTab(table,self.trUtf8(name))
           self.addTab(table,str(name))
           table.sigMcaTableSignal.connect(self.__forward)
        table.fillfrommca(mcaresult)
        self.setview(name=name)
        return

    def __forward(self,ddict):
        self.sigMultiParametersSignal.emit(ddict)


    def gettext(self,**kw):
        if "name" in kw:
            name = kw["name"]
        else:
            name = self.current
        table = self.tables[name]
        lemon = ("#%x%x%x" % (255,250,205)).upper()
        if QTVERSION < '4.0.0':
            hb = table.horizontalHeader().paletteBackgroundColor()
            hcolor = ("#%x%x%x" % (hb.red(), hb.green(), hb.blue())).upper()
        else:
            if DEBUG:
                print("Actual color to ge got")
            hcolor = ("#%x%x%x" % (230,240,249)).upper()
        text=""
        text+=("<nobr>")
        text+=( "<table>")
        text+=( "<tr>")
        if QTVERSION < '4.0.0':
            ncols = table.numCols()
        else:
            ncols = table.columnCount()
        for l in range(ncols):
            text+=('<td align="left" bgcolor="%s"><b>' % hcolor)
            if QTVERSION < '4.0.0':
                text+=(str(table.horizontalHeader().label(l)))
            else:
                text+=(str(table.horizontalHeaderItem(l).text()))
            text+=("</b></td>")
        text+=("</tr>")
        if QTVERSION < '4.0.0': nrows = table.numRows()
        else: nrows = table.rowCount()
        for r in range(nrows):
            text+=("<tr>")
            if QTVERSION < '4.0.0':
                newtext = str(table.text(r,0))
            else:
                item = table.item(r, 0)
                newtext = ""
                if item is not None:
                    newtext = str(item.text())
            if len(newtext):
                color = "white"
                b="<b>"
            else:
                b=""
                color = lemon
            try:
                #MyQTable item has color defined
                cc = table.item(r,0).color
                cc = ("#%x%x%x" % (cc.red(),cc.green(),cc.blue())).upper()
                color = cc
            except:
                pass
            for c in range(ncols):
                if QTVERSION < '4.0.0':
                    newtext = str(table.text(r,c))
                else:
                    item = table.item(r, c)
                    newtext = ""
                    if item is not None:
                        newtext = str(item.text())
                if len(newtext):
                    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+=(newtext)
                if len(b):
                    text+=("</td>")
                else:
                    text+=("</b></td>")
            if QTVERSION < '4.0.0':
                newtext = str(table.text(r,0))
            else:
                item = table.item(r, 0)
                newtext = ""
                if item is not None:
                    newtext = str(item.text())
            if len(newtext):
                text+=("</b>")
            text+=("</tr>")
            #text+=( str(qt.QString("<br>"))
            text+=("\n")
        text+=("</table>")
        text+=("</nobr>")
        return text

    def getHTMLText(self, **kw):
        return self.gettext(**kw)

    if QTVERSION > '4.0.0':
        def getText(self, **kw):
            if "name" in kw:
                name = kw["name"]
            else:
                name = self.current
            table = self.tables[name]
            text=""
            if QTVERSION < '4.0.0':
                ncols = table.numCols()
            else:
                ncols = table.columnCount()
            for l in range(ncols):
                if QTVERSION < '4.0.0':
                    text+=(str(table.horizontalHeader().label(l)))
                else:
                    text+=(str(table.horizontalHeaderItem(l).text()))+"\t"
            text+=("\n")
            if QTVERSION < '4.0.0':
                nrows = table.numRows()
            else:
                nrows = table.rowCount()
            for r in range(nrows):
                if QTVERSION < '4.0.0':
                    newtext = str(table.text(r,0))
                else:
                    item = table.item(r, 0)
                    newtext = ""
                    if item is not None:
                        newtext = str(item.text())+"\t"
                for c in range(ncols):
                    if QTVERSION < '4.0.0':
                        newtext = str(table.text(r,c))
                    else:
                        newtext = ""
                        if c != 4:
                            item = table.item(r, c)
                            if item is not None:
                                newtext = str(item.text())
                        else:
                            item = table.cellWidget(r, c)
                            if item is not None:
                                newtext = str(item.currentText())
                    text+=(newtext)+"\t"
                text+=("\n")
            text+=("\n")
            return text

def test():
    a = qt.QApplication(sys.argv)
    a.lastWindowClosed.connect(a.quit)
    w = ParametersTab()
    w.show()
    from PyMca5.PyMca import specfilewrapper as specfile
    from PyMca5.PyMca import Specfit
    from PyMca5 import PyMcaDataDir
    import numpy
    sf=specfile.Specfile(os.path.join(PyMcaDataDir.PYMCA_DATA_DIR,
                                      "XRFSpectrum.mca"))
    scan=sf.select('2.1')
    mcadata=scan.mca(1)
    y=numpy.array(mcadata)
    #x=numpy.arange(len(y))
    x=numpy.arange(len(y))*0.0502883-0.492773
    fit=Specfit.Specfit()
    fit.setdata(x=x,y=y)
    fit.importfun(os.path.join(os.path.dirname(Specfit.__file__),
                                   "SpecfitFunctions.py"))
    fit.settheory('Hypermet')
    fit.configure(Yscaling=1.,
                  WeightFlag=1,
                  PosFwhmFlag=1,
                  HeightAreaFlag=1,
                  FwhmPoints=16,
                  PositionFlag=1,
                  HypermetTails=1)
    fit.setbackground('Linear')
    if 1:
        mcaresult=fit.mcafit(x=x,xmin=x[300],xmax=x[1000])
        w.fillfrommca(mcaresult)
    else:
        fit.estimate()
        fit.startfit()
        w.fillfromfit(fit.paramlist,current='Fit')
        w.removeview(view='Region 1')
    a.exec_()

if __name__ == "__main__":
    bench=0
    if bench:
        import pstats
        import profile
        profile.run('test()',"test")
        p=pstats.Stats("test")
        p.strip_dirs().sort_stats(-1).print_stats()
    else:
        test()