source: sasview/sansguiframe/src/sans/guiframe/local_perspectives/plotting/profile_dialog.py @ 2d443fd

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 2d443fd was 2d443fd, checked in by Jae Cho <jhjcho@…>, 13 years ago

fixed sld dialog saving

  • Property mode set to 100644
File size: 10.9 KB
Line 
1"""
2SLD Profile Dialog for multifunctional models
3"""
4import wx
5import os
6import sys
7from copy import deepcopy
8from danse.common.plottools.plottables import Graph
9from Plotter1D import ModelPanel1D as PlotPanel
10from sans.guiframe.dataFitting import Data1D
11from sans.guiframe.gui_style import GUIFRAME_ID
12import pylab
13
14DEFAULT_CMAP = None#pylab.cm.jet
15_BOX_WIDTH = 76
16_STATICBOX_WIDTH = 400
17# X Y offset on plot
18_X_OFF = 15
19_Y_OFF = 0.5
20
21#SLD panel size
22if sys.platform.count("win32") > 0:
23    _STATICBOX_WIDTH = 563
24    PANEL_SIZE = 425
25    FONT_VARIANT = 0
26else:
27    _STATICBOX_WIDTH = 605
28    PANEL_SIZE = 500
29    FONT_VARIANT = 1
30   
31     
32class SLDPanel(wx.Dialog):
33    """
34    Provides the SLD profile plot panel.
35    """
36    ## Internal nickname for the window, used by the AUI manager
37    window_name = "Scattering Length Density Profile"
38    ## Name to appear on the window title bar
39    window_caption = "Scattering Length Density Profile"
40    ## Flag to tell the AUI manager to put this panel in the center pane
41    CENTER_PANE = True
42    def __init__(self, parent=None, base=None, data=None, axes =['Radius'], 
43                 id=-1, *args, **kwds):
44        kwds["style"] = wx.DEFAULT_DIALOG_STYLE
45        kwds["size"] = wx.Size(_STATICBOX_WIDTH, PANEL_SIZE) 
46        wx.Dialog.__init__(self, parent, id=id, *args, **kwds)
47
48        if data != None:
49            #Font size
50            kwds = []
51            self.SetWindowVariant(variant=FONT_VARIANT)
52
53            self.SetTitle("Scattering Length Density Profile")
54            self.parent = parent
55            self.data = data
56            self.str = self.data.__str__()
57            ## when 2 data have the same id override the 1 st plotted
58            self.name = self.data.name
59            # Panel for plot
60            self.plotpanel = SLDplotpanel(self, axes, -1, 
61                                             style=wx.TRANSPARENT_WINDOW)
62            self.cmap = DEFAULT_CMAP
63            ## Create Artist and bind it
64            self.subplot = self.plotpanel.subplot
65            # layout
66            self._setup_layout()
67            # plot
68            data_plot = deepcopy(self.data)
69            data_plot.dy = self._set_dy_data()
70            # unit increase to M times for users
71            data_plot.y = self._set_y_data()
72           
73            self.newplot = Data1D(data_plot.x, data_plot.y, data_plot.dy)
74            self.newplot.symbol = GUIFRAME_ID.CURVE_SYMBOL_NUM
75            self.newplot.dy = None
76            self.newplot.name = 'SLD'
77            self.plotpanel.add_image(self.newplot) 
78            self.plotpanel.subplot.set_ylim(min(data_plot.y) - _Y_OFF , 
79                                                max(data_plot.y) + _Y_OFF)
80            self.plotpanel.subplot.set_xlim(min(data_plot.x) - _X_OFF, 
81                                                max(data_plot.x) + _X_OFF)
82            #self.Centre()
83            self.Layout()
84
85    def _set_dy_data(self): 
86        """
87        make fake dy data
88       
89        :return dy:
90        """
91        # set dy as zero
92        dy = [0 for y in self.data.y]
93        return dy     
94
95    def _set_y_data(self): 
96        """
97        make y data unit Mega times
98       
99        :return y_value:
100        """
101        # changes the unit
102        y_value = [yvalue * 1e+006 for yvalue in self.data.y]
103       
104        return y_value     
105   
106    def _setup_layout(self):
107        """
108        Set up the layout
109        """
110        # panel sizer
111        sizer = wx.BoxSizer(wx.VERTICAL)
112        sizer.Add(self.plotpanel, 0, wx.LEFT|wx.RIGHT, 5)
113        sizer.Add(wx.StaticLine(self), 0, wx.ALL|wx.EXPAND, 5)
114        sizer.Add((0, 5))
115        #-----Button------------1
116        id = wx.NewId()
117        button_reset = wx.Button(self, id, "Close")
118        button_reset.SetToolTipString("Close...")
119        button_reset.Bind(wx.EVT_BUTTON, self._close, 
120                          id=button_reset.GetId()) 
121        sizer.Add(button_reset, 0, wx.LEFT, _STATICBOX_WIDTH - 80) 
122        sizer.Add((0, 10))
123        self.SetSizerAndFit(sizer)
124        self.Centre()
125        self.Show(True)
126        button_reset.SetFocus()
127       
128    def _close(self, event):
129        """
130        Close the dialog
131        """
132        self.Close(True)
133
134    def _draw_model(self, event):
135        """
136         on_close, update the model2d plot
137        """
138        pass
139
140    def get_context_menu(self, graph=None):
141        """
142        When the context menu of a plot is rendered, the
143        get_context_menu method will be called to give you a
144        chance to add a menu item to the context menu.
145        :param graph: the Graph object to which we attach the context menu
146       
147        :return: a list of menu items with call-back function
148        """
149        return []
150   
151    def set_schedule_full_draw(self, panel=None, func=None):
152        """
153        Set_schedule for full draw
154        """
155        # Not implemented
156        pass
157   
158    def set_schedule(self, schedule=False):
159        """
160        Set schedule for redraw
161        """
162        # Not implemented
163        pass
164       
165    def set_plot_unfocus(self):
166        """
167        Set_plot unfocus
168        """
169        # NOt implemented
170        pass
171   
172    def on_change_caption(self, name, old_caption, new_caption):
173        """
174        """
175        self.parent.parent.parent.on_change_caption(name, old_caption, new_caption)
176   
177   
178class SLDplotpanel(PlotPanel):
179    """
180    Panel
181    """
182    def __init__(self, parent, axes=[], id=-1, color=None, dpi=None,
183                  **kwargs):
184        """
185        """
186        PlotPanel.__init__(self, parent, id=id, xtransform='x', ytransform='y', 
187                           color=color, dpi=dpi, 
188                           size=(_STATICBOX_WIDTH, PANEL_SIZE-100), **kwargs)
189
190        # Keep track of the parent Frame
191        self.parent = parent
192        self.window_name = "Scattering Length Density Profile"
193        self.window_caption = self.window_name
194        # Internal list of plottable names (because graph
195        # doesn't have a dictionary of handles for the plottables)
196        self.plots = {}
197        self.graph = Graph()
198        self.axes_label = []
199        for idx in range(0, len(axes)):
200            self.axes_label.append(axes[idx])
201        self.xaxis_label = ''
202        self.xaxis_unit = ''
203        self.yaxis_label = ''
204        self.yaxis_unit = ''
205       
206    def add_image(self, plot):
207        """
208        Add image(Theory1D)
209        """
210        self.plots[plot.name] = plot
211        self.plots[plot.name].is_data = False
212        #init graph
213        #self.gaph = Graph()
214        #add plot
215        self.graph.add(plot)
216        #add axes
217        x1_label = self.axes_label[0]
218        self.xaxis_label = '\\rm{%s} '% x1_label
219        self.xaxis_unit = 'A'
220        self.graph.xaxis(self.xaxis_label, self.xaxis_unit)
221        self.yaxis_label = '\\rm{SLD} '
222        self.yaxis_unit = '10^{-6}A^{-2}'
223        self.graph.yaxis(self.yaxis_label, self.yaxis_unit)
224        #draw
225        self.graph.render(self)
226        self.subplot.figure.canvas.draw_idle()
227               
228        # For latter scale changes
229        self.plots[plot.name].xaxis('\\rm{%s} '% x1_label, 'A')
230        self.plots[plot.name].yaxis('\\rm{SLD} ', '10^{-6}A^{-2}')
231       
232    def on_set_focus(self, event):
233        """
234        send to the parenet the current panel on focus
235       
236        """
237        #Not implemented
238        pass
239
240    def on_kill_focus(self, event):
241        """
242        reset the panel color
243       
244        """
245        #Not implemented
246        pass
247   
248    def _add_more_tool(self):
249        """
250        Not implemented
251        """
252        pass 
253   
254    def onChangeCaption(self, event):
255        """
256        Not implemented
257        """
258        pass
259   
260    def _onSave(self, evt):
261        """
262        Save a data set to a text file
263       
264        :param evt: Menu event
265       
266        """
267       
268        path = None
269        wildcard = "Text files (*.txt)|*.txt|"\
270                    "CanSAS 1D files(*.xml)|*.xml" 
271        default_name = "sld_profile"
272        if self.parent != None:
273            self._default_save_location = self.parent.parent._default_save_location
274        dlg = wx.FileDialog(self, "Choose a file",
275                            self._default_save_location,
276                            default_name, wildcard , wx.SAVE)
277       
278        if dlg.ShowModal() == wx.ID_OK:
279            path = dlg.GetPath()
280            # ext_num = 0 for .txt, ext_num = 1 for .xml
281            # This is MAC Fix
282            ext_num = dlg.GetFilterIndex()
283            if ext_num == 0:
284                format = '.txt'
285            else:
286                format = '.xml'
287            path = os.path.splitext(path)[0] + format
288            mypath = os.path.basename(path)
289           
290            #TODO: This is bad design. The DataLoader is designed
291            #to recognize extensions.
292            # It should be a simple matter of calling the .
293            #save(file, data, '.xml') method
294            # of the sans.dataloader.loader.Loader class.
295            from sans.dataloader.loader import  Loader
296            #Instantiate a loader
297            loader = Loader() 
298            data = self.parent.data
299            format = ".txt"
300            if os.path.splitext(mypath)[1].lower() == format:
301                # Make sure the ext included in the file name
302                # especially on MAC
303                fName = os.path.splitext(path)[0] + format
304                self._onsaveTXT(fName)
305            format = ".xml"
306            if os.path.splitext(mypath)[1].lower() == format:
307                # Make sure the ext included in the file name
308                # especially on MAC
309                fName = os.path.splitext(path)[0] + format
310                loader.save(fName, data, format)
311            try:
312                self._default_save_location = os.path.dirname(path)
313                self.parent.parent._default_save_location = self._default_save_location
314            except:
315                pass   
316        dlg.Destroy()
317         
318class ViewerFrame(wx.Frame):
319    """
320    Add comment
321    """
322    def __init__(self, parent, id, title):
323        """
324        comment
325        :param parent: parent panel/container
326        """
327        # Initialize the Frame object
328        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, 
329                          wx.Size(_STATICBOX_WIDTH, PANEL_SIZE))
330        # Panel for 1D plot
331        self.plotpanel    = SLDplotpanel(self, -1, style=wx.RAISED_BORDER)
332
333class ViewApp(wx.App):
334    def OnInit(self):
335        frame = ViewerFrame(None, -1, 'testView')   
336        frame.Show(True)
337        self.SetTopWindow(frame)
338       
339        return True
340               
341if __name__ == "__main__": 
342    app = ViewApp(0)
343    app.MainLoop()     
Note: See TracBrowser for help on using the repository browser.