source: sasview/src/sas/sasgui/guiframe/local_perspectives/plotting/Plotter1D.py @ 2f12acc

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 2f12acc was 2f12acc, checked in by lewis, 8 years ago

Allow deletion of linear fits (closes #466)

Also fixes bug where the linear fit would disappear if the home button
was clicked whilst using a non-linear scale

  • Property mode set to 100644
File size: 29.5 KB
Line 
1
2################################################################################
3# This software was developed by the University of Tennessee as part of the
4# Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
5# project funded by the US National Science Foundation.
6#
7# See the license text in license.txt
8#
9# copyright 2008, University of Tennessee
10################################################################################
11
12
13import wx
14import sys
15import math
16import numpy
17import logging
18from sas.sasgui.plottools.PlotPanel import PlotPanel
19from sas.sasgui.guiframe.events import StatusEvent
20from sas.sasgui.guiframe.events import PanelOnFocusEvent
21from sas.sasgui.guiframe.utils import PanelMenu, IdList
22from sas.sasgui.guiframe.panel_base import PanelBase
23from sas.sasgui.guiframe.gui_style import GUIFRAME_ICON
24from appearanceDialog import appearanceDialog
25from graphAppearance import graphAppearance
26
27DEFAULT_QMAX = 0.05
28DEFAULT_QSTEP = 0.001
29DEFAULT_BEAM = 0.005
30BIN_WIDTH = 1
31IS_MAC = (sys.platform == 'darwin')
32
33
34def find_key(dic, val):
35    """return the key of dictionary dic given the value"""
36    return [k for k, v in dic.iteritems() if v == val][0]
37
38class ModelPanel1D(PlotPanel, PanelBase):
39    """
40    Plot panel for use with the GUI manager
41    """
42
43    ## Internal name for the AUI manager
44    window_name = "plotpanel"
45    ## Title to appear on top of the window
46    window_caption = "Graph"
47    ## Flag to tell the GUI manager that this panel is not
48    #  tied to any perspective
49    ALWAYS_ON = True
50    ## Group ID
51    group_id = None
52    _menu_ids = IdList()
53
54    def __init__(self, parent, id=-1, color=None,
55                 dpi=None, style=wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):
56        PlotPanel.__init__(self, parent, id=id, style=style, **kwargs)
57        PanelBase.__init__(self, parent)
58        ## Reference to the parent window
59        self.parent = parent
60        if hasattr(parent, "parent"):
61            self.parent = self.parent.parent
62        ## Plottables
63        self.plots = {}
64        self.frame = None
65        # context menu
66        self._slicerpop = None
67
68        self._available_data = []
69        self._symbol_labels = self.get_symbol_label()
70        self._color_labels = self.get_color_label()
71        self.currColorIndex = ""
72        self._is_changed_legend_label = False
73        self.is_xtick = False
74        self.is_ytick = False
75
76        self.hide_menu = None
77        ## Unique ID (from gui_manager)
78        self.uid = None
79        self.x_size = None
80        ## Default locations
81        # self._default_save_location = os.getcwd()
82        self.size = None
83        self.vl_ind = 0
84        ## Graph
85        # self.graph = Graph()
86        self.graph.xaxis("\\rm{Q}", 'A^{-1}')
87        self.graph.yaxis("\\rm{Intensity} ", "cm^{-1}")
88        self.graph.render(self)
89        self.cursor_id = None
90
91        # In resizing event
92        self.resizing = False
93        self.canvas.set_resizing(self.resizing)
94        self.Bind(wx.EVT_SIZE, self._OnReSize)
95        self.parent.SetFocus()
96
97
98    def get_symbol_label(self):
99        """
100        Associates label to symbol
101        """
102        _labels = {}
103        i = 0
104        _labels['Circle'] = i
105        i += 1
106        _labels['Cross X '] = i
107        i += 1
108        _labels['Triangle Down'] = i
109        i += 1
110        _labels['Triangle Up'] = i
111        i += 1
112        _labels['Triangle Left'] = i
113        i += 1
114        _labels['Triangle Right'] = i
115        i += 1
116        _labels['Cross +'] = i
117        i += 1
118        _labels['Square'] = i
119        i += 1
120        _labels['diamond'] = i
121        i += 1
122        _labels['Diamond'] = i
123        i += 1
124        _labels['Hexagon1'] = i
125        i += 1
126        _labels['Hexagon2'] = i
127        i += 1
128        _labels['Pentagon'] = i
129        i += 1
130        _labels['Line'] = i
131        i += 1
132        _labels['Dash'] = i
133        i += 1
134        _labels['Vline'] = i
135        i += 1
136        _labels['Step'] = i
137        return _labels
138
139    def get_color_label(self):
140        """
141        Associates label to a specific color
142        """
143        _labels = {}
144        i = 0
145        _labels['Blue'] = i
146        i += 1
147        _labels['Green'] = i
148        i += 1
149        _labels['Red'] = i
150        i += 1
151        _labels['Cyan'] = i
152        i += 1
153        _labels['Magenta'] = i
154        i += 1
155        _labels['Yellow'] = i
156        i += 1
157        _labels['Black'] = i
158        return _labels
159
160
161    def set_data(self, list=None):
162        """
163        """
164        pass
165
166    def _reset(self):
167        """
168        Resets internal data and graph
169        """
170        self.graph.reset()
171        self.plots = {}
172        self.is_zoomed = False
173
174    def _OnReSize(self, event):
175        """
176        On response of the resize of a panel, set axes_visiable False
177        """
178        # It was found that wx >= 2.9.3 sends an event even if no size changed.
179        # So manually recode the size (=x_size) and compare here.
180        # Massy code to work around:<
181        if self.parent._mgr != None:
182            max_panel = self.parent._mgr.GetPane(self)
183            if max_panel.IsMaximized():
184                self.parent._mgr.RestorePane(max_panel)
185                max_panel.Maximize()
186        if self.x_size != None:
187            if self.x_size == self.GetSize():
188                self.resizing = False
189                self.canvas.set_resizing(self.resizing)
190                return
191        self.x_size = self.GetSize()
192
193        # Ready for another event
194        # Do not remove this Skip. Otherwise it will get runtime error on wx>=2.9.
195        event.Skip()
196        # set the resizing flag
197        self.resizing = True
198        self.canvas.set_resizing(self.resizing)
199        self.parent.set_schedule(True)
200        pos_x, pos_y = self.GetPositionTuple()
201        if pos_x != 0 and pos_y != 0:
202            self.size, _ = self.GetClientSizeTuple()
203        self.SetSizer(self.sizer)
204        wx.CallAfter(self.parent.disable_app_menu, self)
205
206    def on_plot_qrange(self, event=None):
207        """
208        On Qmin Qmax vertical line event
209        """
210        if event == None:
211            return
212        event.Skip()
213        active_ctrl = event.active
214        if active_ctrl == None:
215            return
216        if event.id in self.plots.keys():
217            ctrl = event.ctrl
218            self.cursor_id = event.id
219            # Set line position and color
220            colors = ['red', 'purple']
221            x_data = self.plots[self.cursor_id].x
222            values = [max(x_data.min(), float(ctrl[0].GetValue())),
223                      min(x_data.max(), float(ctrl[1].GetValue()))]
224            if self.ly == None:
225                self.ly = []
226                for c, v in zip(colors, values):
227                    h = self.subplot.axvline(x=v, color=c, lw=2.5, alpha=0.7)
228                    h.set_rasterized(True)
229                    self.ly.append(h)
230            try:
231                # Display x,y in the status bar if possible
232                xval = float(active_ctrl.GetValue())
233                position = self.get_data_xy_vals(xval)
234                if position != None:
235                    wx.PostEvent(self.parent, StatusEvent(status=position))
236            except:
237                logging.error(sys.exc_value)
238            if not event.leftdown:
239                # text event
240                try:
241                    is_moved = False
242                    for h, v in zip(self.ly, values):
243                        # check if vline moved
244                        if h.get_xdata() != v:
245                            h.set_xdata(v)
246                            is_moved = True
247                    if is_moved:
248                        self.canvas.draw()
249                except:
250                    logging.error(sys.exc_value)
251                event.Skip()
252                return
253            self.q_ctrl = ctrl
254            for h, c, v in zip(self.ly, colors, values):
255                h.set_color(c)
256                h.set_xdata(v)
257            self.canvas.draw()
258        else:
259            self.q_ctrl = None
260
261    def get_data_xy_vals(self, xval):
262        """
263        Get x, y data values near x = x_val
264        """
265        try:
266            x_data = self.plots[self.cursor_id].x
267            y_data = self.plots[self.cursor_id].y
268            indx = self._find_nearest(x_data, xval)
269            pos_x = x_data[indx]
270            pos_y = y_data[indx]
271            position = str(pos_x), str(pos_y)
272            return position
273        except:
274            return None
275
276    def _find_nearest(self, array, value):
277        """
278        Find and return the nearest value in array to the value.
279        Used in cusor_line()
280        :Param array: numpy array
281        :Param value: float
282        """
283        idx = (numpy.abs(array - value)).argmin()
284        return int(idx)  # array.flat[idx]
285
286    def _check_line_positions(self, pos_x=None, nop=None):
287        """
288        Check vertical line positions
289        :Param pos_x: position of the current line [float]
290        :Param nop: number of plots [int]
291        """
292        ly = self.ly
293        ly0x = ly[0].get_xdata()
294        ly1x = ly[1].get_xdata()
295        self.q_ctrl[0].SetBackgroundColour('white')
296        self.q_ctrl[1].SetBackgroundColour('white')
297        if ly0x >= ly1x:
298            if self.vl_ind == 0:
299                ly[1].set_xdata(pos_x)
300                ly[1].set_zorder(nop)
301                self.q_ctrl[1].SetValue(str(pos_x))
302                self.q_ctrl[0].SetBackgroundColour('pink')
303            elif self.vl_ind == 1:
304                ly[0].set_xdata(pos_x)
305                ly[0].set_zorder(nop)
306                self.q_ctrl[0].SetValue(str(pos_x))
307                self.q_ctrl[1].SetBackgroundColour('pink')
308
309    def _get_cusor_lines(self, event):
310        """
311        Revmove or switch cursor line if drawn
312        :Param event: LeftClick mouse event
313        """
314        ax = event.inaxes
315        if hasattr(event, "action"):
316            dclick = event.action == 'dclick'
317            if ax == None or dclick:
318                # remove the vline
319                self._check_zoom_plot()
320                self.canvas.draw()
321                self.q_ctrl = None
322                return
323        if self.ly != None and event.xdata != None:
324            # Selecting a new line if cursor lines are displayed already
325            dqmin = math.fabs(event.xdata - self.ly[0].get_xdata())
326            dqmax = math.fabs(event.xdata - self.ly[1].get_xdata())
327            is_qmax = dqmin > dqmax
328            if is_qmax:
329                self.vl_ind = 1
330            else:
331                self.vl_ind = 0
332
333    def cusor_line(self, event):
334        """
335        Move the cursor line to write Q range
336        """
337        if self.q_ctrl == None:
338            return
339        # release a q range vline
340        if self.ly != None and not self.leftdown:
341            for ly in self.ly:
342                ly.set_alpha(0.7)
343                self.canvas.draw()
344            return
345        ax = event.inaxes
346        if ax == None or not hasattr(event, 'action'):
347            return
348        end_drag = event.action != 'drag' and event.xdata != None
349        nop = len(self.plots)
350        pos_x, _ = float(event.xdata), float(event.ydata)
351        try:
352            ly = self.ly
353            ly0x = ly[0].get_xdata()
354            ly1x = ly[1].get_xdata()
355            if ly0x == ly1x:
356                if ly[0].get_zorder() > ly[1].get_zorder():
357                    self.vl_ind = 0
358                else:
359                    self.vl_ind = 1
360            vl_ind = self.vl_ind
361            x_data = self.plots[self.cursor_id].x
362            xmin = x_data.min()
363            xmax = x_data.max()
364            indx = self._find_nearest(x_data, pos_x)
365            # Need to hold LeftButton to drag
366            if end_drag:
367                if event.button:
368                    self._check_line_positions(pos_x, nop)
369                return
370            if indx >= len(x_data):
371                indx = len(x_data) - 1
372            pos_x = x_data[indx]
373            if xmin == ly1x:
374                vl_ind = 1
375            elif xmax == ly0x:
376                vl_ind = 0
377            else:
378                ly[vl_ind].set_xdata(pos_x)
379                ly[vl_ind].set_zorder(nop + 1)
380                self._check_line_positions(pos_x, nop)
381            ly[vl_ind].set_xdata(pos_x)
382            ly[vl_ind].set_alpha(1.0)
383            ly[vl_ind].set_zorder(nop + 1)
384            self.canvas.draw()
385            self.q_ctrl[vl_ind].SetValue(str(pos_x))
386        except:
387            logging.error(sys.exc_value)
388
389    def set_resizing(self, resizing=False):
390        """
391        Set the resizing (True/False)
392        """
393        self.resizing = resizing
394        # self.canvas.set_resizing(resizing)
395
396    def schedule_full_draw(self, func='append'):
397        """
398        Put self in schedule to full redraw list
399        """
400        # append/del this panel in the schedule list
401        self.parent.set_schedule_full_draw(self, func)
402
403    def remove_data_by_id(self, id):
404        """
405            Remove data from plot
406        """
407        if id in self.plots.keys():
408            data = self.plots[id]
409            self.graph.delete(data)
410            data_manager = self._manager.parent.get_data_manager()
411            data_list, theory_list = data_manager.get_by_id(id_list=[id])
412
413            if id in data_list.keys():
414                data = data_list[id]
415            if id in theory_list.keys():
416                data = theory_list[id]
417
418            del self.plots[id]
419            self.graph.render(self)
420            self.subplot.figure.canvas.draw_idle()
421            if len(self.graph.plottables) == 0:
422                # onRemove: graph is empty must be the panel must be destroyed
423                self.parent.delete_panel(self.uid)
424
425    def plot_data(self, data):
426        """
427        Data is ready to be displayed
428
429        :param event: data event
430        """
431        if data.__class__.__name__ == 'Data2D':
432            return
433        plot_keys = self.plots.keys()
434        if data.id in plot_keys:
435            # Recover panel prop.s
436            xlo, xhi = self.subplot.get_xlim()
437            ylo, yhi = self.subplot.get_ylim()
438            old_data = self.plots[data.id]
439            if self._is_changed_legend_label:
440                data.label = old_data.label
441            if old_data.__class__.__name__ == 'Data1D':
442                data.custom_color = old_data.custom_color
443                data.symbol = old_data.symbol
444                data.markersize = old_data.markersize
445                data.zorder = len(plot_keys)
446            # Replace data
447            self.graph.replace(data)
448            self.plots[data.id] = data
449            ## Set the view scale for all plots
450            try:
451                self._onEVT_FUNC_PROPERTY()
452            except Exception, exc:
453                wx.PostEvent(self.parent,
454                             StatusEvent(status="Plotting Error: %s" % str(exc), info="error"))
455            if self.is_zoomed:
456                # Recover the x,y limits
457                self.subplot.set_xlim((xlo, xhi))
458                self.subplot.set_ylim((ylo, yhi))
459        else:
460            self.plots[data.id] = data
461            self.graph.add(self.plots[data.id])
462            data.zorder = len(plot_keys)
463            ## Set the view scale for all plots
464            try:
465                self._onEVT_FUNC_PROPERTY()
466                if IS_MAC:
467                    # MAC: forcing to plot 2D avg
468                    self.canvas._onDrawIdle()
469            except Exception, exc:
470                wx.PostEvent(self.parent, StatusEvent(status=\
471                    "Plotting Error: %s" % str(exc), info="error"))
472            self.toolbar.update()
473            self.is_zoomed = False
474
475    def draw_plot(self):
476        """
477        Draw plot
478        """
479        self.draw()
480
481    def onLeftDown(self, event):
482        """
483        left button down and ready to drag
484        Display the position of the mouse on the statusbar
485        """
486        # self.parent.set_plot_unfocus()
487        self._get_cusor_lines(event)
488        ax = event.inaxes
489        PlotPanel.onLeftDown(self, event)
490        if ax != None:
491            try:
492                pos_x = float(event.xdata)  # / size_x
493                pos_y = float(event.ydata)  # / size_y
494                pos_x = "%8.3g" % pos_x
495                pos_y = "%8.3g" % pos_y
496                self.position = str(pos_x), str(pos_y)
497                wx.PostEvent(self.parent, StatusEvent(status=self.position))
498            except:
499                self.position = None
500        # unfocus all
501        self.parent.set_plot_unfocus()
502        # post nd event to notify guiframe that this panel is on focus
503        wx.PostEvent(self.parent, PanelOnFocusEvent(panel=self))
504
505
506    def _ontoggle_hide_error(self, event):
507        """
508        Toggle error display to hide or show
509        """
510        menu = event.GetEventObject()
511        event_id = event.GetId()
512        self.set_selected_from_menu(menu, event_id)
513        # Check zoom
514        xlo, xhi = self.subplot.get_xlim()
515        ylo, yhi = self.subplot.get_ylim()
516
517        selected_plot = self.plots[self.graph.selected_plottable]
518        if self.hide_menu.GetText() == "Hide Error Bar":
519            selected_plot.hide_error = True
520        else:
521            selected_plot.hide_error = False
522        ## increment graph color
523        self.graph.render(self)
524        self.subplot.figure.canvas.draw_idle()
525        if self.is_zoomed:
526            # Recover the x,y limits
527            self.subplot.set_xlim((xlo, xhi))
528            self.subplot.set_ylim((ylo, yhi))
529
530
531    def _onRemove(self, event):
532        """
533        Remove a plottable from the graph and render the graph
534
535        :param event: Menu event
536
537        """
538        menu = event.GetEventObject()
539        event_id = event.GetId()
540        self.set_selected_from_menu(menu, event_id)
541        ## Check if there is a selected graph to remove
542        if self.graph.selected_plottable in self.plots.keys():
543            graph_id = self.graph.selected_plottable
544            self.remove_data_by_id(graph_id)
545
546    def onContextMenu(self, event):
547        """
548        1D plot context menu
549
550        :param event: wx context event
551
552        """
553        self._slicerpop = PanelMenu()
554        self._slicerpop.set_plots(self.plots)
555        self._slicerpop.set_graph(self.graph)
556        ids = iter(self._menu_ids)
557
558        # Various plot options
559        wx_id = ids.next()
560        self._slicerpop.Append(wx_id, '&Save Image', 'Save image as PNG')
561        wx.EVT_MENU(self, wx_id, self.onSaveImage)
562        wx_id = ids.next()
563        self._slicerpop.Append(wx_id, '&Print Image', 'Print image ')
564        wx.EVT_MENU(self, wx_id, self.onPrint)
565
566        wx_id = ids.next()
567        self._slicerpop.Append(wx_id, '&Copy to Clipboard',
568                               'Copy to the clipboard')
569        wx.EVT_MENU(self, wx_id, self.OnCopyFigureMenu)
570
571        self._slicerpop.AppendSeparator()
572
573        for plot in self.plots.values():
574            # title = plot.title
575            name = plot.name
576            plot_menu = wx.Menu()
577            if self.graph.selected_plottable:
578                if not self.graph.selected_plottable in self.plots.keys():
579                    continue
580                if plot != self.plots[self.graph.selected_plottable]:
581                    continue
582
583            wx_id = ids.next()
584            plot_menu.Append(wx_id, "&DataInfo", name)
585            wx.EVT_MENU(self, wx_id, self. _onDataShow)
586            wx_id = ids.next()
587            plot_menu.Append(wx_id, "&Save Points as a File", name)
588            wx.EVT_MENU(self, wx_id, self._onSave)
589            plot_menu.AppendSeparator()
590
591            # add menu of other plugins
592            item_list = self.parent.get_current_context_menu(self)
593            if (not item_list == None) and (not len(item_list) == 0):
594                for item, wx_id in zip(item_list, [ids.next() for i in range(len(item_list))]):
595
596                    try:
597                        plot_menu.Append(wx_id, item[0], name)
598                        wx.EVT_MENU(self, wx_id, item[2])
599                    except:
600                        msg = "ModelPanel1D.onContextMenu: "
601                        msg += "bad menu item  %s" % sys.exc_value
602                        wx.PostEvent(self.parent, StatusEvent(status=msg))
603                plot_menu.AppendSeparator()
604
605            if self.parent.ClassName.count('wxDialog') == 0:
606                if plot.id != 'fit':
607                    wx_id = ids.next()
608                    plot_menu.Append(wx_id, '&Linear Fit', name)
609                    wx.EVT_MENU(self, wx_id, self.onFitting)
610                    plot_menu.AppendSeparator()
611
612                wx_id = ids.next()
613                plot_menu.Append(wx_id, "Remove", name)
614                wx.EVT_MENU(self, wx_id, self._onRemove)
615                if not plot.is_data:
616                    wx_id = ids.next()
617                    plot_menu.Append(wx_id, '&Freeze', name)
618                    wx.EVT_MENU(self, wx_id, self.onFreeze)
619                plot_menu.AppendSeparator()
620
621                if plot.is_data:
622                    wx_id = ids.next()
623                    self.hide_menu = plot_menu.Append(wx_id, "Hide Error Bar", name)
624
625                    if plot.dy is not None and plot.dy != []:
626                        if plot.hide_error:
627                            self.hide_menu.SetText('Show Error Bar')
628                        else:
629                            self.hide_menu.SetText('Hide Error Bar')
630                    else:
631                        self.hide_menu.Enable(False)
632                    wx.EVT_MENU(self, wx_id, self._ontoggle_hide_error)
633
634                    plot_menu.AppendSeparator()
635
636                wx_id = ids.next()
637                plot_menu.Append(wx_id, '&Modify Plot Property', name)
638                wx.EVT_MENU(self, wx_id, self.createAppDialog)
639            wx_id = ids.next()
640            # plot_menu.SetTitle(name)
641            self._slicerpop.AppendMenu(wx_id, '&%s' % name, plot_menu)
642            # Option to hide
643            # TODO: implement functionality to hide a plottable (legend click)
644
645        self._slicerpop.AppendSeparator()
646        loc_menu = wx.Menu()
647        for label in self._loc_labels:
648            wx_id = ids.next()
649            loc_menu.Append(wx_id, str(label), str(label))
650            wx.EVT_MENU(self, wx_id, self.onChangeLegendLoc)
651
652        wx_id = ids.next()
653        self._slicerpop.Append(wx_id, '&Modify Graph Appearance',
654                               'Modify graph appearance')
655        wx.EVT_MENU(self, wx_id, self.modifyGraphAppearance)
656        self._slicerpop.AppendSeparator()
657
658
659        if self.position != None:
660            wx_id = ids.next()
661            self._slicerpop.Append(wx_id, '&Add Text')
662            wx.EVT_MENU(self, wx_id, self._on_addtext)
663            wx_id = ids.next()
664            self._slicerpop.Append(wx_id, '&Remove Text')
665            wx.EVT_MENU(self, wx_id, self._on_removetext)
666            self._slicerpop.AppendSeparator()
667        wx_id = ids.next()
668        self._slicerpop.Append(wx_id, '&Change Scale')
669        wx.EVT_MENU(self, wx_id, self._onProperties)
670        self._slicerpop.AppendSeparator()
671        wx_id = ids.next()
672        self._slicerpop.Append(wx_id, '&Reset Graph Range')
673        wx.EVT_MENU(self, wx_id, self.onResetGraph)
674
675        if self.parent.ClassName.count('wxDialog') == 0:
676            self._slicerpop.AppendSeparator()
677            wx_id = ids.next()
678            self._slicerpop.Append(wx_id, '&Window Title')
679            wx.EVT_MENU(self, wx_id, self.onChangeCaption)
680        try:
681            pos_evt = event.GetPosition()
682            pos = self.ScreenToClient(pos_evt)
683        except:
684            pos_x, pos_y = self.toolbar.GetPositionTuple()
685            pos = (pos_x, pos_y + 5)
686        self.PopupMenu(self._slicerpop, pos)
687
688    def onFreeze(self, event):
689        """
690        on Freeze data
691        """
692        menu = event.GetEventObject()
693        wx_id = event.GetId()
694        self.set_selected_from_menu(menu, wx_id)
695        plot = self.plots[self.graph.selected_plottable]
696        self.parent.onfreeze([plot.id])
697
698    def _onSave(self, evt):
699        """
700        Save a data set to a text file
701
702        :param evt: Menu event
703
704        """
705        menu = evt.GetEventObject()
706        event_id = evt.GetId()
707        self.set_selected_from_menu(menu, event_id)
708        data = self.plots[self.graph.selected_plottable]
709        default_name = data.label
710        if default_name.count('.') > 0:
711            default_name = default_name.split('.')[0]
712        default_name += "_out"
713        if self.parent != None:
714            self.parent.save_data1d(data, default_name)
715
716    def _onDataShow(self, evt):
717        """
718        Show the data set in text
719
720        :param evt: Menu event
721
722        """
723        menu = evt.GetEventObject()
724        event_id = evt.GetId()
725        self.set_selected_from_menu(menu, event_id)
726        data = self.plots[self.graph.selected_plottable]
727        default_name = data.label
728        if default_name.count('.') > 0:
729            default_name = default_name.split('.')[0]
730        # default_name += "_out"
731        if self.parent != None:
732            self.parent.show_data1d(data, default_name)
733
734    def _on_hide(self, event):
735        """
736        Hides the plot when button is pressed
737        """
738        if self.parent is not None:
739            self.parent.hide_panel(self.uid)
740
741    def on_close(self, event):
742        """
743        On Close Event
744        """
745        ID = self.uid
746        self.parent.delete_panel(ID)
747
748    def createAppDialog(self, event):
749        """
750        Create the custom dialog for fit appearance modification
751        """
752        menu = event.GetEventObject()
753        event_id = event.GetId()
754        self.set_selected_from_menu(menu, event_id)
755        self.appearance_selected_plot = \
756                        self.plots[self.graph.selected_plottable]
757        # find current properties
758        curr_color = self.appearance_selected_plot.custom_color
759        curr_symbol = self.appearance_selected_plot.symbol
760        curr_size = self.appearance_selected_plot.markersize
761        curr_label = self.appearance_selected_plot.label
762
763        if curr_color == None:
764            curr_color = self._color_labels['Blue']
765            curr_symbol = 13
766
767        self.appD = appearanceDialog(self, 'Modify Plot Property')
768        icon = self.parent.GetIcon()
769        self.appD.SetIcon(icon)
770        self.appD.set_defaults(float(curr_size), int(curr_color),
771                               str(appearanceDialog.find_key(self.get_symbol_label(),
772                                                             int(curr_symbol))), curr_label)
773        self.appD.Bind(wx.EVT_CLOSE, self.on_AppDialog_close)
774
775    def on_AppDialog_close(self, event):
776        """
777        on_Modify Plot Property_close
778        """
779        if self.appD.okay_clicked == True:
780            info = self.appD.get_current_values()
781            self.appearance_selected_plot.custom_color = \
782                        self._color_labels[info[1].encode('ascii', 'ignore')]
783
784            self.appearance_selected_plot.markersize = float(info[0])
785            self.appearance_selected_plot.symbol = \
786                        self.get_symbol_label()[info[2]]
787            self.appearance_selected_plot.label = str(info[3])
788        self.appD.Destroy()
789        self._check_zoom_plot()
790
791    def modifyGraphAppearance(self, event):
792        """
793        On Modify Graph Appearance
794        """
795        self.graphApp = graphAppearance(self, 'Modify Graph Appearance')
796        icon = self.parent.GetIcon()
797        self.graphApp.SetIcon(icon)
798        self.graphApp.setDefaults(self.grid_on, self.legend_on,
799                                  self.xaxis_label, self.yaxis_label,
800                                  self.xaxis_unit, self.yaxis_unit,
801                                  self.xaxis_font, self.yaxis_font,
802                                  find_key(self.get_loc_label(), self.legendLoc),
803                                  self.xcolor, self.ycolor,
804                                  self.is_xtick, self.is_ytick)
805        self.graphApp.Bind(wx.EVT_CLOSE, self.on_graphApp_close)
806
807    def on_graphApp_close(self, event):
808        """
809        Gets values from graph appearance dialog and sends them off
810        to modify the plot
811        """
812        graph_app = self.graphApp
813        toggle_grid = graph_app.get_togglegrid()
814        legend_loc = graph_app.get_legend_loc()
815        toggle_legend = graph_app.get_togglelegend()
816
817        self.onGridOnOff(toggle_grid)
818        self.ChangeLegendLoc(legend_loc)
819        self.onLegend(toggle_legend)
820
821        self.xaxis_label = graph_app.get_xlab()
822        self.yaxis_label = graph_app.get_ylab()
823        self.xaxis_unit = graph_app.get_xunit()
824        self.yaxis_unit = graph_app.get_yunit()
825        self.xaxis_font = graph_app.get_xfont()
826        self.yaxis_font = graph_app.get_yfont()
827        self.is_xtick = graph_app.get_xtick_check()
828        self.is_ytick = graph_app.get_ytick_check()
829        if self.is_xtick:
830            self.xaxis_tick = self.xaxis_font
831        if self.is_ytick:
832            self.yaxis_tick = self.yaxis_font
833
834        self.xaxis(self.xaxis_label, self.xaxis_unit,
835                   graph_app.get_xfont(), graph_app.get_xcolor(),
836                   self.xaxis_tick)
837        self.yaxis(self.yaxis_label, self.yaxis_unit,
838                   graph_app.get_yfont(), graph_app.get_ycolor(),
839                   self.yaxis_tick)
840
841        graph_app.Destroy()
Note: See TracBrowser for help on using the repository browser.