source: sasview/src/sas/qtgui/Plotting/Plotter2D.py @ 87ca467

ESS_GUIESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 87ca467 was 87ca467, checked in by Piotr Rozyczko <piotr.rozyczko@…>, 5 years ago

Update circular average plot on 2D chart redraw. Show the updated plot
if graph visible - SASVIEW-1205

  • Property mode set to 100644
File size: 20.4 KB
Line 
1import copy
2import numpy
3import functools
4import logging
5
6from PyQt5 import QtCore
7from PyQt5 import QtGui
8from PyQt5 import QtWidgets
9
10
11import matplotlib as mpl
12DEFAULT_CMAP = mpl.cm.jet
13
14from mpl_toolkits.mplot3d import Axes3D
15
16from sas.sascalc.dataloader.manipulations import CircularAverage
17
18from sas.qtgui.Plotting.PlotterData import Data1D
19from sas.qtgui.Plotting.PlotterData import Data2D
20
21import sas.qtgui.Plotting.PlotUtilities as PlotUtilities
22import sas.qtgui.Utilities.GuiUtils as GuiUtils
23from sas.qtgui.Plotting.PlotterBase import PlotterBase
24from sas.qtgui.Plotting.ColorMap import ColorMap
25from sas.qtgui.Plotting.BoxSum import BoxSum
26from sas.qtgui.Plotting.SlicerParameters import SlicerParameters
27from sas.qtgui.Plotting.Binder import BindArtist
28
29# TODO: move to sas.qtgui namespace
30from sas.qtgui.Plotting.Slicers.BoxSlicer import BoxInteractorX
31from sas.qtgui.Plotting.Slicers.BoxSlicer import BoxInteractorY
32from sas.qtgui.Plotting.Slicers.AnnulusSlicer import AnnulusInteractor
33from sas.qtgui.Plotting.Slicers.SectorSlicer import SectorInteractor
34from sas.qtgui.Plotting.Slicers.BoxSum import BoxSumCalculator
35
36# Minimum value of Z for which we will present data.
37MIN_Z = -32
38
39class Plotter2DWidget(PlotterBase):
40    """
41    2D Plot widget for use with a QDialog
42    """
43    def __init__(self, parent=None, manager=None, quickplot=False, dimension=2):
44        self.dimension = dimension
45        super(Plotter2DWidget, self).__init__(parent, manager=manager, quickplot=quickplot)
46
47        self.cmap = DEFAULT_CMAP.name
48        # Default scale
49        self.scale = 'log_{10}'
50        # to set the order of lines drawn first.
51        self.slicer_z = 5
52        # Reference to the current slicer
53        self.slicer = None
54        self.slicer_widget = None
55        # Create Artist and bind it
56        self.connect = BindArtist(self.figure)
57        self.vmin = None
58        self.vmax = None
59        self.im = None
60
61        self.manager = manager
62
63    @property
64    def data(self):
65        return self._data
66
67    @data.setter
68    def data(self, data=None):
69        """ data setter """
70        self._data = data
71        self.qx_data = data.qx_data
72        self.qy_data = data.qy_data
73        self.xmin = data.xmin
74        self.xmax = data.xmax
75        self.ymin = data.ymin
76        self.ymax = data.ymax
77        self.zmin = data.zmin
78        self.zmax = data.zmax
79        self.label = data.name
80        self.xLabel = "%s(%s)"%(data._xaxis, data._xunit)
81        self.yLabel = "%s(%s)"%(data._yaxis, data._yunit)
82        self.title(title=data.title)
83
84    def plot(self, data=None, marker=None, show_colorbar=True, update=False):
85        """
86        Plot 2D self._data
87        marker - unused
88        """
89        # Assing data
90        if isinstance(data, Data2D):
91            self.data = data
92
93        if not self._data:
94            return
95
96        # Toggle the scale
97        zmin_2D_temp, zmax_2D_temp = self.calculateDepth()
98
99        # Prepare and show the plot
100        self.showPlot(data=self.data.data,
101                      qx_data=self.qx_data,
102                      qy_data=self.qy_data,
103                      xmin=self.xmin,
104                      xmax=self.xmax,
105                      ymin=self.ymin, ymax=self.ymax,
106                      cmap=self.cmap, zmin=zmin_2D_temp,
107                      zmax=zmax_2D_temp, show_colorbar=show_colorbar,
108                      update=update)
109
110        self.updateCircularAverage()
111
112    def calculateDepth(self):
113        """
114        Re-calculate the plot depth parameters depending on the scale
115        """
116        # Toggle the scale
117        zmin_temp = self.zmin
118        zmax_temp = self.zmax
119        # self.scale predefined in the baseclass
120        # in numpy > 1.12 power(int, -int) raises ValueException
121        # "Integers to negative integer powers are not allowed."
122        if self.scale == 'log_{10}':
123            if self.zmin is not None:
124                zmin_temp = numpy.power(10.0, self.zmin)
125            if self.zmax is not None:
126                zmax_temp = numpy.power(10.0, self.zmax)
127        else:
128            if self.zmin is not None:
129                # min log value: no log(negative)
130                zmin_temp = MIN_Z if self.zmin <= 0 else numpy.log10(self.zmin)
131            if self.zmax is not None:
132                zmax_temp = numpy.log10(self.zmax)
133
134        return (zmin_temp, zmax_temp)
135
136
137    def createContextMenu(self):
138        """
139        Define common context menu and associated actions for the MPL widget
140        """
141        self.defaultContextMenu()
142
143        self.contextMenu.addSeparator()
144        self.actionDataInfo = self.contextMenu.addAction("&DataInfo")
145        self.actionDataInfo.triggered.connect(
146             functools.partial(self.onDataInfo, self.data))
147
148        self.actionSavePointsAsFile = self.contextMenu.addAction("&Save Points as a File")
149        self.actionSavePointsAsFile.triggered.connect(
150             functools.partial(self.onSavePoints, self.data))
151        self.contextMenu.addSeparator()
152
153        self.actionCircularAverage = self.contextMenu.addAction("&Perform Circular Average")
154        self.actionCircularAverage.triggered.connect(self.onCircularAverage)
155
156        self.actionSectorView = self.contextMenu.addAction("&Sector [Q View]")
157        self.actionSectorView.triggered.connect(self.onSectorView)
158        self.actionAnnulusView = self.contextMenu.addAction("&Annulus [Phi View]")
159        self.actionAnnulusView.triggered.connect(self.onAnnulusView)
160        self.actionBoxSum = self.contextMenu.addAction("&Box Sum")
161        self.actionBoxSum.triggered.connect(self.onBoxSum)
162        self.actionBoxAveragingX = self.contextMenu.addAction("&Box Averaging in Qx")
163        self.actionBoxAveragingX.triggered.connect(self.onBoxAveragingX)
164        self.actionBoxAveragingY = self.contextMenu.addAction("&Box Averaging in Qy")
165        self.actionBoxAveragingY.triggered.connect(self.onBoxAveragingY)
166        # Additional items for slicer interaction
167        if self.slicer:
168            self.actionClearSlicer = self.contextMenu.addAction("&Clear Slicer")
169            self.actionClearSlicer.triggered.connect(self.onClearSlicer)
170            if self.slicer.__class__.__name__ != "BoxSumCalculator":
171                self.actionEditSlicer = self.contextMenu.addAction("&Edit Slicer Parameters")
172                self.actionEditSlicer.triggered.connect(self.onEditSlicer)
173        self.contextMenu.addSeparator()
174        self.actionColorMap = self.contextMenu.addAction("&2D Color Map")
175        self.actionColorMap.triggered.connect(self.onColorMap)
176        self.contextMenu.addSeparator()
177        self.actionChangeScale = self.contextMenu.addAction("Toggle Linear/Log Scale")
178        self.actionChangeScale.triggered.connect(self.onToggleScale)
179
180    def createContextMenuQuick(self):
181        """
182        Define context menu and associated actions for the quickplot MPL widget
183        """
184        self.defaultContextMenu()
185
186        if self.dimension == 2:
187            self.actionToggleGrid = self.contextMenu.addAction("Toggle Grid On/Off")
188            self.contextMenu.addSeparator()
189        self.actionChangeScale = self.contextMenu.addAction("Toggle Linear/Log Scale")
190
191        # Define the callbacks
192        self.actionChangeScale.triggered.connect(self.onToggleScale)
193        if self.dimension == 2:
194            self.actionToggleGrid.triggered.connect(self.onGridToggle)
195
196    def onToggleScale(self, event):
197        """
198        Toggle axis and replot image
199        """
200        # self.scale predefined in the baseclass
201        if self.scale == 'log_{10}':
202            self.scale = 'linear'
203        else:
204            self.scale = 'log_{10}'
205
206        self.plot()
207
208    def onClearSlicer(self):
209        """
210        Remove all sclicers from the chart
211        """
212        if self.slicer is None:
213            return
214
215        self.slicer.clear()
216        self.canvas.draw()
217        self.slicer = None
218
219    def onEditSlicer(self):
220        """
221        Present a small dialog for manipulating the current slicer
222        """
223        assert self.slicer
224        # Only show the dialog if not currently shown
225        if self.slicer_widget:
226            return
227        def slicer_closed():
228            # Need to disconnect the signal!!
229            self.slicer_widget.closeWidgetSignal.disconnect()
230            self.manager.parent.workspace().removeSubWindow(self.slicer_subwindow)
231            # reset slicer_widget on "Edit Slicer Parameters" window close
232            self.slicer_widget = None
233
234        self.param_model = self.slicer.model()
235        # Pass the model to the Slicer Parameters widget
236        self.slicer_widget = SlicerParameters(model=self.param_model,
237                                              validate_method=self.slicer.validate)
238        self.slicer_widget.closeWidgetSignal.connect(slicer_closed)
239        # Add the plot to the workspace
240        self.slicer_subwindow = self.manager.parent.workspace().addSubWindow(self.slicer_widget)
241
242        self.slicer_widget.show()
243
244    def circularAverage(self):
245        """
246        Calculate the circular average and create the Data object for it
247        """
248        # Find the best number of bins
249        npt = numpy.sqrt(len(self.data.data[numpy.isfinite(self.data.data)]))
250        npt = numpy.floor(npt)
251        # compute the maximum radius of data2D
252        self.qmax = max(numpy.fabs(self.data.xmax),
253                        numpy.fabs(self.data.xmin))
254        self.ymax = max(numpy.fabs(self.data.ymax),
255                        numpy.fabs(self.data.ymin))
256        self.radius = numpy.sqrt(numpy.power(self.qmax, 2) + numpy.power(self.ymax, 2))
257        #Compute beam width
258        bin_width = (self.qmax + self.qmax) / npt
259        # Create data1D circular average of data2D
260        circle = CircularAverage(r_min=0, r_max=self.radius, bin_width=bin_width)
261        circ = circle(self.data)
262        dxl = circ.dxl if hasattr(circ, "dxl") else None
263        dxw = circ.dxw if hasattr(circ, "dxw") else None
264
265        new_plot = Data1D(x=circ.x, y=circ.y, dy=circ.dy, dx=circ.dx)
266        new_plot.dxl = dxl
267        new_plot.dxw = dxw
268        new_plot.name = new_plot.title = "Circ avg " + self.data.name
269        new_plot.source = self.data.source
270        new_plot.interactive = True
271        new_plot.detector = self.data.detector
272
273        # Define axes if not done yet.
274        new_plot.xaxis("\\rm{Q}", "A^{-1}")
275        if hasattr(self.data, "scale") and \
276                    self.data.scale == 'linear':
277            new_plot.ytransform = 'y'
278            new_plot.yaxis("\\rm{Residuals} ", "normalized")
279        else:
280            new_plot.yaxis("\\rm{Intensity} ", "cm^{-1}")
281
282        new_plot.group_id = "2daverage" + self.data.name
283        new_plot.id = "Circ avg " + self.data.name
284        new_plot.is_data = True
285
286        return new_plot
287
288    def onCircularAverage(self):
289        """
290        Perform circular averaging on Data2D
291        """
292        new_plot = self.circularAverage()
293
294        item = self._item
295        if self._item.parent() is not None:
296            item = self._item.parent()
297
298        GuiUtils.updateModelItemWithPlot(item, new_plot, new_plot.id)
299
300        self.manager.communicator.plotUpdateSignal.emit([new_plot])
301
302        self.manager.communicator.forcePlotDisplaySignal.emit([item, new_plot])
303
304    def updateCircularAverage(self):
305        """
306        Update circular averaging plot on Data2D change
307        """
308        item = self._item
309        if self._item.parent() is not None:
310            item = self._item.parent()
311
312        # Get all plots for current item
313        plots = GuiUtils.plotsFromModel("", item)
314        ca_caption = '2daverage'+self.data.name
315        # See if current item plots contain 2D average plot
316        test = [ca_caption in plot.group_id for plot in plots]
317        # return prematurely if no circular average plot found
318        if not any(test): return
319
320        # Create a new plot
321        new_plot = self.circularAverage()
322
323        # Overwrite existing plot
324        GuiUtils.updateModelItemWithPlot(item, new_plot, new_plot.id)
325        # Show the new plot, if already visible
326        self.manager.communicator.plotUpdateSignal.emit([new_plot])
327
328    def setSlicer(self, slicer):
329        """
330        Clear the previous slicer and create a new one.
331        slicer: slicer class to create
332        """
333        # Clear current slicer
334        if self.slicer is not None:
335            self.slicer.clear()
336        # Create a new slicer
337        self.slicer_z += 1
338        self.slicer = slicer(self, self.ax, item=self._item, zorder=self.slicer_z)
339        self.ax.set_ylim(self.data.ymin, self.data.ymax)
340        self.ax.set_xlim(self.data.xmin, self.data.xmax)
341        # Draw slicer
342        self.figure.canvas.draw()
343        self.slicer.update()
344
345        # Reset the model on the Edit slicer parameters widget
346        self.param_model = self.slicer.model()
347        if self.slicer_widget:
348            self.slicer_widget.setModel(self.param_model)
349
350    def onSectorView(self):
351        """
352        Perform sector averaging on Q and draw sector slicer
353        """
354        self.setSlicer(slicer=SectorInteractor)
355
356    def onAnnulusView(self):
357        """
358        Perform sector averaging on Phi and draw annulus slicer
359        """
360        self.setSlicer(slicer=AnnulusInteractor)
361
362    def onBoxSum(self):
363        """
364        Perform 2D Data averaging Qx and Qy.
365        Display box slicer details.
366        """
367        self.onClearSlicer()
368        self.slicer_z += 1
369        self.slicer = BoxSumCalculator(self, self.ax, zorder=self.slicer_z)
370
371        self.ax.set_ylim(self.data.ymin, self.data.ymax)
372        self.ax.set_xlim(self.data.xmin, self.data.xmax)
373        self.figure.canvas.draw()
374        self.slicer.update()
375
376        def boxWidgetClosed():
377            # Need to disconnect the signal!!
378            self.boxwidget.closeWidgetSignal.disconnect()
379            # reset box on "Edit Slicer Parameters" window close
380            self.manager.parent.workspace().removeSubWindow(self.boxwidget_subwindow)
381            self.boxwidget = None
382
383        # Get the BoxSumCalculator model.
384        self.box_sum_model = self.slicer.model()
385        # Pass the BoxSumCalculator model to the BoxSum widget
386        self.boxwidget = BoxSum(self, model=self.box_sum_model)
387        # Add the plot to the workspace
388        self.boxwidget_subwindow = self.manager.parent.workspace().addSubWindow(self.boxwidget)
389        self.boxwidget.closeWidgetSignal.connect(boxWidgetClosed)
390
391        self.boxwidget.show()
392
393    def onBoxAveragingX(self):
394        """
395        Perform 2D data averaging on Qx
396        Create a new slicer.
397        """
398        self.setSlicer(slicer=BoxInteractorX)
399
400    def onBoxAveragingY(self):
401        """
402        Perform 2D data averaging on Qy
403        Create a new slicer .
404        """
405        self.setSlicer(slicer=BoxInteractorY)
406
407    def onColorMap(self):
408        """
409        Display the color map dialog and modify the plot's map accordingly
410        """
411        color_map_dialog = ColorMap(self, cmap=self.cmap,
412                                    vmin=self.vmin,
413                                    vmax=self.vmax,
414                                    data=self.data)
415
416        color_map_dialog.apply_signal.connect(self.onApplyMap)
417
418        if color_map_dialog.exec_() == QtWidgets.QDialog.Accepted:
419            self.onApplyMap(color_map_dialog.norm(), color_map_dialog.cmap())
420
421    def onApplyMap(self, v_values, cmap):
422        """
423        Update the chart color map based on data passed from the widget
424        """
425        self.cmap = str(cmap)
426        self.vmin, self.vmax = v_values
427        # Redraw the chart with new cmap
428        self.plot()
429
430    def showPlot(self, data, qx_data, qy_data, xmin, xmax, ymin, ymax,
431                 zmin, zmax, label='data2D', cmap=DEFAULT_CMAP, show_colorbar=True,
432                 update=False):
433        """
434        Render and show the current data
435        """
436        self.qx_data = qx_data
437        self.qy_data = qy_data
438        self.xmin = xmin
439        self.xmax = xmax
440        self.ymin = ymin
441        self.ymax = ymax
442        self.zmin = zmin
443        self.zmax = zmax
444        # If we don't have any data, skip.
445        if data is None:
446            return
447        if data.ndim == 0:
448            return
449        elif data.ndim == 1:
450            output = PlotUtilities.build_matrix(data, self.qx_data, self.qy_data)
451        else:
452            output = copy.deepcopy(data)
453
454        # get the x and y_bin arrays.
455        x_bins, y_bins = PlotUtilities.get_bins(self.qx_data, self.qy_data)
456        self._data.x_bins = x_bins
457        self._data.y_bins = y_bins
458
459        zmin_temp = self.zmin
460        # check scale
461        if self.scale == 'log_{10}':
462            try:
463                if  self.zmin is None  and len(output[output > 0]) > 0:
464                    zmin_temp = self.zmin
465                    output[output > 0] = numpy.log10(output[output > 0])
466                elif self.zmin <= 0:
467                    zmin_temp = self.zmin
468                    output[output > 0] = numpy.zeros(len(output))
469                    output[output <= 0] = MIN_Z
470                else:
471                    zmin_temp = self.zmin
472                    output[output > 0] = numpy.log10(output[output > 0])
473            except:
474                #Too many problems in 2D plot with scale
475                pass
476
477        self.cmap = cmap
478        if self.dimension != 3:
479            #Re-adjust colorbar
480            self.figure.subplots_adjust(left=0.2, right=.8, bottom=.2)
481
482            zmax_temp = self.zmax
483            if self.vmin is not None:
484                zmin_temp = self.vmin
485                zmax_temp = self.vmax
486            if self.im is not None and update:
487                self.im.set_data(output)
488            else:
489                self.im = self.ax.imshow(output, interpolation='nearest',
490                                origin='lower',
491                                vmin=zmin_temp, vmax=zmax_temp,
492                                cmap=self.cmap,
493                                extent=(self.xmin, self.xmax,
494                                        self.ymin, self.ymax))
495
496            cbax = self.figure.add_axes([0.88, 0.2, 0.02, 0.7])
497
498            # Current labels for axes
499            self.ax.set_ylabel(self.y_label)
500            self.ax.set_xlabel(self.x_label)
501
502            # Title only for regular charts
503            if not self.quickplot:
504                self.ax.set_title(label=self._title)
505
506            if cbax is None:
507                ax.set_frame_on(False)
508                cb = self.figure.colorbar(self.im, shrink=0.8, aspect=20)
509            else:
510                cb = self.figure.colorbar(self.im, cax=cbax)
511
512            cb.update_bruteforce(self.im)
513            cb.set_label('$' + self.scale + '$')
514
515            self.vmin = cb.vmin
516            self.vmax = cb.vmax
517
518            if show_colorbar is False:
519                cb.remove()
520
521        else:
522            # clear the previous 2D from memory
523            self.figure.clear()
524
525            self.figure.subplots_adjust(left=0.1, right=.8, bottom=.1)
526
527            data_x, data_y = numpy.meshgrid(self._data.x_bins[0:-1],
528                                            self._data.y_bins[0:-1])
529
530            ax = Axes3D(self.figure)
531
532            # Disable rotation for large sets.
533            # TODO: Define "large" for a dataset
534            SET_TOO_LARGE = 500
535            if len(data_x) > SET_TOO_LARGE:
536                ax.disable_mouse_rotation()
537
538            self.figure.canvas.resizing = False
539            im = ax.plot_surface(data_x, data_y, output, rstride=1,
540                                 cstride=1, cmap=cmap,
541                                 linewidth=0, antialiased=False)
542            self.ax.set_axis_off()
543
544        if self.dimension != 3:
545            self.figure.canvas.draw_idle()
546        else:
547            self.figure.canvas.draw()
548
549    def imageShow(self, img, origin=None):
550        """
551        Show background image
552        :Param img: [imread(path) from matplotlib.pyplot]
553        """
554        if origin is not None:
555            im = self.ax.imshow(img, origin=origin)
556        else:
557            im = self.ax.imshow(img)
558
559    def update(self):
560        self.figure.canvas.draw()
561
562    def draw(self):
563        self.figure.canvas.draw()
564
565    def replacePlot(self, id, new_plot):
566        """
567        Replace data in current chart.
568        This effectively refreshes the chart with changes to one of its plots
569        """
570        self.plot(data=new_plot)
571
572
573class Plotter2D(QtWidgets.QDialog, Plotter2DWidget):
574    """
575    Plotter widget implementation
576    """
577    def __init__(self, parent=None, quickplot=False, dimension=2):
578        QtWidgets.QDialog.__init__(self)
579        Plotter2DWidget.__init__(self, manager=parent, quickplot=quickplot, dimension=dimension)
580        icon = QtGui.QIcon()
581        icon.addPixmap(QtGui.QPixmap(":/res/ball.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
582        self.setWindowIcon(icon)
Note: See TracBrowser for help on using the repository browser.