Changes in / [278ddee:97c60f8] in sasview
- Location:
- src/sas
- Files:
-
- 1 deleted
- 5 edited
Legend:
- Unmodified
- Added
- Removed
-
src/sas/sascalc/data_util/registry.py
r7f75a3f rb699768 7 7 """ 8 8 9 from sas.sascalc.dataloader.loader_exceptions import NoKnownLoaderException 10 9 import os.path 11 10 12 11 class ExtensionRegistry(object): … … 62 61 def __init__(self, **kw): 63 62 self.loaders = {} 64 65 63 def __setitem__(self, ext, loader): 66 64 if ext not in self.loaders: 67 65 self.loaders[ext] = [] 68 66 self.loaders[ext].insert(0,loader) 69 70 67 def __getitem__(self, ext): 71 68 return self.loaders[ext] 72 73 69 def __contains__(self, ext): 74 70 return ext in self.loaders 75 76 71 def formats(self): 77 72 """ … … 81 76 names.sort() 82 77 return names 83 84 78 def extensions(self): 85 79 """ … … 89 83 exts.sort() 90 84 return exts 91 92 85 def lookup(self, path): 93 86 """ 94 87 Return the loader associated with the file type of path. 95 88 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. 99 90 """ 100 91 # Find matching extensions … … 114 105 # Raise an error if there are no matching extensions 115 106 if len(loaders) == 0: 116 raise ValueError("Unknown file type for "+path) 107 raise ValueError, "Unknown file type for "+path 108 # All done 117 109 return loaders 118 119 110 def load(self, path, format=None): 120 111 """ 121 112 Call the loader for the file type of path. 122 113 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. 126 117 """ 127 loaders = []128 118 if format is None: 129 try: 130 loaders = self.lookup(path) 131 except ValueError as e: 132 pass 119 loaders = self.lookup(path) 133 120 else: 134 try: 135 loaders = self.loaders[format] 136 except KeyError as e: 137 pass 121 loaders = self.loaders[format] 138 122 for fn in loaders: 139 123 try: 140 124 return fn(path) 141 except Exception as e:142 pass 125 except: 126 pass # give other loaders a chance to succeed 143 127 # If we get here it is because all loaders failed 144 raise NoKnownLoaderException(e.message) # raise generic exception 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() -
src/sas/sascalc/dataloader/loader.py
r7f75a3f r463e7ffc 1 1 """ 2 2 File handler to support different file extensions. 3 Uses reflectomet erregistry utility.3 Uses reflectometry's registry utility. 4 4 5 5 The default readers are found in the 'readers' sub-module … … 29 29 # Default readers are defined in the readers sub-module 30 30 import readers 31 from loader_exceptions import NoKnownLoaderException, FileContentsException32 31 from readers import ascii_reader 33 32 from readers import cansas_reader 34 from readers import cansas_reader_HDF535 36 33 37 34 logger = logging.getLogger(__name__) … … 42 39 Readers and writers are supported. 43 40 """ 41 44 42 def __init__(self): 45 43 super(Registry, self).__init__() 46 44 47 # Writers45 ## Writers 48 46 self.writers = {} 49 47 50 # List of wildcards48 ## List of wildcards 51 49 self.wildcards = ['All (*.*)|*.*'] 52 50 53 # Creation time, for testing51 ## Creation time, for testing 54 52 self._created = time.time() 55 53 … … 65 63 of a particular reader 66 64 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. 69 68 """ 70 69 try: 71 70 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) 94 79 95 80 def find_plugins(self, dir): -
src/sas/sascalc/dataloader/readers/cansas_reader.py
r7432acb r7432acb 29 29 from sas.sascalc.dataloader.readers.xml_reader import XMLreader 30 30 from sas.sascalc.dataloader.readers.cansas_constants import CansasConstants, CurrentLevel 31 from sas.sascalc.dataloader.loader_exceptions import FileContentsException32 31 33 32 # The following 2 imports *ARE* used. Do not remove either. … … 539 538 540 539 # 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) 547 541 self.cansas_version = self.xmlroot.get("version", "1.0") 548 542 -
src/sas/sascalc/dataloader/readers/cansas_reader_HDF5.py
r7f75a3f rc94280c 13 13 TransmissionSpectrum, Detector 14 14 from sas.sascalc.dataloader.data_info import combine_data_info_with_plottable 15 from sas.sascalc.dataloader.loader_exceptions import FileContentsException16 15 17 16 … … 76 75 if extension in self.ext or self.allow_all: 77 76 # 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') 82 78 # Read in all child elements of top level SASroot 83 79 self.read_children(self.raw_data, []) -
src/sas/sasgui/guiframe/local_perspectives/data_loader/data_loader.py
r235f514 r235f514 11 11 12 12 from sas.sascalc.dataloader.loader import Loader 13 from sas.sascalc.dataloader.loader_exceptions import NoKnownLoaderException14 13 from sas.sasgui.guiframe.plugin_base import PluginBase 15 14 from sas.sasgui.guiframe.events import StatusEvent … … 42 41 APPLICATION_WLIST = config.APPLICATION_WLIST 43 42 44 45 43 class Plugin(PluginBase): 46 44 … … 58 56 """ 59 57 # menu for data files 58 menu_list = [] 60 59 data_file_hint = "load one or more data in the application" 61 60 menu_list = [('&Load Data File(s)', data_file_hint, self.load_data)] 62 61 gui_style = self.parent.get_style() 63 62 style = gui_style & GUIFRAME.MULTIPLE_APPLICATIONS 63 style1 = gui_style & GUIFRAME.DATALOADER_ON 64 64 if style == GUIFRAME.MULTIPLE_APPLICATIONS: 65 65 # menu for data from folder … … 102 102 self.get_data(file_list) 103 103 104 104 105 def can_load_data(self): 105 106 """ … … 107 108 """ 108 109 return True 110 109 111 110 112 def _load_folder(self, event): … … 138 140 """ 139 141 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', 142 143 wx.OK | wx.ICON_EXCLAMATION) 143 144 dial.ShowModal() … … 148 149 """ 149 150 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)] 152 152 153 153 def _process_data_and_errors(self, item, p_file, output, message): … … 178 178 for p_file in path: 179 179 basename = os.path.basename(p_file) 180 # Skip files that start with a period181 if basename.startswith("."):182 msg = "The folder included a potential hidden file - %s." \183 % basename184 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 continue189 180 _, extension = os.path.splitext(basename) 190 181 if extension.lower() in EXTENSIONS: … … 222 213 info="info") 223 214 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")230 215 except: 231 216 logger.error(sys.exc_value) 232 217 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" 235 220 error_message += " is properly formatted.\n" 236 221 error_message += "When contacting the SasView team, mention the" … … 238 223 error_message += "Error: " + str(sys.exc_info()[1]) 239 224 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") 242 226 243 227 if len(file_errors) > 0: … … 252 236 253 237 self.load_complete(output=output, message="Loading data complete!", 254 238 info="info") 255 239 256 240 def load_update(self, output=None, message="", info="warning"): … … 261 245 wx.PostEvent(self.parent, StatusEvent(status=message, info=info, 262 246 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, 269 254 type="stop")) 255 # if error_message != "": 256 # self.load_error(error_message) 270 257 self.parent.add_data(data_list=output)
Note: See TracChangeset
for help on using the changeset viewer.