source: sasview/src/sas/guiframe/local_perspectives/data_loader/data_loader.py @ f21d496

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 f21d496 was f21d496, checked in by Doucet, Mathieu <doucetm@…>, 9 years ago

Cleaning up old "standalone" code

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