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

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

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

  • Property mode set to 100644
File size: 19.4 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        if self._item.parent() is not None:
170            item = self._item.parent()
171        GuiUtils.updateModelItemWithPlot(item, new_plot, new_plot.id)
172
173        self.base.manager.communicator.plotUpdateSignal.emit([new_plot])
174
175        if self.update_model:
176            self.setModelFromParams()
177        self.draw()
178
179    def validate(self, param_name, param_value):
180        """
181        Test the proposed new value "value" for row "row" of parameters
182        """
183        MIN_DIFFERENCE = 0.01
184        isValid = True
185
186        if param_name == 'Delta_Phi [deg]':
187            # First, check the closeness
188            if numpy.fabs(param_value) < MIN_DIFFERENCE:
189                print("Sector angles too close. Please adjust.")
190                isValid = False
191        elif param_name == 'nbins':
192            # Can't be 0
193            if param_value < 1:
194                print("Number of bins cannot be less than or equal to 0. Please adjust.")
195                isValid = False
196        return isValid
197
198    def moveend(self, ev):
199        """
200        Called a dragging motion ends.Get slicer event
201        """
202        # Post parameters
203        self._post_data(self.nbins)
204
205    def restore(self):
206        """
207        Restore the roughness for this layer.
208        """
209        self.main_line.restore()
210        self.left_line.restore()
211        self.right_line.restore()
212
213    def move(self, x, y, ev):
214        """
215        Process move to a new position, making sure that the move is allowed.
216        """
217        pass
218
219    def set_cursor(self, x, y):
220        pass
221
222    def getParams(self):
223        """
224        Store a copy of values of parameters of the slicer into a dictionary.
225        :return params: the dictionary created
226        """
227        params = {}
228        # Always make sure that the left and the right line are at phi
229        # angle of the middle line
230        if numpy.fabs(self.left_line.phi) != numpy.fabs(self.right_line.phi):
231            msg = "Phi left and phi right are different"
232            msg += " %f, %f" % (self.left_line.phi, self.right_line.phi)
233            raise ValueError(msg)
234        params["Phi [deg]"] = self.main_line.theta * 180 / numpy.pi
235        params["Delta_Phi [deg]"] = numpy.fabs(self.left_line.phi * 180 / numpy.pi)
236        params["nbins"] = self.nbins
237        return params
238
239    def setParams(self, params):
240        """
241        Receive a dictionary and reset the slicer with values contained
242        in the values of the dictionary.
243
244        :param params: a dictionary containing name of slicer parameters and
245            values the user assigned to the slicer.
246        """
247        main = params["Phi [deg]"] * numpy.pi / 180
248        phi = numpy.fabs(params["Delta_Phi [deg]"] * numpy.pi / 180)
249
250        # phi should not be too close.
251        if numpy.fabs(phi) < MIN_PHI:
252            phi = MIN_PHI
253            params["Delta_Phi [deg]"] = MIN_PHI
254
255        self.nbins = int(params["nbins"])
256        self.main_line.theta = main
257        # Reset the slicer parameters
258        self.main_line.update()
259        self.right_line.update(phi=phi, delta=None, mline=self.main_line,
260                               side=True, right=True)
261        self.left_line.update(phi=phi, delta=None,
262                              mline=self.main_line, side=True)
263        # Post the new corresponding data
264        self._post_data(nbins=self.nbins)
265
266    def draw(self):
267        """
268        Redraw canvas
269        """
270        self.base.draw()
271
272
273class SideInteractor(BaseInteractor):
274    """
275    Draw an oblique line
276
277    :param phi: the phase between the middle line and one side line
278    :param theta2: the angle between the middle line and x- axis
279
280    """
281    def __init__(self, base, axes, color='black', zorder=5, r=1.0,
282                 phi=numpy.pi / 4, theta2=numpy.pi / 3):
283        BaseInteractor.__init__(self, base, axes, color=color)
284        # Initialize the class
285        self.markers = []
286        self.axes = axes
287        self.color = color
288        # compute the value of the angle between the current line and
289        # the x-axis
290        self.save_theta = theta2 + phi
291        self.theta = theta2 + phi
292        # the value of the middle line angle with respect to the x-axis
293        self.theta2 = theta2
294        # Radius to find polar coordinates this line's endpoints
295        self.radius = r
296        # phi is the phase between the current line and the middle line
297        self.phi = phi
298        # End points polar coordinates
299        x1 = self.radius * numpy.cos(self.theta)
300        y1 = self.radius * numpy.sin(self.theta)
301        x2 = -1 * self.radius * numpy.cos(self.theta)
302        y2 = -1 * self.radius * numpy.sin(self.theta)
303        # Defining a new marker
304        self.inner_marker = self.axes.plot([x1 / 2.5], [y1 / 2.5], linestyle='',
305                                           marker='s', markersize=10,
306                                           color=self.color, alpha=0.6,
307                                           pickradius=5, label="pick",
308                                           zorder=zorder, visible=True)[0]
309
310        # Defining the current line
311        self.line = self.axes.plot([x1, x2], [y1, y2],
312                                   linestyle='-', marker='',
313                                   color=self.color, visible=True)[0]
314        # Flag to differentiate the left line from the right line motion
315        self.left_moving = False
316        # Flag to define a motion
317        self.has_move = False
318        # connecting markers and draw the picture
319        self.connect_markers([self.inner_marker, self.line])
320
321    def set_layer(self, n):
322        """
323        Allow adding plot to the same panel
324        :param n: the number of layer
325        """
326        self.layernum = n
327        self.update()
328
329    def clear(self):
330        """
331        Clear the slicer and all connected events related to this slicer
332        """
333        self.clear_markers()
334        try:
335            self.line.remove()
336            self.inner_marker.remove()
337        except:
338            # Old version of matplotlib
339            for item in range(len(self.axes.lines)):
340                del self.axes.lines[0]
341
342    def update(self, phi=None, delta=None, mline=None,
343               side=False, left=False, right=False):
344        """
345        Draw oblique line
346
347        :param phi: the phase between the middle line and the current line
348        :param delta: phi/2 applied only when the mline was moved
349
350        """
351        self.left_moving = left
352        theta3 = 0
353        if phi is not None:
354            self.phi = phi
355        if delta is None:
356            delta = 0
357        if  right:
358            self.phi = -1 * numpy.fabs(self.phi)
359            #delta=-delta
360        else:
361            self.phi = numpy.fabs(self.phi)
362        if side:
363            self.theta = mline.theta + self.phi
364
365        if mline is not None:
366            if delta != 0:
367                self.theta2 = mline + delta
368            else:
369                self.theta2 = mline.theta
370        if delta == 0:
371            theta3 = self.theta + delta
372        else:
373            theta3 = self.theta2 + delta
374        x1 = self.radius * numpy.cos(theta3)
375        y1 = self.radius * numpy.sin(theta3)
376        x2 = -1 * self.radius * numpy.cos(theta3)
377        y2 = -1 * self.radius * numpy.sin(theta3)
378        self.inner_marker.set(xdata=[x1 / 2.5], ydata=[y1 / 2.5])
379        self.line.set(xdata=[x1, x2], ydata=[y1, y2])
380
381    def save(self, ev):
382        """
383        Remember the roughness for this layer and the next so that we
384        can restore on Esc.
385        """
386        self.save_theta = self.theta
387
388    def moveend(self, ev):
389        self.has_move = False
390        self.base.moveend(ev)
391
392    def restore(self):
393        """
394        Restore the roughness for this layer.
395        """
396        self.theta = self.save_theta
397
398    def move(self, x, y, ev):
399        """
400        Process move to a new position, making sure that the move is allowed.
401        """
402        self.theta = numpy.arctan2(y, x)
403        self.has_move = True
404        if not self.left_moving:
405            if  self.theta2 - self.theta <= 0 and self.theta2 > 0:
406                self.restore()
407                return
408            elif self.theta2 < 0 and self.theta < 0 and \
409                self.theta - self.theta2 >= 0:
410                self.restore()
411                return
412            elif  self.theta2 < 0 and self.theta > 0 and \
413                (self.theta2 + 2 * numpy.pi - self.theta) >= numpy.pi / 2:
414                self.restore()
415                return
416            elif  self.theta2 < 0 and self.theta < 0 and \
417                (self.theta2 - self.theta) >= numpy.pi / 2:
418                self.restore()
419                return
420            elif self.theta2 > 0 and (self.theta2 - self.theta >= numpy.pi / 2 or \
421                (self.theta2 - self.theta >= numpy.pi / 2)):
422                self.restore()
423                return
424        else:
425            if  self.theta < 0 and (self.theta + numpy.pi * 2 - self.theta2) <= 0:
426                self.restore()
427                return
428            elif self.theta2 < 0 and (self.theta - self.theta2) <= 0:
429                self.restore()
430                return
431            elif  self.theta > 0 and self.theta - self.theta2 <= 0:
432                self.restore()
433                return
434            elif self.theta - self.theta2 >= numpy.pi / 2 or  \
435                ((self.theta + numpy.pi * 2 - self.theta2) >= numpy.pi / 2 and \
436                 self.theta < 0 and self.theta2 > 0):
437                self.restore()
438                return
439
440        self.phi = numpy.fabs(self.theta2 - self.theta)
441        if self.phi > numpy.pi:
442            self.phi = 2 * numpy.pi - numpy.fabs(self.theta2 - self.theta)
443        #self.base.base.update()
444        self.base.update()
445
446    def set_cursor(self, x, y):
447        self.move(x, y, None)
448        self.update()
449
450    def getParams(self):
451        params = {}
452        params["radius"] = self.radius
453        params["theta"] = self.theta
454        return params
455
456    def setParams(self, params):
457        x = params["radius"]
458        self.set_cursor(x, None)
459
460
461class LineInteractor(BaseInteractor):
462    """
463    Select an annulus through a 2D plot
464    """
465    def __init__(self, base, axes, color='black',
466                 zorder=5, r=1.0, theta=numpy.pi / 4):
467        BaseInteractor.__init__(self, base, axes, color=color)
468
469        self.markers = []
470        self.color = color
471        self.axes = axes
472        self.save_theta = theta
473        self.theta = theta
474        self.radius = r
475        self.scale = 10.0
476        # Inner circle
477        x1 = self.radius * numpy.cos(self.theta)
478        y1 = self.radius * numpy.sin(self.theta)
479        x2 = -1 * self.radius * numpy.cos(self.theta)
480        y2 = -1 * self.radius * numpy.sin(self.theta)
481        # Inner circle marker
482        self.inner_marker = self.axes.plot([x1 / 2.5], [y1 / 2.5], linestyle='',
483                                           marker='s', markersize=10,
484                                           color=self.color, alpha=0.6,
485                                           pickradius=5, label="pick",
486                                           zorder=zorder,
487                                           visible=True)[0]
488        self.line = self.axes.plot([x1, x2], [y1, y2],
489                                   linestyle='-', marker='',
490                                   color=self.color, visible=True)[0]
491        self.npts = 20
492        self.has_move = False
493        self.connect_markers([self.inner_marker, self.line])
494        self.update()
495
496    def set_layer(self, n):
497        self.layernum = n
498        self.update()
499
500    def clear(self):
501        self.clear_markers()
502        try:
503            self.inner_marker.remove()
504            self.line.remove()
505        except:
506            # Old version of matplotlib
507            for item in range(len(self.axes.lines)):
508                del self.axes.lines[0]
509
510    def update(self, theta=None):
511        """
512        Draw the new roughness on the graph.
513        """
514
515        if theta is not None:
516            self.theta = theta
517        x1 = self.radius * numpy.cos(self.theta)
518        y1 = self.radius * numpy.sin(self.theta)
519        x2 = -1 * self.radius * numpy.cos(self.theta)
520        y2 = -1 * self.radius * numpy.sin(self.theta)
521
522        self.inner_marker.set(xdata=[x1 / 2.5], ydata=[y1 / 2.5])
523        self.line.set(xdata=[x1, x2], ydata=[y1, y2])
524
525    def save(self, ev):
526        """
527        Remember the roughness for this layer and the next so that we
528        can restore on Esc.
529        """
530        self.save_theta = self.theta
531
532    def moveend(self, ev):
533        self.has_move = False
534        self.base.moveend(ev)
535
536    def restore(self):
537        """
538        Restore the roughness for this layer.
539        """
540        self.theta = self.save_theta
541
542    def move(self, x, y, ev):
543        """
544        Process move to a new position, making sure that the move is allowed.
545        """
546        self.theta = numpy.arctan2(y, x)
547        self.has_move = True
548        #self.base.base.update()
549        self.base.update()
550
551    def set_cursor(self, x, y):
552        self.move(x, y, None)
553        self.update()
554
555    def getParams(self):
556        params = {}
557        params["radius"] = self.radius
558        params["theta"] = self.theta
559        return params
560
561    def setParams(self, params):
562        x = params["radius"]
563        self.set_cursor(x, None)
Note: See TracBrowser for help on using the repository browser.