source: sasview/src/sas/sasgui/guiframe/local_perspectives/plotting/SectorSlicer.py @ 235f514

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.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 235f514 was 235f514, checked in by andyfaff, 7 years ago

MAINT: replace '== None' by 'is None'

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