roiSelectionWidget.py 45.6 KB
Newer Older
1
2
3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
myron's avatar
myron committed
4
5
6
# from  PyQt4 import Qt, QtCore
from silx.gui import qt as Qt
from silx.gui import qt as QtCore
Alessandro Mirone's avatar
Alessandro Mirone committed
7
# from . import ui
8
9
import os
import PyMca5.PyMcaIO.EdfFile as edf
Alessandro MIRONE's avatar
Alessandro MIRONE committed
10
import PyMca5
11

12
import PyMca5.PyMcaIO.specfilewrapper as specfile
13
14
from . import localfilesdialog
from . import myMaskImageWidget
15
16

import numpy
17
import string
18
19
20
import six
from six.moves import range
from six.moves import zip
21

22
from . import xrs_rois
Alessandro Mirone's avatar
Alessandro Mirone committed
23
from . import xrs_utilities
24

25
26
from . import spotdetection
from . import match
Alessandro MIRONE's avatar
Alessandro MIRONE committed
27
import pickle
myron's avatar
myron committed
28
import h5py
Alessandro Mirone's avatar
Alessandro Mirone committed
29
30
from  XRStools.installation_dir import installation_dir

Alessandro Mirone's avatar
Alessandro Mirone committed
31
SKIP_WARNING = False
Alessandro MIRONE's avatar
Alessandro MIRONE committed
32

operator for beamline's avatar
operator for beamline committed
33
FASTDEBUG=False
Alessandro MIRONE's avatar
Alessandro MIRONE committed
34
35
36
try:
    import PyTango
except:
Alessandro Mirone's avatar
Alessandro Mirone committed
37
    print( " Could not load PyTango")
Alessandro MIRONE's avatar
Alessandro MIRONE committed
38

39

Alessandro Mirone's avatar
Alessandro Mirone committed
40
41
42
43
44
45
def h5_assign_force(h5group, name, item):
    if name in h5group:
        del h5group[name]
    h5group[name] = item


Alessandro Mirone's avatar
Alessandro Mirone committed
46
# @ui.UILoadable
47
48
class spotdetectioncontrol(Qt.QDockWidget):
    def __init__(self, parent,flag,  detectionCallBack=None,  fatteningCallBack=None,
49
                 thresholdCallBack=None,
50
51
52
                 annotateMaskCallBack=None,    relabeliseMaskCallBack=None,
                 resetMask           = None):

Alessandro Mirone's avatar
Alessandro Mirone committed
53
54
55
56
57
58
59

              
        super(spotdetectioncontrol , self).__init__(parent)
        Qt.loadUi(  os.path.join(  installation_dir,"resources" ,  "spotdetectioncontrol.ui" ), self)
        
        # Qt.QDialog.__init__(self, parent, flag)
        # self.loadUi()  # load the ui file
60

61
        self.detectionButton .setToolTip("Run a Canny edge detection. If threshold entry contains a float >0 and <1,\n then all pixel <threshold*maxval are set to zero beforehand." )
alex mirone's avatar
alex mirone committed
62
        self.HoughDetection  .setToolTip("Run a specialised  Canny edge detection for LINES. If threshold entry contains a float >0 and <1 ,\nthe  all pixel <threshold*maxval are set to zero beforehand." )
63
64
        self.thresholdButton .setToolTip("Use this for existing ROIs : ROIs is regenerated starting from its maximum  and expanding till threshold*maxvalue"  )
        
Alessandro Mirone's avatar
Alessandro Mirone committed
65
66
67
68
69
70
        # self.detectionButton.clicked.connect(detectionCallBack)
        self.detectionCallBack = detectionCallBack
        self.detectionButton.clicked.connect(self.my_detectionCallBack)


        
71
72
73
74
        self.HoughDetection.clicked.connect(self.my_HoughCallBack)


        
75
76
77
78
79
        # self.fatteningSpinBox.valueChanged[int].connect(fatteningCallBack)

        self.fatteningCallBack = fatteningCallBack
        self.inflateButton.clicked.connect(self.callcallback)

80
81
82
83
84

        self.thresholdCallBack = thresholdCallBack
        self.thresholdButton.clicked.connect(self.callThrecallback)


85
86
87
        self.annotateButton.clicked.connect(annotateMaskCallBack)
        self.relabeliseButton.clicked.connect(relabeliseMaskCallBack)
        self.resetButton.clicked.connect(resetMask)
88

89
        self.geo_informations = None
Alessandro Mirone's avatar
Alessandro Mirone committed
90
91
92
93
94
        
    def my_detectionCallBack(self):
        thr_s =  str(self.thresholdEdit.text())
        self.detectionCallBack(thr_s = thr_s)
        
95
96
97
98
    def my_HoughCallBack(self):
        thr_s =  str(self.thresholdEdit.text())
        self.detectionCallBack(thr_s = thr_s, Hough=True)
        
99

100
    def callThrecallback(self):
Alessandro Mirone's avatar
Alessandro Mirone committed
101
102
        print( self.thresholdEdit.text())
        print( str(self.thresholdEdit.text()))
103
104
        # value= string.atof(str(self.thresholdEdit.text()))
        value= float(str(self.thresholdEdit.text()))
105
        self.thresholdCallBack(value)
106
107
108
109
110

    def callcallback(self):
        value= self.fatteningSpinBox.value()
        self.fatteningCallBack(value)
   
Alessandro Mirone's avatar
Alessandro Mirone committed
111
# @ui.UILoadable
112
class imageview(Qt.QWidget):
Alessandro Mirone's avatar
Alessandro Mirone committed
113
    all_layouts=[]
114
115
    def __init__(self, parent=None, isglobal=False, layoutsNames =None):

Alessandro Mirone's avatar
Alessandro Mirone committed
116
117
118
119
120
121
122
123
              
        super(imageview, self).__init__(parent)
        Qt.loadUi(  os.path.join(  installation_dir,"resources" ,  "imageview.ui" ), self)

        
        # Qt.QWidget.__init__(self, parent)
        # self.loadUi()  # load the ui file
        
alex's avatar
alex committed
124
        print(  layoutsNames  ) 
125
        if not isglobal:
126
            self.registeringLayoutComboBox.addItems( layoutsNames     )
Alessandro Mirone's avatar
Alessandro Mirone committed
127
128
            self.all_layouts.append(self.registeringLayoutComboBox)
        else:
129
            self.registeringLayoutComboBox.addItems( layoutsNames )
Alessandro Mirone's avatar
Alessandro Mirone committed
130
131
132
133
134
            self.registeringLayoutComboBox.currentIndexChanged.connect(self.changeAll)
    
    def changeAll(self,index):
        for t in self.all_layouts:
            t.setCurrentIndex(index)
135

136
            
137
   
Alessandro Mirone's avatar
Alessandro Mirone committed
138
# @ui.UILoadable
139
140
141
class spotregistrationcontrol(Qt.QDockWidget):
    def __init__(self, parent,flag,  globregistrationCallBack=None,
                 registrationCallBack=None):
Alessandro Mirone's avatar
Alessandro Mirone committed
142
143
144


              
Alessandro Mirone's avatar
Alessandro Mirone committed
145
        super( spotregistrationcontrol, self).__init__(parent)
Alessandro Mirone's avatar
Alessandro Mirone committed
146
147
148
149
        Qt.loadUi(  os.path.join(  installation_dir,"resources" ,  "spotregistrationcontrol.ui" ), self)
   
        # Qt.QDialog.__init__(self, parent, flag)
        # self.loadUi()  # load the ui file
150
151
152
153
154
155
156
157
        
        self.globregistrationButton.clicked.connect(globregistrationCallBack)
        self.registrationButton.clicked.connect(registrationCallBack)

        self.tableWidget.setRowCount(3)
        self.tableWidget.setColumnCount(4)
        count=1
        for n in range(1,12+1):
158
            self.tableWidget.setItem( 2-(n-1)//4,(n-1)%4,  Qt.QTableWidgetItem("%d"%n))
159
160
161

        self.tableWidget.resizeColumnsToContents()

Alessandro MIRONE's avatar
Alessandro MIRONE committed
162
163
164
165
        def _mousePressEvent( event):
            """ in case of problems, generate the code for spotregistrationcontrol from ui
                and reimplement it as a class method """

Alessandro Mirone's avatar
Alessandro Mirone committed
166
167
168
            print( " evento at ", event.pos())
            print( "  widget ",   self.tableWidget.itemAt( event.pos()))
            print(    self.tableWidget.itemAt( event.pos()).text())
Alessandro MIRONE's avatar
Alessandro MIRONE committed
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184


            drag      =  Qt.QDrag(   self.tableWidget)
            mimeData  =  Qt.QMimeData()

            mimeData.setText( self.tableWidget.itemAt( event.pos()).text()   );
            drag.setMimeData(mimeData)
            ## iconPixmap = Qt.QPixmap(_cross_data)
            ## drag.setPixmap(iconPixmap)

            dropAction = drag.exec_();


        self.tableWidget.mousePressEvent = _mousePressEvent
        

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
class MyTableModel(Qt.QAbstractTableModel):
    def __init__(self, parent, mylist, header, *args):
        Qt.QAbstractTableModel.__init__(self, parent, *args)
        self.mylist = mylist
        self.header = header
    def rowCount(self, parent):
        return len(self.mylist)
    def columnCount(self, parent):
        return len(self.mylist[0])
    def data(self, index, role):
        if not index.isValid():
            return None
        # elif role != Qt.DisplayRole:
        #     return None
        return self.mylist[index.row()][index.column()]
    def headerData(self, col, orientation, role):
        # if orientation == Qt.Horizontal and role == Qt.DisplayRole:
        #     return self.header[col]
        return None
    # def sort(self, col, order):
    #     """sort table by given column number col"""
    #     self.emit(SIGNAL("layoutAboutToBeChanged()"))
    #     self.mylist = sorted(self.mylist,
    #         key=operator.itemgetter(col))
    #     if order == Qt.DescendingOrder:
    #         self.mylist.reverse()
    #     self.emit(SIGNAL("layoutChanged()"))


214
    
Alessandro Mirone's avatar
Alessandro Mirone committed
215
# @ui.UILoadable
216
class mainwindow(Qt.QMainWindow):
operator for beamline's avatar
operator for beamline committed
217
    user_input_signal = QtCore.pyqtSignal(object)
Alessandro Mirone's avatar
Alessandro Mirone committed
218
    def __init__(self, parent=None, labelformat="ROI%02d",layout="2X3-12"):
Alessandro Mirone's avatar
Alessandro Mirone committed
219
220
221
222
      
        super(mainwindow, self).__init__(parent)

        Qt.loadUi(  os.path.join(  installation_dir,"resources" ,  "mainwindow.ui" ), self)
myron's avatar
myron committed
223
224
225

        self.geo_informations=None
        self.isOK=0
226
227
        self.labelformat = labelformat

Alessandro Mirone's avatar
Alessandro Mirone committed
228
        self.layout=layout
229
        self.image=None
Alessandro Mirone's avatar
Alessandro Mirone committed
230
        
231
232


233
        # self.actionLoad.triggered.connect(self.LoadRemote )
234
235
236
        self.actionSelectScanFiles.triggered.connect(self.LoadLocal)
        self.actionSpot_detection.triggered.connect(self.CreateSpotDetectionDockWidget)
        self.actionGlobalSpotDetection.triggered.connect(self.CreateGlobalSpotDetectionDockWidget)
237
238
239
240
241
242
        self.showIsData = True
        # self.actionShowDatas.triggered.connect(self.showDatas)
        # self.actionShowMasks.triggered.connect(self.showMasks)
        self.actionShowDatas.triggered.connect(self.showToggle)
        # self.actionShowMasks.triggered.connect(self.showToggle)

243
244
245
        self.actionRegistration.triggered.connect(self.CreateRegistrationWidget)


Alessandro MIRONE's avatar
Alessandro MIRONE committed
246
247
248
        self.actionWrite_mask_on_file.triggered.connect(  self.write_mask_on_file  )
        self.actionLoad_mask_from_file.triggered.connect(  self.read_mask_from_file  )
        ## self.actionRemote_load.triggered.connect(  self.remoteMaskload  )
Alessandro Mirone's avatar
Alessandro Mirone committed
249
        self.actionRemote_load.triggered.connect(  self.remoteMaskload  )
Alessandro MIRONE's avatar
Alessandro MIRONE committed
250
        self.actionPush_mask_remotely.triggered.connect(  self.PushMask  )
251
252
253
        self.actionWrite_masksDict_on_file.triggered.connect(  self.write_masksDict_on_file  )
        self.actionLoad_masksDict_from_file.triggered.connect(  self.load_masksDict_from_file  )
        
Alessandro MIRONE's avatar
Alessandro MIRONE committed
254
        
myron's avatar
myron committed
255
256
257
258
259
260
        self.actionExit.triggered.connect(self.Exit)
        self.actionConfirm_And_Exit.triggered.connect(self.confirm_and_Exit)

        self.actionLoad_image_from_hdf5.triggered.connect(self.load_image_from_hdf5)

        self.actionLoad_maskDict_from_hdf5.triggered.connect(self.load_maskDict_from_hdf5)
261
        self.actionWrite_maskDict_to_hdf5.triggered.connect(self.write_maskDict_to_hdf5)
myron's avatar
myron committed
262

263
        self.load_user_input = {}
myron's avatar
myron committed
264
265
266
267
268
269

    def Exit(self):
        self.isOK=0
        self.close()
    def confirm_and_Exit(self):
        self.isOK=1
270
        self.roiobj_returned = self.getRoiObj()      
myron's avatar
myron committed
271
272
        self.close()

Alessandro MIRONE's avatar
Alessandro MIRONE committed
273
274
275
276
277
    def remoteMaskload(self):
        ## 
        pathtolima = "id20/xrs/mpx-ram"
        dev = PyTango.DeviceProxy(pathtolima ) 

Alessandro Mirone's avatar
Alessandro Mirone committed
278
        string =dev.getRoifrompickle()
279
280
        masks = pickle.loads(string)
        masksDict = self.masks2MasksDict(masks)
Alessandro MIRONE's avatar
Alessandro MIRONE committed
281

282
        self.load_masksDict(masksDict)
Alessandro MIRONE's avatar
Alessandro MIRONE committed
283
284
285
286
            

    def PushMask(self):
        ## 
287
 
Alessandro Mirone's avatar
Alessandro Mirone committed
288
        masks = self.getMasks()
Alessandro MIRONE's avatar
Alessandro MIRONE committed
289

290
291
292
293
294
295
296
297
        correspondance = self.getLabelCorrespondance()

        new_masks = []
        for m in masks:
            new_masks.append(  ( correspondance[m[0]-1], m[1],m[2])   )
        masks = new_masks
    
        
alex's avatar
alex committed
298
299
        print( " de mainWindow je vais pusher : " , masks)
        print( " ========================================" )
Alessandro MIRONE's avatar
Alessandro MIRONE committed
300
        masks_string = pickle.dumps(masks)
301
302
303
304
        
        pathtolima = "id20/xrs/mpx-ram"
        dev = PyTango.DeviceProxy(pathtolima ) 
        # open("mask","w").write(masks_string)
Alessandro MIRONE's avatar
Alessandro MIRONE committed
305
306
        dev.setRoifromPickle( masks_string  )

307
    def getMasks(self) :
308
        totnofrois, gmask = self.recomposeGlobalMask()
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
        globalMask = self.mws[0].getSelectionMask().astype("i")
        masks = [] 
        nrois = globalMask.max()
        nummaxroi = (globalMask).max()
        masks = []
        for n in range(1,totnofrois +1):
            rawindices = numpy.nonzero( globalMask == n )
            if(len(rawindices)):
                if(len(rawindices[0])):
                    Y1 = rawindices[0].min()
                    Y2 = rawindices[0].max()+1
                    X1 = rawindices[1].min()
                    X2 = rawindices[1].max()+1
                    submask = (globalMask[Y1:Y2, X1:X2 ] == n).astype("i")
                    # submask = (globalMask[Y1:Y2, X1:X2 ] / n).astype("i"
                    masks.append(  ( n, [Y1,X1], submask  )  )
            else:
                masks.append(  ( n, [-1,-1], numpy.array([[1]])  )  )
        return masks

Alessandro Mirone's avatar
Alessandro Mirone committed
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
    # def getMasks(self) :
    #     totnofrois = self.recomposeGlobalMask()
    #     globalMask = self.mws[0].getSelectionMask().astype("i")
    #     masks = [] 
    #     nrois = globalMask.max()
    #     nummaxroi = (globalMask).max()
    #     masks = []
    #     for n in range(1, nummaxroi+1):
    #         rawindices = numpy.nonzero( globalMask == n )
    #         if(len(rawindices)):
    #             if(len(rawindices[0])):
    #                 Y1 = rawindices[0].min()
    #                 Y2 = rawindices[0].max()+1
    #                 X1 = rawindices[1].min()
    #                 X2 = rawindices[1].max()+1
    #                 submask = (globalMask[Y1:Y2, X1:X2 ] == n).astype("i")
    #                 masks.append(  ( n, [Y1,X1], submask  )  )
    #     return masks
347

348
349
350
351
    def getRoiObj(self):
        
        roiob=xrs_rois.roi_object()
        if self.image is not None:
Cavallari's avatar
Cavallari committed
352
            roiob.load_rois_fromMasksDict( self.getMasksDict(), newshape = self.image.shape )
353
            roiob.input_image = self.image
Cavallari's avatar
Cavallari committed
354
        return roiob
355

356

mirone's avatar
mirone committed
357
    def write_maskDict_to_hdf5(self, fn=None):
myron's avatar
myron committed
358
        if(not fn ) :
mirone's avatar
mirone committed
359
360
361
362
363
364
            filename =  (Qt.QFileDialog.getSaveFileName())
            if isinstance(filename, tuple):
                filename = str(filename[0])
        else:
            filename = fn
            
365
        if filename is None:
366
367
            return
        
mirone's avatar
mirone committed
368
        self.load_user_input ["roi"]= str(filename)+":/roi_from_selector/"
369
370
371

        self.user_input_signal.emit( self.load_user_input  )
        
mirone's avatar
mirone committed
372
        self.saveMaskDictOnH5( str(filename)+":/roi_from_selector/"  )
373

374
    ## w4r.load_maskDict_from_givenhdf5andgroup(roiaddress[0], roiaddress[1] )
Alessandro Mirone's avatar
Alessandro Mirone committed
375
    def  saveMaskDictOnH5( self, roiaddress, masktype ="ROI" , filterMask = None ) :
myron's avatar
API ok    
myron committed
376
377
        
        if not ( isinstance(roiaddress , list) or isinstance(roiaddress, tuple) ):
378
            roiaddress =   xrs_utilities.split_hdf5_address( roiaddress )
myron's avatar
API ok    
myron committed
379
                 
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
        h5=h5py.File(roiaddress[0],'a')
        image4roi = self.image
        if  masktype=="ROI":
            h5.require_group(roiaddress[1]+"/rois_definition")
            h5group =  h5[roiaddress[1]+"/rois_definition"]
        else:
            h5.require_group(roiaddress[1])
            h5group =  h5[roiaddress[1]]
        README="""image : the image upon which the rois have been selected
        rois_dict : a directory contain for each selected roi a subdirectory with the rois mask and its bottomleft corener position.
        """
        h5_assign_force(h5group , "image" , image4roi   )
        h5_assign_force(h5group , "README" , README   )
        if masktype=="ROI":
            masks = self.getMasksDict()
            h5group.require_group("rois_dict")
            h5group=h5group["rois_dict"]
            # remove all previous ROIS from h5group
            for key in h5group:
                del h5group[key]
Alessandro Mirone's avatar
Alessandro Mirone committed
400
                
Alessandro Mirone's avatar
Alessandro Mirone committed
401
            ### filterMask = None
402
403
404
405
406
407
408
409
410
411
412
413
            xrs_rois.write_rois_toh5(h5group, self.getMasksDict(), filterMask=filterMask )
        else:
            totnrois, filtermask  =  self.recomposeGlobalMask()
            filtermask = np.equal(0,filtermask).astype("i")
            h5_assign_force( h5group,"filter",  filtermask)
        h5.flush()
        h5.close()





414
    
415
416
    def getMasksDict(self) :
        masks = self.getMasks()
417
418
419
        return self.masks2MasksDict(masks)

    def masks2MasksDict(self,masks):
420
421
        masksDict={}
        for m in masks:
Alessandro Mirone's avatar
Alessandro Mirone committed
422
423
            if(m[1][0]>=0 and m[1][1]>=0  ):
                masksDict[ self.labelformat% (m[0]-1)  ]=[m[1],m[2]]
424
        return masksDict
Alessandro MIRONE's avatar
Alessandro MIRONE committed
425
426
427
428
429
430
431
432
433
434
435
        


    def recomposeGlobalMask(self):
      offset=0
      globalMask = self.mws[0].getSelectionMask().astype("i")
      for (name,geo,nofrois), mw in    zip(self.names_geos_nofrois[:], self.mws[1:]):
          localmask = numpy.less(0,mw.getSelectionMask() ) 
          globalMask[geo] =  offset*localmask +  mw.getSelectionMask()
          offset += nofrois
      self.mws[0].setSelectionMask(globalMask  )
436
      return offset, globalMask
Alessandro MIRONE's avatar
Alessandro MIRONE committed
437
438
439
440
441
442
443
444
445
446
447
448
449
450

    
    def decomposeGlobalMask(self):
      offset=0
      globalMask = self.mws[0].getSelectionMask().astype("i")
      for (name,geo,nofrois), mw in    zip(self.names_geos_nofrois[:], self.mws[1:]):
          localmask = numpy.less(0,globalMask[geo]  ) 
          Mask =    globalMask[geo] - offset *localmask
          offset += nofrois
          mw.setSelectionMask(Mask  )
          

    def write_mask_on_file(self):
        filename =  Qt.QFileDialog.getSaveFileName()
451
452
        if isinstance(filename, tuple):
            filename = filename[0]
Alessandro Mirone's avatar
Alessandro Mirone committed
453
        print( filename)
Alessandro MIRONE's avatar
Alessandro MIRONE committed
454
455
456
457
458
459
460
        if filename is not None:
            filename=str(filename)
            self.recomposeGlobalMask()
            globalMask = self.mws[0].getSelectionMask().astype("i")
            ef = edf.EdfFile( filename, "w+")
            ef.WriteImage( {}, globalMask )

461
462
    def write_masksDict_on_file(self):
        filename =  Qt.QFileDialog.getSaveFileName()
463
464
        if isinstance(filename, tuple):
            filename = filename[0]
465
466

        
Alessandro Mirone's avatar
Alessandro Mirone committed
467
        print( filename)
468
469
        if filename is not None:
            filename=str(filename)
Alessandro Mirone's avatar
Alessandro Mirone committed
470
            masksDict = self.getMasksDict()
471
472
473
474
475
476
477
            filename=str(filename)
            f = open(filename, 'wb')
            pickle.dump(masksDict ,  f)
            f.close()
            
    def load_masksDict_from_file(self):
        filename =  Qt.QFileDialog.getOpenFileName()
478
        if isinstance(filename, tuple):
479
            filename = filename[0]
480

Alessandro Mirone's avatar
Alessandro Mirone committed
481
        print( filename)
482
483
484
485
486
        if filename is not None:
            filename=str(filename)
            f = open(filename, 'rb')
            masksDict = pickle.load( f)
            f.close()
Alessandro Mirone's avatar
Alessandro Mirone committed
487
488
489
490
            self.load_masksDict( masksDict)


    def load_masksDict(self, masksDict):
491
492
493
494
495
496
            self.recomposeGlobalMask()
            mask  = self.mws[0].getSelectionMask().astype("i")
            mask[:]=0
            mask =   convert_redmatrix_to_matrix(masksDict,mask, offsetX=0, offsetY=0)
            self.mws[0].setSelectionMask(mask)
            self.decomposeGlobalMask()
497
498
            self.annotateAllMasksCallBack()

Alessandro MIRONE's avatar
Alessandro MIRONE committed
499
500
501

    def read_mask_from_file(self):
        filename =  Qt.QFileDialog.getOpenFileName()
502
        if isinstance(filename, tuple):
503
            filename = filename[0]
504

Alessandro MIRONE's avatar
Alessandro MIRONE committed
505
506
507
508
509
510
511
        if filename is not None:
            filename=str(filename)
            ef = edf.EdfFile( filename, "r")
            mask = ef.GetData(0)
            self.recomposeGlobalMask()
            self.mws[0].setSelectionMask(mask)
            self.decomposeGlobalMask()
512
513
514



515
 
516
    def detectionCallBack(self, thr_s="", Hough=False):
Alessandro Mirone's avatar
Alessandro Mirone committed
517
        print( " in  detectionCallBack, Hough " , Hough)
518
        itab =  self.viewsTab.currentIndex()
519
520
521
        if itab==0:
            return 
        
522
        globalMask = self.mws[0].getSelectionMask().astype("i")
Alessandro Mirone's avatar
Alessandro Mirone committed
523
524
        roiroiMask = self.roiroiw.getSelectionMask().astype("i")
        
525
526
527
528
529
        offset=0
        for (name,geo,nofrois), mw in    zip(self.names_geos_nofrois[:itab-1], self.mws[1:itab]):
            offset += nofrois

        (name,geo,nofrois), mw   =     self.names_geos_nofrois[itab-1], self.mws[itab]
Alessandro Mirone's avatar
Alessandro Mirone committed
530
        self.detectSpotsSubMask( name,geo,nofrois, mw  , globalMask , roiroiMask, offset,thr_s=thr_s , Hough=Hough  )
531
532
        self.mws[0].setSelectionMask( globalMask )

533

534
535
    def get_geo(self):
        if self.geo_informations is None:
Alessandro Mirone's avatar
Alessandro Mirone committed
536
            subset_infos = xrs_rois.get_geo_informations( (self.image.shape+(self.layout,) ) )
537
        else:
Alessandro Mirone's avatar
Alessandro Mirone committed
538
539
540
541
            subset_infos = self.geo_informations


        dl = subset_infos["analyser_nIDs"]
542
        dl1k = list(dl[list(dl.keys())[0]].keys())
Alessandro Mirone's avatar
Alessandro Mirone committed
543
544
545
546
        if len(dl1k)==1:
            for t in imageview.all_layouts:
                t.setCurrentIndex(1)
                
547
        return subset_infos
548

549
550
551
552
553
554
555
556
557
558
559
560
561
562
563

    def getLabelCorrespondance(self):
        res = []
        itab=1
        # print " CORRESPONDANCE "
        # print self.mws[1:]
        # print self.names_geos_nofrois[:]
        
        for (name,geo,nofrois), mw in    zip(self.names_geos_nofrois[:], self.mws[1:]):
            subset_infos = self.get_geo()
            if "3x4" in str(self.layouts[itab].currentText() ):
                a_ids = subset_infos["analyser_nIDs"][ subset_infos["subnames"][itab-1]] ["3x4"]
            else:
                a_ids = subset_infos["analyser_nIDs"][ subset_infos["subnames"][itab-1]] ["Vertical"]
 
564
565
            # res.extend(list(numpy.array(a_ids) +len(res) ))
            res.extend(list(numpy.array(range(1,1+12) ) +len(res) ))
566
567
568
569
            # print " res "  ,res
            itab+=1
        return res
    
570
571
572
    def annotateOneMaskCallBack(self):
        itab =  self.viewsTab.currentIndex()     
        if itab>0:
573
            subset_infos = self.get_geo()
Alessandro MIRONE's avatar
Alessandro MIRONE committed
574
575
576
577
578
579

            if "3x4" in str(self.layouts[itab].currentText() ):
                a_ids = subset_infos["analyser_nIDs"][ subset_infos["subnames"][itab-1]] ["3x4"]
            else:
                a_ids = subset_infos["analyser_nIDs"][ subset_infos["subnames"][itab-1]] ["Vertical"]

580
            self.mws[itab].annotateSpots( a_ids, self.get_offset(  itab ) )
581
582

    def annotateAllMasksCallBack(self):
Alessandro MIRONE's avatar
Alessandro MIRONE committed
583
        itab=1
584
        for (name,geo,nofrois), mw in    zip(self.names_geos_nofrois[:], self.mws[1:]):
Alessandro MIRONE's avatar
Alessandro MIRONE committed
585

586
            subset_infos = self.get_geo()
Alessandro MIRONE's avatar
Alessandro MIRONE committed
587
588
589
590
591
            if "3x4" in str(self.layouts[itab].currentText() ):
                a_ids = subset_infos["analyser_nIDs"][ subset_infos["subnames"][itab-1]] ["3x4"]
            else:
                a_ids = subset_infos["analyser_nIDs"][ subset_infos["subnames"][itab-1]] ["Vertical"]

592
            mw.annotateSpots( a_ids, self.get_offset(itab) )
Alessandro MIRONE's avatar
Alessandro MIRONE committed
593
            itab+=1
594

595
596
597
598
599
600
    def get_offset(self,itab):
        offset=0
        for (name,geo,nofrois), mw in    zip(self.names_geos_nofrois[:itab-1], self.mws[1:itab]):
            offset += nofrois   
        return offset

601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
    def relabeliseAllMasksCallBack(self):
        offset=0
        for (name,geo,nofrois), mw in    zip(self.names_geos_nofrois[:], self.mws[1:]):
            self.relabeliseSpots( mw, nofrois, name , geo, offset)

    def relabeliseOneMaskCallBack(self):
        itab =  self.viewsTab.currentIndex()     
        if itab==0: return
        offset=0
        for (name,geo,nofrois), mw in    zip(self.names_geos_nofrois[:itab-1], self.mws[1:itab]):
            offset += nofrois
        (name,geo,nofrois), mw  =    self.names_geos_nofrois[itab-1], self.mws[itab]
        self.relabeliseSpots( mw , nofrois, name, geo, offset)

    def relabeliseSpots(self,mw, nofrois, name, geo, offset):

        mask = mw.getSelectionMask( ).astype("i")
        mask = (mask>0).astype("i")
        newmask = spotdetection.relabelise(mask,mask, nofrois)
        self.checkNspots(newmask.max(), nofrois , name) 
        mw.setSelectionMask( newmask )

        globalMask = self.mws[0].getSelectionMask().astype("i")
        globalMask[geo] = newmask
        self.mws[0].setSelectionMask( globalMask )

    def resetOneMask(self):
        itab =  self.viewsTab.currentIndex()
        if itab==0: return 
        mw = self.mws[itab]
        mw.graph.clearMarkers()
        mask = mw.getSelectionMask( ).astype("i")
        mask[:]=0
        mw.setSelectionMask( mask)

    def resetAllMasks(self):
        ret = self.warnForGloablChange()
Alessandro Mirone's avatar
Alessandro Mirone committed
638
        print( ret)
639
640
641
642
643
644
645
        if ret:
            for (name,geo,nofrois), mw in    zip(self.names_geos_nofrois[:], self.mws[1:]):
                mw.graph.clearMarkers()
                mask = mw.getSelectionMask( ).astype("i")
                mask[:]=0
                mw.setSelectionMask( mask)

646
647
648
649
650
651
652
653


    def threshold(self,itab,value ):
        globalMask = self.mws[0].getSelectionMask().astype("i")
        name,geo,nofrois =   self.names_geos_nofrois[itab-1]

        mw = self.mws[itab]
        mask = mw.getSelectionMask( )
Alessandro Mirone's avatar
Alessandro Mirone committed
654
        print( mask.sum())
655
656
657
658
659
660
661
662
663

        data = self.image[geo]

        mask = spotdetection.threshold_mask(mask, data ,  value  ) 
        mw.setSelectionMask(mask  )

        globalMask[geo] = mask
        self.mws[0].setSelectionMask( globalMask )
        
Alessandro Mirone's avatar
Alessandro Mirone committed
664
        print( mask.sum())
665
666
667


    def localThresholdCallBack(self,value):
668
669
        itab =  self.viewsTab.currentIndex()
        if itab==0: return 
670
671
672
673
        self.threshold(itab,value)

    def globalThresholdCallBack(self,value):
        ret = self.warnForGloablChange()
Alessandro Mirone's avatar
Alessandro Mirone committed
674
        print( ret)
675
676
677
678
        if ret:
            for itab in range(1, len(self.mws )  ) :
                self.threshold(itab,value)

679
680
681
682
683
684
685

    def fatten(self, itab, value  ) :
        globalMask = self.mws[0].getSelectionMask().astype("i")
        name,geo,nofrois =   self.names_geos_nofrois[itab-1]

        mw = self.mws[itab]
        mask = mw.getSelectionMask( )
686
687
688
689
        if value>0:
            mask = spotdetection.grow_mask(mask, 1+2*value  )
        else:
            mask = spotdetection.shrink_mask(mask, 1-2*value  )
690
691
692
693
        mw.setSelectionMask(mask  )

        globalMask[geo] = mask
        self.mws[0].setSelectionMask( globalMask )
694
695
696
697
698
699
700
701


    def fatteningCallBack(self,value):
        itab =  self.viewsTab.currentIndex()
        if itab==0: return 
        self.fatten(itab,value)

    def GlobalfatteningCallBack(self,value):
Alessandro Mirone's avatar
Alessandro Mirone committed
702
        print( " in GlobalfatteningCallBack  ", value  )
703
        ret = self.warnForGloablChange()
Alessandro Mirone's avatar
Alessandro Mirone committed
704
        print( ret)
705
706
707
708
709
        if ret:
            for itab in range(1, len(self.mws )  ) :
                self.fatten(itab,value)


710
711
712
        
    def checkNspots(self,nspots, nofrois,name ) :
        if nspots != nofrois:
Alessandro Mirone's avatar
Alessandro Mirone committed
713
714
715
716
717
718
719
            if not SKIP_WARNING :
                msgBox = Qt.QMessageBox ()
                msgBox.setText("Warning: found %d spots instead of expected %d "%(nspots , nofrois ) );
                msgBox.setInformativeText("For detector %s " %  name);
                msgBox.setStandardButtons(Qt.QMessageBox.Ok );
                msgBox.setDefaultButton(Qt.QMessageBox.Cancel);
                ret = msgBox.exec_();
720

Alessandro Mirone's avatar
Alessandro Mirone committed
721
    def    detectSpotsSubMask( self, name,geo,nofrois, mw   , globalMask,roiroiMask,  offset ,thr_s="", Hough=False):
Alessandro MIRONE's avatar
Alessandro MIRONE committed
722
723
        itab =  self.viewsTab.currentIndex()
        if itab: 
724
            subset_infos = self.get_geo() 
Alessandro MIRONE's avatar
Alessandro MIRONE committed
725
726
727
728
729
730
731
732
733
            if "3x4" in str(self.layouts[itab].currentText() ):
                a_ids = subset_infos["analyser_nIDs"][ subset_infos["subnames"][itab-1]] ["3x4"]
            else:
                a_ids = subset_infos["analyser_nIDs"][ subset_infos["subnames"][itab-1]] ["Vertical"]

                
        else:
            a_ids = None

734
        submatrix = mw.getImageData()
Alessandro Mirone's avatar
Alessandro Mirone committed
735
        subroiroi = roiroiMask[geo]
Alessandro Mirone's avatar
Alessandro Mirone committed
736
737
738
739
740
741
742
743
744
        tval = -1
        try:
            tval = float(thr_s)
        except:
            tval=-1


        geos = self.get_geo()
        dl    = geos["analyser_nIDs"]
745
746
        dll   = dl[list(dl.keys())[0]]
        ll = dll[list(dll.keys())[0]]
Alessandro Mirone's avatar
Alessandro Mirone committed
747
        nrois = len(ll)
748
        
Alessandro Mirone's avatar
Alessandro Mirone committed
749
750
        mask  = spotdetection.get_spots_mask( submatrix,subroiroi,
                                              median_size = 5 , tval=tval, nofroi=nrois, Hough=Hough ) 
751
752
753
754
755
756
    
        self.checkNspots(mask.max(), nofrois , name) 

        mw.setSelectionMask( mask)
        globalMask[geo]=mask+offset*numpy.less(0,mask)

Alessandro MIRONE's avatar
Alessandro MIRONE committed
757
758


759
        mw.annotateSpots( a_ids , self.get_offset(itab)  )
Alessandro MIRONE's avatar
Alessandro MIRONE committed
760
        
761
    def GlobaldetectionCallBack(self, warn=True,  thr_s="", Hough=False):
Alessandro Mirone's avatar
Alessandro Mirone committed
762
        print( " GlobaldetectionCallBack ",  warn)
Alessandro MIRONE's avatar
Alessandro MIRONE committed
763
        if 1 or warn:
Alessandro Mirone's avatar
Alessandro Mirone committed
764
            print( " in Global  detectionCallBack" )
765
766
767
768
769
770
            ret = self.warnForGloablChange()
        else:
            ret = True
        if ret:
            offset=0
            globalMask = self.mws[0].getSelectionMask().astype("i")
Alessandro Mirone's avatar
Alessandro Mirone committed
771
772
            roiroiMask = self.roiroiw.getSelectionMask().astype("i")
         
773
            for (name,geo,nofrois), mw in    zip(self.names_geos_nofrois, self.mws[1:]):
Alessandro Mirone's avatar
Alessandro Mirone committed
774
                self.detectSpotsSubMask( name,geo,nofrois, mw  , globalMask ,roiroiMask,  offset ,thr_s=thr_s, Hough=Hough)
775
776
777
778
                offset += nofrois
            self.mws[0].setSelectionMask( globalMask )


779
780
781
782
783
784
785
786
    def showToggle(self):
        if self.showIsData :
            self.showMasks()
            self.showIsData  = not self.showIsData 
        else:
            self.showDatas()
            self.showIsData  = not self.showIsData 
            
787
788
789
790
791
792
793
794
795
    def showMasks(self):
        for (name,geo,nofrois), mw in    zip(self.names_geos_nofrois, self.mws[1:]):
            mask = mw.getSelectionMask().astype("i")
            mw.setImageData(mask  , xScale=(0.0, 1.0), yScale=(0., 1.))

    def showDatas(self):
        Data = self.mws[0].getImageData()
        for (name,geo,nofrois), mw in    zip(self.names_geos_nofrois, self.mws[1:]):
            d  = Data[geo]
796
797
798
799
            mask = mw.getSelectionMask().astype("i")
            if mask.sum():
                mm = (d*mask).max()
                d=numpy.minimum(mm,d )
800
801
802
803
            mw.setImageData(d  , xScale=(0.0, 1.0), yScale=(0., 1.))


    def warnForGloablChange(self):
Alessandro Mirone's avatar
Alessandro Mirone committed
804
805
806
807
808
809
810
811
812
813
        if not SKIP_WARNING:
            msgBox = Qt.QMessageBox ()
            msgBox.setText("You are going to recalculate the GLOBAL mask");
            msgBox.setInformativeText("This will reset all modifications to local masks. Do you want to proceed?");
            msgBox.setStandardButtons(Qt.QMessageBox.Ok |  Qt.QMessageBox.Cancel);
            msgBox.setDefaultButton(Qt.QMessageBox.Cancel);
            ret = msgBox.exec_();
            return ret==Qt.QMessageBox.Ok
        else:
            return True
814
815
816
817
818
        

    def CreateSpotDetectionDockWidget(self):
        w = spotdetectioncontrol(self, QtCore.Qt.Widget,detectionCallBack=self.detectionCallBack,  
                                 fatteningCallBack=self.fatteningCallBack,
819
                                 thresholdCallBack  =   self.localThresholdCallBack, 
820
821
822
823
824
825
826
827
828
                                 annotateMaskCallBack=self.annotateOneMaskCallBack,
                                 relabeliseMaskCallBack=self.relabeliseOneMaskCallBack,
                                 resetMask           = self.resetOneMask
                                 )
        self.addDockWidget ( QtCore.Qt.LeftDockWidgetArea, w )
        # w.setAllowedAreas (QtCore.Qt.AllDockWidgetAreas)
        w.show()

    def globregistration(self):
Alessandro Mirone's avatar
Alessandro Mirone committed
829
        print( " in globregistration ")
830
831
832
833
834
        for itab in range(1,len(self.mws)):
            self.registerTab(itab)

    def registration(self):
        itab =  self.viewsTab.currentIndex()     
Alessandro Mirone's avatar
Alessandro Mirone committed
835
        print( self.layouts[itab].currentText())
836
837
838
839
        self.registerTab(itab)

    def registerTab(self, itab):
        if itab>0:
840
            
841
            subset_infos = self.get_geo() 
Alessandro MIRONE's avatar
Alessandro MIRONE committed
842
843
844
845
            if "3x4" in str(self.layouts[itab].currentText() ):
                a_ids = subset_infos["analyser_nIDs"][ subset_infos["subnames"][itab-1]]["3x4"]
            else:
                a_ids = subset_infos["analyser_nIDs"][ subset_infos["subnames"][itab-1]] ["Vertical"]
846
847
848
849
                
            name,geo,nofrois = self.names_geos_nofrois[itab-1]
            self.registerSpots( self.mws[itab], self.layouts[itab].currentText(), name, nofrois , a_ids)

Alessandro MIRONE's avatar
Alessandro MIRONE committed
850

851
            self.mws[itab].annotateSpots(a_ids , self.get_offset(itab))
852

853
    def registerSpots( self,  mw, layoutString , name, nofrois, a_ids) :
854
855
856
857
858
859
860
861
862

        mask = mw.getSelectionMask().astype("i")
        newmask = spotdetection.relabelise(mask,mask, nofrois)
        self.checkNspots(newmask.max(), nofrois , name) 
        mask = newmask
        nspots = mask.max()
        spots = []
        for i in range(1,nspots+1):
            zone = (mask==i)
Alessandro MIRONE's avatar
Alessandro MIRONE committed
863
            mask[zone]=i+100
864
865
866
867
868
869
870
871
872
873
            m = zone.astype("f")
            msum=m.sum()
            if msum:
                ny,nx = m.shape
                px= (m.sum(axis=0)*numpy.arange(nx)).sum()/msum
                py= (m.sum(axis=1)*numpy.arange(ny)).sum()/msum
                spots.append((py,px,i))

        self.checkNspots(len(spots), nofrois , name) 
            
Alessandro Mirone's avatar
Alessandro Mirone committed
874
        print( type(str(layoutString)))
875
876
877
        if "3x4" in str(layoutString):
            
            positions = [ [px,py]   for (py,px,i) in spots ]
Alessandro Mirone's avatar
Alessandro Mirone committed
878
            print( str( numpy.array(positions)))
Alessandro MIRONE's avatar
Alessandro MIRONE committed
879
880
881
            choices = match.register(numpy.array(positions)  )
            

882
883
            newspots = []
            for (cx,cy),(y,x,i) in zip(choices, spots ):
Alessandro Mirone's avatar
Alessandro Mirone committed
884
                print( x,y, cx, cy)
operator for beamline's avatar
operator for beamline committed
885
                newspots.append((y,x,i,  int((cy*4+cx)+1)  ) )
886
887
888
889
890
891
        else:
            spots.sort()
            newspots = []
            for k,(y,x,i) in enumerate( spots):
                newspots.append((y,x,i,k+1) ) 

Alessandro Mirone's avatar
Alessandro Mirone committed
892
        print( " NEWSPOTS ", newspots)
Alessandro MIRONE's avatar
Alessandro MIRONE committed
893

894
895
        for (y,x,i,k) in newspots:
            zone = (mask==(i+100))
896
            mask[zone] = a_ids[k-1]
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
                
        mw.setSelectionMask(mask)
            
    def CreateRegistrationWidget(self):

        w = spotregistrationcontrol(self, QtCore.Qt.Widget,globregistrationCallBack=self.globregistration,  
                                    registrationCallBack=self.registration
                                )

        self.addDockWidget ( QtCore.Qt.LeftDockWidgetArea, w )
        w.show()

    def CreateGlobalSpotDetectionDockWidget(self):
        w = spotdetectioncontrol(self, QtCore.Qt.Widget,detectionCallBack=self.GlobaldetectionCallBack, 
                                 fatteningCallBack=self.GlobalfatteningCallBack,
912
                                 thresholdCallBack  =   self.globalThresholdCallBack, 
913
914
915
916
917
                                 annotateMaskCallBack=self.annotateAllMasksCallBack,
                                 relabeliseMaskCallBack=self.relabeliseAllMasksCallBack,
                                 resetMask           = self.resetAllMasks
                                 )
        w.detectionButton.setText("GLOBAL detection")
918
        w.HoughDetection.setText("GLOBAL Hough")
919
920
        self.addDockWidget ( QtCore.Qt.LeftDockWidgetArea, w )
        # w.setAllowedAreas (QtCore.Qt.AllDockWidgetAreas)
Alessandro Mirone's avatar
Alessandro Mirone committed
921
        self.globalSpotDectionWidget = w
922
923
924
925
926
927
        w.show()

    def set_roiob(self, roiob):
        self.roiob=roiob

    def LoadRemote(self):
Alessandro MIRONE's avatar
Alessandro MIRONE committed
928

929
930
931
932
933
934
935
936
        if self.roiob is None:
            mb = qt.QMessageBox();
            mb.setText("No roi-object has been associated to the roi manager. Cannot Load.");
            mb.exec_();
            return
        self.showImage(self.roiob)


937
938
    def create_viewWidget(self, image = None, nofrois = None, changeTagOn=False, isglobal=False , layoutsNames = None) :
        view = imageview(self, isglobal, layoutsNames =layoutsNames)        
939
940
941
        maskW  =myMaskImageWidget.MaskImageWidget(self, aspect=True,
                                                  profileselection=True,
                                                  maxNRois=nofrois )
942
943
        maskW.setY1AxisInverted(1)

944
945
946
947
948
949
950
951
952
953
954
        maskW.setAcceptDrops(True)


        maskW.setDefaultColormap(2, logflag=True)

        maskW.changeTagOn = changeTagOn
        maskW.setImageData(image  , xScale=(0.0, 1.0), yScale=(0., 1.))
        maskW.setSelectionMask(image*0 , plot=True)
        view.roiContainerWidget.layout().addWidget(maskW)
        return view, maskW
            
955
    def showImage(self, image, geo_informations=None):
Alessandro Mirone's avatar
Alessandro Mirone committed
956
        self.image=image
957
958
959
960
961
        if geo_informations is None:
            geo_informations = self.get_geo()  
        self.geo_informations = geo_informations

        self.image=image
962

Alessandro MIRONE's avatar
Alessandro MIRONE committed
963
        subset_infos = geo_informations
964
965
966

        self.viewsTab.clear()       
        totNofrois = subset_infos["nofrois"]
967
968
969
        nofrois = totNofrois//len( subset_infos["subgeos"]  )
        
        # "analyser_nIDs": {"DETECTOR":{ "Vertical": V1234} }
970

971
972
973
        layoutsNames = list(list(subset_infos["analyser_nIDs"].items())[0][1].keys())
        layoutsNames.sort(reverse=True)
        
974
975
        self.mws=[]
        self.layouts=[]
976
        view, mw = self.create_viewWidget(image = image, nofrois = totNofrois , changeTagOn = False, isglobal=True  , layoutsNames = layoutsNames)
Alessandro Mirone's avatar
Alessandro Mirone committed
977
        
978
979
980
981
        self.viewsTab.addTab(view, "Global")
        self.mws.append(mw)
        self.layouts.append(view.registeringLayoutComboBox)

982
        self.names_geos_nofrois = list(zip(subset_infos["subnames"],  subset_infos["subgeos"], [nofrois]*len(subset_infos["subgeos"])  ))
983
984

        for name,geo,nofr in self.names_geos_nofrois :
985
            view, mw = self.create_viewWidget(image = image[     geo ], nofrois = nofrois, changeTagOn = True , layoutsNames = layoutsNames )
Alessandro Mirone's avatar
Alessandro Mirone committed
986
            
987
988
989
990
991
            self.viewsTab.addTab(view, name)
            self.mws.append(mw)
            self.layouts.append(view.registeringLayoutComboBox)
            

992
        view, roiroiw = self.create_viewWidget(image = image, nofrois = 1 , isglobal=True, changeTagOn = False  , layoutsNames = layoutsNames)
Alessandro Mirone's avatar
Alessandro Mirone committed
993
994
995
996
997
998
999
1000
        
        self.viewsTab.addTab(view, "ROI of ROIS")
        self.roiroiw = roiroiw
        self.layouts.append(view.registeringLayoutComboBox)