source: sasview/src/sas/qtgui/Plotting/Slicers/AnnulusSlicer.py

ESS_GUI
Last change on this file was 63467b6, checked in by Piotr Rozyczko <piotr.rozyczko@…>, 3 weeks ago

Improved handling of 2d plot children. Refactored model tree search.

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