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


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

Legend:

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

    r7f75a3f rb699768  
    77""" 
    88 
    9 from sas.sascalc.dataloader.loader_exceptions import NoKnownLoaderException 
    10  
     9import os.path 
    1110 
    1211class ExtensionRegistry(object): 
     
    6261    def __init__(self, **kw): 
    6362        self.loaders = {} 
    64  
    6563    def __setitem__(self, ext, loader): 
    6664        if ext not in self.loaders: 
    6765            self.loaders[ext] = [] 
    6866        self.loaders[ext].insert(0,loader) 
    69  
    7067    def __getitem__(self, ext): 
    7168        return self.loaders[ext] 
    72  
    7369    def __contains__(self, ext): 
    7470        return ext in self.loaders 
    75  
    7671    def formats(self): 
    7772        """ 
     
    8176        names.sort() 
    8277        return names 
    83  
    8478    def extensions(self): 
    8579        """ 
     
    8983        exts.sort() 
    9084        return exts 
    91  
    9285    def lookup(self, path): 
    9386        """ 
    9487        Return the loader associated with the file type of path. 
    9588         
    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 
     89        Raises ValueError if file type is not known. 
    9990        """         
    10091        # Find matching extensions 
     
    114105        # Raise an error if there are no matching extensions 
    115106        if len(loaders) == 0: 
    116             raise ValueError("Unknown file type for "+path) 
     107            raise ValueError, "Unknown file type for "+path 
     108        # All done 
    117109        return loaders 
    118  
    119110    def load(self, path, format=None): 
    120111        """ 
    121112        Call the loader for the file type of path. 
    122113 
    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. 
     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.         
    126117        """ 
    127         loaders = [] 
    128118        if format is None: 
    129             try: 
    130                 loaders = self.lookup(path) 
    131             except ValueError as e: 
    132                 pass 
     119            loaders = self.lookup(path) 
    133120        else: 
    134             try: 
    135                 loaders = self.loaders[format] 
    136             except KeyError as e: 
    137                 pass 
     121            loaders = self.loaders[format] 
    138122        for fn in loaders: 
    139123            try: 
    140124                return fn(path) 
    141             except Exception as e: 
    142                 pass  # give other loaders a chance to succeed 
     125            except: 
     126                pass # give other loaders a chance to succeed 
    143127        # If we get here it is because all loaders failed 
    144         raise NoKnownLoaderException(e.message)  # raise generic exception 
     128        raise # reraises last exception 
     129 
     130def 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 
     174if __name__ == "__main__": test() 
  • src/sas/sascalc/dataloader/loader.py

    r7f75a3f r463e7ffc  
    11""" 
    22    File handler to support different file extensions. 
    3     Uses reflectometer registry utility. 
     3    Uses reflectometry's 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 
    31 from loader_exceptions import NoKnownLoaderException, FileContentsException 
    3231from readers import ascii_reader 
    3332from readers import cansas_reader 
    34 from readers import cansas_reader_HDF5 
    35  
    3633 
    3734logger = logging.getLogger(__name__) 
     
    4239    Readers and writers are supported. 
    4340    """ 
     41 
    4442    def __init__(self): 
    4543        super(Registry, self).__init__() 
    4644 
    47         # Writers 
     45        ## Writers 
    4846        self.writers = {} 
    4947 
    50         # List of wildcards 
     48        ## List of wildcards 
    5149        self.wildcards = ['All (*.*)|*.*'] 
    5250 
    53         # Creation time, for testing 
     51        ## Creation time, for testing 
    5452        self._created = time.time() 
    5553 
     
    6563            of a particular reader 
    6664 
    67         Defaults to the ascii (multi-column), cansas XML, and cansas NeXuS 
    68         readers if no reader was registered for the file's extension. 
     65        Defaults to the ascii (multi-column) reader 
     66        if no reader was registered for the file's 
     67        extension. 
    6968        """ 
    7069        try: 
    7170            return super(Registry, self).load(path, format=format) 
    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 
     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) 
    9479 
    9580    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 
    31 from sas.sascalc.dataloader.loader_exceptions import FileContentsException 
    3231 
    3332# The following 2 imports *ARE* used. Do not remove either. 
     
    539538 
    540539        # Load in xml file and get the cansas version from the header 
    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 
     540        self.set_xml_file(xml_file) 
    547541        self.cansas_version = self.xmlroot.get("version", "1.0") 
    548542 
  • src/sas/sascalc/dataloader/readers/cansas_reader_HDF5.py

    r7f75a3f rc94280c  
    1313    TransmissionSpectrum, Detector 
    1414from sas.sascalc.dataloader.data_info import combine_data_info_with_plottable 
    15 from sas.sascalc.dataloader.loader_exceptions import FileContentsException 
    1615 
    1716 
     
    7675            if extension in self.ext or self.allow_all: 
    7776                # Load the data file 
    78                 try: 
    79                     self.raw_data = h5py.File(filename, 'r') 
    80                 except Exception as e: 
    81                     raise FileContentsException, e 
     77                self.raw_data = h5py.File(filename, 'r') 
    8278                # Read in all child elements of top level SASroot 
    8379                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 
    13 from sas.sascalc.dataloader.loader_exceptions import NoKnownLoaderException 
    1413from sas.sasgui.guiframe.plugin_base import PluginBase 
    1514from sas.sasgui.guiframe.events import StatusEvent 
     
    4241APPLICATION_WLIST = config.APPLICATION_WLIST 
    4342 
    44  
    4543class Plugin(PluginBase): 
    4644 
     
    5856        """ 
    5957        # menu for data files 
     58        menu_list = [] 
    6059        data_file_hint = "load one or more data in the application" 
    6160        menu_list = [('&Load Data File(s)', data_file_hint, self.load_data)] 
    6261        gui_style = self.parent.get_style() 
    6362        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 
    104105    def can_load_data(self): 
    105106        """ 
     
    107108        """ 
    108109        return True 
     110 
    109111 
    110112    def _load_folder(self, event): 
     
    138140        """ 
    139141        if error is not None or str(error).strip() != "": 
    140             dial = wx.MessageDialog(self.parent, str(error), 
    141                                     'Error Loading File', 
     142            dial = wx.MessageDialog(self.parent, str(error), 'Error Loading File', 
    142143                                    wx.OK | wx.ICON_EXCLAMATION) 
    143144            dial.ShowModal() 
     
    148149        """ 
    149150        if os.path.isdir(path): 
    150             return [os.path.join(os.path.abspath(path), filename) for filename 
    151                     in os.listdir(path)] 
     151            return [os.path.join(os.path.abspath(path), filename) for filename 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 
    189180            _, extension = os.path.splitext(basename) 
    190181            if extension.lower() in EXTENSIONS: 
     
    222213                info="info") 
    223214 
    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") 
    230215            except: 
    231216                logger.error(sys.exc_value) 
    232217 
    233                 error_message = "The Data file you selected could not be " 
    234                 error_message += "loaded.\nMake sure the content of your file" 
     218                error_message = "The Data file you selected could not be loaded.\n" 
     219                error_message += "Make sure the content of your file" 
    235220                error_message += " is properly formatted.\n" 
    236221                error_message += "When contacting the SasView team, mention the" 
     
    238223                error_message += "Error: " + str(sys.exc_info()[1]) 
    239224                file_errors[basename] = [error_message] 
    240                 self.load_update(output=output, message=error_message, 
    241                                  info="warning") 
     225                self.load_update(output=output, message=error_message, info="warning") 
    242226 
    243227        if len(file_errors) > 0: 
     
    252236 
    253237        self.load_complete(output=output, message="Loading data complete!", 
    254                            info="info") 
     238            info="info") 
    255239 
    256240    def load_update(self, output=None, message="", info="warning"): 
     
    261245            wx.PostEvent(self.parent, StatusEvent(status=message, info=info, 
    262246                                                  type="progress")) 
    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, 
     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, 
    269254                                              type="stop")) 
     255        # if error_message != "": 
     256        #    self.load_error(error_message) 
    270257        self.parent.add_data(data_list=output) 
Note: See TracChangeset for help on using the changeset viewer.