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

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 5777106 was 5777106, checked in by Mathieu Doucet <doucetm@…>, 11 years ago

Moving things around. Will definitely not build.

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