source: sasview/src/sas/qtgui/Plotting/Plotter2D.py @ 34f13a83

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

Disabled native matplotlib toolbar due to bugs in its 2.1.0
implementation. Will revisit when upgrading to 3.0.
SASVIEW-1103, SASVIEW-1106

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