source: sasview/src/sas/sasgui/guiframe/local_perspectives/plotting/AnnulusSlicer.py @ 895e7359

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 895e7359 was 895e7359, checked in by Piotr Rozyczko <rozyczko@…>, 7 years ago

Converted more syntax not covered by 2to3

  • Property mode set to 100644
File size: 16.8 KB
Line 
1import numpy
2from PyQt4 import QtGui
3from PyQt4 import QtCore
4
5from BaseInteractor import _BaseInteractor
6from sas.sasgui.guiframe.dataFitting import Data1D
7import sas.qtgui.Utilities.GuiUtils as GuiUtils
8from sas.qtgui.Utilities.GuiUtils import formatNumber
9from sas.qtgui.Plotting.SlicerModel import SlicerModel
10
11class AnnulusInteractor(_BaseInteractor, SlicerModel):
12    """
13    Select an annulus through a 2D plot.
14    This interactor is used to average 2D data  with the region
15    defined by 2 radius.
16    this class is defined by 2 Ringinterators.
17    """
18    def __init__(self, base, axes, item=None, color='black', zorder=3):
19
20        _BaseInteractor.__init__(self, base, axes, color=color)
21        SlicerModel.__init__(self)
22
23        self.markers = []
24        self.axes = axes
25        self.base = base
26        self._item = item
27        self.qmax = min(numpy.fabs(self.base.data.xmax),
28                        numpy.fabs(self.base.data.xmin))  # must be positive
29        self.connect = self.base.connect
30
31        # Number of points on the plot
32        self.nbins = 36
33        # Cursor position of Rings (Left(-1) or Right(1))
34        self.xmaxd = self.base.data.xmax
35        self.xmind = self.base.data.xmin
36
37        if (self.xmaxd + self.xmind) > 0:
38            self.sign = 1
39        else:
40            self.sign = -1
41        # Inner circle
42        self.inner_circle = RingInteractor(self, self.axes,
43                                           zorder=zorder,
44                                           r=self.qmax / 2.0, sign=self.sign)
45        self.inner_circle.qmax = self.qmax
46        self.outer_circle = RingInteractor(self, self.axes,
47                                           zorder=zorder + 1, r=self.qmax / 1.8,
48                                           sign=self.sign)
49        self.outer_circle.qmax = self.qmax * 1.2
50        self.update()
51        self._post_data()
52
53        self.setModelFromParams()
54
55    def set_layer(self, n):
56        """
57        Allow adding plot to the same panel
58
59        :param n: the number of layer
60
61        """
62        self.layernum = n
63        self.update()
64
65    def clear(self):
66        """
67        Clear the slicer and all connected events related to this slicer
68        """
69        self.clear_markers()
70        self.outer_circle.clear()
71        self.inner_circle.clear()
72        self.base.connect.clearall()
73
74    def update(self):
75        """
76        Respond to changes in the model by recalculating the profiles and
77        resetting the widgets.
78        """
79        # Update locations
80        self.inner_circle.update()
81        self.outer_circle.update()
82
83    def save(self, ev):
84        """
85        Remember the roughness for this layer and the next so that we
86        can restore on Esc.
87        """
88        self.inner_circle.save(ev)
89        self.outer_circle.save(ev)
90
91    def _post_data(self, nbins=None):
92        """
93        Uses annulus parameters to plot averaged data into 1D data.
94
95        :param nbins: the number of points to plot
96
97        """
98        # Data to average
99        data = self.base.data
100        if data is None:
101            return
102
103        from sas.sascalc.dataloader.manipulations import Ring
104        rmin = min(numpy.fabs(self.inner_circle.get_radius()),
105                   numpy.fabs(self.outer_circle.get_radius()))
106        rmax = max(numpy.fabs(self.inner_circle.get_radius()),
107                   numpy.fabs(self.outer_circle.get_radius()))
108        # If the user does not specify the numbers of points to plot
109        # the default number will be nbins= 36
110        if nbins is None:
111            self.nbins = 36
112        else:
113            self.nbins = nbins
114        # Create the data1D Q average of data2D
115        sect = Ring(r_min=rmin, r_max=rmax, nbins=self.nbins)
116        sector = sect(self.base.data)
117
118        if hasattr(sector, "dxl"):
119            dxl = sector.dxl
120        else:
121            dxl = None
122        if hasattr(sector, "dxw"):
123            dxw = sector.dxw
124        else:
125            dxw = None
126        new_plot = Data1D(x=(sector.x - numpy.pi) * 180 / numpy.pi,
127                          y=sector.y, dy=sector.dy)
128        new_plot.dxl = dxl
129        new_plot.dxw = dxw
130        new_plot.name = "AnnulusPhi" + "(" + self.base.data.name + ")"
131        new_plot.title = "AnnulusPhi" + "(" + self.base.data.name + ")"
132
133        new_plot.source = self.base.data.source
134        new_plot.interactive = True
135        new_plot.detector = self.base.data.detector
136        # If the data file does not tell us what the axes are, just assume...
137        new_plot.xaxis("\\rm{\phi}", 'degrees')
138        new_plot.yaxis("\\rm{Intensity} ", "cm^{-1}")
139        if hasattr(data, "scale") and data.scale == 'linear' and \
140                self.base.data.name.count("Residuals") > 0:
141            new_plot.ytransform = 'y'
142            new_plot.yaxis("\\rm{Residuals} ", "/")
143
144        new_plot.group_id = "AnnulusPhi" + self.base.data.name
145        new_plot.id = "AnnulusPhi" + self.base.data.name
146        new_plot.is_data = True
147        new_plot.xtransform = "x"
148        new_plot.ytransform = "y"
149        GuiUtils.updateModelItemWithPlot(self._item, new_plot, new_plot.id)
150        self.base.manager.communicator.plotUpdateSignal.emit([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
388class CircularMask(_BaseInteractor):
389    """
390     Draw a ring Given a radius
391    """
392    def __init__(self, base, axes, color='grey', zorder=3, side=None):
393        """
394        :param: the color of the line that defined the ring
395        :param r: the radius of the ring
396        :param sign: the direction of motion the the marker
397        """
398        _BaseInteractor.__init__(self, base, axes, color=color)
399        self.markers = []
400        self.axes = axes
401        self.base = base
402        self.is_inside = side
403        self.qmax = min(numpy.fabs(self.base.data.xmax),
404                        numpy.fabs(self.base.data.xmin))  # must be positive
405        self.connect = self.base.connect
406
407        # Cursor position of Rings (Left(-1) or Right(1))
408        self.xmaxd = self.base.data.xmax
409        self.xmind = self.base.data.xmin
410
411        if (self.xmaxd + self.xmind) > 0:
412            self.sign = 1
413        else:
414            self.sign = -1
415        # Inner circle
416        self.outer_circle = RingInteractor(self, self.axes, 'blue',
417                                           zorder=zorder + 1, r=self.qmax / 1.8,
418                                           sign=self.sign)
419        self.outer_circle.qmax = self.qmax * 1.2
420        self.update()
421        self._post_data()
422
423    def set_layer(self, n):
424        """
425        Allow adding plot to the same panel
426        :param n: the number of layer
427        """
428        self.layernum = n
429        self.update()
430
431    def clear(self):
432        """
433        Clear the slicer and all connected events related to this slicer
434        """
435        self.clear_markers()
436        self.outer_circle.clear()
437        self.base.connect.clearall()
438
439    def update(self):
440        """
441        Respond to changes in the model by recalculating the profiles and
442        resetting the widgets.
443        """
444        # Update locations
445        self.outer_circle.update()
446        self._post_data()
447        out = self._post_data()
448        return out
449
450    def save(self, ev):
451        """
452        Remember the roughness for this layer and the next so that we
453        can restore on Esc.
454        """
455        self.outer_circle.save(ev)
456
457    def _post_data(self):
458        """
459        Uses annulus parameters to plot averaged data into 1D data.
460
461        :param nbins: the number of points to plot
462
463        """
464        # Data to average
465        data = self.base.data
466
467        # If we have no data, just return
468        if data is None:
469            return
470        mask = data.mask
471        from sas.sascalc.dataloader.manipulations import Ringcut
472
473        rmin = 0
474        rmax = numpy.fabs(self.outer_circle.get_radius())
475
476        # Create the data1D Q average of data2D
477        mask = Ringcut(r_min=rmin, r_max=rmax)
478
479        if self.is_inside:
480            out = (mask(data) == False)
481        else:
482            out = (mask(data))
483        return out
484
485
486    def moveend(self, ev):
487        """
488        Called when any dragging motion ends.
489        Post an event (type =SlicerParameterEvent)
490        to plotter 2D with a copy  slicer parameters
491        Call  _post_data method
492        """
493        self.base.thaw_axes()
494        # create a 1D data plot
495        self._post_data()
496
497    def restore(self):
498        """
499        Restore the roughness for this layer.
500        """
501        self.outer_circle.restore()
502
503    def move(self, x, y, ev):
504        """
505        Process move to a new position, making sure that the move is allowed.
506        """
507        pass
508
509    def set_cursor(self, x, y):
510        pass
511
512    def getParams(self):
513        """
514        Store a copy of values of parameters of the slicer into a dictionary.
515
516        :return params: the dictionary created
517
518        """
519        params = {}
520        params["outer_radius"] = numpy.fabs(self.outer_circle._inner_mouse_x)
521        return params
522
523    def setParams(self, params):
524        """
525        Receive a dictionary and reset the slicer with values contained
526        in the values of the dictionary.
527
528        :param params: a dictionary containing name of slicer parameters and
529            values the user assigned to the slicer.
530        """
531        outer = numpy.fabs(params["outer_radius"])
532        # Update the picture
533        self.outer_circle.set_cursor(outer, self.outer_circle._inner_mouse_y)
534        # Post the data given the nbins entered by the user
535        self._post_data()
536
537    def draw(self):
538        self.base.update()
539
Note: See TracBrowser for help on using the repository browser.