Changes in / [97c60f8:278ddee] in sasview


Ignore:
Location:
src/sas
Files:
1 added
5 edited

Legend:

Unmodified
Added
Removed
  • src/sas/sascalc/data_util/registry.py

    rb699768 r7f75a3f  
    77""" 
    88 
    9 import os.path 
     9from sas.sascalc.dataloader.loader_exceptions import NoKnownLoaderException 
     10 
    1011 
    1112class ExtensionRegistry(object): 
     
    6162    def __init__(self, **kw): 
    6263        self.loaders = {} 
     64 
    6365    def __setitem__(self, ext, loader): 
    6466        if ext not in self.loaders: 
    6567            self.loaders[ext] = [] 
    6668        self.loaders[ext].insert(0,loader) 
     69 
    6770    def __getitem__(self, ext): 
    6871        return self.loaders[ext] 
     72 
    6973    def __contains__(self, ext): 
    7074        return ext in self.loaders 
     75 
    7176    def formats(self): 
    7277        """ 
     
    7681        names.sort() 
    7782        return names 
     83 
    7884    def extensions(self): 
    7985        """ 
     
    8389        exts.sort() 
    8490        return exts 
     91 
    8592    def lookup(self, path): 
    8693        """ 
    8794        Return the loader associated with the file type of path. 
    8895         
    89         Raises ValueError if file type is not known. 
     96        :param path: Data file path 
     97        :raises ValueError: When no loaders are found for the file. 
     98        :return: List of available readers for the file extension 
    9099        """         
    91100        # Find matching extensions 
     
    105114        # Raise an error if there are no matching extensions 
    106115        if len(loaders) == 0: 
    107             raise ValueError, "Unknown file type for "+path 
    108         # All done 
     116            raise ValueError("Unknown file type for "+path) 
    109117        return loaders 
     118 
    110119    def load(self, path, format=None): 
    111120        """ 
    112121        Call the loader for the file type of path. 
    113122 
    114         Raises ValueError if no loader is available. 
    115         Raises KeyError if format is not available. 
    116         May raise a loader-defined exception if loader fails.         
     123        :raise ValueError: if no loader is available. 
     124        :raise KeyError: if format is not available. 
     125        May raise a loader-defined exception if loader fails. 
    117126        """ 
     127        loaders = [] 
    118128        if format is None: 
    119             loaders = self.lookup(path) 
     129            try: 
     130                loaders = self.lookup(path) 
     131            except ValueError as e: 
     132                pass 
    120133        else: 
    121             loaders = self.loaders[format] 
     134            try: 
     135                loaders = self.loaders[format] 
     136            except KeyError as e: 
     137                pass 
    122138        for fn in loaders: 
    123139            try: 
    124140                return fn(path) 
    125             except: 
    126                 pass # give other loaders a chance to succeed 
     141            except Exception as e: 
     142                pass  # give other loaders a chance to succeed 
    127143        # If we get here it is because all loaders failed 
    128         raise # reraises last exception 
    129  
    130 def test(): 
    131     reg = ExtensionRegistry() 
    132     class CxError(Exception): pass 
    133     def cx(file): return 'cx' 
    134     def new_cx(file): return 'new_cx' 
    135     def fail_cx(file): raise CxError 
    136     def cat(file): return 'cat' 
    137     def gunzip(file): return 'gunzip' 
    138     reg['.cx'] = cx 
    139     reg['.cx1'] = cx 
    140     reg['.cx'] = new_cx 
    141     reg['.gz'] = gunzip 
    142     reg['.cx.gz'] = new_cx 
    143     reg['.cx1.gz'] = fail_cx 
    144     reg['.cx1'] = fail_cx 
    145     reg['.cx2'] = fail_cx 
    146     reg['new_cx'] = new_cx 
    147  
    148     # Two loaders associated with .cx 
    149     assert reg.lookup('hello.cx') == [new_cx,cx] 
    150     # Make sure the last loader applies first 
    151     assert reg.load('hello.cx') == 'new_cx' 
    152     # Make sure the next loader applies if the first fails 
    153     assert reg.load('hello.cx1') == 'cx' 
    154     # Make sure the format override works 
    155     assert reg.load('hello.cx1',format='.cx.gz') == 'new_cx' 
    156     # Make sure the format override works 
    157     assert reg.load('hello.cx1',format='new_cx') == 'new_cx' 
    158     # Make sure the case of all loaders failing is correct 
    159     try:  reg.load('hello.cx2') 
    160     except CxError: pass # correct failure 
    161     else: raise AssertError,"Incorrect error on load failure" 
    162     # Make sure the case of no loaders fails correctly 
    163     try: reg.load('hello.missing') 
    164     except ValueError,msg: 
    165         assert str(msg)=="Unknown file type for hello.missing",'Message: <%s>'%(msg) 
    166     else: raise AssertError,"No error raised for missing extension" 
    167     assert reg.formats() == ['new_cx'] 
    168     assert reg.extensions() == ['.cx','.cx.gz','.cx1','.cx1.gz','.cx2','.gz'] 
    169     # make sure that it supports multiple '.' in filename 
    170     assert reg.load('hello.extra.cx1') == 'cx' 
    171     assert reg.load('hello.gz') == 'gunzip' 
    172     assert reg.load('hello.cx1.gz') == 'gunzip' # Since .cx1.gz fails 
    173  
    174 if __name__ == "__main__": test() 
     144        raise NoKnownLoaderException(e.message)  # raise generic exception 
  • src/sas/sascalc/dataloader/loader.py

    r463e7ffc r7f75a3f  
    11""" 
    22    File handler to support different file extensions. 
    3     Uses reflectometry's registry utility. 
     3    Uses reflectometer registry utility. 
    44 
    55    The default readers are found in the 'readers' sub-module 
     
    2929# Default readers are defined in the readers sub-module 
    3030import readers 
     31from loader_exceptions import NoKnownLoaderException, FileContentsException 
    3132from readers import ascii_reader 
    3233from readers import cansas_reader 
     34from readers import cansas_reader_HDF5 
     35 
    3336 
    3437logger = logging.getLogger(__name__) 
     
    3942    Readers and writers are supported. 
    4043    """ 
    41  
    4244    def __init__(self): 
    4345        super(Registry, self).__init__() 
    4446 
    45         ## Writers 
     47        # Writers 
    4648        self.writers = {} 
    4749 
    48         ## List of wildcards 
     50        # List of wildcards 
    4951        self.wildcards = ['All (*.*)|*.*'] 
    5052 
    51         ## Creation time, for testing 
     53        # Creation time, for testing 
    5254        self._created = time.time() 
    5355 
     
    6365            of a particular reader 
    6466 
    65         Defaults to the ascii (multi-column) reader 
    66         if no reader was registered for the file's 
    67         extension. 
     67        Defaults to the ascii (multi-column), cansas XML, and cansas NeXuS 
     68        readers if no reader was registered for the file's extension. 
    6869        """ 
    6970        try: 
    7071            return super(Registry, self).load(path, format=format) 
    71         except: 
    72             try: 
    73                 # No reader was found. Default to the ascii reader. 
    74                 ascii_loader = ascii_reader.Reader() 
    75                 return ascii_loader.read(path) 
    76             except: 
    77                 cansas_loader = cansas_reader.Reader() 
    78                 return cansas_loader.read(path) 
     72        except NoKnownLoaderException as e: 
     73            pass  # try the ASCII reader 
     74        try: 
     75            ascii_loader = ascii_reader.Reader() 
     76            return ascii_loader.read(path) 
     77        except FileContentsException: 
     78            pass  # try the cansas XML reader 
     79        try: 
     80            cansas_loader = cansas_reader.Reader() 
     81            return cansas_loader.read(path) 
     82        except FileContentsException: 
     83            pass  # try the cansas NeXuS reader 
     84        try: 
     85            cansas_nexus_loader = cansas_reader_HDF5.Reader() 
     86            return cansas_nexus_loader.read(path) 
     87        except FileContentsException: 
     88            logging.errors("No default loader can load the data") 
     89            # No known reader available. Give up and throw an error 
     90            msg = "\n\tUnknown data format: %s.\n\tThe file is not a " % path 
     91            msg += "known format that can be loaded by SasView.\n" 
     92            msg += "Traceback:\n%s" % e.message 
     93            raise NoKnownLoaderException, msg 
    7994 
    8095    def find_plugins(self, dir): 
  • src/sas/sascalc/dataloader/readers/cansas_reader.py

    r7432acb r7432acb  
    2929from sas.sascalc.dataloader.readers.xml_reader import XMLreader 
    3030from sas.sascalc.dataloader.readers.cansas_constants import CansasConstants, CurrentLevel 
     31from sas.sascalc.dataloader.loader_exceptions import FileContentsException 
    3132 
    3233# The following 2 imports *ARE* used. Do not remove either. 
     
    538539 
    539540        # Load in xml file and get the cansas version from the header 
    540         self.set_xml_file(xml_file) 
     541        from lxml import etree 
     542        try: 
     543            self.set_xml_file(xml_file) 
     544        except etree.XMLSyntaxError: 
     545            msg = "Cansas cannot load this file" 
     546            raise FileContentsException, msg 
    541547        self.cansas_version = self.xmlroot.get("version", "1.0") 
    542548 
  • src/sas/sascalc/dataloader/readers/cansas_reader_HDF5.py

    rc94280c r7f75a3f  
    1313    TransmissionSpectrum, Detector 
    1414from sas.sascalc.dataloader.data_info import combine_data_info_with_plottable 
     15from sas.sascalc.dataloader.loader_exceptions import FileContentsException 
    1516 
    1617 
     
    7576            if extension in self.ext or self.allow_all: 
    7677                # Load the data file 
    77                 self.raw_data = h5py.File(filename, 'r') 
     78                try: 
     79                    self.raw_data = h5py.File(filename, 'r') 
     80                except Exception as e: 
     81                    raise FileContentsException, e 
    7882                # Read in all child elements of top level SASroot 
    7983                self.read_children(self.raw_data, []) 
  • src/sas/sasgui/guiframe/local_perspectives/data_loader/data_loader.py

    r235f514 r235f514  
    1111 
    1212from sas.sascalc.dataloader.loader import Loader 
     13from sas.sascalc.dataloader.loader_exceptions import NoKnownLoaderException 
    1314from sas.sasgui.guiframe.plugin_base import PluginBase 
    1415from sas.sasgui.guiframe.events import StatusEvent 
     
    4142APPLICATION_WLIST = config.APPLICATION_WLIST 
    4243 
     44 
    4345class Plugin(PluginBase): 
    4446 
     
    5658        """ 
    5759        # menu for data files 
    58         menu_list = [] 
    5960        data_file_hint = "load one or more data in the application" 
    6061        menu_list = [('&Load Data File(s)', data_file_hint, self.load_data)] 
    6162        gui_style = self.parent.get_style() 
    6263        style = gui_style & GUIFRAME.MULTIPLE_APPLICATIONS 
    63         style1 = gui_style & GUIFRAME.DATALOADER_ON 
    6464        if style == GUIFRAME.MULTIPLE_APPLICATIONS: 
    6565            # menu for data from folder 
     
    102102        self.get_data(file_list) 
    103103 
    104  
    105104    def can_load_data(self): 
    106105        """ 
     
    108107        """ 
    109108        return True 
    110  
    111109 
    112110    def _load_folder(self, event): 
     
    140138        """ 
    141139        if error is not None or str(error).strip() != "": 
    142             dial = wx.MessageDialog(self.parent, str(error), 'Error Loading File', 
     140            dial = wx.MessageDialog(self.parent, str(error), 
     141                                    'Error Loading File', 
    143142                                    wx.OK | wx.ICON_EXCLAMATION) 
    144143            dial.ShowModal() 
     
    149148        """ 
    150149        if os.path.isdir(path): 
    151             return [os.path.join(os.path.abspath(path), filename) for filename in os.listdir(path)] 
     150            return [os.path.join(os.path.abspath(path), filename) for filename 
     151                    in os.listdir(path)] 
    152152 
    153153    def _process_data_and_errors(self, item, p_file, output, message): 
     
    178178        for p_file in path: 
    179179            basename = os.path.basename(p_file) 
     180            # Skip files that start with a period 
     181            if basename.startswith("."): 
     182                msg = "The folder included a potential hidden file - %s." \ 
     183                      % basename 
     184                msg += " Do you wish to load this file as data?" 
     185                msg_box = wx.MessageDialog(None, msg, 'Warning', 
     186                                           wx.OK | wx.CANCEL) 
     187                if msg_box.ShowModal() == wx.ID_CANCEL: 
     188                    continue 
    180189            _, extension = os.path.splitext(basename) 
    181190            if extension.lower() in EXTENSIONS: 
     
    213222                info="info") 
    214223 
     224            except NoKnownLoaderException as e: 
     225                logging.error(e.message) 
     226                self.load_update(output=None, message=e.message, info="warning") 
     227                self.load_complete(output=None, 
     228                                   message="Loading data failed!", 
     229                                   info="warning") 
    215230            except: 
    216231                logger.error(sys.exc_value) 
    217232 
    218                 error_message = "The Data file you selected could not be loaded.\n" 
    219                 error_message += "Make sure the content of your file" 
     233                error_message = "The Data file you selected could not be " 
     234                error_message += "loaded.\nMake sure the content of your file" 
    220235                error_message += " is properly formatted.\n" 
    221236                error_message += "When contacting the SasView team, mention the" 
     
    223238                error_message += "Error: " + str(sys.exc_info()[1]) 
    224239                file_errors[basename] = [error_message] 
    225                 self.load_update(output=output, message=error_message, info="warning") 
     240                self.load_update(output=output, message=error_message, 
     241                                 info="warning") 
    226242 
    227243        if len(file_errors) > 0: 
     
    236252 
    237253        self.load_complete(output=output, message="Loading data complete!", 
    238             info="info") 
     254                           info="info") 
    239255 
    240256    def load_update(self, output=None, message="", info="warning"): 
     
    245261            wx.PostEvent(self.parent, StatusEvent(status=message, info=info, 
    246262                                                  type="progress")) 
    247     def load_complete(self, output, message="", error_message="", path=None, 
    248                       info="warning"): 
    249         """ 
    250          post message to  status bar and return list of data 
    251         """ 
    252         wx.PostEvent(self.parent, StatusEvent(status=message, 
    253                                               info=info, 
     263 
     264    def load_complete(self, output, message="", info="warning"): 
     265        """ 
     266         post message to status bar and return list of data 
     267        """ 
     268        wx.PostEvent(self.parent, StatusEvent(status=message, info=info, 
    254269                                              type="stop")) 
    255         # if error_message != "": 
    256         #    self.load_error(error_message) 
    257270        self.parent.add_data(data_list=output) 
Note: See TracChangeset for help on using the changeset viewer.