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

Last change on this file since a0f13e6 was b9ab979, checked in by Piotr Rozyczko <piotr.rozyczko@…>, 6 years ago

Automatically show sector/annulus/box plots SASVIEW-980

  • Property mode set to 100644
File size: 12.6 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        self.base.manager.communicator.forcePlotDisplaySignal.emit([item, new_plot])
151
152        if self.update_model:
153            self.setModelFromParams()
154        self.draw()
155
156    def validate(self, param_name, param_value):
157        """
158        Test the proposed new value "value" for row "row" of parameters
159        """
160        MIN_DIFFERENCE = 0.01
161        isValid = True
162
163        if param_name == 'inner_radius':
164            # First, check the closeness
165            if numpy.fabs(param_value - self.getParams()['outer_radius']) < MIN_DIFFERENCE:
166                print("Inner and outer radii too close. Please adjust.")
167                isValid = False
168            elif param_value > self.qmax:
169                print("Inner radius exceeds maximum range. Please adjust.")
170                isValid = False
171        elif param_name == 'outer_radius':
172            # First, check the closeness
173            if numpy.fabs(param_value - self.getParams()['inner_radius']) < MIN_DIFFERENCE:
174                print("Inner and outer radii too close. Please adjust.")
175                isValid = False
176            elif param_value > self.qmax:
177                print("Outer radius exceeds maximum range. Please adjust.")
178                isValid = False
179        elif param_name == 'nbins':
180            # Can't be 0
181            if param_value < 1:
182                print("Number of bins cannot be less than or equal to 0. Please adjust.")
183                isValid = False
184
185        return isValid
186
187    def moveend(self, ev):
188        """
189        Called when any dragging motion ends.
190        Redraw the plot with new parameters.
191        """
192        self._post_data(self.nbins)
193
194    def restore(self):
195        """
196        Restore the roughness for this layer.
197        """
198        self.inner_circle.restore()
199        self.outer_circle.restore()
200
201    def move(self, x, y, ev):
202        """
203        Process move to a new position, making sure that the move is allowed.
204        """
205        pass
206
207    def set_cursor(self, x, y):
208        pass
209
210    def getParams(self):
211        """
212        Store a copy of values of parameters of the slicer into a dictionary.
213        :return params: the dictionary created
214        """
215        params = {}
216        params["inner_radius"] = numpy.fabs(self.inner_circle._inner_mouse_x)
217        params["outer_radius"] = numpy.fabs(self.outer_circle._inner_mouse_x)
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        """
229        inner = numpy.fabs(params["inner_radius"])
230        outer = numpy.fabs(params["outer_radius"])
231        self.nbins = int(params["nbins"])
232        # Update the picture
233        self.inner_circle.set_cursor(inner, self.inner_circle._inner_mouse_y)
234        self.outer_circle.set_cursor(outer, self.outer_circle._inner_mouse_y)
235        # Post the data given the nbins entered by the user
236        self._post_data(self.nbins)
237
238    def draw(self):
239        """
240        """
241        self.base.draw()
242
243
244class RingInteractor(BaseInteractor):
245    """
246     Draw a ring Given a radius
247    """
248    def __init__(self, base, axes, color='black', zorder=5, r=1.0, sign=1):
249        """
250        :param: the color of the line that defined the ring
251        :param r: the radius of the ring
252        :param sign: the direction of motion the the marker
253
254        """
255        BaseInteractor.__init__(self, base, axes, color=color)
256        self.markers = []
257        self.axes = axes
258        # Current radius of the ring
259        self._inner_mouse_x = r
260        # Value of the center of the ring
261        self._inner_mouse_y = 0
262        # previous value of that radius
263        self._inner_save_x = r
264        # Save value of the center of the ring
265        self._inner_save_y = 0
266        # Class instantiating RingIterator class
267        self.base = base
268        # the direction of the motion of the marker
269        self.sign = sign
270        # # Create a marker
271        # Inner circle marker
272        x_value = [self.sign * numpy.fabs(self._inner_mouse_x)]
273        self.inner_marker = self.axes.plot(x_value, [0], linestyle='',
274                                           marker='s', markersize=10,
275                                           color=self.color, alpha=0.6,
276                                           pickradius=5, label="pick",
277                                           zorder=zorder,
278                                           visible=True)[0]
279        # Draw a circle
280        [self.inner_circle] = self.axes.plot([], [], linestyle='-', marker='', color=self.color)
281        # The number of points that make the ring line
282        self.npts = 40
283
284        self.connect_markers([self.inner_marker])
285        self.update()
286
287    def set_layer(self, n):
288        """
289        Allow adding plot to the same panel
290
291        :param n: the number of layer
292
293        """
294        self.layernum = n
295        self.update()
296
297    def clear(self):
298        """
299        Clear the slicer and all connected events related to this slicer
300        """
301        self.clear_markers()
302        self.inner_marker.remove()
303        self.inner_circle.remove()
304
305    def get_radius(self):
306        """
307        :return self._inner_mouse_x: the current radius of the ring
308        """
309        return self._inner_mouse_x
310
311    def update(self):
312        """
313        Draw the new roughness on the graph.
314        """
315        # Plot inner circle
316        x = []
317        y = []
318        for i in range(self.npts):
319            phi = 2.0 * numpy.pi / (self.npts - 1) * i
320
321            xval = 1.0 * self._inner_mouse_x * numpy.cos(phi)
322            yval = 1.0 * self._inner_mouse_x * numpy.sin(phi)
323
324            x.append(xval)
325            y.append(yval)
326
327        self.inner_marker.set(xdata=[self.sign * numpy.fabs(self._inner_mouse_x)],
328                              ydata=[0])
329        self.inner_circle.set_data(x, y)
330
331    def save(self, ev):
332        """
333        Remember the roughness for this layer and the next so that we
334        can restore on Esc.
335        """
336        self._inner_save_x = self._inner_mouse_x
337        self._inner_save_y = self._inner_mouse_y
338
339    def moveend(self, ev):
340        """
341        Called after a dragging motion
342        """
343        self.base.moveend(ev)
344
345    def restore(self):
346        """
347        Restore the roughness for this layer.
348        """
349        self._inner_mouse_x = self._inner_save_x
350        self._inner_mouse_y = self._inner_save_y
351
352    def move(self, x, y, ev):
353        """
354        Process move to a new position, making sure that the move is allowed.
355        """
356        self._inner_mouse_x = x
357        self._inner_mouse_y = y
358        self.base.base.update()
359
360    def set_cursor(self, x, y):
361        """
362        draw the ring given x, y value
363        """
364        self.move(x, y, None)
365        self.update()
366
367    def getParams(self):
368        """
369        Store a copy of values of parameters of the slicer into a dictionary.
370        :return params: the dictionary created
371        """
372        params = {}
373        params["radius"] = numpy.fabs(self._inner_mouse_x)
374        return params
375
376    def setParams(self, params):
377        """
378        Receive a dictionary and reset the slicer with values contained
379        in the values of the dictionary.
380
381        :param params: a dictionary containing name of slicer parameters and
382            values the user assigned to the slicer.
383
384        """
385        x = params["radius"]
386        self.set_cursor(x, self._inner_mouse_y)
387
388
Note: See TracBrowser for help on using the repository browser.