source: sasview/sansguiframe/src/sans/guiframe/local_perspectives/data_loader/data_loader.py @ 70ecd530

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 70ecd530 was 70ecd530, checked in by Gervaise Alina <gervyh@…>, 13 years ago

minor cchange to allow sphinx build

  • Property mode set to 100644
File size: 9.0 KB
Line 
1
2"""
3plugin DataLoader responsible of loading data
4"""
5import os
6import sys
7import wx
8import logging
9
10from sans.dataloader.loader import Loader
11import sans.dataloader.data_info as DataInfo
12from sans.guiframe.plugin_base import PluginBase
13from sans.guiframe.events import StatusEvent
14from sans.guiframe.events import NewPlotEvent
15from sans.guiframe.dataFitting import Data1D
16from sans.guiframe.dataFitting import Data2D
17from sans.guiframe.utils import parse_name
18from sans.guiframe.gui_style import GUIFRAME
19from sans.guiframe.gui_manager import DEFAULT_OPEN_FOLDER
20try:
21    # Try to find a local config
22    import imp
23    path = os.getcwd()
24    if(os.path.isfile("%s/%s.py" % (path, 'local_config'))) or \
25        (os.path.isfile("%s/%s.pyc" % (path, 'local_config'))):
26        fObj, path, descr = imp.find_module('local_config', [path])
27        config = imp.load_module('local_config', fObj, path, descr) 
28    else:
29        # Try simply importing local_config
30        import local_config as config
31except:
32    # Didn't find local config, load the default
33    import sans.guiframe.config as config
34
35if config is None:
36    import sans.guiframe.config as config
37   
38       
39extension_list = []
40if config.APPLICATION_STATE_EXTENSION is not None:
41    extension_list.append(config.APPLICATION_STATE_EXTENSION)
42EXTENSIONS = config.PLUGIN_STATE_EXTENSIONS + extension_list   
43PLUGINS_WLIST = config.PLUGINS_WLIST
44APPLICATION_WLIST = config.APPLICATION_WLIST
45
46class Plugin(PluginBase):
47   
48    def __init__(self, standalone=False):
49        PluginBase.__init__(self, name="DataLoader", standalone=standalone)
50        #Default location
51        self._default_save_location = DEFAULT_OPEN_FOLDER
52        self.loader = Loader() 
53        self._data_menu = None 
54       
55    def help(self, evt):
56        """
57        Show a general help dialog.
58        """
59        from help_panel import  HelpWindow
60        frame = HelpWindow(None, -1) 
61        if hasattr(frame, "IsIconized"):
62            if not frame.IsIconized():
63                try:
64                    icon = self.parent.GetIcon()
65                    frame.SetIcon(icon)
66                except:
67                    pass 
68        frame.Show(True)
69       
70    def populate_file_menu(self):
71        """
72        get a menu item and append it under file menu of the application
73        add load file menu item and load folder item
74        """
75        #menu for data files
76        menu_list = []
77        data_file_hint = "load one or more data in the application"
78        menu_list = [('&Load Data File(s)', data_file_hint, self.load_data)]
79        gui_style = self.parent.get_style()
80        style = gui_style & GUIFRAME.MULTIPLE_APPLICATIONS
81        style1 = gui_style & GUIFRAME.DATALOADER_ON
82        if style == GUIFRAME.MULTIPLE_APPLICATIONS:
83            #menu for data from folder
84            data_folder_hint = "load multiple data in the application"
85            menu_list.append(('&Load Data Folder', data_folder_hint, 
86                              self._load_folder))
87        return menu_list
88   
89
90    def load_data(self, event):
91        """
92        Load data
93        """
94        path = None
95        self._default_save_location = self.parent._default_save_location
96        if self._default_save_location == None:
97            self._default_save_location = os.getcwd()
98       
99        cards = self.loader.get_wildcards()
100        temp = [APPLICATION_WLIST] + PLUGINS_WLIST
101        for item in temp:
102            if item in cards:
103                cards.remove(item)
104        wlist =  '|'.join(cards)
105        style = wx.OPEN|wx.FD_MULTIPLE
106        dlg = wx.FileDialog(self.parent, 
107                            "Choose a file", 
108                            self._default_save_location, "",
109                             wlist,
110                             style=style)
111        if dlg.ShowModal() == wx.ID_OK:
112            file_list = dlg.GetPaths()
113            if len(file_list) >= 0 and not(file_list[0]is None):
114                self._default_save_location = os.path.dirname(file_list[0])
115                path = self._default_save_location
116        dlg.Destroy()
117       
118        if path is None or not file_list or file_list[0] is None:
119            return
120        self.parent._default_save_location = self._default_save_location
121        self.get_data(file_list)
122       
123       
124    def can_load_data(self):
125        """
126        if return True, then call handler to laod data
127        """
128        return True
129 
130       
131    def _load_folder(self, event):
132        """
133        Load entire folder
134        """
135        path = None
136        self._default_save_location = self.parent._default_save_location
137        if self._default_save_location == None:
138            self._default_save_location = os.getcwd()
139        dlg = wx.DirDialog(self.parent, "Choose a directory", 
140                           self._default_save_location,
141                            style=wx.DD_DEFAULT_STYLE)
142        if dlg.ShowModal() == wx.ID_OK:
143            path = dlg.GetPath()
144            self._default_save_location = path
145        dlg.Destroy()
146        if path is not None:
147            self._default_save_location = os.path.dirname(path)
148        else:
149            return   
150        file_list = self.get_file_path(path)
151        self.get_data(file_list)
152        self.parent._default_save_location = self._default_save_location
153       
154    def load_error(self, error=None):
155        """
156        Pop up an error message.
157       
158        :param error: details error message to be displayed
159        """
160        if error is not None or str(error).strip() != "":
161            dial = wx.MessageDialog(self.parent, str(error), 'Error Loading File',
162                                wx.OK | wx.ICON_EXCLAMATION)
163            dial.ShowModal() 
164       
165    def get_file_path(self, path):
166        """
167        Receive a list containing folder then return a list of file
168        """
169        if os.path.isdir(path):
170            return [os.path.join(os.path.abspath(path),
171                                  file) for file in os.listdir(path)]
172   
173    def get_data(self, path, format=None):
174        """
175        """
176        message = ""
177        log_msg = ''
178        output = {}
179        error_message = ""
180        for p_file in path:
181            basename  = os.path.basename(p_file)
182            root, extension = os.path.splitext(basename)
183            if extension.lower() in EXTENSIONS:
184                log_msg = "Data Loader cannot "
185                log_msg += "load: %s\n" % str(p_file)
186                log_msg += """Please try to open that file from "open project" """
187                log_msg += """or "open analysis" menu\n"""
188                error_message = log_msg + "\n"
189                logging.info(log_msg)
190                continue
191       
192            try:
193                temp =  self.loader.load(p_file, format)
194                if temp.__class__.__name__ == "list":
195                    for item in temp:
196                        data = self.parent.create_gui_data(item, p_file)
197                        output[data.id] = data
198                else:
199                    data = self.parent.create_gui_data(temp, p_file)
200                    output[data.id] = data
201                message = "Loading Data..." + str(p_file) + "\n"
202                self.load_update(output=output, message=message)
203            except:
204                 error = "Error while loading Data: %s\n" % str(p_file)
205                 error += str(sys.exc_value) + "\n"
206                 error_message = "The data file you selected could not be loaded.\n"
207                 error_message += "Make sure the content of your file"
208                 error_message += " is properly formatted.\n\n"
209                 error_message += "When contacting the DANSE team, mention the"
210                 error_message += " following:\n%s" % str(error)
211                 self.load_update(output=output, message=error_message)
212               
213        message = "Loading Data Complete! "
214        message += log_msg
215        self.load_complete(output=output, error_message=error_message,
216                       message=message, path=path)
217           
218    def load_update(self, output=None, message=""):
219        """
220        print update on the status bar
221        """
222        if message != "":
223            wx.PostEvent(self.parent, StatusEvent(status=message,
224                                                  type="progress",
225                                                   info="warning"))
226    def load_complete(self, output, message="", error_message="", path=None):
227        """
228         post message to  status bar and return list of data
229        """
230        wx.PostEvent(self.parent, StatusEvent(status=message,
231                                              info="warning",
232                                              type="stop"))
233        if error_message != "":
234            self.load_error(error_message)
235        self.parent.add_data(data_list=output)
236   
237   
238       
239   
Note: See TracBrowser for help on using the repository browser.