source: sasview/guiframe/local_perspectives/plotting/SectorSlicer.py @ 0c218d9

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 0c218d9 was 0c218d9, checked in by Jae Cho <jhjcho@…>, 15 years ago

Improved the behaviors of the sector average lines.
Removed some known bugs.

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