source: sasview/guiframe/local_perspectives/plotting/AnnulusSlicer.py @ 1b69256

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 1b69256 was 70cf5d3, checked in by Gervaise Alina <gervyh@…>, 15 years ago

allow selecting for fit for average data1D

  • Property mode set to 100644
File size: 13.2 KB
Line 
1#TODO: the line slicer should listen to all 2DREFRESH events, get the data and slice it
2#      before pushing a new 1D data update.
3
4#
5#TODO: NEED MAJOR REFACTOR
6#
7
8import math
9import wx
10from copy import deepcopy
11# Debug printout
12from sans.guicomm.events import NewPlotEvent, StatusEvent,SlicerParameterEvent,EVT_SLICER_PARS
13from BaseInteractor import _BaseInteractor
14
15
16class AnnulusInteractor(_BaseInteractor):
17    """
18         Select an annulus through a 2D plot.
19         This interactor is used to average 2D data  with the region
20         defined by 2 radius.
21         this class is defined by 2 Ringinterators.
22    """
23    def __init__(self,base,axes,color='black', zorder=3):
24       
25        _BaseInteractor.__init__(self, base, axes, color=color)
26        self.markers = []
27        self.axes = axes
28        self.base= base
29        self.qmax = min(math.fabs(self.base.data2D.xmax),math.fabs(self.base.data2D.xmin))  #must be positive
30        self.connect = self.base.connect
31   
32        ## Number of points on the plot
33        self.nbins = 20
34       
35        #Cursor position of Rings (Left(-1) or Right(1))
36        self.xmaxd=self.base.data2D.xmax
37        self.xmind=self.base.data2D.xmin
38
39        if (self.xmaxd+self.xmind)>0:
40            self.sign=1
41        else:
42            self.sign=-1
43                 
44        # Inner circle
45        self.inner_circle = RingInteractor(self, self.base.subplot, zorder=zorder, r=self.qmax/2.0,sign=self.sign)
46        self.inner_circle.qmax = self.qmax
47        self.outer_circle = RingInteractor(self, self.base.subplot, zorder=zorder+1, r=self.qmax/1.8,sign=self.sign)
48        self.outer_circle.qmax = self.qmax*1.2
49       
50        self.update()
51        self._post_data()
52       
53        # Bind to slice parameter events
54        self.base.Bind(EVT_SLICER_PARS, self._onEVT_SLICER_PARS)
55       
56       
57
58    def _onEVT_SLICER_PARS(self, event):
59        """
60            receive an event containing parameters values to reset the slicer
61            @param event: event of type SlicerParameterEvent with params as
62            attribute
63        """
64        wx.PostEvent(self.base, StatusEvent(status="AnnulusSlicer._onEVT_SLICER_PARS"))
65        event.Skip()
66        if event.type == self.__class__.__name__:
67            self.set_params(event.params)
68            self.base.update()
69
70    def set_layer(self, n):
71        """
72             Allow adding plot to the same panel
73             @param n: the number of layer
74        """
75        self.layernum = n
76        self.update()
77       
78    def clear(self):
79        """
80            Clear the slicer and all connected events related to this slicer
81        """
82        self.clear_markers()
83        self.outer_circle.clear()
84        self.inner_circle.clear()
85        self.base.connect.clearall()
86        self.base.Unbind(EVT_SLICER_PARS)
87       
88       
89    def update(self):
90        """
91            Respond to changes in the model by recalculating the profiles and
92            resetting the widgets.
93        """
94        # Update locations       
95        self.inner_circle.update()
96        self.outer_circle.update()
97       
98
99    def save(self, ev):
100        """
101            Remember the roughness for this layer and the next so that we
102            can restore on Esc.
103        """
104        self.base.freeze_axes()
105        self.inner_circle.save(ev)
106        self.outer_circle.save(ev)
107
108    def _post_data(self,nbins=None):
109        """
110            Uses annulus parameters to plot averaged data into 1D data.
111            @param nbins: the number of points to plot
112        """
113        #Data to average
114        data = self.base.data2D
115        # If we have no data, just return
116        if data == None:
117            return
118       
119        from DataLoader.manipulations import SectorPhi
120   
121        rmin= min(math.fabs(self.inner_circle.get_radius()),
122                  math.fabs(self.outer_circle.get_radius()))
123        rmax = max(math.fabs(self.inner_circle.get_radius()),
124                   math.fabs(self.outer_circle.get_radius()))
125        #if the user does not specify the numbers of points to plot
126        # the default number will be nbins= 20
127        if nbins==None:
128            self.nbins= 20
129        else:
130            self.nbins = nbins
131        ## create the data1D Q average of data2D   
132        sect = SectorPhi(r_min=rmin , r_max= rmax,
133                          phi_min=0, phi_max=2*math.pi , nbins=self.nbins)
134        sector = sect(self.base.data2D)
135       
136        from sans.guiframe.dataFitting import Data1D
137        if hasattr(sector,"dxl"):
138            dxl= sector.dxl
139        else:
140            dxl= None
141        if hasattr(sector,"dxw"):
142            dxw= sector.dxw
143        else:
144            dxw= None
145       
146        new_plot = Data1D(x=sector.x,y=sector.y,dy=sector.dy,dxl=dxl,dxw=dxw)
147        new_plot.name = "SectorPhi" +"("+ self.base.data2D.name+")"
148       
149        new_plot.source=self.base.data2D.source
150        #new_plot.info=self.base.data2D.info
151       
152        new_plot.interactive = True
153        new_plot.detector =self.base.data2D.detector
154        # If the data file does not tell us what the axes are, just assume...
155        new_plot.xaxis("\\rm{\phi}", 'degrees')
156        new_plot.yaxis("\\rm{Intensity} ","cm^{-1}")
157        new_plot.group_id = "SectorPhi"+self.base.data2D.name
158        new_plot.id= "SectorPhi"+self.base.data2D.name
159        #new_plot.is_data= True
160       
161        new_plot.xtransform="x"
162        new_plot.ytransform="y"
163        wx.PostEvent(self.base.parent, NewPlotEvent(plot=new_plot,
164                                                 title="SectorPhi" ))
165       
166         
167    def moveend(self, ev):
168        """
169            Called when any dragging motion ends.
170            Post an event (type =SlicerParameterEvent)
171            to plotter 2D with a copy  slicer parameters
172            Call  _post_data method
173        """
174        self.base.thaw_axes()
175        # Post parameters to plotter 2D
176        event = SlicerParameterEvent()
177        event.type = self.__class__.__name__
178        event.params = self.get_params()
179        wx.PostEvent(self.base, event)
180        # create a 1D data plot
181        self._post_data()
182           
183    def restore(self):
184        """
185        Restore the roughness for this layer.
186        """
187        self.inner_circle.restore()
188        self.outer_circle.restore()
189
190    def move(self, x, y, ev):
191        """
192        Process move to a new position, making sure that the move is allowed.
193        """
194        pass
195       
196    def set_cursor(self, x, y):
197        pass
198       
199    def get_params(self):
200        """
201            Store a copy of values of parameters of the slicer into a dictionary.
202            @return params: the dictionary created
203        """
204        params = {}
205        params["inner_radius"] = math.fabs(self.inner_circle._inner_mouse_x)
206        params["outer_radius"] = math.fabs(self.outer_circle._inner_mouse_x)
207        params["nbins"] = self.nbins
208        return params
209   
210    def set_params(self, params):
211        """
212            Receive a dictionary and reset the slicer with values contained
213            in the values of the dictionary.
214            @param params: a dictionary containing name of slicer parameters and
215            values the user assigned to the slicer.
216        """
217        inner = math.fabs(params["inner_radius"] )
218        outer = math.fabs(params["outer_radius"] )
219        self.nbins = int(params["nbins"])
220        ## Update the picture
221        self.inner_circle.set_cursor(inner, self.inner_circle._inner_mouse_y)
222        self.outer_circle.set_cursor(outer, self.outer_circle._inner_mouse_y)
223        ## Post the data given the nbins entered by the user
224        self._post_data(self.nbins)
225       
226    def freeze_axes(self):
227        self.base.freeze_axes()
228       
229    def thaw_axes(self):
230        self.base.thaw_axes()
231
232    def draw(self):
233        self.base.draw()
234
235       
236class RingInteractor(_BaseInteractor):
237    """
238         Draw a ring Given a radius
239         @param: the color of the line that defined the ring
240         @param r: the radius of the ring
241         @param sign: the direction of motion the the marker
242    """
243    def __init__(self,base,axes,color='black', zorder=5, r=1.0,sign=1):
244       
245        _BaseInteractor.__init__(self, base, axes, color=color)
246        self.markers = []
247        self.axes = axes
248        # Current radius of the ring
249        self._inner_mouse_x = r
250        #Value of the center of the ring
251        self._inner_mouse_y = 0
252        # previous value of that radius
253        self._inner_save_x  = r
254        #Save value of the center of the ring
255        self._inner_save_y  = 0
256        #Class instantiating RingIterator class
257        self.base= base
258        #the direction of the motion of the marker
259        self.sign=sign
260        ## Create a marker
261        try:
262            # Inner circle marker
263            self.inner_marker = self.axes.plot([self.sign*math.fabs(self._inner_mouse_x)],[0], linestyle='',
264                                          marker='s', markersize=10,
265                                          color=self.color, alpha=0.6,
266                                          pickradius=5, label="pick", 
267                                          zorder=zorder, # Prefer this to other lines
268                                          visible=True)[0]
269        except:
270            self.inner_marker = self.axes.plot([self.sign*math.fabs(self._inner_mouse_x)],[0], linestyle='',
271                                          marker='s', markersize=10,
272                                          color=self.color, alpha=0.6,
273                                          label="pick", 
274                                          visible=True)[0]
275            message  = "\nTHIS PROTOTYPE NEEDS THE LATEST VERSION OF MATPLOTLIB\n"
276            message += "Get the SVN version that is at least as recent as June 1, 2007"
277           
278            owner=self.base.base.parent
279            wx.PostEvent(owner, StatusEvent(status="AnnulusSlicer: %s"%message))
280           
281        # Draw a circle
282        [self.inner_circle] = self.axes.plot([],[],
283                                      linestyle='-', marker='',
284                                      color=self.color)
285        # the number of points that make the ring line
286        self.npts = 40
287           
288        self.connect_markers([self.inner_marker])
289        self.update()
290
291    def set_layer(self, n):
292        """
293             Allow adding plot to the same panel
294             @param n: the number of layer
295        """
296        self.layernum = n
297        self.update()
298       
299    def clear(self):
300        """
301            Clear the slicer and all connected events related to this slicer
302        """
303        self.clear_markers()
304        try:
305            self.inner_marker.remove()
306            self.inner_circle.remove()
307        except:
308            # Old version of matplotlib
309            for item in range(len(self.axes.lines)):
310                del self.axes.lines[0]
311       
312       
313       
314    def get_radius(self):
315        """
316            @return self._inner_mouse_x: the current radius of the ring
317        """
318        return self._inner_mouse_x
319       
320    def update(self):
321        """
322            Draw the new roughness on the graph.
323        """
324        # Plot inner circle
325        x = []
326        y = []
327        for i in range(self.npts):
328            phi = 2.0*math.pi/(self.npts-1)*i
329           
330            xval = 1.0*self._inner_mouse_x*math.cos(phi) 
331            yval = 1.0*self._inner_mouse_x*math.sin(phi) 
332           
333            x.append(xval)
334            y.append(yval)
335           
336        self.inner_marker.set(xdata=[self.sign*math.fabs(self._inner_mouse_x)],ydata=[0])
337        self.inner_circle.set_data(x, y)       
338
339    def save(self, ev):
340        """
341        Remember the roughness for this layer and the next so that we
342        can restore on Esc.
343        """
344        self._inner_save_x = self._inner_mouse_x
345        self._inner_save_y = self._inner_mouse_y
346        self.base.freeze_axes()
347
348    def moveend(self, ev):
349        """
350            Called after a dragging motion
351        """
352        self.base.moveend(ev)
353           
354    def restore(self):
355        """
356        Restore the roughness for this layer.
357        """
358        self._inner_mouse_x = self._inner_save_x
359        self._inner_mouse_y = self._inner_save_y
360
361    def move(self, x, y, ev):
362        """
363        Process move to a new position, making sure that the move is allowed.
364        """
365        self._inner_mouse_x = x
366        self._inner_mouse_y = y
367        self.base.base.update()
368       
369    def set_cursor(self, x, y):
370        """
371            draw the ring given x, y value
372        """
373        self.move(x, y, None)
374        self.update()
375       
376       
377    def get_params(self):
378        """
379            Store a copy of values of parameters of the slicer into a dictionary.
380            @return params: the dictionary created
381        """
382        params = {}
383        params["radius"] = math.fabs(self._inner_mouse_x)
384        return params
385   
386    def set_params(self, params):
387        """
388            Receive a dictionary and reset the slicer with values contained
389            in the values of the dictionary.
390            @param params: a dictionary containing name of slicer parameters and
391            values the user assigned to the slicer.
392        """
393        x = params["radius"] 
394        self.set_cursor(x, self._inner_mouse_y)
395       
396       
Note: See TracBrowser for help on using the repository browser.