source: sasview/src/sas/qtgui/Plotting/Slicers/SectorSlicer.py @ b1a7a81

ESS_GUIESS_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 b1a7a81 was e20870bc, checked in by Piotr Rozyczko <rozyczko@…>, 6 years ago

Masking dialog for fitting

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