Changeset d22da51 in sasview for DataLoader
- Timestamp:
- Jul 9, 2008 1:53:01 PM (16 years ago)
- Branches:
- master, ESS_GUI, ESS_GUI_Docs, ESS_GUI_batch_fitting, ESS_GUI_bumps_abstraction, ESS_GUI_iss1116, ESS_GUI_iss879, ESS_GUI_iss959, ESS_GUI_opencl, ESS_GUI_ordering, ESS_GUI_sync_sascalc, costrafo411, magnetic_scatt, release-4.1.1, release-4.1.2, release-4.2.2, release_4.0.1, ticket-1009, ticket-1094-headless, ticket-1242-2d-resolution, ticket-1243, ticket-1249, ticket885, unittest-saveload
- Children:
- 3dd7cce
- Parents:
- f8de7de
- Location:
- DataLoader
- Files:
-
- 2 added
- 4 edited
Legend:
- Unmodified
- Added
- Removed
-
DataLoader/loader.py
r1b0b3ca rd22da51 1 1 # This program is public domain 2 2 """ 3 File extension registry. 4 5 This provides routines for opening files based on extension, 6 and registers the built-in file extensions. 3 @organization: Module loader contains class Loader which uses 4 some readers to return values contained in a file readed. 5 7 6 """ 8 7 import imp,os,sys 9 8 import logging 10 9 import os.path 10 logging.basicConfig(level=logging.ERROR, 11 format='%(asctime)s %(levelname)s %(message)s', 12 filename='loader_log.txt', 13 filemode='w') 14 11 15 def _findReaders(dir): 12 16 # List of plugin objects … … 23 27 path = [os.path.abspath(dir)] 24 28 file = None 25 #print "in findplugings",path26 29 try: 27 30 (file, path, info) = imp.find_module(name, path) … … 31 34 plugins.append(module.Reader()) 32 35 except: 33 log ("Error accessing Reader in %s\n %s" % (name, sys.exc_value))36 logging("Error accessing Reader in %s\n %s" % (name, sys.exc_value)) 34 37 except : 35 log ("Error importing %s\n %s" % (name, sys.exc_value))38 logging("Error importing %s\n %s" % (name, sys.exc_value)) 36 39 finally: 37 40 if not file==None: … … 41 44 pass 42 45 return plugins 46 47 43 48 class Loader(object): 44 49 """ 50 Loader class extracts data from a given file. 51 This provides routines for opening files based on extension, 52 and readers built-in file extensions. 53 It uses functionalities for class Load 54 @note: For loader to operate properly each readers used should 55 contain a class name "Reader" that contains a field call ext. 56 Can be used as follow: 57 L=Loader() 58 self.assertEqual(l.__contains__('.tiff'),True) 59 #Recieves data 60 data=L.load(path) 61 """ 62 #Store instance of class Load 45 63 __load = None 64 65 46 66 class Load(object): 47 67 48 68 def __init__(self): 69 #Dictionary containing readers and extension as keys 49 70 self.readers = {} 50 self.reading=None71 #Load all readers in plugins 51 72 self.__setitem__() 52 #print "in loader",self.readers73 53 74 54 75 def __setitem__(self, ext=None, reader=None): 76 """ 77 __setitem__ sets in a dictionary(self.readers) a given reader 78 with a file extension that it can read. 79 @param ext: extension given of type string 80 @param reader:instance Reader class 81 @raise : ValueError will be raise if a "plugins" directory is not found 82 and the user didn't add a reader as parameter or if the user didn't 83 add a reader as a parameter and plugins directory doesn't contain 84 plugin reader. 85 if an extension is not specified and a reader does not contain a field 86 ext , a ValueError "missing extension" is raised. 87 @note: when called without parameters __setitem__ will try to load 88 readers inside a "plugins" directory 89 """ 55 90 import os 56 91 if reader==None and ext==None:#1st load 57 92 plugReader=None 58 93 if os.path.isdir('plugins'): 59 #print "plugreader in pluging",plugReader60 94 plugReader=_findReaders('plugins')# import all module in plugins 61 95 if os.path.isdir('../plugins'): 62 #print "plugreader in Dataloader pluging",plugReader63 96 plugReader=_findReaders('../plugins') 64 97 else: 65 98 if os.path.isdir('..\DataLoader\plugins'): 66 99 os.chdir(os.path.abspath('..\DataLoader\plugins'))# change the current 67 #directory to dataLoader\plugins68 100 plugReader=_findReaders('plugins') 69 101 … … 76 108 self.readers[ext] = [] 77 109 self.readers[ext].insert(0,preader) 78 79 #print "plugreader",plugReader 80 #print "In setitem",self.readers 110 #Reader and extension are given 81 111 elif reader !=None and ext !=None: 82 112 if ext not in self.readers: … … 84 114 self.readers[ext].insert(0,reader) 85 115 elif reader!=None: 86 for item in reader.ext: 87 ext=item 88 if ext not in self.readers:#assign extension with its reader 89 self.readers[ext] = [] 90 self.readers[ext].insert(0,reader) 116 #only reader is receive try to find a field ext 117 if reader.ext: 118 for item in reader.ext: 119 ext=item 120 if ext not in self.readers:#assign extension with its reader 121 self.readers[ext] = [] 122 self.readers[ext].insert(0,reader) 123 else: 124 raise ValueError,"missing extension" 91 125 else: 92 126 raise ValueError,"missing reader" 93 127 94 128 95 129 def __getitem__(self, ext): 130 """ 131 __getitem__ get a list of readers that can read a file with that extension 132 @param ext: file extension 133 @return self.readers[ext]:list of readers that can read a file 134 with that extension 135 """ 96 136 return self.readers[ext] 97 137 98 138 def __contains__(self, ext): 139 """ 140 @param ext:file extension 141 @return: True or False whether there is a reader file with that extension 142 """ 99 143 return ext in self.readers 100 144 … … 122 166 idx = file.find('.') 123 167 ext = file[idx:] if idx >= 0 else '' 124 #print "exten",ext 125 #print self.readers 168 126 169 try: 127 170 return self.readers[ext] 128 171 except: 129 #raise ValueError, "Unknown file type '%s'"%ext 130 print "Unknown file type '%s'"%ext 131 132 133 def getAcTReader(self,path): 134 return self.reading 172 173 raise ValueError, "Unknown file type '%s'"%ext 174 175 135 176 136 177 def load(self, path, format=None): 137 178 """ 138 Call the loader for the file type of path. 139 140 Raises ValueError if no loader is available. 141 May raise a loader-defined exception if loader fails. 179 Call reader for the file type of path. 180 @param path: path to file to load 181 @param format: extension of file to load 182 @return Data if sucessful 183 or None is not reader was able to read that file 184 Raises ValueError if no reader is available. 185 May raise a loader-defined exception if loader fails. 142 186 """ 143 187 try: 144 #print "in load",os.path.abspath(path)145 188 os.path.isfile( os.path.abspath(path)) 146 #print "went here in load check path"147 189 except: 148 raise ValueError," file doesn't exist" 190 raise ValueError," file path unknown" 191 149 192 if format is None: 150 readers = self.lookup(path) 193 try: 194 readers = self.lookup(path) 195 except ValueError,msg: 196 raise ValueError,str(msg) 151 197 else: 152 198 readers = self.readers[format] 153 199 if readers!=None: 154 155 200 for fn in readers: 156 201 try: 157 #print "path",os.getcwd( )158 202 value=fn.read(path) 159 self.reading= fn.__class__160 203 return value 161 204 except ValueError,msg: 162 print str(msg) 205 logging.error(str(msg)) 206 else: 207 raise ValueError,"Loader contains no reader" 208 209 163 210 def __init__(self): 164 211 """ Create singleton instance """ -
DataLoader/plugins/tiff_reader.py
r0fc05f9 rd22da51 40 40 Example data manipulation 41 41 """ 42 42 43 ## File type 43 44 type = [] -
DataLoader/test/testLoad.py
r1b0b3ca rd22da51 1 1 """ 2 2 Unit tests for DataLoader module 3 log file "test_log.txt" contains all errors when running loader 4 It is create in the folder where test is runned 3 5 """ 6 import logging 7 logging.basicConfig(level=logging.DEBUG, 8 format='%(asctime)s %(levelname)s %(message)s', 9 filename='test_log.txt', 10 filemode='w') 11 12 13 #logger.info('oops I did it again') 4 14 5 15 import unittest … … 38 48 L.__setitem__('.bmp',read5) 39 49 50 def testLoad0(self): 51 """test reading empty file""" 52 self.assertEqual(self.L.load('empty.txt'),None) 53 40 54 def testLoad1(self): 41 """test reading empty file, no file can read it""" 42 self.assertEqual(self.L.load('empty.txt'),None) 43 self.assertEqual( self.L.getAcTReader('empty.txt'),None) 44 55 """test reading 2 columns""" 56 45 57 #Testing loading a txt file of 2 columns, the only reader should be read1 46 58 xload,yload,dyload=self.L.load('test_2_columns.txt') … … 55 67 self.assertEqual(xload[i],x[i]) 56 68 self.assertEqual(yload[i],y[i]) 57 self.assertEqual( self.L.getAcTReader('test_2_columns.txt'),self.read1.__class__)69 58 70 59 71 def testLoad2(self): 60 """Testing loading a txt file of 3 columns , the only reader should be read2"""72 """Testing loading a txt file of 3 columns""" 61 73 xload,yload,dyload= self.L.load('test_3_columns.txt') 62 74 x=[0,0.204082,0.408163,0.612245,0.816327,1.02041,1.22449] … … 71 83 self.assertEqual(yload[i],y[i]) 72 84 self.assertEqual(dyload[i],dy[i]) 73 self.assertEqual(self.L.getAcTReader('test_3_columns.txt'),self.read2.__class__)85 74 86 75 87 def testload3(self): … … 81 93 self.assertEqual(ymin,-0.01684257151702391) 82 94 self.assertEqual(ymax,0.017950440578015116) 83 self.assertEqual(self.L.getAcTReader('MAR07232_rest.ASC'),self.read3.__class__)95 84 96 #tested corrupted file.asc 85 self.assertEqual(self.L.load('AR07232_rest.ASC') ,None) 86 97 try:self.L.load('AR07232_rest.ASC') 98 except ValueError,msg: 99 #logging.log(10,str(msg)) 100 logging.error(str(msg)) 87 101 def testload4(self): 88 102 """ Testing loading danse file""" … … 91 105 92 106 self.assertEqual(data.__class__,danse_reader.ReaderInfo) 93 self.assertEqual(self.L.getAcTReader('MP_New.sans'),self.read4.__class__)107 94 108 #tested corrupted file.sans 95 self.assertEqual(self.L.load('P_New.sans'),None) 96 109 try: self.L.load('P_New.sans') 110 except ValueError,msg: 111 #logging.log(40,str(msg)) 112 logging.error(str(msg)) 113 #else: raise ValueError,"No error raised for missing extension" 97 114 def testload5(self): 98 115 """ Testing loading image file""" 99 116 data=self.L.load('angles_flat.png') 100 117 self.assertEqual(data.__class__,tiff_reader.ReaderInfo) 101 self.assertEqual(self.L.getAcTReader('angles_flat.png'),self.read5.__class__) 118 119 def testload6(self): 120 """test file with unknown extension""" 121 try:self.L.load('hello.missing') 122 except ValueError,msg: 123 self.assertEqual( str(msg),"Unknown file type '.missing'") 124 else: raise ValueError,"No error raised for missing extension" 125 126 #self.L.lookup('hello.missing') 127 try: self.L.lookup('hello.missing') 128 except ValueError,msg: 129 self.assertEqual( str(msg),"Unknown file type '.missing'") 130 else: raise ValueError,"No error raised for missing extension" 131 132 def testload7(self): 133 """ test file containing an image but as extension .txt""" 134 self.assertEqual(self.L.load('angles_flat.txt'),None) 102 135 103 -
DataLoader/test/testplugings.py
r1b0b3ca rd22da51 6 6 import math 7 7 import DataLoader 8 from DataLoader.loader import SingleLoader8 from DataLoader.loader import Loader 9 9 from DataLoader.readers import TXT3_Reader,TXT2_Reader 10 10 from DataLoader.readers import IgorReader,danse_reader,tiff_reader … … 15 15 def testplugin(self): 16 16 """ test loading with plugging""" 17 l= SingleLoader()17 l=Loader() 18 18 self.assertEqual(l.__contains__('.tiff'),True) 19 19 self.assertEqual(l.__contains__('.png'),True) 20 20 self.assertEqual(l.__contains__('.txt'),True) 21 #self.assertEqual(l.getAcTReader('angles_flat.png'),tiff_reader.Reader) 22 #self.assertEqual(l.load('angles_flat.png').__class__,tiff_reader.ReaderInfo) 23 #print l.load('_THETA_weights.txt') 21
Note: See TracChangeset
for help on using the changeset viewer.