source: sasview/src/sas/sasgui/guiframe/local_perspectives/plotting/SectorSlicer.py @ 57b7ee2

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 57b7ee2 was 57b7ee2, checked in by Piotr Rozyczko <rozyczko@…>, 7 years ago

Code review changes for Slicer Parameter Editor

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