source: sasview/guiframe/local_perspectives/plotting/boxSlicer.py @ d7a39e5

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 d7a39e5 was d955bf19, checked in by Gervaise Alina <gervyh@…>, 14 years ago

working on documentation

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