source: sasview/src/sans/guiframe/local_perspectives/plotting/boxSlicer.py @ 8f56250

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 8f56250 was 8f56250, checked in by Jeff Krzywon <jeffery.krzywon@…>, 10 years ago

I modified boxSlicer to fix the issue outlined in Trac ticket #210. More details are available in the ticket.

  • Property mode set to 100644
File size: 20.1 KB
Line 
1
2
3import wx
4#import copy
5#from copy import deepcopy
6import math
7import numpy
8from sans.guiframe.events import NewPlotEvent
9from sans.guiframe.events import StatusEvent
10from sans.guiframe.events import SlicerParameterEvent
11from sans.guiframe.events import EVT_SLICER_PARS
12from BaseInteractor import _BaseInteractor
13from sans.guiframe.dataFitting import Data1D
14#import SlicerParameters
15
16
17class BoxInteractor(_BaseInteractor):
18    """
19    BoxInteractor define a rectangle that return data1D average of Data2D
20    in a rectangle area defined by -x, x ,y, -y
21    """
22    def __init__(self, base, axes, color='black', zorder=3):
23        _BaseInteractor.__init__(self, base, axes, color=color)
24        ## Class initialization
25        self.markers = []
26        self.axes = axes
27        ##connecting artist
28        self.connect = self.base.connect
29        ## which direction is the preferred interaction direction
30        self.direction = None
31        ## determine x y  values
32        self.x = 0.5 * min(math.fabs(self.base.data2D.xmax),
33                           math.fabs(self.base.data2D.xmin))
34        self.y = 0.5 * min(math.fabs(self.base.data2D.xmax),
35                           math.fabs(self.base.data2D.xmin))       
36        ## when reach qmax reset the graph
37        self.qmax = max(self.base.data2D.xmax, self.base.data2D.xmin,
38                        self.base.data2D.ymax, self.base.data2D.ymin)   
39        ## Number of points on the plot
40        self.nbins = 30
41        ## If True, I(|Q|) will be return, otherwise,
42        #negative q-values are allowed
43        self.fold = True       
44        ## reference of the current  Slab averaging
45        self.averager = None
46        ## Create vertical and horizaontal lines for the rectangle
47        self.vertical_lines = VerticalLines(self,
48                                            self.base.subplot, 
49                                            color='blue', 
50                                            zorder=zorder,
51                                            y=self.y ,
52                                            x=self.x)
53        self.vertical_lines.qmax = self.qmax
54       
55        self.horizontal_lines = HorizontalLines(self,
56                                               self.base.subplot,
57                                               color='green', 
58                                               zorder=zorder,
59                                               x=self.x,
60                                               y=self.y)
61        self.horizontal_lines.qmax = self.qmax
62        ## draw the rectangle and plost the data 1D resulting
63        ## of averaging data2D
64        self.update()
65        self._post_data()
66        ## Bind to slice parameter events
67        self.base.Bind(EVT_SLICER_PARS, self._onEVT_SLICER_PARS)
68
69    def _onEVT_SLICER_PARS(self, event):
70        """
71        receive an event containing parameters values to reset the slicer
72       
73        :param event: event of type SlicerParameterEvent with params as
74            attribute
75        """
76        wx.PostEvent(self.base.parent,
77                     StatusEvent(status="BoxSlicer._onEVT_SLICER_PARS"))
78        event.Skip()
79        if event.type == self.__class__.__name__:
80            self.set_params(event.params)
81            self.base.update()
82           
83    def update_and_post(self):
84        """
85        Update the slicer and plot the resulting data
86        """
87        self.update()
88        self._post_data()
89       
90    def set_layer(self, n):
91        """
92        Allow adding plot to the same panel
93       
94        :param n: the number of layer
95       
96        """
97        self.layernum = n
98        self.update()
99       
100    def clear(self):
101        """
102        Clear the slicer and all connected events related to this slicer
103        """
104        self.averager = None
105        self.clear_markers()
106        self.horizontal_lines.clear()
107        self.vertical_lines.clear()
108        self.base.connect.clearall()
109        self.base.Unbind(EVT_SLICER_PARS)
110       
111    def update(self):
112        """
113        Respond to changes in the model by recalculating the profiles and
114        resetting the widgets.
115        """
116        ##Update the slicer if an horizontal line is dragged   
117        if self.horizontal_lines.has_move:
118            self.horizontal_lines.update()
119            self.vertical_lines.update(y=self.horizontal_lines.y)
120        ##Update the slicer if a vertical line is dragged   
121        if self.vertical_lines.has_move:
122            self.vertical_lines.update()
123            self.horizontal_lines.update(x=self.vertical_lines.x)
124                 
125    def save(self, ev):
126        """
127        Remember the roughness for this layer and the next so that we
128        can restore on Esc.
129        """
130        self.base.freeze_axes()
131        self.vertical_lines.save(ev)
132        self.horizontal_lines.save(ev)
133   
134    def _post_data(self):
135        pass
136       
137    def post_data(self, new_slab=None, nbins=None, direction=None):
138        """
139        post data averaging in Qx or Qy given new_slab type
140       
141        :param new_slab: slicer that determine with direction to average
142        :param nbins: the number of points plotted when averaging
143        :param direction: the direction of averaging
144       
145        """
146        if self.direction == None:
147            self.direction = direction
148           
149        x_min = -1 * math.fabs(self.vertical_lines.x)
150        x_max = math.fabs(self.vertical_lines.x)
151        y_min = -1 * math.fabs(self.horizontal_lines.y)
152        y_max = math.fabs(self.horizontal_lines.y)
153       
154        if nbins != None:
155            self.nbins = nbins
156        if self.averager == None:
157            if new_slab == None:
158                msg = "post data:cannot average , averager is empty"
159                raise ValueError, msg
160            self.averager = new_slab
161        if self.direction == "X":
162            if self.fold:
163                x_low = 0
164            else:
165                x_low = math.fabs(x_min)
166            bin_width = (x_max + x_low)/self.nbins
167        elif self.direction == "Y":
168            if self.fold:
169                y_low = 0
170            else:
171                y_low = math.fabs(y_min)
172            bin_width = (y_max + y_low)/self.nbins
173        else:
174            msg = "post data:no Box Average direction was supplied"
175            raise ValueError, msg
176        ## Average data2D given Qx or Qy
177        box = self.averager(x_min=x_min, x_max=x_max, y_min=y_min, y_max=y_max,
178                         bin_width=bin_width)
179        box.fold = self.fold
180        boxavg = box(self.base.data2D)
181        #3 Create Data1D to plot
182        if hasattr(boxavg, "dxl"):
183            dxl = boxavg.dxl
184        else:
185            dxl = None
186        if hasattr(boxavg, "dxw"):
187            dxw = boxavg.dxw
188        else:
189            dxw = None
190        new_plot = Data1D(x=boxavg.x, y=boxavg.y, dy=boxavg.dy)
191        new_plot.dxl  = dxl
192        new_plot.dxw  = dxw
193        new_plot.name = str(self.averager.__name__) + \
194                        "(" + self.base.data2D.name + ")"
195        new_plot.source = self.base.data2D.source
196        new_plot.interactive = True
197        new_plot.detector = self.base.data2D.detector
198        ## If the data file does not tell us what the axes are, just assume...
199        new_plot.xaxis("\\rm{Q}", "A^{-1}")
200        new_plot.yaxis("\\rm{Intensity} ", "cm^{-1}")
201
202        data = self.base.data2D
203        if hasattr(data, "scale") and data.scale == 'linear' and \
204                self.base.data2D.name.count("Residuals") > 0:
205            new_plot.ytransform = 'y'
206            new_plot.yaxis("\\rm{Residuals} ", "/")
207           
208        new_plot.group_id = "2daverage" + self.base.data2D.name
209        new_plot.id = (self.averager.__name__) + self.base.data2D.name
210        new_plot.is_data= True
211        self.base.parent.update_theory(data_id=self.base.data2D.id, \
212                                       theory=new_plot)
213        wx.PostEvent(self.base.parent, NewPlotEvent(plot=new_plot,
214                                title=str(self.averager.__name__)))
215         
216    def moveend(self, ev):
217        """
218        Called after a dragging event.
219        Post the slicer new parameters and creates a new Data1D
220        corresponding to the new average
221        """
222        self.base.thaw_axes()
223        # Post paramters
224        event = SlicerParameterEvent()
225        event.type = self.__class__.__name__
226        event.params = self.get_params()
227        wx.PostEvent(self.base.parent, event)
228        # create the new data1D
229        self._post_data()
230           
231    def restore(self):
232        """
233        Restore the roughness for this layer.
234        """
235        self.horizontal_lines.restore()
236        self.vertical_lines.restore()
237       
238    def move(self, x, y, ev):
239        """
240        Process move to a new position, making sure that the move is allowed.
241        """
242        pass
243       
244    def set_cursor(self, x, y):
245        pass
246       
247    def get_params(self):
248        """
249        Store a copy of values of parameters of the slicer into a dictionary.
250       
251        :return params: the dictionary created
252       
253        """
254        params = {}
255        params["x_max"] = math.fabs(self.vertical_lines.x)
256        params["y_max"] = math.fabs(self.horizontal_lines.y)
257        params["nbins"] = self.nbins
258        return params
259   
260    def set_params(self, params):
261        """
262        Receive a dictionary and reset the slicer with values contained
263        in the values of the dictionary.
264       
265        :param params: a dictionary containing name of slicer parameters and
266            values the user assigned to the slicer.
267        """
268        self.x = float(math.fabs(params["x_max"]))
269        self.y = float(math.fabs(params["y_max"] ))
270        self.nbins = params["nbins"]
271       
272        self.horizontal_lines.update(x=self.x, y=self.y)
273        self.vertical_lines.update(x=self.x, y=self.y)
274        self.post_data(nbins=None)
275       
276    def freeze_axes(self):
277        """
278        """
279        self.base.freeze_axes()
280       
281    def thaw_axes(self):
282        """
283        """
284        self.base.thaw_axes()
285
286    def draw(self):
287        """
288        """
289        self.base.draw()
290
291
292class HorizontalLines(_BaseInteractor):
293    """
294    Draw 2 Horizontal lines centered on (0,0) that can move
295    on the x- direction and in opposite direction
296    """
297    def __init__(self, base, axes, color='black', zorder=5, x=0.5, y=0.5):
298        """
299        """
300        _BaseInteractor.__init__(self, base, axes, color=color)
301        ##Class initialization
302        self.markers = []
303        self.axes = axes
304        ## Saving the end points of two lines
305        self.x = x
306        self.save_x = x
307       
308        self.y = y
309        self.save_y = y
310        ## Creating a marker
311        try:
312            # Inner circle marker
313            self.inner_marker = self.axes.plot([0], [self.y], linestyle='',
314                                          marker='s', markersize=10,
315                                          color=self.color, alpha=0.6,
316                                          pickradius=5, label="pick", 
317                                          # Prefer this to other lines
318                                          zorder=zorder, 
319                                          visible=True)[0]
320        except:
321            self.inner_marker = self.axes.plot([0], [self.y], linestyle='',
322                                          marker='s', markersize=10,
323                                          color=self.color, alpha=0.6,
324                                          label="pick", visible=True)[0]
325            message  = "\nTHIS PROTOTYPE NEEDS THE LATEST VERSION "
326            message += "OF MATPLOTLIB\n Get the SVN version that"
327            message += " is at least as recent as June 1, 2007"
328            owner = self.base.base.parent
329            wx.PostEvent(owner,
330                         StatusEvent(status="AnnulusSlicer: %s" % message))
331        ## Define 2 horizontal lines
332        self.top_line = self.axes.plot([self.x, -self.x], [self.y, self.y],
333                                      linestyle='-', marker='',
334                                      color=self.color, visible=True)[0]
335        self.bottom_line = self.axes.plot([self.x, -self.x], [-self.y, -self.y],
336                                      linestyle='-', marker='',
337                                      color=self.color, visible=True)[0]
338        ## Flag to check the motion of the lines
339        self.has_move = False
340        ## Connecting markers to mouse events and draw
341        self.connect_markers([self.top_line, self.inner_marker])
342        self.update()
343
344    def set_layer(self, n):
345        """
346        Allow adding plot to the same panel
347       
348        :param n: the number of layer
349       
350        """
351        self.layernum = n
352        self.update()
353       
354    def clear(self):
355        """
356        Clear this slicer  and its markers
357        """
358        self.clear_markers()
359        try:
360            self.inner_marker.remove()
361            self.top_line.remove() 
362            self.bottom_line.remove()
363        except:
364            # Old version of matplotlib
365            for item in range(len(self.axes.lines)):
366                del self.axes.lines[0]
367   
368    def update(self, x=None, y=None):
369        """
370        Draw the new roughness on the graph.
371       
372        :param x: x-coordinates to reset current class x
373        :param y: y-coordinates to reset current class y
374       
375        """
376        ## Reset x, y- coordinates if send as parameters
377        if x != None:
378            self.x = numpy.sign(self.x) * math.fabs(x)
379        if y != None:
380            self.y = numpy.sign(self.y) * math.fabs(y)
381        ## Draw lines and markers
382        self.inner_marker.set(xdata=[0], ydata=[self.y])
383        self.top_line.set(xdata=[self.x, -self.x], ydata=[self.y, self.y])
384        self.bottom_line.set(xdata=[self.x,-self.x], ydata=[-self.y, -self.y])
385       
386    def save(self, ev):
387        """
388        Remember the roughness for this layer and the next so that we
389        can restore on Esc.
390        """
391        self.save_x = self.x
392        self.save_y = self.y
393        self.base.freeze_axes()
394
395    def moveend(self, ev):
396        """
397        Called after a dragging this edge and set self.has_move to False
398        to specify the end of dragging motion
399        """
400        self.has_move = False
401        self.base.moveend(ev)
402             
403    def restore(self):
404        """
405        Restore the roughness for this layer.
406        """
407        self.x = self.save_x
408        self.y = self.save_y
409       
410    def move(self, x, y, ev):
411        """
412        Process move to a new position, making sure that the move is allowed.
413        """
414        self.y = y
415        self.has_move = True
416        self.base.base.update()
417       
418 
419class VerticalLines(_BaseInteractor):
420    """
421    Select an annulus through a 2D plot
422    """
423    def __init__(self, base, axes, color='black', zorder=5, x=0.5, y=0.5):
424        """
425        """
426        _BaseInteractor.__init__(self, base, axes, color=color)
427        self.markers = []
428        self.axes = axes
429        self.x = math.fabs(x)
430        self.save_x = self.x
431        self.y = math.fabs(y)
432        self.save_y = y
433        try:
434            # Inner circle marker
435            self.inner_marker = self.axes.plot([self.x], [0], linestyle='',
436                                          marker='s', markersize=10,
437                                          color=self.color, alpha=0.6,
438                                          pickradius=5, label="pick", 
439                                          # Prefer this to other lines
440                                          zorder=zorder, visible=True)[0]
441        except:
442            self.inner_marker = self.axes.plot([self.x], [0], linestyle='',
443                                          marker='s', markersize=10,
444                                          color=self.color, alpha=0.6,
445                                          label="pick", visible=True)[0]
446            message  = "\nTHIS PROTOTYPE NEEDS THE LATEST VERSION"
447            message += " OF MATPLOTLIB\n Get the SVN version that is"
448            message += " at least as recent as June 1, 2007"
449           
450        self.right_line = self.axes.plot([self.x, self.x],
451                                         [self.y , -self.y],
452                                      linestyle='-', marker='',
453                                      color=self.color, visible=True)[0]
454        self.left_line = self.axes.plot([-self.x, -self.x],
455                                        [self.y, -self.y],
456                                      linestyle='-', marker='',
457                                      color=self.color, visible=True)[0]
458        self.has_move = False
459        self.connect_markers([self.right_line, self.inner_marker])
460        self.update()
461
462    def set_layer(self, n):
463        """
464        Allow adding plot to the same panel
465       
466        :param n: the number of layer
467       
468        """
469        self.layernum = n
470        self.update()
471       
472    def clear(self):
473        """
474        Clear this slicer  and its markers
475        """
476        self.clear_markers()
477        try:
478            self.inner_marker.remove()
479            self.left_line.remove()
480            self.right_line.remove()
481        except:
482            # Old version of matplotlib
483            for item in range(len(self.axes.lines)):
484                del self.axes.lines[0]
485
486    def update(self, x=None, y=None):
487        """
488        Draw the new roughness on the graph.
489       
490        :param x: x-coordinates to reset current class x
491        :param y: y-coordinates to reset current class y
492       
493        """
494        ## reset x, y -coordinates if given as parameters
495        if x != None:
496            self.x = numpy.sign(self.x) * math.fabs(x)
497        if y != None:
498            self.y = numpy.sign(self.y) * math.fabs(y)
499        ## draw lines and markers 
500        self.inner_marker.set(xdata=[self.x], ydata=[0]) 
501        self.left_line.set(xdata=[-self.x, -self.x], ydata=[self.y, -self.y]) 
502        self.right_line.set(xdata=[self.x, self.x], ydata=[self.y, -self.y]) 
503   
504    def save(self, ev):
505        """
506        Remember the roughness for this layer and the next so that we
507        can restore on Esc.
508        """
509        self.save_x = self.x
510        self.save_y = self.y
511        self.base.freeze_axes()
512       
513    def moveend(self, ev):
514        """
515        Called after a dragging this edge and set self.has_move to False
516        to specify the end of dragging motion
517        """
518        self.has_move = False
519        self.base.moveend(ev)
520               
521    def restore(self):
522        """
523        Restore the roughness for this layer.
524        """
525        self.x = self.save_x
526        self.y = self.save_y
527     
528    def move(self, x, y, ev):
529        """
530        Process move to a new position, making sure that the move is allowed.
531        """
532        self.has_move = True
533        self.x = x
534        self.base.base.update()
535       
536   
537class BoxInteractorX(BoxInteractor):
538    """
539    Average in Qx direction
540    """
541    def __init__(self, base, axes, color='black', zorder=3):
542        BoxInteractor.__init__(self, base, axes, color=color)
543        self.base = base
544        self._post_data()
545       
546    def _post_data(self):
547        """
548        Post data creating by averaging in Qx direction
549        """
550        from sans.dataloader.manipulations import SlabX
551        self.post_data(SlabX, direction="X")   
552       
553
554class BoxInteractorY(BoxInteractor):
555    """
556    Average in Qy direction
557    """
558    def __init__(self, base, axes, color='black', zorder=3):
559        BoxInteractor.__init__(self, base, axes, color=color)
560        self.base = base
561        self._post_data()
562       
563    def _post_data(self):
564        """
565        Post data creating by averaging in Qy direction
566        """
567        from sans.dataloader.manipulations import SlabY
568        self.post_data(SlabY, direction="Y")   
569       
570       
Note: See TracBrowser for help on using the repository browser.