MainWindow.py 37.8 KB
Newer Older
1
2
3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
mirone's avatar
mirone committed
4
5
6
7
8
9


try:
    from PyQt4 import Qt, QtCore, QtGui
except:
    from PyQt5 import Qt, QtCore, QtGui
myron's avatar
myron committed
10
11
12
13
14
15


from silx.gui import qt as Qt
from silx.gui import qt as QtCore
from silx.gui import qt as QtGui

mirone's avatar
mirone committed
16
# from .. import ui
17
18
19
20

from .subsetTable import subsetTable
from .scansTable import scansTable
from .acquisition import acquisition
myron's avatar
myron committed
21
22
from .edgesTable import edgesTable

23
24
from .source import source

myron's avatar
myron committed
25
26
27
from .. import roiSelectionWidget
from ..roiNmaSelectionGui import roiNmaSelectionWidget

myron's avatar
myron committed
28
29

import numpy as np
myron's avatar
myron committed
30
from XRStools import xrs_read, xrs_rois, xrs_extraction
myron's avatar
myron committed
31
32
33
import os
import PyMca5.PyMcaIO.specfilewrapper as SpecIO

myron's avatar
myron committed
34
from silx.gui.plot.PlotWindow import Plot1D  , Plot2D
myron's avatar
myron committed
35
from  collections import OrderedDict as odict
Alessandro Mirone's avatar
Alessandro Mirone committed
36
37

from scipy import optimize
38
import sys
myron's avatar
myron committed
39
40
     
import traceback
41
from six import StringIO
42

Alessandro Mirone's avatar
Alessandro Mirone committed
43

44
import yaml 
myron's avatar
myron committed
45
Resolver = yaml.resolver.Resolver
46
47
import re
from six import u
myron's avatar
myron committed
48
49
50
51
52
53
54
55
56
57
58
Resolver.add_implicit_resolver(
        u'tag:yaml.org,2002:float',
        re.compile(u(r"""^(?:[-+]?(?:[0-9][0-9_]*)(\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?
                    |\.[0-9_]+(?:[eE][-+][0-9]+)?
                    |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*
                    |[-+]?\.(?:inf|Inf|INF)
                    |\.(?:nan|NaN|NAN))$"""), re.X),
        list(u'-+0123456789.'))
import yaml
import yaml.resolver

myron's avatar
myron committed
59
60
61
DEBUG=0
DEBUG2=0
import pickle
myron's avatar
myron committed
62

Alessandro Mirone's avatar
Alessandro Mirone committed
63
64
65
66
67
from XRStools.installation_dir import installation_dir
import os

my_dir = os.path.dirname(os.path.abspath(__file__))
my_relativ_path =  my_dir [len( os.path.commonprefix([ installation_dir , my_dir  ])):]
mirone's avatar
mirone committed
68
69
if my_relativ_path[0]=="/":
    my_relativ_path = my_relativ_path[1:]
Alessandro Mirone's avatar
Alessandro Mirone committed
70

myron's avatar
myron committed
71
class MainWindow(Qt.QMainWindow) :
72
    def __init__(self, parent=None):
myron's avatar
myron committed
73
       
Alessandro Mirone's avatar
Alessandro Mirone committed
74
        super(  MainWindow, self).__init__(parent)
mirone's avatar
mirone committed
75
76
77
78
        print(  installation_dir  )
        print(  "resources"  )
        print(  my_relativ_path  )
        print(os.path.join(  installation_dir,"resources" , my_relativ_path ,  "MainWindow.ui" )    )
Alessandro Mirone's avatar
Alessandro Mirone committed
79
80
        Qt.loadUi(  os.path.join(  installation_dir,"resources" , my_relativ_path ,  "MainWindow.ui" ), self)
        
myron's avatar
myron committed
81
82
        sys.excepthook = excepthook

83
84
85
86
87
        self.tabWidget.clear()
        self.subsettable = subsetTable()
        self.scanstable  = scansTable()
        self.acquisition =  acquisition()
        self.source =  source()
myron's avatar
myron committed
88
        self.edges =  edgesTable()
89
        
myron's avatar
myron committed
90
        rsw = roiSelectionWidget.mainwindow()
mirone's avatar
mirone committed
91
        self.rsw = rsw
92
        
myron's avatar
myron committed
93
94
95
        self.tabWidget.addTab( rsw  ,"Spatial ROIS")

        sprsw = roiNmaSelectionWidget.mainwindow()
96
97
98
99
100

        rsw.user_input_signal.connect(sprsw.update_user_input)

        sprsw.user_input_signal.connect(self.source.update_user_input)

mirone's avatar
mirone committed
101
102
        self.sprsw = sprsw
        
myron's avatar
myron committed
103
104
        self.tabWidget.addTab( sprsw  ,"Spectral ROIS")
        
105
106
107
108
109
110
111
112
113
114
115
        self.tabWidget.addTab( self.source  ,"experiment")

        sca = QtGui.QScrollArea()
        sca.setWidgetResizable(True) 
        sca.setWidget(self.subsettable)
        self.tabWidget.addTab( sca  ,"analyzers subsets")
        
        sca = QtGui.QScrollArea()
        sca.setWidgetResizable(True) 
        sca.setWidget(self.scanstable)
        self.tabWidget.addTab( sca  ,"scans selection")
myron's avatar
myron committed
116
117

        self.tabWidget.addTab( self.edges  ,"edges")
118
119
120
        
        self.tabWidget.addTab( self.acquisition  ,"loading")
        self.acquisition.pushButton.clicked.connect(self.acquire)
myron's avatar
myron committed
121
        self.acquisition.pushButton_saveAnalysis.clicked.connect(self.saveAnalysis)
myron's avatar
myron committed
122
    
myron's avatar
myron committed
123
        self.lw = None
myron's avatar
myron committed
124
125
        self.lw_ex = None
        self.plots=[]
126
        self.plots_conf = {}
Alessandro Mirone's avatar
Alessandro Mirone committed
127
        self.emitter2plotC={}
myron's avatar
myron committed
128
129

        self.actionSave_Configuration.triggered.connect(self.saveConfiguration)
130
131
132
        self.actionLoad_Configuration.triggered.connect(self.loadConfiguration)

    def loadConfiguration(self):
133
        self.loadConfigurationOption(None)
134
135
    def loadConfigurationOption(self, option=None):

136

myron's avatar
myron committed
137
        if not option:
138
139
140
141
142
143
144
145
            filename = QtGui.QFileDialog.getOpenFileName(None, "select", )
            if isinstance(filename, tuple):
                filename = filename[0]

            filename=str(filename)
            if len(filename)==0: return
        else:
            filename = option
146
147
148
149
150

        d = yaml.load(open(filename,"r"), yaml.Loader)
        
        selected_scans_d = d["selected_scans"]
        selected_scans = []
mirone's avatar
mirone committed
151
152
153
        if selected_scans_d is not None:
            for name, scan in selected_scans_d.items():
                selected_scans.append( [name]+scan)
154
155
156
157
        self.setScansSelection( selected_scans )   

        selected_subsets_d = d["selected_subsets"]
        selected_subsets = []
mirone's avatar
mirone committed
158
159
160
        if selected_subsets_d is not None:
            for name, subset in selected_subsets_d.items():
                selected_subsets.append( [subset[0],name]+subset[1:])
161
162
163
164
165
166
167
        self.setSubsetsSelection( selected_subsets )   

        selected_acquisition_d = d["selected_acquisition"]
        names = [ "method", "refscan", "include_elastic", "output_prefix"]
        selected_acquisition =  [     selected_acquisition_d[name] for name in names    ]
        self.setLoadingSelection(selected_acquisition)

myron's avatar
myron committed
168
        selected_experiment_d = d["selected_experiment"]
169
170
        names = [ "specfile_name" , "roifile_address" ]
        selected_experiment =  [     selected_experiment_d[name] for name in names    ]
myron's avatar
myron committed
171
        self.setExperimentSelection(selected_experiment)
172
173
174
175
176


        selected_edges_d = d["selected_edges"]
        formula, edges = selected_edges_d["formula"] , selected_edges_d["edges"]
        self.setEdgesSelection( formula ,  edges )
myron's avatar
myron committed
177
178
179
180
181


        if "plots" in d:
            self.plots_conf = d["plots"]
            self.consume_plots_definitions()
182
183

    def consume_plots_definitions(self):
184
185
186
        if self.plots_conf is  None:
            return

187
188
189
190
191
192
193
194
195
        for plotC in self.plots:
            name = plotC.name
            if name in self.plots_conf:
                defs = self.plots_conf[name]
                names = ["hfcore_shift" , "pea_center", "pea_width","pea_shape","pea_height","lin_back0", "lin_back1", "hf_factor"]
                inputs = plotC.inputs
                for i,n in zip(inputs, names):
                    if defs[n] is not None:
                        i.setText("%e"%defs[n])
myron's avatar
myron committed
196
197
                        
                D = defs
198
199
                roisDefs = odict()
                for rn in [ "range1","range2", "Output", "Norm"   ]:
200
                    roisDefs[rn]  = odict([["from", D[rn][0]] ,["to",D[rn][1]],["type", "energy"] ]) 
201
202
203
                plotC.plot.getCurvesRoiDockWidget().setRois(roisDefs)
                del self.plots_conf[name]

myron's avatar
myron committed
204
205
206
207

        
    def saveConfiguration(self):
        filename = QtGui.QFileDialog.getSaveFileName(None, "select", )
208
209
        if isinstance(filename, tuple):
            filename = filename[0]
myron's avatar
myron committed
210
211
212
213
214
215
216
        
        filename=str(filename)
        if len(filename)==0: return
        selected_scans       =  self.getScansSelection()
        selected_subsets     =  self.getSubsetsSelection()
        selected_acquisition =  self.getLoadingSelection()
        specfile_name , roifile_address =  self.getExperimentSelection()
217
218
        selected_edges = self.getEdgesSelection( ) # [[ "H2O",1.0]] ,  {'O':['K'] } ) 

myron's avatar
myron committed
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
        print( " DEVO SALVARE " )
        print  (  selected_scans  ) 
        print  (  selected_subsets  ) 
        print  (  selected_acquisition  ) 
        print  (  specfile_name , roifile_address  )
        for plotC in self.plots:
            print( " per plotC ", plotC.name)
            print  (  [ tok.text() for tok in plotC.inputs ]  ) 
            print( plotC.plot.getCurvesRoiDockWidget().getRois() )

        # @@@@@@@@@@ààà quando si ricarica se c'e' un plotC di nome corrispondente inizializzare
        # @@@@@@@@@@@@ se no si tiene da parte e si consuma quando si fa un'acquire

        ## recuperare anche output prefix
        # yaml.load( file o stringa,yaml.Loader)

        ## fare per batch senza grafica
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
        file = open(filename,"w")
        
        file.write("selected_scans :\n" ) 
        for scan in selected_scans:
            name, nums = scan[0], scan[1:]
            file.write( "    %s : %s\n"%( name , str(list(nums)) ) )
            
        file.write("selected_subsets :\n" ) 
        for subset in selected_subsets:
            scal, name, nums = subset[0], subset[1], subset[2:]
            file.write("    %s : %s\n"%( name , str([scal] + list(nums)) ) )

        file.write("selected_acquisition :\n" ) 
        acqui = selected_acquisition
        names = [ "method", "refscan", "include_elastic", "output_prefix"]
        vals = acqui[0], acqui[1], acqui[2], acqui[3]
        for n,v in zip(names, vals ) :
            file.write("    %s : %s\n"%( n,v) )
                
        file.write("selected_experiment :\n" ) 
        names = [ "specfile_name" , "roifile_address" ]
        vals =  specfile_name , roifile_address
        for n,v in zip(names, vals ) :
            file.write("    %s : %s\n"%( n,v) )

        file.write("selected_edges :\n" ) 
        formula, edges = selected_edges
        file.write("    %s : %s\n"%( " formula",  str(formula)) )
        file.write("    %s : %s\n"%( " edges",  str(edges)) )

            
        file.write("plots :\n" ) 
        for plotC in self.plots:
            print( " per plotC ", plotC.name)
            file.write("    %s   :\n"%plotC.name   ) 
            vals = [ tok.text() for tok in plotC.inputs ]
            names = ["hfcore_shift" , "pea_center", "pea_width","pea_shape","pea_height","lin_back0", "lin_back1", "hf_factor"] 
            for n,v in zip(names, vals ) :
                file.write("        %s : %s\n"%( n,v) )

            dizio_rois = plotC.plot.getCurvesRoiDockWidget().getRois()
            for kroi, val in dizio_rois.items():
278
                file.write("        %s :   [%e,%e]\n"% (kroi, val.getFrom(), val.getTo()  )  )
279
280
                
        file.close()
myron's avatar
myron committed
281
        
282
283
    def acquire(self):
        print(" =============== LOADING============ ")
myron's avatar
myron committed
284
285
286
        selected_scans       =  self.getScansSelection()
        selected_subsets     =  self.getSubsetsSelection()
        selected_acquisition =  self.getLoadingSelection()
myron's avatar
myron committed
287
            
myron's avatar
myron committed
288
289
290
        if not DEBUG:
            specfile_name , roifile_address =  self.getExperimentSelection()
            formulas, edges = self.getEdgesSelection()
myron's avatar
myron committed
291
292
293
294
295
296
297
298
            if len(edges)!=1:
                raise Exception(" So far only one edge can be processed")
            element = list(edges.keys())[0]
            if len(edges[element])!=1:
                raise Exception(" So far only one edge can be processed")
            else:
                edge = edges[element][0]
        
myron's avatar
myron committed
299
300
301
302
            forms=[]
            weights=[]
            for f,ww in formulas:
                forms.append(f)
303
                weights.append(float(ww) )
304
        
myron's avatar
myron committed
305
            self.lw, roinums = integrate( specfile_name,  roifile_address,  selected_scans, selected_subsets, selected_acquisition  ) 
myron's avatar
myron committed
306
307
308
309
310

        for p in self.plots:
            self.tabWidget.removeTab( self.tabWidget.indexOf(p))
            p.deleteLater()
            del p
myron's avatar
myron committed
311
312
313
314
315
316
317

                  
        toreport = {}
        for plotC in self.plots:
            vals = [ tok.text() for tok in plotC.inputs ]
            dizio_rois = plotC.plot.getCurvesRoiDockWidget().getRois()
            toreport[plotC.name]=[vals, dizio_rois ]
myron's avatar
myron committed
318
319
320
321
322
        self.plots=[]


        self.lw_ex_s = []
        
myron's avatar
myron committed
323
324
325
326
327
328
329
330
331
        for iplot,subset in enumerate(selected_subsets):

            if not DEBUG:
                scal = subset[0]
                name = subset[1]
                nums = subset[2:]

                nums = [ i for i in range(len(roinums)) if roinums[i] in nums ]

332
                lw_ex = xrs_extraction.edge_extraction( self.lw,forms,weights,{element:[edge]})
myron's avatar
myron committed
333
                lw_ex.analyzerAverage(nums, errorweighing=False)
myron's avatar
myron committed
334
                y = np.maximum(1.0e-10 , lw_ex.avsignals)
myron's avatar
myron committed
335

336
337
338

                print("   INITIALISATION y, ", y)
                
myron's avatar
myron committed
339
                plotC = plotContainer(lw_ex.eloss, y, name, lw_ex, element, edge )
myron's avatar
myron committed
340
                plotC.controller=self
myron's avatar
myron committed
341
                self.plots.append(plotC)
myron's avatar
myron committed
342
                self.tabWidget.addTab(plotC, name)
myron's avatar
myron committed
343
344
345
346
347
348
349

                if name in toreport:
                    vals, dizio = toreport[name]
                    for tok,v in zip(plotC.inputs, vals):
                        tok.setText(v)
                    plotC.plot.getCurvesRoiDockWidget().setRois(dizio)
                
350
                self.consume_plots_definitions()
myron's avatar
myron committed
351

352
                
myron's avatar
myron committed
353
354
355
356
357
358
359
            else:
                scal = subset[0]
                name = subset[1]
                nums = subset[2:]
                saved = np.load("debug%d.npy"%iplot)
                eloss, y = saved

myron's avatar
myron committed
360
                plotC = plotContainer(eloss, y, name)
myron's avatar
myron committed
361
362
                self.plots.append(plotC)
                self.tabWidget.addTab(plotC, name)
myron's avatar
myron committed
363
                
myron's avatar
myron committed
364

myron's avatar
myron committed
365
                
myron's avatar
myron committed
366
367
368
369
370
    def saveAnalysis(self):
        prefix = str(self.acquisition.lineEdit_outputPrefix.text())
        for C in self.plots:
            C.saveAnalysis(prefix)
                
371
372
373
    def setScansSelection(self,    selection):
        self.scanstable.set_selection( selection )
    def getScansSelection(self):
Alessandro Mirone's avatar
Alessandro Mirone committed
374
375
        res,mini,maxi = self.scanstable.get_selection()
        return res
376
377
378
379
380
381
382
    def setSubsetsSelection(self,    selection):
        self.subsettable.set_selection( selection )
    def getSubsetsSelection(self):
        return self.subsettable.get_selection()
       
        
    def setLoadingSelection(self,    selection):
mirone's avatar
mirone committed
383
384
        if selection is not None:
            self.acquisition.set_selection( selection )
385
386
387
388
389
    def getLoadingSelection(self):
        return self.acquisition.get_selection()
    
    def setExperimentSelection(self,    selection):
        self.source.set_selection( selection )
myron's avatar
myron committed
390
391

        
392
393
    def getExperimentSelection(self):
        return self.source.get_selection()
myron's avatar
myron committed
394
395
396
397
398
    
    def setEdgesSelection(self,    formulas, edges):
        self.edges.set_selection( formulas, edges )
    def getEdgesSelection(self):
        return self.edges.get_selection()
399
       
myron's avatar
myron committed
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
def integrate( specfile_name,  roifile_address,  selected_scans, selected_subsets, selected_acquisition  ) :
        print(" SETTING PATH TO LW", specfile_name)
        assert( os.path.exists(specfile_name )   )
        if not os.path.isdir(specfile_name):
            specfile_dir = os.path.dirname(specfile_name)

        print(" DEBUG   lw creo ", specfile_dir)
        lw = xrs_read.Hydra(specfile_dir)

        print("LOADING ROIS")
        myroi = xrs_rois.load_rois_fromh5_address(roifile_address)
            
        
        print("DEBUG roi ", roifile_address ) ;
        lw.set_roiObj(myroi)
        
        print(" TRIMMING KEYS")
        print  ( list(myroi.red_rois.keys()  ) ) 

        roinums = [ int(''.join(filter(str.isdigit, str(key) )))           for key in     myroi.red_rois.keys()     ]
        roinums.sort()
421
422
        #### subsets =  self.getSubsetsSelection()
        subsets =  selected_subsets
myron's avatar
myron committed
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
        new_subsets=[]
        scaling = np.zeros(72)
        for ss in subsets:
            
            first = ss[:2]
            last  = ss[2:]
            nl = [ i for i in range(len(roinums)) if roinums[i] in last ]

            scal,name = first
            scaling[nl] = scal
            
            if len(nl):
                nuovo = first +nl
                print(" APPENDING SET ")
                print( nuovo)
                new_subsets.append(  nuovo   )
            else:
                print( " NIENTE PER ")
                print( first)

443
        method, ref_scan, keep_elastic,   output_prefix  = selected_acquisition
myron's avatar
myron committed
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
        print(" CALCULATING COMPENSATION", ref_scan, method)
        print("DEBUG compensation factor ", ref_scan, method   ) 
        lw.get_compensation_factor(ref_scan, method=method )
        
        print(" --------------------------------------------------------")
        print(lw.cenom_dict.keys())
        print("=====================================================")

        
        print(" LOADING GROUPS OF SCANS   ")
        for scan in selected_scans:
            scan_ns = scan[1:]
            scan_name = scan[0]
            print("DEBUG  LOADING ", scan_name, scan_ns, method)
            lw.load_scan( scan_ns, method=method, direct=True, scan_type=scan_name) #  scaling = scaling)


        print(" DEBUG get spe ",  method, keep_elastic)
        lw.get_spectrum_new( method=method , include_elastic=keep_elastic)    
                        

        print(" SET detector angles")
        specfile = SpecIO.Specfile( specfile_name )
        
        scan = specfile.select(str(ref_scan))
        
        rvd  = scan.motorpos("RVD" )  
        rvu  = scan.motorpos("RVU" )  
        rvb  = scan.motorpos("RVB" )
        
        rhr  = scan.motorpos("RHR" )  
        rhl  = scan.motorpos("RHL" )  
        rhb  = scan.motorpos("RHB" )  
        
        lw.get_tths(rvd=rvd, rvu=rvu, rvb=rvb, rhr=rhr, rhl=rhl, rhb=rhb, order=[0, 1, 2, 3, 4, 5])

myron's avatar
myron committed
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
        return lw, roinums



class MyPlot1D(Plot1D):
    def __init__(self, parent=None):
        super(MyPlot1D, self).__init__(parent)  # , backend = "gl")
    #     self.shint = 400
        
    #     self.setSizePolicy( Qt.QSizePolicy.Fixed, Qt.QSizePolicy.Fixed  ) # ou maximum        
    # def sizeHint(self ) :
    #     return Qt.QSize( self.shint, self.shint)
    
    # def setSizeHint(self, val ) :
    #     self.shint = val
    #     self.updateGeometry()
        

myron's avatar
myron committed
498
499


Alessandro Mirone's avatar
Alessandro Mirone committed
500
# @ui.UILoadable
myron's avatar
myron committed
501
class plotContainer(QtGui.QWidget) :
502
    def __init__(self, eloss, y, name, lw_ex, element, edge, parent=None):
Alessandro Mirone's avatar
Alessandro Mirone committed
503
504
505
506
507
508


        super( plotContainer, self).__init__(parent)
        Qt.loadUi(  os.path.join(  installation_dir,"resources" , my_relativ_path, "plotContainer.ui" ), self)

        
myron's avatar
myron committed
509
510
511
        self.plot =  MyPlot1D()
        self.layout().addWidget(self.plot)
        
Alessandro Mirone's avatar
Alessandro Mirone committed
512
513
514
515
516
        plot =  self.plot
        plot.getFitAction().setVisible(True)
        plot.setVisible(True)
        plot.getFitAction().setVisible(True)
        y = np.maximum(1.0e-3 , y)
myron's avatar
myron committed
517
        plot.addCurve(x=eloss, y=y, legend = name, replace="True")
Alessandro Mirone's avatar
Alessandro Mirone committed
518
        plot.setYAxisLogarithmic(True)
myron's avatar
myron committed
519
520
        self.name = name
        self.lw_ex = lw_ex
Alessandro Mirone's avatar
Alessandro Mirone committed
521

myron's avatar
myron committed
522
523
        E0,E1 = eloss.min(), eloss.max()
        
Alessandro Mirone's avatar
Alessandro Mirone committed
524
        roisDefs = odict( [
myron's avatar
myron committed
525
            ["ICR",  odict([["from",E0-0.1*(E1-E0) ],["to", E1+0.3*(E1-E0)   ],["type","energy"]])],
myron's avatar
myron committed
526
            ["range1", odict([["from",E0+0.1*(E1-E0) ],["to", E0+0.3*(E1-E0)   ],["type","energy"]])],
527
528
529
            ["range2", odict([["from",E0+0.6*(E1-E0)],["to",E0+0.8*(E1-E0)],["type","energy"]])],
            ["Output", odict([["from",E0+0.1*(E1-E0)],["to",E0+0.9*(E1-E0)],["type","energy"]])],
            ["Norm", odict([["from",E0+0.6*(E1-E0)],["to",E0+0.7*(E1-E0)],["type","energy"]])]
Alessandro Mirone's avatar
Alessandro Mirone committed
530
531
532
533
        ]   )
        
        plot.getCurvesRoiDockWidget().setRois(roisDefs)
        plot.getCurvesRoiDockWidget().setVisible(True)
myron's avatar
myron committed
534
        ## plot.getCurvesRoiDockWidget().roiWidget.showAllMarkers(True)
Alessandro Mirone's avatar
Alessandro Mirone committed
535
536
537
538
        # plot.getCurvesRoiDockWidget().roiWidget._isInit = True
        plot.getCurvesRoiDockWidget().sigROISignal.connect(self.on_rois_changed)
                
        self.pushButton_guess.clicked.connect(self.do_guess)
myron's avatar
myron committed
539
540
541
        self.pushButton_fit.clicked.connect(self.do_fit)
        self.pushButton_plot.clicked.connect(self.plotta)
        
Alessandro Mirone's avatar
Alessandro Mirone committed
542
543
        self.eloss = eloss
        self.y = y 
myron's avatar
myron committed
544
545
546
        self.inputs = [self.lineEdit_hfshift,self.lineEdit_A0,self.lineEdit_A1,self.lineEdit_A2,self.lineEdit_A3,self.lineEdit_A4,self.lineEdit_A5,self.lineEdit_A6]
        self.element = element
        self.edge = edge
myron's avatar
myron committed
547
548
549
550
        
        self.pushButton_save.clicked.connect(self.saveAnalysis_local)
        
        
myron's avatar
myron committed
551
552
553
554
555
556
557
558
559
560
561
562
563
    def checkInputs(self):
        
        for tok in self.inputs:
            if len( str( tok.text()))==0:
                tok.setText("0")
        for tok in self.inputs:
            try:
                tmp = float( str(tok.text()))
            except:
                tok.setText("ERROR")
                


Alessandro Mirone's avatar
Alessandro Mirone committed
564
565
566
        
    def do_guess(self):
        roisDef = self.plot.getCurvesRoiDockWidget().getRois()
567
568
        range1 =[ roisDef["range1"].getFrom()  ,   roisDef["range1"].getTo()  ]
        range2 =[ roisDef["range2"].getFrom()  ,   roisDef["range2"].getTo()  ]
Alessandro Mirone's avatar
Alessandro Mirone committed
569
570
571
572
573
        
        print( self.plot.getCurvesRoiDockWidget().getRois())
        
        # define fitting ranges
        region1 = np.where(np.logical_and(self.eloss >= range1[0], self.eloss <= range1[1]))
myron's avatar
myron committed
574
575
576

        print(" REGION 1 " , region1)
        
Alessandro Mirone's avatar
Alessandro Mirone committed
577
        region2 = np.where(np.logical_and(self.eloss >= range2[0], self.eloss <= range2[1]))
myron's avatar
myron committed
578
        print(" REGION 2 " , region2)
Alessandro Mirone's avatar
Alessandro Mirone committed
579
580
581
582
        # region  = np.append(region1*weights[0],region2*weights[1])
        region  = np.append(region1,region2)

        # find indices for guessing start values from HF J_total
myron's avatar
myron committed
583
584
585
586
587
588
        
        # print(" QUI FITTO ")
        # fitfct = lambda a: np.sum( (self.y[region] - pearson7_zeroback(self.eloss,a)[region] - 
        #                             np.polyval(a[4:6],self.eloss[region]) )**2.0 )

        fact = self.y[region].max()
myron's avatar
myron committed
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
        # fitfct = functor2minim( self.eloss[region1], self.y[region1]/fact   ) 
        # guess1 = optimize.minimize(fitfct, [1.0,1.0,1.0,1.0  ], method='SLSQP').x
        # guess1 = optimize.minimize(fitfct, [1.0,1.0,1.0,1.0  ], method='SLSQP').x


        fitfct = functorObjectV(  self.y[region1]/fact , self.eloss[region1],  0   ) 
        bndsa = [ -np.inf]+ [ 0  for tmp in range(3)]
        bndsb =  [ np.inf for tmp in range(4)]

        guess = [1.0,1.0,1.0,1.0  ]
        guess_alt = []
        for t in self.inputs[1:5]:
            if len(str(t.text()))==0:
                break
            else:
                guess_alt.append(float(  str(t.text()) ))
        else:
            guess = guess_alt

        guess[3]/=fact
     
        soluzione    = optimize.least_squares(fitfct,guess , method='trf', bounds=[bndsa,bndsb] ) # constraints=cons)
        guess1       = soluzione.x

myron's avatar
myron committed
613
        guess1[3]*=fact
Alessandro Mirone's avatar
Alessandro Mirone committed
614
        print(" IL RISULTATO DEL FIT EST ", guess1)
myron's avatar
myron committed
615
616
        guess=list(guess1)+[0.0,0.0,1.0]
        
myron's avatar
myron committed
617
618
619
620
621
622
623
        self.lineEdit_A0.setText(str("%e"%guess[0]))
        self.lineEdit_A1.setText(str("%e"%guess[1]))
        self.lineEdit_A2.setText(str("%e"%guess[2]))
        self.lineEdit_A3.setText(str("%e"%guess[3]))
        self.lineEdit_A4.setText(str("%e"%guess[4]))
        self.lineEdit_A5.setText(str("%e"%guess[5]))
        self.lineEdit_A6.setText(str("%e"%guess[6]))
myron's avatar
myron committed
624
        
myron's avatar
myron committed
625
        # fit = fitfct.funct( guess  ,   self.eloss  )
myron's avatar
myron committed
626
        fit = fitfct.funct( guess  ,   self.eloss  )
myron's avatar
myron committed
627
        self.plot.addCurve(x=self.eloss, y=fit, legend = "guess", replace=False)
myron's avatar
myron committed
628
629
        self.guess=guess

Alessandro Mirone's avatar
Alessandro Mirone committed
630
631
632
633



        
myron's avatar
myron committed
634
635
    def do_fit(self):

myron's avatar
myron committed
636
637
638
639
        roisDef = self.plot.getCurvesRoiDockWidget().getRois()
        self.checkInputs()
        HFcore_shift = float(self.inputs[0].text())
        guess = [ float(tok.text())  for tok in self.inputs ][1:]
myron's avatar
myron committed
640

641
        
642
643
        result = removeCorePearson(guess,  self.eloss, self.y, roisDef,HFcore_shift, self.lw_ex, self.element, self.edge)
        guess = result["x"]
myron's avatar
myron committed
644
645
646
647
648
649
650
651
652
653

        self.lineEdit_A0.setText(str("%e"%guess[0]))
        self.lineEdit_A1.setText(str("%e"%guess[1]))
        self.lineEdit_A2.setText(str("%e"%guess[2]))
        self.lineEdit_A3.setText(str("%e"%guess[3]))
        self.lineEdit_A4.setText(str("%e"%guess[4]))
        self.lineEdit_A5.setText(str("%e"%guess[5]))
        self.lineEdit_A6.setText(str("%e"%guess[6]))
        
        self.plotta()
myron's avatar
myron committed
654
655
656
657
658
659
660
661
662
663
664

    def saveAnalysis_local(self):
        roisDef = self.plot.getCurvesRoiDockWidget().getRois()
        prefix =  str(self.controller.acquisition.lineEdit_outputPrefix.text())
        self.saveAnalysis_nogui( prefix, roisDef)

    def saveAnalysis(self, prefix):
        roisDef = self.plot.getCurvesRoiDockWidget().getRois()
        self.saveAnalysis_nogui( prefix, roisDef)
        
    def saveAnalysis_nogui(self, prefix, roisDef):
665
666
667
        y_tot=self.y
        eloss = self.eloss
        this_plot_def = roisDef
myron's avatar
myron committed
668

669
670
671
672
        fitfct_result = self.plotta(doplot=True)
        sqwav    =         (y_tot - fitfct_result.peapol)
        sqwaverr =         self.lw_ex.averrors
        allfit = fitfct_result.fit
myron's avatar
myron committed
673
674

        
675
676
        rangeOutput =[ this_plot_def["Output"].getFrom()  ,  this_plot_def["Output"].getTo()    ]
        rangeNorm =[ this_plot_def["Norm"].getFrom()  ,  this_plot_def["Norm"].getTo()    ]
677
678
        regionOutput = np.where(np.logical_and(eloss >= rangeOutput[0], eloss <= rangeOutput[1]))
                
myron's avatar
myron committed
679
        data = np.zeros((len(regionOutput[0]),3),"d")
680
681
682
683
        data[:,0] = eloss[regionOutput]
        data[:,1] = sqwav[regionOutput]
        data[:,2] = sqwaverr[regionOutput]
        
myron's avatar
myron committed
684
        regionNorm = np.where(np.logical_and(data[:,0] >= rangeNorm[0], data[:,0] <= rangeNorm[1]))
685

myron's avatar
myron committed
686
687
        if len(regionNorm):
            norm = np.trapz(data[regionNorm,1],data[regionNorm,0])
myron's avatar
myron committed
688
            print(" NORM ", norm)
myron's avatar
myron committed
689
690
            data[:,1] /= norm
            data[:,2] /= norm
691
        np.savetxt(prefix+"_"+self.name+".txt",data)
myron's avatar
myron committed
692

693
694
695
696
697
698
        data = np.zeros((len(eloss),4),"d")
        data[:,0] = eloss
        data[:,1] = y_tot
        data[:,2] = allfit 
        data[:,3] = fitfct_result.peapol
        # np.savetxt(prefix+"_"+self.name+"_all.txt",data)
myron's avatar
myron committed
699

myron's avatar
myron committed
700
        
701
702
        return

myron's avatar
myron committed
703

myron's avatar
myron committed
704
        
705
    def plotta(self, doplot=True):
myron's avatar
myron committed
706
707
        
        roisDef = self.plot.getCurvesRoiDockWidget().getRois()
708
        self.checkInputs()        
myron's avatar
myron committed
709
        HFcore_shift = float(self.inputs[0].text())
myron's avatar
myron committed
710
        guess = [ float(tok.text())  for tok in self.inputs ][1:]        
myron's avatar
myron committed
711
        HF_core = np.interp(self.eloss,self.eloss+HFcore_shift,self.lw_ex.av_C[self.element][self.edge])
myron's avatar
myron committed
712
713
714
        fitfct_result = functorObjectV( self.y, self.eloss,  HF_core   ) 
        fitfct_result(guess)

715
716
717
718
        if doplot:
            self.plot.addCurve(x=self.eloss, y=fitfct_result.fit, legend = "Fit(Pearson+linear+CoreHF)", replace=False)
            self.plot.addCurve(x=self.eloss, y=fitfct_result.hf_fit, legend = "Core HF", replace=False)
            self.plot.addCurve(x=self.eloss, y=fitfct_result.peapol, legend = "pea+pol", replace=False)
myron's avatar
myron committed
719
        
720
        return fitfct_result
myron's avatar
myron committed
721
        
Alessandro Mirone's avatar
Alessandro Mirone committed
722
723
724
725
726
    def on_rois_changed(self, message):
        print(" ROIS changed ", message, self.sender())



727

myron's avatar
myron committed
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
class functor2minim:
    def __init__(self, eloss, y):
        self.eloss=eloss
        self.y = y
        print(" ELOSS ===================================================================================")
        print( eloss)

    def funct(self, a,eloss):
        pear =  pearson7_zeroback(eloss,a)
        poly =  np.polyval(a[4:6],eloss   )
        tot = pear+poly
        return tot
        
    def __call__(self, a):
        tot = self.funct( a,  self.eloss)
        diff = self.y-tot
        res = (diff*diff/self.y).sum()
        print(" RETURN ", res)
        return res
Alessandro Mirone's avatar
Alessandro Mirone committed
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761


def pearson7_zeroback(x,a):
    """
    returns a pearson function but without y-offset
    a[0] = Peak position
    a[1] = FWHM
    a[2] = Shape, 1 = Lorentzian, infinite = Gaussian
    a[3] = Peak intensity
    """
    x = np.array(x)
    y = a[3] * (1.0+(2.0**(1.0/a[2])-1.0) * (2.0*(x-a[0])/a[1])**2.0)**(-a[2])
    return y


myron's avatar
myron committed
762
763
class myObject(object):
    pass
Alessandro Mirone's avatar
Alessandro Mirone committed
764

myron's avatar
myron committed
765
766
767
768
769
770
771
772
773
774
class functorObject:
    def __init__(self, y, eloss, hfcore):
        self.y      =  y
        self.eloss  =  eloss
        self.hfcore =  hfcore
    def __call__(self, x):
        pea = pearson7_zeroback(self.eloss,x[0:4])
        pol = np.polyval(x[4:6],self.eloss)
        hf  = self.hfcore*x[6]

myron's avatar
myron committed
775
776
        self.hf_fit = hf  ##
        self.fit = pea+pol+hf ##
777
778
        self.peapol=pea+pol
        
myron's avatar
myron committed
779
780
781
        diff = self.y-self.fit
        
        res  = (diff*diff/self.y).sum()
myron's avatar
myron committed
782

myron's avatar
myron committed
783
784
785
786
        # np.save( "Oeloss",self.eloss)
        # np.save( "Oy",self.y)
        # np.save( "Ohf",hf)
        # np.save( "Of" ,    +pea+pol+hf         )
myron's avatar
myron committed
787
        
myron's avatar
myron committed
788
789
        print(" RETURN  ",  res)
        return res
myron's avatar
myron committed
790
791
792
793
794
795
796
        
class functorObjectV:
    
    def __init__(self, y, eloss, hfcore):
        self.y      =  y
        self.eloss  =  eloss
        self.hfcore =  hfcore
myron's avatar
myron committed
797
798
799
800
801
802
803

    def funct(self, a,eloss):
        pear =  pearson7_zeroback(eloss,a)
        poly =  np.polyval(a[4:6],eloss   )
        tot = pear+poly
        return tot

myron's avatar
myron committed
804
805
806
807
        
    def __call__(self, x):
        
        pea = pearson7_zeroback(self.eloss,x[0:4])
myron's avatar
myron committed
808
809
810
811
812
813
        if len(x)==7:
            pol = np.polyval(x[4:6],self.eloss)
            hf  = self.hfcore*x[6]
        else:
            pol=0
            hf=0
myron's avatar
myron committed
814

Alessandro Mirone's avatar
Alessandro Mirone committed
815

myron's avatar
myron committed
816
817
        self.hf_fit = hf  ##
        self.fit = pea+pol+hf ##
818
        self.peapol = pea+pol
myron's avatar
myron committed
819
820
821
        
        diff = self.y-self.fit
        res  = diff/np.sqrt(self.y)
Alessandro Mirone's avatar
Alessandro Mirone committed
822

myron's avatar
myron committed
823
824
825
826
827
828
        # np.save( "Oeloss",self.eloss)
        # np.save( "Oy",self.y)
        # np.save( "Ohf",hf)
        # np.save( "Of" ,    +pea+pol+hf         )
        
        return res
829
830

def removeCorePearson(guess,  eloss, y_tot, roisDef,HFcore_shift, lw_ex, element, edge):
831
832
    range1 =[ roisDef["range1"].getFrom()  ,   roisDef["range1"].getTo()  ]
    range2 =[ roisDef["range2"].getFrom()  ,   roisDef["range2"].getTo()  ]
833
834
835
836
    region1 = np.where(np.logical_and(eloss >= range1[0], eloss <= range1[1]))
    region2 = np.where(np.logical_and(eloss >= range2[0], eloss <= range2[1]))
    region  = np.append(region1,region2)
    HF_core = np.interp(eloss,eloss+HFcore_shift,lw_ex.av_C[element][edge])
837
838
839
    
    print(" qui y_tot all inizio di removecorepearson est " , y_tot)
    
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
    fact = y_tot[region].max()
    guess[3] /=fact
    guess[4] /=fact
    guess[5] /=fact
    guess[6] /=fact
    y=y_tot/fact
    y_reg1 = y[region1]
    eloss_reg1 = eloss[region1]
    HF_core_reg1 = HF_core[region1]
    y_reg2 = y[region2]
    eloss_reg2 = eloss[region2]
    HF_core_reg2 = HF_core[region2]
    y_reg = y[region]
    eloss_reg = eloss[region]
    HF_core_reg = HF_core[region]
    fitfct = functorObjectV( y_reg, eloss_reg,  HF_core_reg   ) 
    bndsa = [ -np.inf]+ [ 0  for tmp in range(6)]
    bndsa[5]=-np.inf
    bndsb =  [ np.inf for tmp in range(7)]
    soluzione    = optimize.least_squares(fitfct, guess, method='trf', bounds=[bndsa,bndsb] ) # constraints=cons)
    guess = soluzione.x
    print ( "RISULTATO ", soluzione)
myron's avatar
myron committed
862
863
864
865
    guess[3] *=fact
    guess[4] *=fact
    guess[5] *=fact
    guess[6] *=fact
866
867
868
869
    fitfct_result = functorObjectV( y_tot, eloss,  HF_core   ) 
    fitfct_result(guess)
    result = {}
    result["x"] = guess
myron's avatar
myron committed
870
    return result
myron's avatar
myron committed
871
872


873
874
875
876
877
878
879
880
881
882
883
884
885
886
def batch( filename):
    d = yaml.load(open(filename,"r"), yaml.Loader)

    selected_scans_d = d["selected_scans"]
    selected_scans = []
    for name, scan in selected_scans_d.items():
        selected_scans.append( [name]+scan)

    selected_subsets_d = d["selected_subsets"]
    selected_subsets = []
    for name, subset in selected_subsets_d.items():
        selected_subsets.append( [subset[0],name]+subset[1:])

    selected_acquisition_d = d["selected_acquisition"]
myron's avatar
myron committed
887
888
889
890
891

    if selected_acquisition_d["output_prefix"] is None:
        selected_acquisition_d["output_prefix"] = ""
    
    
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
    names = [ "method", "refscan", "include_elastic", "output_prefix"]
    selected_acquisition =  [     selected_acquisition_d[name] for name in names    ]
        
    selected_experiment_d = d["selected_experiment"]
    names = [ "specfile_name" , "roifile_address" ]
    selected_experiment =  [     selected_experiment_d[name] for name in names    ]

    lw, roinums = integrate( selected_experiment[0], selected_experiment[1]  ,  selected_scans, selected_subsets, selected_acquisition  ) 


    selected_edges_d = d["selected_edges"]
    formula, edges = selected_edges_d["formula"] , selected_edges_d["edges"]
    if len(edges)!=1:
        raise Exception(" So far only one edge can be processed")
    element = list(edges.keys())[0]
    if len(edges[element])!=1:
        raise Exception(" So far only one edge can be processed")
    else:
        edge = edges[element][0]
        
    forms=[]
    weights=[]
    for f,ww in formula:
        forms.append(f)
        weights.append(float(ww) )


myron's avatar
myron committed
919
920
921
922
    if "plots" in d:
        plots_def = d["plots"]
    else:
        plots_def = {}
923
924
925
926
927
928
929
930
        
    for iplot,subset in enumerate(selected_subsets):
        scal = subset[0]
        name = subset[1]
        nums = subset[2:]

        if name not in plots_def:
            continue
myron's avatar
myron committed
931
932

        this_plot_def = plots_def [name]
933
934
935
936
937
938
939
940
        
        nums = [ i for i in range(len(roinums)) if roinums[i] in nums ]        
        lw_ex = xrs_extraction.edge_extraction( lw,forms,weights,{element:edge})
        lw_ex.analyzerAverage(nums, errorweighing=False)
        
        eloss = lw_ex.eloss

        
myron's avatar
myron committed
941
942
        range1 =[ this_plot_def["range1"][0]  ,  this_plot_def["range1"][1]    ]
        range2 =[ this_plot_def["range2"][0]  ,  this_plot_def["range2"][1]    ]        
943
944
945
946
        region1 = np.where(np.logical_and(eloss >= range1[0], eloss <= range1[1]))
        region2 = np.where(np.logical_and(eloss >= range2[0], eloss <= range2[1]))
        region  = np.append(region1,region2)

myron's avatar
myron committed
947
        HFcore_shift = this_plot_def["hfcore_shift"]
948
        HF_core = np.interp(eloss,eloss+HFcore_shift,lw_ex.av_C[element][edge])
myron's avatar
myron committed
949
        guess = [ this_plot_def[k] for k in ["pea_center","pea_width","pea_shape","pea_height","lin_back0","lin_back1","hf_factor"]    ]
950
        
myron's avatar
myron committed
951
        y_tot = np.maximum(1.0e-10 , lw_ex.avsignals)
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
        fact = y_tot[region].max()
        guess[3] /=fact
        guess[4] /=fact
        guess[5] /=fact
        guess[6] /=fact

        y=y_tot/fact
        
        y_reg1 = y[region1]
        eloss_reg1 = eloss[region1]
        HF_core_reg1 = HF_core[region1]
        
        y_reg2 = y[region2]
        eloss_reg2 = eloss[region2]
        HF_core_reg2 = HF_core[region2]
        
        y_reg = y[region]
        eloss_reg = eloss[region]
        HF_core_reg = HF_core[region]
        
        fitfct = functorObjectV( y_reg, eloss_reg,  HF_core_reg   ) 
        bndsa = [ -np.inf]+ [ 0  for tmp in range(6)]
        bndsa[5]=-np.inf
        bndsb =  [ np.inf for tmp in range(7)]
        soluzione    = optimize.least_squares(fitfct, guess, method='trf', bounds=[bndsa,bndsb] ) # constraints=cons)
        guess = soluzione.x
        print ( "RISULTATO ", soluzione)
        
980
981
982
983
984
985
        guess[3] *=fact
        guess[4] *=fact
        guess[5] *=fact
        guess[6] *=fact
        y=y*fact

986
        
987
        fitfct_result = functorObjectV( y, eloss,  HF_core   ) 
988
        fitfct_result(guess)
myron's avatar
myron committed
989

990
991
992
993
        all4plot      =         (y )
        fit4plot      =         (fitfct_result.fit)
        sqwav    =         (y - fitfct_result.peapol)
        sqwaverr =         lw_ex.averrors
myron's avatar
myron committed
994
995
996
997
998
999
1000

        rangeOutput =[ this_plot_def["Output"][0]  ,  this_plot_def["Output"][1]    ]
        rangeNorm =[ this_plot_def["Norm"][0]  ,  this_plot_def["Norm"][1]    ]
        regionOutput = np.where(np.logical_and(eloss >= rangeOutput[0], eloss <= rangeOutput[1]))
        
        
        data = np.zeros((len(regionOutput[0]),3),"d")