source: sasview/guiframe/local_perspectives/plotting/SectorSlicer.py @ 9fca3ea

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 9fca3ea was 18eba35, checked in by Gervaise Alina <gervyh@…>, 16 years ago

small bugs fixed: clearing slicer improved

  • Property mode set to 100644
File size: 21.7 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.Bind(EVT_SLICER_PARS, self._onEVT_SLICER_PARS)
66
67    def _onEVT_SLICER_PARS(self, event):
68       
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.clearall()
99       
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            #print "main_theta--->",self.main_line.get_radius()*180/3.14
116            self.right_line.update( delta = -self.left_line.phi/2+math.pi,mline= self.main_line.theta)
117            #print "main_theta--->",self.main_line.get_radius()*180/3.14
118            self.left_line.update( delta = self.left_line.phi/2+math.pi ,mline= self.main_line.theta)
119            #print "main_theta--->",self.main_line.get_radius()*180/3.14
120            #print "Main line has moved ---> phi right",math.degrees(self.main_line.theta),math.degrees(self.main_line.get_radius()),math.degrees(self.main_line.get_radius()+self.right_line.theta)
121            #print "Main line has moved ---> phi left",math.degrees(self.left_line.theta+self.main_line.get_radius())
122        if self.left_line.has_move:
123            #print "left line has moved --->"
124            self.main_line.update()
125            self.left_line.update(phi=None,delta=None, mline=self.main_line,side=True, left=True)
126            #self.right_line.update(-1*delta,linem=self.main_line,linel=self.left_line)
127            self.right_line.update(phi=self.left_line.phi,delta=None, mline=self.main_line,side=True,left=False, right=True)
128       
129        if self.right_line.has_move:
130       
131            self.main_line.update()
132            self.right_line.update(phi=None,delta=None, mline=self.main_line,side=True, left=False,right=True)
133            #print "right line has moved --->",self.right_line.phi
134            self.left_line.update(phi=self.right_line.phi,delta=None, mline=self.main_line,side=True, left=False)
135   
136       
137   
138
139    def save(self, ev):
140        """
141        Remember the roughness for this layer and the next so that we
142        can restore on Esc.
143        """
144        self.base.freeze_axes()
145        self.inner_circle.save(ev)
146        self.outer_circle.save(ev)
147
148    def _post_data(self, nbins=None):
149        # Compute data
150        data = self.base.data2D
151        # If we have no data, just return
152        if data == None:
153            return
154
155        name = "Sector "
156        from DataLoader.manipulations import SectorQ
157        radius = self.qmax #radius=math.sqrt(math.pow(self.qmax,2)+math.pow(self.qmax,2))
158        phimin =  -self.left_line.phi+self.main_line.theta
159        phimax = self.left_line.phi+self.main_line.theta
160        #phimin = min(self.right_line.theta+math.pi,self.left_line.theta+math.pi)
161        #phimax = max(self.right_line.theta+math.pi,self.left_line.theta+math.pi)
162        #print "sector Q angles=",phimin*180/math.pi,phimax*180/math.pi,self.main_line.theta*180/math.pi
163        #phi must be 0 to 2pi with cut-off line sts on the left.
164        if nbins==None:
165            nbins = 20
166        sect = SectorQ(r_min=0.0, r_max= radius , phi_min=phimin+math.pi, phi_max=phimax+math.pi, nbins=nbins)
167        #sect = SectorQ(r_min=-1*radius , r_max= radius , phi_min=phimin, phi_max=phimax)
168       
169       
170        sector = sect(self.base.data2D)
171       
172        from sans.guiframe.dataFitting import Data1D
173        if hasattr(sector,"dxl"):
174            dxl= sector.dxl
175        else:
176            dxl= None
177        if hasattr(sector,"dxw"):
178            dxw= sector.dxw
179        else:
180            dxw= None
181       
182        new_plot = Data1D(x=sector.x,y=sector.y,dy=sector.dy,dxl=dxl,dxw=dxw)
183        new_plot.name = "SectorQ" +"("+ self.base.data2D.name+")"
184       
185       
186
187        new_plot.source=self.base.data2D.source
188        #new_plot.info=self.base.data2D.info
189        new_plot.interactive = True
190        #print "loader output.detector",self.base.data2D.info,output.source,
191        new_plot.detector =self.base.data2D.detector
192        #print "loader output.detector",new_plot.detector
193        # If the data file does not tell us what the axes are, just assume...
194        new_plot.xaxis("\\rm{Q}", 'A^{-1}')
195        new_plot.yaxis("\\rm{Intensity} ","cm^{-1}")
196        new_plot.group_id = "SectorQ"+self.base.data2D.name
197        new_plot.id = "SectorQ"+self.base.data2D.name
198        wx.PostEvent(self.base.parent, NewPlotEvent(plot=new_plot,
199                                                 title="SectorQ"+self.base.data2D.name ))
200       
201         
202       
203    def moveend(self, ev):
204        self.base.thaw_axes()
205       
206        # Post paramters
207        event = SlicerParameterEvent()
208        event.type = self.__class__.__name__
209        event.params = self.get_params()
210        #wx.PostEvent(self.base.parent, event)
211        wx.PostEvent(self.base, event)
212        self._post_data()
213           
214    def restore(self):
215        """
216        Restore the roughness for this layer.
217        """
218        self.main_line.restore()
219        self.left_line.restore()
220        self.right_line.restore()
221
222    def move(self, x, y, ev):
223        """
224        Process move to a new position, making sure that the move is allowed.
225        """
226        pass
227       
228    def set_cursor(self, x, y):
229        pass
230       
231    def get_params(self):
232        params = {}
233        params["main_phi"] = self.main_line.theta
234        if math.fabs(self.left_line.phi) != math.fabs(self.right_line.phi):
235            raise ValueError,"Phi left and phi right are different %f, %f"%(self.left_line.phi, self.right_line.phi)
236        params["left_phi"] = math.fabs(self.left_line.phi)
237        params["right_phi"] = math.fabs(self.right_line.phi)
238        params["nbins"] = self.nbins
239        return params
240   
241    def set_params(self, params):
242       
243        main = params["main_phi"] 
244        phi = math.fabs(params["left_phi"] )
245        self.nbins = int(params["nbins"])
246        self.main_line.theta= main
247       
248        self.main_line.update()
249        self.right_line.update(phi=phi,delta=None, mline=self.main_line,side=True,right=True)
250        self.left_line.update(phi=phi,delta=None, mline=self.main_line,side=True)
251       
252        self._post_data(nbins=self.nbins)
253       
254    def freeze_axes(self):
255        self.base.freeze_axes()
256       
257    def thaw_axes(self):
258        self.base.thaw_axes()
259
260    def draw(self):
261        self.base.draw()
262
263       
264class SideInteractor(_BaseInteractor):
265    """
266         Select an annulus through a 2D plot
267    """
268    def __init__(self,base,axes,color='black', zorder=5, r=1.0,phi=math.pi/4, theta2= math.pi/3):
269       
270        _BaseInteractor.__init__(self, base, axes, color=color)
271        self.markers = []
272        self.axes = axes
273       
274           
275        self.save_theta = theta2 + phi
276        self.theta= theta2 + phi
277        self.theta2 = theta2
278        self.radius = r
279        self.phi = phi
280        self.scale = 10.0
281         # Inner circle
282        x1= self.radius*math.cos(self.theta)
283        y1= self.radius*math.sin(self.theta)
284        x2= -1*self.radius*math.cos(self.theta)
285        y2= -1*self.radius*math.sin(self.theta)
286       
287        try:
288            # Inner circle marker
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                                          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([x1/2.5],[y1/2.5], 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           
304         
305       
306       
307        self.line = self.axes.plot([x1,x2],[y1,y2],
308                                      linestyle='-', marker='',
309                                      color=self.color,
310                                      visible=True)[0]
311        self.left_moving=False
312       
313        self.npts = 20
314        self.has_move=False
315        self.connect_markers([self.inner_marker, self.line])
316        #self.update()
317
318    def set_layer(self, n):
319        self.layernum = n
320        self.update()
321       
322    def clear(self):
323        self.clear_markers()
324        try:
325            self.line.remove()
326            self.inner_marker.remove()
327        except:
328            # Old version of matplotlib
329            for item in range(len(self.axes.lines)):
330                del self.axes.lines[0]
331       
332       
333       
334    def get_radius(self):
335       
336        return self.theta - self.save_theta
337       
338    def update(self,phi=None,delta=None, mline=None,side=False, left= False, right=False):
339        """
340        Draw the new roughness on the graph.
341        """
342        #print "update left or right ", self.has_move
343        self.left_moving=left
344        theta3=0
345        if phi !=None:
346            self.phi= phi
347        if delta==None:
348            delta = 0
349
350        if  right:
351            self.phi = -1*math.fabs(self.phi)
352            #delta=-delta
353        else:
354            self.phi =math.fabs(self.phi)
355        if side:
356            self.theta=  mline.theta + self.phi
357                   
358        if mline!=None :
359            if delta!=0:
360                self.theta2 = mline+delta
361            else:
362                self.theta2 = mline.theta
363        if delta==0:
364            theta3=self.theta+delta
365        else:
366            theta3=self.theta2+delta
367       
368            #self.phi= math.fabs(self.theta2 - (self.theta+delta))
369        #print "U:for line side theta2, phi, theta",math.degrees(self.theta2),math.degrees(self.phi),math.degrees(self.theta)
370        #if self.theta2 >= self.theta and self.theta>=0:
371        #    print "between 0-pi",math.degrees(self.theta)
372       
373        x1= self.radius*math.cos(theta3)
374        y1= self.radius*math.sin(theta3)
375        x2= -1*self.radius*math.cos(theta3)
376        y2= -1*self.radius*math.sin(theta3)
377       
378        self.inner_marker.set(xdata=[x1/2.5],ydata=[y1/2.5])
379        self.line.set(xdata=[x1,x2], ydata=[y1,y2]) 
380       
381       
382       
383       
384    def save(self, ev):
385        """
386        Remember the roughness for this layer and the next so that we
387        can restore on Esc.
388        """
389        self.save_theta= self.theta
390        self.base.freeze_axes()
391
392    def moveend(self, ev):
393       
394        self.has_move=False
395        self.base.moveend(ev)
396           
397    def restore(self):
398        """
399        Restore the roughness for this layer.
400        """
401        self.theta = self.save_theta
402
403    def move(self, x, y, ev):
404        """
405        Process move to a new position, making sure that the move is allowed.
406        """
407       
408        self.theta= math.atan2(y,x)
409        self.has_move=True
410        #ToDo: Simplify below
411        if not self.left_moving:
412            if  self.theta2-self.theta <= 0 and self.theta2>0:#>= self.theta2:
413                #print "my theta", self.theta
414                self.restore()
415                return 
416            elif self.theta2 < 0 and self.theta < 0 and self.theta-self.theta2 >= 0:
417                self.restore()
418                return                             
419            elif  self.theta2 < 0 and self.theta > 0 and self.theta2+2*math.pi-self.theta >=math.pi/2:
420                #print "my theta", self.theta
421                self.restore()
422                return 
423            elif  self.theta2 < 0 and self.theta < 0 and self.theta2-self.theta >=math.pi/2:
424                #print "my theta", self.theta
425                self.restore()
426                return 
427            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:
428                #print "self theta encore"
429                self.restore()
430                return 
431        else:
432            #print "left move"
433            if  self.theta < 0 and self.theta+math.pi*2-self.theta2 <= 0:
434                self.restore()
435                return 
436            elif self.theta2 < 0 and self.theta-self.theta2 <= 0:
437                self.restore()
438                return                             
439            elif  self.theta > 0 and self.theta-self.theta2 <=0:
440                #print "my theta", self.theta
441                self.restore()
442                return 
443            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):
444                #print "self theta encore"
445                self.restore()
446                return 
447           
448        self.phi= math.fabs(self.theta2 - self.theta)
449        if self.phi>math.pi:
450            self.phi= 2*math.pi-math.fabs(self.theta2 - self.theta)
451       
452        #print "move , self.phi, self.theta,", self.theta*180/math.pi,self.theta2*180/math.pi,self.phi*180/math.pi
453       
454           
455       
456        self.base.base.update()
457       
458    def set_cursor(self, x, y):
459        self.move(x, y, None)
460        self.update()
461       
462       
463    def get_params(self):
464        params = {}
465        params["radius"] = self.radius
466        params["theta"] = self.theta
467        return params
468   
469    def set_params(self, params):
470
471        x = params["radius"] 
472        self.set_cursor(x, self._inner_mouse_y)
473       
474 
475       
476class LineInteractor(_BaseInteractor):
477    """
478         Select an annulus through a 2D plot
479    """
480    def __init__(self,base,axes,color='black', zorder=5, r=1.0,theta=math.pi/4):
481       
482        _BaseInteractor.__init__(self, base, axes, color=color)
483        self.markers = []
484        self.axes = axes
485       
486        self.save_theta = theta
487        self.theta= theta
488       
489        self.radius = r
490     
491        self.scale = 10.0
492     
493        #raise "Version error", message
494           
495        # Inner circle
496        x1= self.radius*math.cos(self.theta)
497        y1= self.radius*math.sin(self.theta)
498        x2= -1*self.radius*math.cos(self.theta)
499        y2= -1*self.radius*math.sin(self.theta)
500        try:
501            # Inner circle marker
502            self.inner_marker = self.axes.plot([x1/2.5],[y1/2.5], linestyle='',
503                                          marker='s', markersize=10,
504                                          color=self.color, alpha=0.6,
505                                          pickradius=5, label="pick", 
506                                          zorder=zorder, # Prefer this to other lines
507                                          visible=True)[0]
508        except:
509            self.inner_marker = self.axes.plot([x1/2.5],[y1/2.5], linestyle='',
510                                          marker='s', markersize=10,
511                                          color=self.color, alpha=0.6,
512                                          label="pick", 
513                                          visible=True)[0]
514            message  = "\nTHIS PROTOTYPE NEEDS THE LATEST VERSION OF MATPLOTLIB\n"
515            message += "Get the SVN version that is at least as recent as June 1, 2007"
516           
517       
518        self.line = self.axes.plot([x1,x2],[y1,y2],
519                                      linestyle='-', marker='',
520                                      color=self.color,
521                                      visible=True)[0]
522     
523        self.npts = 20
524        self.has_move=False
525        self.connect_markers([self.inner_marker, self.line])
526        self.update()
527
528    def set_layer(self, n):
529        self.layernum = n
530        self.update()
531       
532    def clear(self):
533        self.clear_markers()
534        try:
535            self.inner_marker.remove()
536            self.line.remove()
537        except:
538            # Old version of matplotlib
539            for item in range(len(self.axes.lines)):
540                del self.axes.lines[0]
541       
542       
543       
544    def get_radius(self):
545       
546        return self.theta - self.save_theta
547       
548    def update(self, theta=None):
549        """
550        Draw the new roughness on the graph.
551        """
552        #print "update main line", self.theta
553        if theta !=None:
554            self.theta= theta
555        x1= self.radius*math.cos(self.theta)
556        y1= self.radius*math.sin(self.theta)
557        x2= -1*self.radius*math.cos(self.theta)
558        y2= -1*self.radius*math.sin(self.theta)
559       
560        self.inner_marker.set(xdata=[x1/2.5],ydata=[y1/2.5])
561        self.line.set(xdata=[x1,x2], ydata=[y1,y2]) 
562     
563       
564       
565    def save(self, ev):
566        """
567        Remember the roughness for this layer and the next so that we
568        can restore on Esc.
569        """
570        self.save_theta= self.theta
571        self.base.freeze_axes()
572
573    def moveend(self, ev):
574       
575        self.has_move=False
576        self.base.moveend(ev)
577           
578    def restore(self):
579        """
580        Restore the roughness for this layer.
581        """
582        self.theta = self.save_theta
583
584    def move(self, x, y, ev):
585        """
586        Process move to a new position, making sure that the move is allowed.
587        """
588       
589        self.theta= math.atan2(y,x)
590        #print "main_line previous theta --- next theta ",math.degrees(self.save_theta),math.degrees(self.theta)
591       
592        self.has_move=True
593       
594        self.base.base.update()
595       
596    def set_cursor(self, x, y):
597        self.move(x, y, None)
598        self.update()
599       
600       
601    def get_params(self):
602        params = {}
603        params["radius"] = self.radius
604        params["theta"] = self.theta
605        return params
606   
607    def set_params(self, params):
608
609        x = params["radius"] 
610        self.set_cursor(x, self._inner_mouse_y)
611
612
613       
Note: See TracBrowser for help on using the repository browser.