roifinder_and_gui.py 179 KB
Newer Older
1
2
3
4
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

5
6
import numpy as np
import matplotlib.pyplot as plt
7
import shelve
8
from matplotlib.path import Path
christoph's avatar
christoph committed
9
from . import xrs_utilities, xrs_rois, xrs_scans, roiSelectionWidget, math_functions 
10
11
from matplotlib.widgets import Cursor, Button
from scipy.ndimage import measurements
12
from scipy import signal, stats
christoph's avatar
christoph committed
13
import copy
14
import matplotlib
christoph's avatar
christoph committed
15

16

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# def findroisColumns(scans,scannumbers,roi_obj, whichroi,logscaling=False):
#         """
#         Constructs a waterfall plot from the columns in a scan, i.e. energy vs. pixel number along the ROI
#         scannumbers = scannumber or list of scannumbers from which to construct the plot
#         whichroi    = integer (starting from 0) from which ROI to use for constructing the plot
#         """
#         if not isinstance(scannumbers,list):
#                 scannums = []
#                 scannums.append(scannumbers)
#         else:
#                 scannums = scannumbers 

#         if not roi_obj.indices:
#                 'Please define some zoom ROIs first.'
#                 return
#         if not roi_obj.kind == 'zoom':
#                 'Currently this feature only works for ROIs of type \'zoom\'.'
#                 return

#         xinds     = np.unique(roi_obj.x_indices[whichroi])
#         yinds     = np.unique(roi_obj.y_indices[whichroi])
#         scanname  = 'Scan%03d' % scannums[0]
#         edfmats   = np.zeros_like(scans[scanname].edfmats)
#         energy    = scans[scanname].energy
#         waterfall = np.zeros((len(yinds),len(energy)))

#         for scannum in scannums:
#                 scanname = 'Scan%03d' % scannum
#                 scanedf  = scans[scanname].edfmats
#                 scanmonitor = scans[scanname].monitor
#                 for ii in range(len(energy)):
#                         edfmats[ii,:,:] += scanedf[ii,:,:]/scanmonitor[ii]

#         for ii in range(len(energy)):
#                 for jj in range(len(yinds)):
#                         waterfall[jj,ii] = np.sum(edfmats[ii,xinds,yinds[jj]])

#         plt.figure()
#         for ii in range(len(yinds)):
#                 plt.plot(waterfall[ii,:])

#         fig = plt.figure()
#         ax = fig.add_subplot(111)

#         if logscaling:
#                 ax.imshow(np.log(np.transpose(waterfall)), interpolation='nearest')
#         else:
#                 ax.imshow(np.transpose(waterfall), interpolation='nearest')

#         ax.set_aspect('auto')
#         plt.xlabel('ROI pixel')
#         plt.ylabel('energy point')
#         plt.show()


# def get_auto_rois_eachdet(scans,DET_PIXEL_NUM ,scannumbers,kernel_size=5,threshold=100.0,logscaling=True,colormap='jet',interpolation='bilinear'):
#     """
#     Define ROIs automatically using median filtering and a variable threshold for each detector
#     separately.
#     scannumbers   = either single scannumber or list of scannumbers
#     kernel_size   = used kernel size for the median filter (must be an odd integer)
#     logscaling    = set to 'True' if images is to be shown on log-scale (default is True)
#     colormap      = string to define the colormap which is to be used for display (anything 
christoph's avatar
christoph committed
80
#                     supported by matplotlib, 'Blues' by default)
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#     interpolation = interpolation scheme to be used for displaying the image (anything
#                     supported by matplotlib, 'nearest' by default)
#     """
#     # check that kernel_size is odd
#     if not kernel_size % 2 == 1:
#             print( 'The \'kernal_size\' must be an odd number.' )
#             return

#     # create a big image
#     image = xrs_scans.create_sum_image(scans,scannumbers)

#     # break down the image into 256x256 pixel images
#     det_images, offsets = xrs_rois.break_down_det_image(image,DET_PIXEL_NUM)

#     # create one roi_object per sub-image
#     temp_objs = []
#     for ii in range(det_images.shape[0]):
#             temp = roi_finder()
#             temp.get_auto_rois(det_images[ii,:,:],kernel_size=kernel_size,threshold=threshold,logscaling=logscaling,colormap=colormap,interpolation=interpolation)
#             temp_objs.append(temp)

#     # merge all roi_objects into one
#     merged_obj   = xrs_rois.merge_roi_objects_by_matrix(temp_objs,image.shape,offsets,DET_PIXEL_NUM)
#     roi_obj = merged_obj
#     return roi_obj

christoph's avatar
christoph committed
107
# def get_polygon_rois_eachdet(scans,DET_PIXEL_NUM,  scannumbers,logscaling=True,colormap='Blues',interpolation='nearest'):
108
109
110
111
112
113
114
#         """
#         Define a polygon shaped ROI from an image constructed from 
#         the sum of all edf-files in 'scannumbers'
#         image_shape = tuple with shape of the current image (i.e. (256,256))
#         scannumbers = either single scannumber or list of scannumbers
#         logscaling  = set to 'True' if images is to be shown on log-scale (default is True)
#         colormap    = string to define the colormap which is to be used for display (anything 
christoph's avatar
christoph committed
115
#                       supported by matplotlib, 'Blues' by default)
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#         interpolation = interpolation scheme to be used for displaying the image (anything
#                         supported by matplotlib, 'nearest' by default)
#         """

#         # create a big image
#         image = xrs_scans.create_sum_image(scans,scannumbers)

#         # break down the image into 256x256 pixel images
#         det_images, offsets = xrs_rois.break_down_det_image(image,DET_PIXEL_NUM)

#         # create one roi_object per sub-image
#         temp_objs = []
#         for modind in range(det_images.shape[0]):
#                 temp = roi_finder()
#                 temp.get_polygon_rois( det_images[modind,:,:],modind,logscaling=logscaling,colormap=colormap,interpolation=interpolation)
#                 temp_objs.append(temp)

#         # merge all roi_objects into one
#         merged_obj   = xrs_rois.merge_roi_objects_by_matrix(temp_objs,image.shape,offsets,DET_PIXEL_NUM)
#         roi_obj = merged_obj
#         return roi_obj

christoph's avatar
christoph committed
138
# def get_zoom_rois(scans,scannumbers,logscaling=True,colormap='Blues',interpolation='nearest'):
139
140
141
142
143
144
145
146
#         # create a big image
#         image = xrs_scans.create_sum_image(scans,scannumbers)

#         # create one roi_object per sub-image
#         roi_obj = roi_finder()
#         roi_obj.get_zoom_rois(image,logscaling=logscaling,colormap=colormap,interpolation=interpolation)        

#         return roi_obj.roi_obj
147
148
149
150



class roi_finder:
christoph's avatar
christoph committed
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
    def __init__(self):
        self.roi_obj = xrs_rois.roi_object() # empty roi object

    def appendROIobject(self,roi_object):
        self.roi_obj.append(roi_object)

    def deleterois(self):
        """
        Clear the existing ROIs by creating a fresh roi_object.
        """
        self.roi_obj = xrs_rois.roi_object()

    def roi_widget(self, input_image, layout="2X3-12", shape = [512,768] ):
        """ **roi_widget**
        Use the ROI widget to define ROIs.

        input_image  = 2D array to define the ROIs from
        layout       = detector layout
        shape        = image shape/detector shape
        """
        #%matplotlib qt
        matplotlib.use('Qt4Agg')  
        w4r = roiSelectionWidget.mainwindow(layout=layout)
        w4r.showImage( input_image )
        w4r.show()
        self.roi_obj.load_rois_fromMasksDict( w4r.getMasksDict(), newshape = shape )

christoph's avatar
christoph committed
178
    def get_linear_rois( self, input_image, logscaling=True, height=5, colormap='Blues', interpolation='nearest' ):
christoph's avatar
christoph committed
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
        """
        Define ROIs by clicking two points on a 2D image.
        number_of_rois = integer defining how many ROIs should be determined
        input_object   = 2D array, scan_object, or dictionary of scans to define the ROIs from
        logscaling     = boolean, to determine wether the image is shown on a log-scale (default = True)
        height         = integer defining the height (in pixels) of the ROIs
        """
        # make sure the matplotlib interactive mode is off
        plt.ioff()

        # clear all existing rois
        self.deleterois()

        # check that the input is a 2d matrix
        if not len(input_image.shape) == 2:
            print( 'Please provide a 2D numpy array as input!' )
            return

        # save input image for later use
        self.roi_obj.input_image = copy.deepcopy(input_image)

        # calculate the logarithm if 'logscaling' == True
        if logscaling:
            # set all zeros to ones:
            input_image[input_image[:,:] == 0.0] = 1.0
            input_image = np.log(np.abs(input_image))

        # prepare a figure
        fig, ax = plt.subplots()
        plt.subplots_adjust(bottom=0.2)
        cursor = Cursor(ax, useblit=True, color='red', linewidth=1 )

        # Initialize suptitle, which will be updated
        titlestring = 'Start by clicking the \'Next\'-button.'
        titleInst=plt.suptitle(titlestring)

        # generate an image to be displayed
        figure_obj = plt.imshow(input_image,interpolation=interpolation)

        # set the colormap for the image
        figure_obj.set_cmap(colormap)

        rois   = []
        class Index:
            ind  = 0
            def next(self, event):
                titlestring = 'Click two points for ROI Nr. %02d, \'Finish\' to end.' %(self.ind+1)
                titleInst.set_text(titlestring) # Update title
                # Try needed, as FINISH button closes the figure and ginput() generates _tkinter.TclError
                try:
                    one_roi = define_lin_roi(height,input_image.shape)
                    for index in one_roi:
                        input_image[index[0],index[1]] += 1.0e6
                    figure_obj.set_data(input_image)
                    plt.hold(True)
                    plt.draw()
                    rois.append(one_roi)
                    self.ind += 1
                    # Begin defining the next ROI right after current
                    self.next(self)
                except KeyboardInterrupt: # to prevent "dead" figures
                    plt.close()
                    pass
                except:
                    pass

            def prev(self, event):
                self.ind -= 1
                try:
                    titlestring = 'Click the \'Next\' button again to continue.'
                    titleInst.set_text(titlestring) # Update title
                    # print titlestring
                    for index in rois[-1]:
                        input_image[index[0],index[1]] -= 1.0e6
                    figure_obj.set_data(input_image)
                    plt.hold(True)
                    rois.pop()
                except:
                    pass

            def close(self, event):
260
261
262
                plt.hold(False)
                plt.ion()
                plt.close('all')
christoph's avatar
christoph committed
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290

            def dmy(self, event):
                pass # adding a dummy function for the dummy button

        callback = Index()
        axprev   = plt.axes([0.5, 0.05, 0.1, 0.075])
        axnext   = plt.axes([0.61, 0.05, 0.1, 0.075])
        axclose  = plt.axes([0.72, 0.05, 0.1, 0.075])
        axdmy    = plt.axes([0.001, 0.001, 0.001, 0.001]) # for some reason the first botton disappears when clicked
        bdmy     = Button(axdmy,'')                        # which is why I am including a dummy button here
        bdmy.on_clicked(callback.dmy)                   # this way, the real buttons work
        bnext    = Button(axnext, 'Next')
        bnext.on_clicked(callback.next)
        bprev    = Button(axprev, 'Back')
        bprev.on_clicked(callback.prev)
        bclose   = Button(axclose, 'Finish')
        bclose.on_clicked(callback.close)
        plt.show()

        # assign the defined rois to the roi_object class
        self.roi_obj.roi_matrix     = xrs_rois.convert_inds_to_matrix(rois,input_image.shape)
        self.roi_obj.red_rois       = xrs_rois.convert_matrix_to_redmatrix(self.roi_obj.roi_matrix)
        self.roi_obj.indices        = rois 
        self.roi_obj.kind           = 'linear'
        self.roi_obj.x_indices      = xrs_rois.convert_inds_to_xinds(rois)
        self.roi_obj.y_indices      = xrs_rois.convert_inds_to_yinds(rois)
        self.roi_obj.masks          = xrs_rois.convert_roi_matrix_to_masks(self.roi_obj.roi_matrix)
        self.roi_obj.number_of_rois = int(np.amax(self.roi_obj.roi_matrix))
291
        #plt.draw()
christoph's avatar
christoph committed
292

293
    def get_zoom_rois( self, input_image, logscaling=True, colormap='Blues', interpolation='nearest'):
christoph's avatar
christoph committed
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
        """
        Define ROIs by clicking two points on a 2D image.
        number_of_rois = integer defining how many ROIs should be determined
        input_object   = 2D array, scan_object, or dictionary of scans to define the ROIs from
        logscaling     = boolean, to determine wether the image is shown on a log-scale (default = True)
        height         = integer defining the height (in pixels) of the ROIs
        """
        # make sure the matplotlib interactive mode is off
        plt.ioff()

        # clear all existing rois
        self.deleterois()

        # check that the input is a 2d matrix
        if not len(input_image.shape) == 2:
            print( 'please provide a 2D numpy array as input!' )
            return                

        # save input image for later use
        self.roi_obj.input_image = copy.deepcopy(input_image)

        # calculate the logarithm if 'logscaling' == True
        if logscaling:
            # set all zeros to ones:
            input_image[input_image[:,:] == 0.0] = 1.0
            input_image = np.log(np.abs(input_image))

        # prepare a figure
        fig, ax = plt.subplots()
        plt.subplots_adjust(bottom=0.2)
        cursor = Cursor(ax, useblit=True, color='red', linewidth=1 )

        # Initialize suptitle, which will be updated
        titlestring = 'Start by clicking the \'Next\' button.'
        titleInst=plt.suptitle(titlestring)

        # generate an image to be displayed
        figure_obj = plt.imshow(input_image,interpolation=interpolation)

        # activate the zoom function already
        thismanager = plt.get_current_fig_manager()
        thismanager.toolbar.zoom()

        # set the colormap for the image
        figure_obj.set_cmap(colormap)
        #plt.colorbar()

        # initialize a matrix for the rois (will be filled with areas of ones, twos, etc
        rois = []

        # print info to start: 
        print( 'Start by clicking the \'Next\' button.' )

        class Index:
            ind          = 0
            initstage    = True
            next_clicked = False
351
352

            def next( self, event ):
christoph's avatar
christoph committed
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
                # for some reason, the first time this is used, it doesn't work, so here is one dummy round
                if self.initstage:
                    #self.ind += 1
                    self.initstage = False
                    plt.sca(ax)
                    one_roi = define_zoom_roi(input_image,verbose=True)
                    #for index in one_roi:
                    #	input_image[index[0],index[1]] *= 1.0
                    # reset the matrix to be displayed
                    figure_obj.set_data(input_image)
                    # reset the zoom
                    plt.xlim(0.0,input_image.shape[1])
                    plt.ylim(input_image.shape[0],0.0)
                    plt.draw()
                    titlestring = 'Zoom in to define ROI Nr. %02d, hit \'Next\' to continue.' % (self.ind + 1)
                    titleInst.set_text(titlestring) # Update title
                else:
                    self.ind += 1
                    plt.sca(ax)
                    one_roi = define_zoom_roi(input_image)
                    for index in one_roi:
                        input_image[index[0],index[1]] += 1.0e10
                    # reset the matrix to be displayed
                    figure_obj.set_data(input_image)
                    # reset the zoom
                    plt.xlim(0.0,input_image.shape[1])
                    plt.ylim(input_image.shape[0],0.0)
                    plt.draw()
                    rois.append(one_roi)
                    titlestring = 'Zoom in to define ROI Nr. %02d, hit \'Next\' to continue, \'Finish\' to end.' % (self.ind + 1)
                    titleInst.set_text(titlestring) # Update title

            def prev(self, event):
                self.ind -= 1
                titlestring = 'Undoing ROI Nr. %02d. Zoom again, click the \'Next\' button to continue.' % (self.ind + 1)
                titleInst.set_text(titlestring) # Update title
                #thedata[roimatrix == self.ind+1]   -= 1.0e6
                #roi_matrix[roimatrix == self.ind+1] = 0.0
                for index in rois[-1]:
                    input_image[index[0],index[1]] -= 1.0e10
                figure_obj.set_data(input_image)
                plt.hold(True)
                rois.pop()

            def close(self, event):
                plt.sca(ax)
                one_roi = define_zoom_roi(input_image)
                for index in one_roi:
                    input_image[index[0],index[1]] += 1.0e10
                # reset the matrix to be displayed
                figure_obj.set_data(input_image)
                # reset the zoom
                plt.xlim(0.0,input_image.shape[1])
                plt.ylim(input_image.shape[0],0.0)
                plt.draw()
                rois.append(one_roi)
                titlestring = 'Last ROI is Nr. %02d.' % (self.ind + 1)
                titleInst.set_text(titlestring) # Update title
                plt.close()

            def dmy(self, event):
                pass # adding a dummy function for the dummy button

        callback = Index()
        axprev   = plt.axes([0.5, 0.05, 0.1, 0.075])
        axnext   = plt.axes([0.61, 0.05, 0.1, 0.075])
        axclose  = plt.axes([0.72, 0.05, 0.1, 0.075])
        axdmy    = plt.axes([0.001, 0.001, 0.001, 0.001]) # for some reason the first botton disappears when clicked
        bdmy     = Button(axdmy,'')                       # which is why I am including a dummy button here
        bdmy.on_clicked(callback.dmy)                     # this way, the real buttons work
        bnext    = Button(axnext, 'Next')
        bnext.on_clicked(callback.next)
        bprev    = Button(axprev, 'Back')
        bprev.on_clicked(callback.prev)
        bclose   = Button(axclose, 'Finish')
        bclose.on_clicked(callback.close)
        plt.show()

        # assign the defined rois to the roi_object class
        self.roi_obj.roi_matrix     = (xrs_rois.convert_inds_to_matrix(rois,input_image.shape))
        self.roi_obj.red_rois       = xrs_rois.convert_matrix_to_redmatrix(self.roi_obj.roi_matrix)
        self.roi_obj.indices        = rois 
        self.roi_obj.kind           = 'zoom'
        self.roi_obj.x_indices      = xrs_rois.convert_inds_to_xinds(rois)
        self.roi_obj.y_indices      = xrs_rois.convert_inds_to_yinds(rois)
        self.roi_obj.masks          = xrs_rois.convert_roi_matrix_to_masks(self.roi_obj.roi_matrix)
        self.roi_obj.number_of_rois = int(np.amax(self.roi_obj.roi_matrix))

christoph's avatar
christoph committed
441
    def get_auto_rois(self,input_image,kernel_size=5,threshold=100.0,logscaling=True,colormap='Blues',interpolation='bilinear'):
christoph's avatar
christoph committed
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
        """
        Define ROIs by choosing a threshold using a slider bar under the figure. In this function, the entire 
        detector is shown.
        input_image = 2D numpy array with the image to be displayed
        kernal_size = integer defining the median filter window (has to be odd)
        theshold    = initial number defining the upper end value for the slider bar (amax(input_image)/threshold defines this number), can be within GUI
        logscaling  = boolean, if True (default) the logarithm of input_image is displayed
        colormap    = matplotlib color scheme used in the display
        interpolation = matplotlib interpolation scheme used for the display
        """
        # make sure the matplotlib interactive mode is off
        plt.ioff()

        # clear all existing rois
        self.deleterois()

        # clear existing figure
        # plt.clf()

        # save input image for later use
        self.roi_obj.input_image = copy.deepcopy(input_image)

        # calculate the logarithm if 'logscaling' == True
        if logscaling:
            # set all zeros to ones:
            input_image[input_image[:,:] == 0.0] = 1.0
            input_image = np.log(np.abs(input_image))

        ax = plt.subplot(111) 
        plt.subplots_adjust(left=0.05, bottom=0.2)

        # print out some instructions
        plt.suptitle('Use the slider bar to select ROIs, close the plotting window when satisfied.')

        # initial threshold value
        thres0 = 0.0

        # create a figure object
        figure_obj = plt.imshow(input_image,interpolation=interpolation)
        figure_obj.set_cmap(colormap)

        # prepare the slider bar
        thresxcolor = 'lightgoldenrodyellow'
        thresxamp  = plt.axes([0.2, 0.10, 0.55, 0.03], axisbg=thresxcolor)
        maxthreshold=np.floor(np.amax(input_image)) # maximum of slider
        sthres = plt.Slider(thresxamp, 'Threshold', 0.0, maxthreshold, valinit=thres0)

        textBox=plt.figtext(0.50, 0.065, 'Multiplier: 1.0',verticalalignment='center')

        # define what happens when the slider is touched
        def update(val):
            # parse a threshold from the slider
            thres     = sthres.val*thresMultiplier.factor
            # median filter the image
            newmatrix = signal.medfilt2d(input_image, kernel_size=kernel_size)
            # set pixels below the threshold to zero
            belowthres_indices = newmatrix < thres
            newmatrix[belowthres_indices] = 0
            # identify connected regions (this is already the roi_matrix)
            self.roi_obj.roi_matrix,numfoundrois = measurements.label(newmatrix)
            print( str(numfoundrois) + ' ROIs found!' )
            figure_obj.set_data(newmatrix)
            plt.draw()

        # Buttons for changing multiplier for the value of slider
        class thresMultiplierClass:
            factor = 1.0;
            def __new__(cls):
                return self.factor
            def increase(self,event):
                self.factor *=2.0
                textBox.set_text('Multiplier: ' + str(self.factor))
                return self.factor
            def decrease(self,event):
                self.factor /=2.0
                textBox.set_text('Multiplier: ' + str(self.factor))
                return self.factor

        # call the update function when the slider is touched
        sthres.on_changed(update)

        thresMultiplier = thresMultiplierClass()
        axincrease   = plt.axes([0.8, 0.05, 0.05, 0.03])
        axdecrease   = plt.axes([0.7, 0.05, 0.05, 0.03])
        bnincrease    = Button(axincrease, 'x 2')
        bndecrease    = Button(axdecrease, '/ 2')
        bnincrease.on_clicked(thresMultiplier.increase)  # First change threshold
        bnincrease.on_clicked(update)		         # Then update image
        bndecrease.on_clicked(thresMultiplier.decrease)
        bndecrease.on_clicked(update)
        # ADDITION ENDS

        plt.show()

        # assign the defined rois to the roi_object class
        self.roi_obj.red_rois       = xrs_rois.convert_matrix_to_redmatrix(self.roi_obj.roi_matrix)
        self.roi_obj.indices        = xrs_rois.convert_matrix_rois_to_inds(self.roi_obj.roi_matrix)
        self.roi_obj.kind           = 'auto'
        self.roi_obj.x_indices      = xrs_rois.convert_inds_to_xinds(self.roi_obj.indices)
        self.roi_obj.y_indices      = xrs_rois.convert_inds_to_yinds(self.roi_obj.indices)
        self.roi_obj.masks          = xrs_rois.convert_roi_matrix_to_masks(self.roi_obj.roi_matrix)
        self.roi_obj.number_of_rois = int(np.amax(self.roi_obj.roi_matrix))

christoph's avatar
christoph committed
545
    def get_auto_rois_eachdet(self, input_image, kernel_size=5, threshold=100.0, logscaling=True, colormap='Blues', interpolation='bilinear'):
christoph's avatar
christoph committed
546
547
548
549
550
551
        """
        Define ROIs automatically using median filtering and a variable threshold for each detector
        separately.
        scannumbers   = either single scannumber or list of scannumbers
        kernel_size   = used kernel size for the median filter (must be an odd integer)
        logscaling    = set to 'True' if images is to be shown on log-scale (default is True)
christoph's avatar
christoph committed
552
        colormap      = string to define the colormap which is to be used for display (anything supported by matplotlib, 'Blues' by default)
alex's avatar
alex committed
553
        interpolation = interpolation scheme to be used for displaying the image (anything supported by matplotlib, 'nearest' by default)
christoph's avatar
christoph committed
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
        """
        # check that kernel_size is odd
        if not kernel_size % 2 == 1:
            print( 'The \'kernal_size\' must be an odd number.' )
            return

        self.roi_obj.input_image = copy.deepcopy(input_image)

        # big many pixels in one detector image
        DET_PIXEL_NUM = input_image.shape[0]/2

        # break down the image into 256x256 pixel images
        det_images, offsets = xrs_rois.break_down_det_image(input_image,DET_PIXEL_NUM)

        # create one roi_object per sub-image
        temp_objs = []
        for ii in range(det_images.shape[0]):
            temp = roi_finder()
            temp.get_auto_rois(det_images[ii,:,:], kernel_size=kernel_size, threshold=threshold, \
                                logscaling=logscaling, colormap=colormap, interpolation=interpolation)
            temp_objs.append(temp)

        # merge all roi_objects into one
        merged_obj   = xrs_rois.merge_roi_objects_by_matrix(temp_objs,input_image.shape,offsets,DET_PIXEL_NUM)

        # assign the defined rois to the roi_object class
        self.roi_obj.roi_matrix     = merged_obj.roi_matrix
        self.roi_obj.red_rois       = xrs_rois.convert_matrix_to_redmatrix(self.roi_obj.roi_matrix)
        self.roi_obj.indices        = xrs_rois.convert_matrix_rois_to_inds(self.roi_obj.roi_matrix)
        self.roi_obj.kind           = 'auto'
        self.roi_obj.x_indices      = xrs_rois.convert_inds_to_xinds(self.roi_obj.indices)
        self.roi_obj.y_indices      = xrs_rois.convert_inds_to_yinds(self.roi_obj.indices)
        self.roi_obj.masks          = xrs_rois.convert_roi_matrix_to_masks(self.roi_obj.roi_matrix)
        self.roi_obj.number_of_rois = int(np.amax(self.roi_obj.roi_matrix))

christoph's avatar
christoph committed
589
    def get_polygon_rois(self,input_image,modind=-1,logscaling=True,colormap='Blues',interpolation='nearest'):
christoph's avatar
christoph committed
590
591
592
593
594
595
596
597
598
599
600
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
        """
        Define ROIs by clicking arbitrary number of points on a 2D image:
        LEFT CLICK to define the corner points of polygon, 
        MIDDLE CLICK to finish current ROI and move to the next ROI,
        RIGHT CLICK to cancel the previous point of polygon
        input_object   = 2D array, scan_object, or dictionary of scans to define the ROIs from
        modind	     = integer to identify module, if -1 (default), no module info will be in title (the case of one big image)
        logscaling     = boolean, to determine wether the image is shown on a log-scale (default = True)

        """
        # make sure the matplotlib interactive mode is off
        plt.ioff()

        # clear all existing rois
        self.deleterois()

        # check that the input is a 2d matrix
        if not len(input_image.shape) == 2:
            print( 'Please provide a 2D numpy array as input!' )
            return

        # save input image for later use
        self.roi_obj.input_image = copy.deepcopy(input_image)

        # calculate the logarithm if 'logscaling' == True
        if logscaling:
            # set all zeros to ones:
            input_image[input_image[:,:] == 0.0] = 1.0
            input_image = np.log(np.abs(input_image))

        # prepare a figure
        fig, ax = plt.subplots()
        plt.subplots_adjust(bottom=0.2)

        moduleNames='VD:','HR:','VU:','HL:','VB:','HB:',''  # for plot title

        # Initialize suptitle, which will be updated
        titlestring = ''
        titleInst=plt.suptitle(titlestring)

        cursor = Cursor(ax, useblit=True, color='red', linewidth=1 )

        # generate an image to be displayed
        figure_obj = plt.imshow(input_image,interpolation=interpolation)

        # set the colormap for the image
        figure_obj.set_cmap(colormap)

        rois   = []
        class Index:
            ind  = 1
            def next(self, event):

                titlestring = '%s next ROI is Nr. %02d:\n Left button to new points, middle to finish ROI. Hit \'Finish\' to end with this image.' % (moduleNames[modind], self.ind)
                titleInst.set_text(titlestring) # Update title

                # Try needed, as FINISH button closes the figure and ginput() generates _tkinter.TclError 
                try:
                    one_roi = define_polygon_roi(input_image.shape)
                    for index in one_roi:
                        input_image[int(index[0]),int(index[1])] += 1.0e6
                    figure_obj.set_data(input_image)
                    plt.hold(True)
                    plt.draw()
                    rois.append(one_roi)
                    self.ind += 1
                    # Begin defining the next ROI right after current
                    self.next(self)
                except KeyboardInterrupt:	# to prevent "dead" figures
                    plt.close()
                    pass		
                except:
                    pass

            def prev(self, event):
                self.ind -= 1
                for index in rois[-1]:
                    input_image[index[0],index[1]] -= 1.0e6
                figure_obj.set_data(input_image)
                plt.hold(True)
                plt.draw()
                rois.pop()
                self.next(self)

            def close(self, event):
                plt.close()

            def dmy(self, event):
                pass # adding a dummy function for the dummy button

        callback = Index()	
        axprev   = plt.axes([0.5, 0.05, 0.1, 0.075])
        axnext   = plt.axes([0.61, 0.05, 0.1, 0.075])
        axclose  = plt.axes([0.72, 0.05, 0.1, 0.075])
        axdmy    = plt.axes([0.001, 0.001, 0.001, 0.001]) # for some reason the first botton disappears when clicked
        bdmy     = Button(axdmy,'')                        # which is why I am including a dummy button here
        bdmy.on_clicked(callback.dmy)                   # this way, the real buttons work
        bnext    = Button(axnext, 'Next')
        bnext.on_clicked(callback.next)
        bprev    = Button(axprev, 'Back')
        bprev.on_clicked(callback.prev)
        bclose   = Button(axclose, 'Finish')
        bclose.on_clicked(callback.close)

        # START: initiate NEXT button press
        callback.next(self)		

        # assign the defined rois to the roi_object class
        self.roi_obj.roi_matrix     = xrs_rois.convert_inds_to_matrix(rois,input_image.shape)
        self.roi_obj.red_rois       = xrs_rois.convert_matrix_to_redmatrix(self.roi_obj.roi_matrix)
        self.roi_obj.indices        = rois 
        self.roi_obj.kind           = 'polygon'
        self.roi_obj.x_indices      = xrs_rois.convert_inds_to_xinds(rois)
        self.roi_obj.y_indices      = xrs_rois.convert_inds_to_yinds(rois)
        self.roi_obj.masks          = xrs_rois.convert_roi_matrix_to_masks(self.roi_obj.roi_matrix)
        self.roi_obj.number_of_rois = int(np.amax(self.roi_obj.roi_matrix))

christoph's avatar
christoph committed
707
    def show_rois( self, interpolation='nearest', cmap='Blues' ):
christoph's avatar
christoph committed
708
709
710
711
        """ **show_rois**
        Creates a figure with the defined ROIs as numbered boxes on it.

        Args:
alex's avatar
alex committed
712
713
          * interpolation (str) : Interpolation scheme used in the plot.
          * colormap (str) : Colormap used in the plot.
christoph's avatar
christoph committed
714
        """
715
        self.roi_obj.show( cmap=cmap,interpolation=interpolation )
christoph's avatar
christoph committed
716

717
    def import_simo_style_rois( self, roiList, detImageShape=(512,768) ):
christoph's avatar
christoph committed
718
719
720
721
        """ **import_simo_style_rois**
        Converts Simo-style ROIs to the conventions used here.

        Arguments:
alex's avatar
alex committed
722
723
          * roiList (list): List of tuples that have [(xmin, xmax, ymin, ymax), (xmin, xmax, ymin, ymax), ...].
          * detImageShape (tuple): Shape of the detector image (for convertion to roiMatrix)
christoph's avatar
christoph committed
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
        """
        indices = []
        for roi in roiList:
            inds = []
            for ii in range(roi[0],roi[1]):
                for jj in range(roi[2],roi[3]):
                    inds.append((ii,jj))
            indices.append(inds)
        # assign the defined rois to the roi_object class
        if detImageShape:
            self.roi_obj.roi_matrix     = xrs_rois.convert_inds_to_matrix(indices,detImageShape)
        self.roi_obj.red_rois       = xrs_rois.convert_matrix_to_redmatrix(self.roi_obj.roi_matrix)
        self.roi_obj.indices        = indices
        self.roi_obj.kind           = 'simoStyle'
        self.roi_obj.x_indices      = xrs_rois.convert_inds_to_xinds(indices)
        self.roi_obj.y_indices      = xrs_rois.convert_inds_to_yinds(indices)
        self.roi_obj.masks          = xrs_rois.convert_roi_matrix_to_masks(self.roi_obj.roi_matrix)
        self.roi_obj.number_of_rois = int(np.amax(self.roi_obj.roi_matrix))

    def refine_pw_rois(self, roi_obj, pw_data, n_components=2, method='nnma', cov_thresh=-1):
        """**refine_pw_rois**

        Use decomposition of pixelwise data for each ROI to find which of the pixels holds
        data from the sample and which one only has background. 

        Args:
alex's avatar
alex committed
750
751
752
753
          * roi_obj (roi_object): ROI object to be refined.
          * pw_data       (list): List containing one 2D numpy array per ROI holding pixel-wise signals.
          * n_components   (int): Number of components in the decomposition.
          * method      (string): Keyword describing which decomposition to be used ('pca', 'ica', 'nnma').
christoph's avatar
christoph committed
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
        """
        # check if available method is used
        avail_methods = ['pca','ica','nnma']
        if not method in avail_methods:
            print('Please use one of the following methods: ' + str(avail_methods) + '!')
            return

        # check if scikit learn is available
        try:
            from sklearn.decomposition import FastICA, PCA, ProjectedGradientNMF
        except ImportError:
            raise ImportError('Please install the scikit-learn package to use this feature.')
            return

        counter = 0
        new_rois = {}
770
        for data, key in zip(pw_data, sorted(roi_obj.red_rois  ,   key = lambda x:  int(''.join(filter(str.isdigit, str(x) )))   )): # go through each matrix (one per ROI)
christoph's avatar
christoph committed
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852

            # decompose data, choose method
            if method == 'nnma': # non negative matrix factorisation
                nnm = ProjectedGradientNMF(n_components=n_components)
                N   = nnm.fit_transform(data)
            elif method == 'pca': # principal component analysis
                pca = PCA(n_components=n_components)
                N = pca.fit_transform(data)
            elif method == 'ica': # independent component analysis
                ica = FastICA(n_components=n_components)
                N = ica.fit_transform(data)
            else:
                print('No method: \'' + method + '\' available. Will stop here.' )

            # let user decide which component belongs to the data:
            user_choise = 0
            plt.cla()
            title_txt = 'Click component that resembles the sample spectrum for ROI %02d'%(counter+1) + '.'
            plt.title(title_txt)
            legendstr = []
            for ii in range(n_components):
                plt.plot(N[:,ii])
                legendstr.append('Component No. %01d' %ii)
            plt.legend(legendstr)
            plt.xlabel('points along scan')
            plt.ylabel('intensity [arb. units]')
            user_input = np.array(plt.ginput(1,timeout=-1)[0])

            # which curve was chosen
            nearest_points = [(np.abs(N[:,ii]-user_input[1])).argmin() for ii in range(n_components)]
            user_choice = (np.abs(nearest_points-user_input[0])).argmin()

            # find covariance for all pixels with user choice
            covariance = np.array([])
            for ii in range(len(data[0,:])):
                covariance = np.append(covariance, np.cov(data[:,ii],N[:,user_choice])[0,0])

            # plot covariance, let user choose the the cutoff in y direction
            plt.cla()
            title_txt = 'Click to define a y-threshold for ROI %02d'%(counter+1) + '.'
            plt.title(title_txt)
            plt.plot(covariance,'-o')
            plt.xlabel('pixels in ROI')
            plt.ylabel('covariance [arb. units]')
            if cov_thresh < 0:
                user_cutoff = np.array(plt.ginput(1,timeout=-1)[0])
            elif cov_thresh>0 and isinstance(cov_thresh,int):
                if len(covariance) < cov_thresh:
                    print('ROI has fewer pixels than cov_thresh, will break here.')
                    return
                else:
                    user_cutoff = np.array([0.0, np.sort(covariance)[-cov_thresh]])
            else:
                print('Please provide cov_thresh as positive integer!')

            # find the ROI indices above the cutoff, reassign ROI indices
            inds = covariance >= user_cutoff[1]
            #print('inds is ', inds)
            ravel_roi        = roi_obj.red_rois[key][1].ravel()
            ravel_roi[~inds] = 0.0
            roi_obj.red_rois[key][1] = np.reshape(ravel_roi, (roi_obj.red_rois[key][1].shape))

            # end loop
            counter += 1

        # reassign ROI object
        self.roi_obj.roi_matrix     = xrs_rois.convert_redmatrix_to_matrix(roi_obj.red_rois, np.zeros(self.roi_obj.input_image.shape))
        self.roi_obj.indices        = xrs_rois.convert_matrix_rois_to_inds(self.roi_obj.roi_matrix)
        self.roi_obj.kind           = 'refined'
        self.roi_obj.x_indices      = xrs_rois.convert_inds_to_xinds(self.roi_obj.indices)
        self.roi_obj.y_indices      = xrs_rois.convert_inds_to_yinds(self.roi_obj.indices)
        self.roi_obj.masks          = xrs_rois.convert_roi_matrix_to_masks(self.roi_obj.roi_matrix)
        self.roi_obj.number_of_rois = int(np.amax(self.roi_obj.roi_matrix))


    def refine_rois_MF(self, hydra_obj, scan_numbers, n_components=2, method='nnma', cov_thresh=-1):
        """**refine_rois_MF**

        Use decomposition of pixelwise data for each ROI to find which of the pixels holds
        data from the sample and which one only has background. 

        Args:
853
854
          * hydra_obj   (hydra_object): Object from the xrs_read.Hydra class that hold scans to be used           
                                        for the refinement of the ROIs.
alex's avatar
alex committed
855
856
857
          * scan_numbers (int or list): Scan numbers of scans to be used in the refinement.
          * n_components         (int): Number of components in the decomposition.
          * method            (string): Keyword describing which decomposition to be used ('pca', 'ica', 'nnma').
christoph's avatar
christoph committed
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
        """
        # check if available method is used
        if not method in ['pca','ica','nnma']:
            print('Please use one of the following methods: ' + str(avail_methods) + '!')
            return

        # check if scikit learn is available
        try:
            from sklearn.decomposition import FastICA, PCA, ProjectedGradientNMF
        except ImportError:
            from sklearn.decomposition import FastICA, PCA
            from sklearn.decomposition import NMF as ProjectedGradientNMF
        except:
            raise ImportError('Please install the scikit-learn package to use this feature.')
            return

        # make scan_numbers itarable
        if isinstance(scan_numbers,list):
            scannums = scan_numbers
        elif isinstance(scan_numbers,int):
            scannums = [scan_numbers]

        # get EDF-files and pw_data
        hydra_obj.load_scan(scannums, direct=False)
        pw_data = hydra_obj.get_pw_matrices( scannums, method='pixel' )

        counter = 0
        new_rois = {}
886
        for data, key in zip(pw_data, sorted(self.roi_obj.red_rois, key = lambda x:  int(''.join(filter(str.isdigit, str(x) )))    )): # go through each matrix (one per ROI)
christoph's avatar
christoph committed
887
888
889
890
891
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
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962

            # decompose data, choose method
            if method == 'nnma': # non negative matrix factorisation
                nnm = ProjectedGradientNMF(n_components=n_components)
                N   = nnm.fit_transform(data)
            elif method == 'pca': # principal component analysis
                pca = PCA(n_components=n_components)
                N = pca.fit_transform(data)
            elif method == 'ica': # independent component analysis
                ica = FastICA(n_components=n_components)
                N = ica.fit_transform(data)
            else:
                print('No method: \'' + method + '\' available. Will stop here.' )

            # let user decide which component belongs to the data:
            user_choise = 0
            plt.cla()
            title_txt = 'Click component that resembles the sample spectrum for ROI %02d'%(counter+1) + '.'
            plt.title(title_txt)
            legendstr = []
            for ii in range(n_components):
                plt.plot(N[:,ii])
                legendstr.append('Component No. %01d' %ii)
            plt.legend(legendstr)
            plt.xlabel('points along scan')
            plt.ylabel('intensity [arb. units]')
            user_input = np.array(plt.ginput(1,timeout=-1)[0])

            # which curve was chosen
            nearest_points = [(np.abs(N[:,ii]-user_input[1])).argmin() for ii in range(n_components)]
            user_choice = (np.abs(nearest_points-user_input[0])).argmin()

            # find covariance for all pixels with user choice
            covariance = np.array([])
            for ii in range(len(data[0,:])):
                covariance = np.append(covariance, np.cov(data[:,ii],N[:,user_choice])[0,0])

            # plot covariance, let user choose the the cutoff in y direction
            plt.cla()
            title_txt = 'Click to define a y-threshold for ROI %02d'%(counter+1) + '.'
            plt.title(title_txt)
            plt.plot(covariance,'-o')
            plt.xlabel('pixels in ROI')
            plt.ylabel('covariance [arb. units]')
            if cov_thresh < 0:
                user_cutoff = np.array(plt.ginput(1,timeout=-1)[0])
            elif cov_thresh>0 and isinstance(cov_thresh,int):
                if len(covariance) < cov_thresh:
                    print('ROI has fewer pixels than cov_thresh, will break here.')
                    return
                else:
                    user_cutoff = np.array([0.0, np.sort(covariance)[-cov_thresh]])
            else:
                print('Please provide cov_thresh as positive integer!')

            # find the ROI indices above the cutoff, reassign ROI indices
            inds = covariance >= user_cutoff[1]
            #print('inds is ', inds)
            ravel_roi        = self.roi_obj.red_rois[key][1].ravel()
            ravel_roi[~inds] = 0.0
            self.roi_obj.red_rois[key][1] = np.reshape(ravel_roi, (self.roi_obj.red_rois[key][1].shape))

            # end loop
            counter += 1

        # reassign ROI object
        self.roi_obj.roi_matrix     = xrs_rois.convert_redmatrix_to_matrix(self.roi_obj.red_rois, np.zeros(self.roi_obj.input_image.shape))
        self.roi_obj.indices        = xrs_rois.convert_matrix_rois_to_inds(self.roi_obj.roi_matrix)
        self.roi_obj.kind           = 'refined'
        self.roi_obj.x_indices      = xrs_rois.convert_inds_to_xinds(self.roi_obj.indices)
        self.roi_obj.y_indices      = xrs_rois.convert_inds_to_yinds(self.roi_obj.indices)
        self.roi_obj.masks          = xrs_rois.convert_roi_matrix_to_masks(self.roi_obj.roi_matrix)
        self.roi_obj.number_of_rois = int(np.amax(self.roi_obj.roi_matrix))
        # compact the new red_rois
        self.roi_obj.red_rois       = xrs_rois.convert_matrix_to_redmatrix(self.roi_obj.roi_matrix, labelformat= 'ROI%02d')

963
964

        
christoph's avatar
christoph committed
965
966
967
    def find_pw_rois(self,roi_obj,pw_data,save_dataset=False):
        """
        **find_pw_rois**
alex's avatar
alex committed
968
969
970
971
972
973
974
975
         Allows for manual refinement of ROIs by plotting the spectra pixel-wise.
         Loops through the spectra pixel-by-pixel and ROI by ROI, click above the
         black line to keep the pixel plotted, click below the black line to discard 
         the pixel.

         Args:
          * roi_obj (roi_object): ROI object from the XRStools.xrs_rois module with roughly defined ROIs.
          * pw_data (np.array): List containing one 2D numpy array per ROI holding pixel-wise signals.
christoph's avatar
christoph committed
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
        """
        counter = 0
        new_indices = []
        pixelCounter = 0
        for data in pw_data: # go through each ROI
            refined_indices = []
            for ii in range(len(data[0,:])):
                user_choice = 1
                plt.cla()
                title_txt = 'Click above to keep/below black line to discard pixel for ROI %02d'%(counter+1) + '.'
                plt.title(title_txt)
                plt.plot(data[:,ii],'b-')
                axes = plt.gca()
                offset = np.mean(axes.get_ylim())
                plt.plot(np.zeros(len(data[:,ii])) + offset,'k-')
                plt.xlabel('points along scan')
                plt.ylabel('intensity [arb. units]')
                plt.legend(['Pixel No. %02d'%ii])
                # let user click a point on figure
                user_input = np.array(plt.ginput(1,timeout=-1)[0])
                if user_input[1] >= offset:
                    refined_indices.append(roi_obj.indices[counter][ii])
                elif user_input[1] < offset:
                    user_choice = 0
                else: