source: sasview/src/sas/sasgui/guiframe/local_perspectives/plotting/SectorSlicer.py @ 116260a

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 116260a was 116260a, checked in by Piotr Rozyczko <piotr.rozyczko@…>, 7 years ago

enable real time updates of more 1D charts

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