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

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 8729965 was 8729965, checked in by butler, 9 years ago

Removed print statment and started work on dataloader help

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