source: sasview/guiframe/local_perspectives/plotting/SectorSlicer.py @ 4158af4

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 4158af4 was 55a0dc1, checked in by Gervaise Alina <gervyh@…>, 14 years ago

remove reference to guicomm in guiframe

  • Property mode set to 100644
File size: 22.1 KB
Line 
1
2import math
3import wx
4#from copy import deepcopy
5from BaseInteractor import _BaseInteractor
6from sans.guiframe.events import NewPlotEvent
7from sans.guiframe.events import StatusEvent
8from sans.guiframe.events import SlicerParameterEvent
9from sans.guiframe.events import EVT_SLICER_PARS
10from sans.guiframe.dataFitting import Data1D
11
12
13class SectorInteractor(_BaseInteractor):
14    """
15    Draw a sector slicer.Allow to performQ averaging on data 2D
16    """
17    def __init__(self, base, axes, color='black', zorder=3):
18       
19        _BaseInteractor.__init__(self, base, axes, color=color)
20        ## Class initialization
21        self.markers = []
22        self.axes = axes   
23        ## connect the plot to event
24        self.connect = self.base.connect
25       
26        ## compute qmax limit to reset the graph     
27        x = math.pow(max(self.base.data2D.xmax, 
28                         math.fabs(self.base.data2D.xmin)), 2)
29        y = math.pow(max(self.base.data2D.ymax, 
30                         math.fabs(self.base.data2D.ymin)), 2)
31        self.qmax = math.sqrt(x + y)
32        ## Number of points on the plot
33        self.nbins = 20
34        ## Angle of the middle line
35        self.theta2 = math.pi/3
36        ## Absolute value of the Angle between the middle line and any side line
37        self.phi = math.pi/12
38        ## Middle line
39        self.main_line = LineInteractor(self, self.base.subplot, color='blue', 
40                                        zorder=zorder, r=self.qmax,
41                                           theta= self.theta2)
42        self.main_line.qmax = self.qmax
43        ## Right Side line
44        self.right_line = SideInteractor(self, self.base.subplot, color='black',
45                                          zorder=zorder, r=self.qmax,
46                                          phi=-1*self.phi, theta2=self.theta2)
47        self.right_line.qmax = self.qmax
48        ## Left Side line
49        self.left_line = SideInteractor(self, self.base.subplot, color='black',
50                                        zorder=zorder, r=self.qmax,
51                                           phi=self.phi, theta2=self.theta2)
52        self.left_line.qmax = self.qmax
53        ## draw the sector               
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    def _onEVT_SLICER_PARS(self, event):
60        """
61        receive an event containing parameters values to reset the slicer
62       
63        :param event: event of type SlicerParameterEvent with params as
64        attribute
65       
66        """
67        wx.PostEvent(self.base.parent,
68                     StatusEvent(status="SectorSlicer._onEVT_SLICER_PARS"))
69        event.Skip()
70        if event.type == self.__class__.__name__:
71            self.set_params(event.params)
72            self.base.update()
73           
74    def set_layer(self, n):
75        """
76         Allow adding plot to the same panel
77         
78        :param n: the number of layer
79       
80        """
81        self.layernum = n
82        self.update()
83       
84    def clear(self):
85        """
86        Clear the slicer and all connected events related to this slicer
87        """
88        self.clear_markers()
89        self.main_line.clear()
90        self.left_line.clear()
91        self.right_line.clear()
92        self.base.connect.clearall()
93        self.base.Unbind(EVT_SLICER_PARS)
94       
95    def update(self):
96        """
97        Respond to changes in the model by recalculating the profiles and
98        resetting the widgets.
99        """
100        # Update locations 
101        ## Check if the middle line was dragged and
102        #update the picture accordingly     
103        if self.main_line.has_move:
104            self.main_line.update()
105            self.right_line.update(delta=-self.left_line.phi/2,
106                                    mline=self.main_line.theta)
107            self.left_line.update(delta=self.left_line.phi/2,
108                                   mline=self.main_line.theta)
109        ## Check if the left side has moved and update the slicer accordingly 
110        if self.left_line.has_move:
111            self.main_line.update()
112            self.left_line.update(phi=None, delta=None, mline=self.main_line,
113                                  side=True, left=True)
114            self.right_line.update(phi=self.left_line.phi, delta=None,
115                                     mline=self.main_line, side=True,
116                                     left=False, right=True)
117        ## Check if the right side line has moved and
118        #update the slicer accordingly
119        if self.right_line.has_move:
120            self.main_line.update()
121            self.right_line.update(phi=None, delta=None, mline=self.main_line,
122                                   side=True, left=False, right=True)
123            self.left_line.update(phi=self.right_line.phi, delta=None,
124                                    mline=self.main_line, side=True, left=False)
125           
126    def save(self, ev):
127        """
128        Remember the roughness for this layer and the next so that we
129        can restore on Esc.
130        """
131        self.base.freeze_axes()
132        self.main_line.save(ev)
133        self.right_line.save(ev)
134        self.left_line.save(ev)
135
136    def _post_data(self, nbins=None):
137        """
138        compute sector averaging of data2D into data1D
139       
140        :param nbins: the number of point to plot for the average 1D data
141        """
142        ## get the data2D to average
143        data = self.base.data2D
144        # If we have no data, just return
145        if data == None:
146            return
147        ## Averaging
148        from DataLoader.manipulations import SectorQ
149        radius = self.qmax
150        phimin =  -self.left_line.phi + self.main_line.theta
151        phimax = self.left_line.phi + self.main_line.theta
152        if nbins == None:
153            nbins = 20
154        sect = SectorQ(r_min=0.0, r_max=radius,
155                        phi_min=phimin + math.pi,
156                        phi_max=phimax + math.pi, nbins=nbins)
157     
158        sector = sect(self.base.data2D)
159        ##Create 1D data resulting from average
160       
161        if hasattr(sector, "dxl"):
162            dxl = sector.dxl
163        else:
164            dxl = None
165        if hasattr(sector, "dxw"):
166            dxw = sector.dxw
167        else:
168            dxw = None
169        new_plot = Data1D(x=sector.x, y=sector.y, dy=sector.dy)
170        new_plot.dxl = dxl
171        new_plot.dxw = dxw
172        new_plot.name = "SectorQ" + "(" + self.base.data2D.name + ")"
173        new_plot.source = self.base.data2D.source
174        #new_plot.info=self.base.data2D.info
175        new_plot.interactive = True
176        new_plot.detector = self.base.data2D.detector
177        # If the data file does not tell us what the axes are, just assume...
178        new_plot.xaxis("\\rm{Q}", 'A^{-1}')
179        new_plot.yaxis("\\rm{Intensity} ", "cm^{-1}")
180        new_plot.group_id = "SectorQ" + self.base.data2D.name
181        new_plot.id = "SectorQ" + self.base.data2D.name
182        new_plot.is_data = True
183        wx.PostEvent(self.base.parent, NewPlotEvent(plot=new_plot,
184                                    title="SectorQ" + self.base.data2D.name))
185       
186    def moveend(self, ev):
187        """
188        Called a dragging motion ends.Get slicer event
189        """
190        self.base.thaw_axes()
191        ## Post parameters
192        event = SlicerParameterEvent()
193        event.type = self.__class__.__name__
194        event.params = self.get_params()
195        ## Send slicer paramers to plotter2D
196        wx.PostEvent(self.base, event)
197       
198    def restore(self):
199        """
200        Restore the roughness for this layer.
201        """
202        self.main_line.restore()
203        self.left_line.restore()
204        self.right_line.restore()
205
206    def move(self, x, y, ev):
207        """
208        Process move to a new position, making sure that the move is allowed.
209        """
210        pass
211       
212    def set_cursor(self, x, y):
213        """
214        """
215        pass
216       
217    def get_params(self):
218        """
219        Store a copy of values of parameters of the slicer into a dictionary.
220       
221        :return params: the dictionary created
222       
223        """
224        params = {}
225        ## Always make sure that the left and the right line are at phi
226        ## angle of the middle line
227        if math.fabs(self.left_line.phi) != math.fabs(self.right_line.phi):
228            msg = "Phi left and phi right are different"
229            msg += " %f, %f" % (self.left_line.phi, self.right_line.phi)
230            raise ValueError, msg
231        params["Phi"] = self.main_line.theta
232        params["Delta_Phi"] = math.fabs(self.left_line.phi)
233        params["nbins"] = self.nbins
234        return params
235   
236    def set_params(self, params):
237        """
238        Receive a dictionary and reset the slicer with values contained
239        in the values of the dictionary.
240       
241        :param params: a dictionary containing name of slicer parameters and
242            values the user assigned to the slicer.
243        """
244        main = params["Phi"] 
245        phi = math.fabs(params["Delta_Phi"])
246        self.nbins = int(params["nbins"])
247        self.main_line.theta = main
248        ## Reset the slicer parameters
249        self.main_line.update()
250        self.right_line.update(phi=phi, delta=None, mline=self.main_line,
251                               side=True, right=True)
252        self.left_line.update(phi=phi, delta=None, 
253                              mline=self.main_line, side=True)
254        ## post the new corresponding data
255        self._post_data(nbins=self.nbins)
256       
257    def freeze_axes(self):
258        """
259        """
260        self.base.freeze_axes()
261   
262    def thaw_axes(self):
263        """
264        """
265        self.base.thaw_axes()
266
267    def draw(self):
268        """
269        """
270        self.base.draw()
271
272       
273class SideInteractor(_BaseInteractor):
274    """
275    Draw an oblique line
276   
277    :param phi: the phase between the middle line and one side line
278    :param theta2: the angle between the middle line and x- axis
279   
280    """
281    def __init__(self, base, axes, color='black', zorder=5, r=1.0,
282                 phi=math.pi/4, theta2= math.pi/3):
283        """
284        """
285        _BaseInteractor.__init__(self, base, axes, color=color)
286        ## Initialize the class
287        self.markers = []
288        self.axes = axes
289        ## compute the value of the angle between the current line and
290        ## the x-axis 
291        self.save_theta = theta2 + phi
292        self.theta = theta2 + phi
293        ## the value of the middle line angle with respect to the x-axis
294        self.theta2 = theta2
295        ## Radius to find polar coordinates this line's endpoints
296        self.radius = r
297        ## phi is the phase between the current line and the middle line
298        self.phi = phi
299        ## End points polar coordinates
300        x1 = self.radius * math.cos(self.theta)
301        y1 = self.radius * math.sin(self.theta)
302        x2 = -1 * self.radius * math.cos(self.theta)
303        y2 = -1 * self.radius * math.sin(self.theta)
304        ## defining a new marker
305        try:
306            self.inner_marker = self.axes.plot([x1/2.5], [y1/2.5], linestyle='',
307                                          marker='s', markersize=10,
308                                          color=self.color, alpha=0.6,
309                                          pickradius=5, label="pick", 
310                                          # Prefer this to other lines
311                                          zorder=zorder, visible=True)[0]
312        except:
313            self.inner_marker = self.axes.plot([x1/2.5],[y1/2.5], 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"
318            message += " VERSION 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="sectorSlicer: %s" % message))
323       
324        ## Defining the current line
325        self.line = self.axes.plot([x1, x2], [y1, y2],
326                                      linestyle='-', marker='',
327                                      color=self.color, visible=True)[0]
328        ## Flag to differentiate the left line from the right line motion
329        self.left_moving = False
330        ## Flag to define a motion
331        self.has_move = False
332        ## connecting markers and draw the picture
333        self.connect_markers([self.inner_marker, self.line])
334       
335    def set_layer(self, n):
336        """
337        Allow adding plot to the same panel
338         
339        :param n: the number of layer
340       
341        """
342        self.layernum = n
343        self.update()
344       
345    def clear(self):
346        """
347        Clear the slicer and all connected events related to this slicer
348        """
349        self.clear_markers()
350        try:
351            self.line.remove()
352            self.inner_marker.remove()
353        except:
354            # Old version of matplotlib
355            for item in range(len(self.axes.lines)):
356                del self.axes.lines[0]
357   
358    def update(self, phi=None, delta=None, mline=None,
359               side=False, left= False, right=False):
360        """
361        Draw oblique line
362       
363        :param phi: the phase between the middle line and the current line
364        :param delta: phi/2 applied only when the mline was moved
365       
366        """
367        #print "update left or right ", self.has_move
368        self.left_moving = left
369        theta3 = 0
370        if phi != None:
371            self.phi = phi
372        if delta == None:
373            delta = 0
374        if  right:
375            self.phi = -1 * math.fabs(self.phi)
376            #delta=-delta
377        else:
378            self.phi = math.fabs(self.phi)
379        if side:
380            self.theta = mline.theta + self.phi
381                   
382        if mline != None :
383            if delta != 0:
384                self.theta2 = mline + delta
385            else:
386                self.theta2 = mline.theta
387        if delta == 0:
388            theta3 = self.theta + delta
389        else:
390            theta3 = self.theta2 + delta
391        x1 = self.radius * math.cos(theta3)
392        y1 = self.radius * math.sin(theta3)
393        x2 = -1 * self.radius * math.cos(theta3)
394        y2 = -1 * self.radius * math.sin(theta3)
395        self.inner_marker.set(xdata=[x1/2.5], ydata=[y1/2.5])
396        self.line.set(xdata=[x1, x2], ydata=[y1, y2]) 
397       
398    def save(self, ev):
399        """
400        Remember the roughness for this layer and the next so that we
401        can restore on Esc.
402        """
403        self.save_theta = self.theta
404        self.base.freeze_axes()
405
406    def moveend(self, ev):
407        """
408        """
409        self.has_move = False
410        self.base.moveend(ev)
411           
412    def restore(self):
413        """
414        Restore the roughness for this layer.
415        """
416        self.theta = self.save_theta
417
418    def move(self, x, y, ev):
419        """
420        Process move to a new position, making sure that the move is allowed.
421        """
422        self.theta = math.atan2(y, x)
423        self.has_move = True
424        #ToDo: Simplify below
425        if not self.left_moving:
426            if  self.theta2 - self.theta <= 0 and self.theta2 > 0:
427                self.restore()
428                return 
429            elif self.theta2 < 0 and self.theta < 0 and \
430                self.theta-self.theta2 >= 0:
431                self.restore()
432                return                             
433            elif  self.theta2 < 0 and self.theta > 0 and \
434                (self.theta2 + 2 * math.pi - self.theta) >= math.pi/2:
435                #print "my theta", self.theta
436                self.restore()
437                return 
438            elif  self.theta2 < 0 and self.theta < 0 and \
439                (self.theta2 - self.theta) >= math.pi/2:
440                #print "my theta", self.theta
441                self.restore()
442                return 
443            elif self.theta2 > 0 and (self.theta2-self.theta >= math.pi/2 or \
444                (self.theta2-self.theta >= math.pi/2)):
445                #print "self theta encore"
446                self.restore()
447                return 
448        else:
449            #print "left move"
450            if  self.theta < 0 and (self.theta + math.pi*2-self.theta2) <= 0:
451                self.restore()
452                return 
453            elif self.theta2 < 0 and (self.theta-self.theta2) <= 0:
454                self.restore()
455                return                             
456            elif  self.theta > 0 and self.theta-self.theta2 <= 0:
457                #print "my theta", self.theta
458                self.restore()
459                return 
460            elif self.theta-self.theta2 >= math.pi/2 or  \
461                ((self.theta + math.pi * 2 - self.theta2) >= math.pi/2 and \
462                 self.theta < 0 and self.theta2 > 0):
463                #print "self theta encore"
464                self.restore()
465                return 
466           
467        self.phi = math.fabs(self.theta2 - self.theta)
468        if self.phi > math.pi:
469            self.phi = 2 * math.pi - math.fabs(self.theta2 - self.theta)
470        self.base.base.update()
471       
472    def set_cursor(self, x, y):
473        """
474        """
475        self.move(x, y, None)
476        self.update()
477   
478    def get_params(self):
479        """
480        """
481        params = {}
482        params["radius"] = self.radius
483        params["theta"] = self.theta
484        return params
485   
486    def set_params(self, params):
487        """
488        """
489        x = params["radius"] 
490        self.set_cursor(x, self._inner_mouse_y)
491       
492
493class LineInteractor(_BaseInteractor):
494    """
495    Select an annulus through a 2D plot
496    """
497    def __init__(self, base, axes, color='black',
498                 zorder=5, r=1.0, theta=math.pi/4):
499        """
500        """
501        _BaseInteractor.__init__(self, base, axes, color=color)
502       
503        self.markers = []
504        self.axes = axes
505        self.save_theta = theta
506        self.theta= theta
507        self.radius = r
508        self.scale = 10.0
509        # Inner circle
510        x1 = self.radius * math.cos(self.theta)
511        y1 = self.radius * math.sin(self.theta)
512        x2 = -1*self.radius * math.cos(self.theta)
513        y2 = -1*self.radius * math.sin(self.theta)
514        try:
515            # Inner circle marker
516            self.inner_marker = self.axes.plot([x1/2.5], [y1/2.5], linestyle='',
517                                          marker='s', markersize=10,
518                                          color=self.color, alpha=0.6,
519                                          pickradius=5, label="pick", 
520                                          # Prefer this to other lines
521                                          zorder=zorder, 
522                                          visible=True)[0]
523        except:
524            self.inner_marker = self.axes.plot([x1/2.5], [y1/2.5], linestyle='',
525                                          marker='s', markersize=10,
526                                          color=self.color, alpha=0.6,
527                                          label="pick", 
528                                          visible=True)[0]
529            message  = "\nTHIS PROTOTYPE NEEDS THE LATEST VERSION"
530            message += " OF MATPLOTLIB\n Get the SVN version that is at"
531            message += " least as recent as June 1, 2007"
532        self.line = self.axes.plot([x1, x2], [y1, y2],
533                                      linestyle='-', marker='',
534                                      color=self.color, visible=True)[0]
535        self.npts = 20
536        self.has_move = False
537        self.connect_markers([self.inner_marker, self.line])
538        self.update()
539
540    def set_layer(self, n):
541        """
542        """
543        self.layernum = n
544        self.update()
545       
546    def clear(self):
547        """
548        """
549        self.clear_markers()
550        try:
551            self.inner_marker.remove()
552            self.line.remove()
553        except:
554            # Old version of matplotlib
555            for item in range(len(self.axes.lines)):
556                del self.axes.lines[0]
557 
558    def update(self, theta=None):
559        """
560        Draw the new roughness on the graph.
561        """
562       
563        if theta != None:
564            self.theta = theta
565        x1 = self.radius * math.cos(self.theta)
566        y1 = self.radius * math.sin(self.theta)
567        x2 = -1 * self.radius * math.cos(self.theta)
568        y2 = -1 * self.radius * math.sin(self.theta)
569       
570        self.inner_marker.set(xdata=[x1/2.5], ydata=[y1/2.5])
571        self.line.set(xdata=[x1, x2], ydata=[y1, y2]) 
572   
573    def save(self, ev):
574        """
575        Remember the roughness for this layer and the next so that we
576        can restore on Esc.
577        """
578        self.save_theta= self.theta
579        self.base.freeze_axes()
580
581    def moveend(self, ev):
582        """
583        """
584        self.has_move = False
585        self.base.moveend(ev)
586           
587    def restore(self):
588        """
589        Restore the roughness for this layer.
590        """
591        self.theta = self.save_theta
592
593    def move(self, x, y, ev):
594        """
595        Process move to a new position, making sure that the move is allowed.
596        """
597        self.theta = math.atan2(y, x)
598        self.has_move = True
599        self.base.base.update()
600       
601    def set_cursor(self, x, y):
602        """
603        """
604        self.move(x, y, None)
605        self.update()
606       
607    def get_params(self):
608        """
609        """
610        params = {}
611        params["radius"] = self.radius
612        params["theta"] = self.theta
613        return params
614   
615    def set_params(self, params):
616        """
617        """
618        x = params["radius"] 
619        self.set_cursor(x, self._inner_mouse_y)
620       
Note: See TracBrowser for help on using the repository browser.