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

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

Minor widget resize for better plot visibility in Mask Editor.
Also, fixed a missing reference.

  • Property mode set to 100644
File size: 19.0 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    def calculateDepth(self):
111        """
112        Re-calculate the plot depth parameters depending on the scale
113        """
114        # Toggle the scale
115        zmin_temp = self.zmin
116        zmax_temp = self.zmax
117        # self.scale predefined in the baseclass
118        # in numpy > 1.12 power(int, -int) raises ValueException
119        # "Integers to negative integer powers are not allowed."
120        if self.scale == 'log_{10}':
121            if self.zmin is not None:
122                zmin_temp = numpy.power(10.0, self.zmin)
123            if self.zmax is not None:
124                zmax_temp = numpy.power(10.0, self.zmax)
125        else:
126            if self.zmin is not None:
127                # min log value: no log(negative)
128                zmin_temp = MIN_Z if self.zmin <= 0 else numpy.log10(self.zmin)
129            if self.zmax is not None:
130                zmax_temp = numpy.log10(self.zmax)
131
132        return (zmin_temp, zmax_temp)
133
134
135    def createContextMenu(self):
136        """
137        Define common context menu and associated actions for the MPL widget
138        """
139        self.defaultContextMenu()
140
141        self.contextMenu.addSeparator()
142        self.actionDataInfo = self.contextMenu.addAction("&DataInfo")
143        self.actionDataInfo.triggered.connect(
144             functools.partial(self.onDataInfo, self.data))
145
146        self.actionSavePointsAsFile = self.contextMenu.addAction("&Save Points as a File")
147        self.actionSavePointsAsFile.triggered.connect(
148             functools.partial(self.onSavePoints, self.data))
149        self.contextMenu.addSeparator()
150
151        self.actionCircularAverage = self.contextMenu.addAction("&Perform Circular Average")
152        self.actionCircularAverage.triggered.connect(self.onCircularAverage)
153
154        self.actionSectorView = self.contextMenu.addAction("&Sector [Q View]")
155        self.actionSectorView.triggered.connect(self.onSectorView)
156        self.actionAnnulusView = self.contextMenu.addAction("&Annulus [Phi View]")
157        self.actionAnnulusView.triggered.connect(self.onAnnulusView)
158        self.actionBoxSum = self.contextMenu.addAction("&Box Sum")
159        self.actionBoxSum.triggered.connect(self.onBoxSum)
160        self.actionBoxAveragingX = self.contextMenu.addAction("&Box Averaging in Qx")
161        self.actionBoxAveragingX.triggered.connect(self.onBoxAveragingX)
162        self.actionBoxAveragingY = self.contextMenu.addAction("&Box Averaging in Qy")
163        self.actionBoxAveragingY.triggered.connect(self.onBoxAveragingY)
164        # Additional items for slicer interaction
165        if self.slicer:
166            self.actionClearSlicer = self.contextMenu.addAction("&Clear Slicer")
167            self.actionClearSlicer.triggered.connect(self.onClearSlicer)
168            if self.slicer.__class__.__name__ != "BoxSumCalculator":
169                self.actionEditSlicer = self.contextMenu.addAction("&Edit Slicer Parameters")
170                self.actionEditSlicer.triggered.connect(self.onEditSlicer)
171        self.contextMenu.addSeparator()
172        self.actionColorMap = self.contextMenu.addAction("&2D Color Map")
173        self.actionColorMap.triggered.connect(self.onColorMap)
174        self.contextMenu.addSeparator()
175        self.actionChangeScale = self.contextMenu.addAction("Toggle Linear/Log Scale")
176        self.actionChangeScale.triggered.connect(self.onToggleScale)
177
178    def createContextMenuQuick(self):
179        """
180        Define context menu and associated actions for the quickplot MPL widget
181        """
182        self.defaultContextMenu()
183
184        if self.dimension == 2:
185            self.actionToggleGrid = self.contextMenu.addAction("Toggle Grid On/Off")
186            self.contextMenu.addSeparator()
187        self.actionChangeScale = self.contextMenu.addAction("Toggle Linear/Log Scale")
188
189        # Define the callbacks
190        self.actionChangeScale.triggered.connect(self.onToggleScale)
191        if self.dimension == 2:
192            self.actionToggleGrid.triggered.connect(self.onGridToggle)
193
194    def onToggleScale(self, event):
195        """
196        Toggle axis and replot image
197        """
198        # self.scale predefined in the baseclass
199        if self.scale == 'log_{10}':
200            self.scale = 'linear'
201        else:
202            self.scale = 'log_{10}'
203
204        self.plot()
205
206    def onClearSlicer(self):
207        """
208        Remove all sclicers from the chart
209        """
210        if self.slicer is None:
211            return
212
213        self.slicer.clear()
214        self.canvas.draw()
215        self.slicer = None
216
217    def onEditSlicer(self):
218        """
219        Present a small dialog for manipulating the current slicer
220        """
221        assert self.slicer
222        # Only show the dialog if not currently shown
223        if self.slicer_widget:
224            return
225        def slicer_closed():
226            # Need to disconnect the signal!!
227            self.slicer_widget.closeWidgetSignal.disconnect()
228            self.manager.parent.workspace().removeSubWindow(self.slicer_subwindow)
229            # reset slicer_widget on "Edit Slicer Parameters" window close
230            self.slicer_widget = None
231
232        self.param_model = self.slicer.model()
233        # Pass the model to the Slicer Parameters widget
234        self.slicer_widget = SlicerParameters(model=self.param_model,
235                                              validate_method=self.slicer.validate)
236        self.slicer_widget.closeWidgetSignal.connect(slicer_closed)
237        # Add the plot to the workspace
238        self.slicer_subwindow = self.manager.parent.workspace().addSubWindow(self.slicer_widget)
239
240        self.slicer_widget.show()
241
242    def onCircularAverage(self):
243        """
244        Perform circular averaging on Data2D
245        """
246        # Find the best number of bins
247        npt = numpy.sqrt(len(self.data.data[numpy.isfinite(self.data.data)]))
248        npt = numpy.floor(npt)
249        # compute the maximum radius of data2D
250        self.qmax = max(numpy.fabs(self.data.xmax),
251                        numpy.fabs(self.data.xmin))
252        self.ymax = max(numpy.fabs(self.data.ymax),
253                        numpy.fabs(self.data.ymin))
254        self.radius = numpy.sqrt(numpy.power(self.qmax, 2) + numpy.power(self.ymax, 2))
255        #Compute beam width
256        bin_width = (self.qmax + self.qmax) / npt
257        # Create data1D circular average of data2D
258        circle = CircularAverage(r_min=0, r_max=self.radius, bin_width=bin_width)
259        circ = circle(self.data)
260        dxl = circ.dxl if hasattr(circ, "dxl") else None
261        dxw = circ.dxw if hasattr(circ, "dxw") else None
262
263        new_plot = Data1D(x=circ.x, y=circ.y, dy=circ.dy, dx=circ.dx)
264        new_plot.dxl = dxl
265        new_plot.dxw = dxw
266        new_plot.name = new_plot.title = "Circ avg " + self.data.name
267        new_plot.source = self.data.source
268        new_plot.interactive = True
269        new_plot.detector = self.data.detector
270
271        # Define axes if not done yet.
272        new_plot.xaxis("\\rm{Q}", "A^{-1}")
273        if hasattr(self.data, "scale") and \
274                    self.data.scale == 'linear':
275            new_plot.ytransform = 'y'
276            new_plot.yaxis("\\rm{Residuals} ", "normalized")
277        else:
278            new_plot.yaxis("\\rm{Intensity} ", "cm^{-1}")
279
280        new_plot.group_id = "2daverage" + self.data.name
281        new_plot.id = "Circ avg " + self.data.name
282        new_plot.is_data = True
283        item = self._item
284        if self._item.parent() is not None:
285            item = self._item.parent()
286        GuiUtils.updateModelItemWithPlot(item, new_plot, new_plot.id)
287
288        self.manager.communicator.plotUpdateSignal.emit([new_plot])
289
290    def setSlicer(self, slicer):
291        """
292        Clear the previous slicer and create a new one.
293        slicer: slicer class to create
294        """
295        # Clear current slicer
296        if self.slicer is not None:
297            self.slicer.clear()
298        # Create a new slicer
299        self.slicer_z += 1
300        self.slicer = slicer(self, self.ax, item=self._item, zorder=self.slicer_z)
301        self.ax.set_ylim(self.data.ymin, self.data.ymax)
302        self.ax.set_xlim(self.data.xmin, self.data.xmax)
303        # Draw slicer
304        self.figure.canvas.draw()
305        self.slicer.update()
306
307        # Reset the model on the Edit slicer parameters widget
308        self.param_model = self.slicer.model()
309        if self.slicer_widget:
310            self.slicer_widget.setModel(self.param_model)
311
312    def onSectorView(self):
313        """
314        Perform sector averaging on Q and draw sector slicer
315        """
316        self.setSlicer(slicer=SectorInteractor)
317
318    def onAnnulusView(self):
319        """
320        Perform sector averaging on Phi and draw annulus slicer
321        """
322        self.setSlicer(slicer=AnnulusInteractor)
323
324    def onBoxSum(self):
325        """
326        Perform 2D Data averaging Qx and Qy.
327        Display box slicer details.
328        """
329        self.onClearSlicer()
330        self.slicer_z += 1
331        self.slicer = BoxSumCalculator(self, self.ax, zorder=self.slicer_z)
332
333        self.ax.set_ylim(self.data.ymin, self.data.ymax)
334        self.ax.set_xlim(self.data.xmin, self.data.xmax)
335        self.figure.canvas.draw()
336        self.slicer.update()
337
338        def boxWidgetClosed():
339            # Need to disconnect the signal!!
340            self.boxwidget.closeWidgetSignal.disconnect()
341            # reset box on "Edit Slicer Parameters" window close
342            self.manager.parent.workspace().removeSubWindow(self.boxwidget_subwindow)
343            self.boxwidget = None
344
345        # Get the BoxSumCalculator model.
346        self.box_sum_model = self.slicer.model()
347        # Pass the BoxSumCalculator model to the BoxSum widget
348        self.boxwidget = BoxSum(self, model=self.box_sum_model)
349        # Add the plot to the workspace
350        self.boxwidget_subwindow = self.manager.parent.workspace().addSubWindow(self.boxwidget)
351        self.boxwidget.closeWidgetSignal.connect(boxWidgetClosed)
352
353        self.boxwidget.show()
354
355    def onBoxAveragingX(self):
356        """
357        Perform 2D data averaging on Qx
358        Create a new slicer.
359        """
360        self.setSlicer(slicer=BoxInteractorX)
361
362    def onBoxAveragingY(self):
363        """
364        Perform 2D data averaging on Qy
365        Create a new slicer .
366        """
367        self.setSlicer(slicer=BoxInteractorY)
368
369    def onColorMap(self):
370        """
371        Display the color map dialog and modify the plot's map accordingly
372        """
373        color_map_dialog = ColorMap(self, cmap=self.cmap,
374                                    vmin=self.vmin,
375                                    vmax=self.vmax,
376                                    data=self.data)
377
378        color_map_dialog.apply_signal.connect(self.onApplyMap)
379
380        if color_map_dialog.exec_() == QtWidgets.QDialog.Accepted:
381            self.onApplyMap(color_map_dialog.norm(), color_map_dialog.cmap())
382
383    def onApplyMap(self, v_values, cmap):
384        """
385        Update the chart color map based on data passed from the widget
386        """
387        self.cmap = str(cmap)
388        self.vmin, self.vmax = v_values
389        # Redraw the chart with new cmap
390        self.plot()
391
392    def showPlot(self, data, qx_data, qy_data, xmin, xmax, ymin, ymax,
393                 zmin, zmax, label='data2D', cmap=DEFAULT_CMAP, show_colorbar=True,
394                 update=False):
395        """
396        Render and show the current data
397        """
398        self.qx_data = qx_data
399        self.qy_data = qy_data
400        self.xmin = xmin
401        self.xmax = xmax
402        self.ymin = ymin
403        self.ymax = ymax
404        self.zmin = zmin
405        self.zmax = zmax
406        # If we don't have any data, skip.
407        if data is None:
408            return
409        if data.ndim == 0:
410            return
411        elif data.ndim == 1:
412            output = PlotUtilities.build_matrix(data, self.qx_data, self.qy_data)
413        else:
414            output = copy.deepcopy(data)
415
416        # get the x and y_bin arrays.
417        x_bins, y_bins = PlotUtilities.get_bins(self.qx_data, self.qy_data)
418        self._data.x_bins = x_bins
419        self._data.y_bins = y_bins
420
421        zmin_temp = self.zmin
422        # check scale
423        if self.scale == 'log_{10}':
424            try:
425                if  self.zmin is None  and len(output[output > 0]) > 0:
426                    zmin_temp = self.zmin
427                    output[output > 0] = numpy.log10(output[output > 0])
428                elif self.zmin <= 0:
429                    zmin_temp = self.zmin
430                    output[output > 0] = numpy.zeros(len(output))
431                    output[output <= 0] = MIN_Z
432                else:
433                    zmin_temp = self.zmin
434                    output[output > 0] = numpy.log10(output[output > 0])
435            except:
436                #Too many problems in 2D plot with scale
437                pass
438
439        self.cmap = cmap
440        if self.dimension != 3:
441            #Re-adjust colorbar
442            self.figure.subplots_adjust(left=0.2, right=.8, bottom=.2)
443
444            zmax_temp = self.zmax
445            if self.vmin is not None:
446                zmin_temp = self.vmin
447                zmax_temp = self.vmax
448            if self.im is not None and update:
449                self.im.set_data(output)
450            else:
451                self.im = self.ax.imshow(output, interpolation='nearest',
452                                origin='lower',
453                                vmin=zmin_temp, vmax=zmax_temp,
454                                cmap=self.cmap,
455                                extent=(self.xmin, self.xmax,
456                                        self.ymin, self.ymax))
457
458            cbax = self.figure.add_axes([0.88, 0.2, 0.02, 0.7])
459
460            # Current labels for axes
461            self.ax.set_ylabel(self.y_label)
462            self.ax.set_xlabel(self.x_label)
463
464            # Title only for regular charts
465            if not self.quickplot:
466                self.ax.set_title(label=self._title)
467
468            if cbax is None:
469                ax.set_frame_on(False)
470                cb = self.figure.colorbar(self.im, shrink=0.8, aspect=20)
471            else:
472                cb = self.figure.colorbar(self.im, cax=cbax)
473
474            cb.update_bruteforce(self.im)
475            cb.set_label('$' + self.scale + '$')
476
477            self.vmin = cb.vmin
478            self.vmax = cb.vmax
479
480            if show_colorbar is False:
481                cb.remove()
482
483        else:
484            # clear the previous 2D from memory
485            self.figure.clear()
486
487            self.figure.subplots_adjust(left=0.1, right=.8, bottom=.1)
488
489            data_x, data_y = numpy.meshgrid(self._data.x_bins[0:-1],
490                                            self._data.y_bins[0:-1])
491
492            ax = Axes3D(self.figure)
493
494            # Disable rotation for large sets.
495            # TODO: Define "large" for a dataset
496            SET_TOO_LARGE = 500
497            if len(data_x) > SET_TOO_LARGE:
498                ax.disable_mouse_rotation()
499
500            self.figure.canvas.resizing = False
501            im = ax.plot_surface(data_x, data_y, output, rstride=1,
502                                 cstride=1, cmap=cmap,
503                                 linewidth=0, antialiased=False)
504            self.ax.set_axis_off()
505
506        if self.dimension != 3:
507            self.figure.canvas.draw_idle()
508        else:
509            self.figure.canvas.draw()
510
511    def update(self):
512        self.figure.canvas.draw()
513
514    def draw(self):
515        self.figure.canvas.draw()
516
517    def replacePlot(self, id, new_plot):
518        """
519        Replace data in current chart.
520        This effectively refreshes the chart with changes to one of its plots
521        """
522        self.plot(data=new_plot)
523
524
525class Plotter2D(QtWidgets.QDialog, Plotter2DWidget):
526    """
527    Plotter widget implementation
528    """
529    def __init__(self, parent=None, quickplot=False, dimension=2):
530        QtWidgets.QDialog.__init__(self)
531        Plotter2DWidget.__init__(self, manager=parent, quickplot=quickplot, dimension=dimension)
532        icon = QtGui.QIcon()
533        icon.addPixmap(QtGui.QPixmap(":/res/ball.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
534        self.setWindowIcon(icon)
Note: See TracBrowser for help on using the repository browser.