Changeset daa56d0 in sasview


Ignore:
Timestamp:
Sep 3, 2008 9:47:12 AM (16 years ago)
Author:
Mathieu Doucet <doucetm@…>
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:
d831626
Parents:
e390933
Message:

Mostly completed DataLoader?. Reimplemented using REFL registry as base class. Added writing capability and dynamic loading of readers (need zip file support for future py2exe use). All tests pass.

Location:
DataLoader
Files:
3 added
3 deleted
7 edited

Legend:

Unmodified
Added
Removed
  • DataLoader/loader.py

    r579ba85 rdaa56d0  
    1 # This program is public domain 
    21""" 
    3     @organization: Module loader contains class Loader which uses  
    4     some readers to return values contained in a file readed. 
    5     @ author : Paul Kienzler 
    6     @modifiied by gervaise alina 
     2    File handler to support different file extensions. 
     3    Uses reflectometry's registry utility. 
    74""" 
    8 import imp,os,sys 
     5 
     6""" 
     7This software was developed by the University of Tennessee as part of the 
     8Distributed Data Analysis of Neutron Scattering Experiments (DANSE) 
     9project funded by the US National Science Foundation.  
     10 
     11See the license text in license.txt 
     12 
     13copyright 2008, University of Tennessee 
     14""" 
     15 
     16from data_util.registry import ExtensionRegistry 
     17import os  
     18import sys 
    919import logging 
    10 import os.path 
    11 logging.basicConfig(level=logging.ERROR, 
    12                     format='%(asctime)s %(levelname)s %(message)s', 
    13                     filename='test_log.txt', 
    14                     filemode='w') 
     20import imp 
     21import time 
    1522 
    16 def _findReaders(dir): 
    17     # List of plugin objects 
    18     plugins = [] 
    19     # Go through files in plug-in directory 
    20     try: 
     23class Registry(ExtensionRegistry): 
     24    """ 
     25        Registry class for file format extensions. 
     26        Readers and writers are supported. 
     27    """ 
     28     
     29    def __init__(self): 
     30        super(Registry, self).__init__() 
    2131         
    22         list = os.listdir(dir) 
    23         for item in list: 
     32        ## Writers 
     33        self.writers = {} 
     34         
     35        ## Creation time, for testing 
     36        self._created = time.time() 
     37         
     38        # Find internal readers 
     39        try: 
     40            cwd = os.path.split(__file__)[0] 
     41        except: 
     42            cwd = os.getcwd() 
     43            logging.error("Registry: could not find the installed reader's directory\n %s" % sys.exc_value) 
    2444             
    25             toks = os.path.splitext(os.path.basename(item)) 
    26             if toks[1]=='.py' and not toks[0]=='__init__': 
     45        dir = os.path.join(cwd, 'readers') 
     46        n = self.find_plugins(dir) 
     47        logging.info("Loader found %i readers" % n) 
     48         
     49    def find_plugins(self, dir): 
     50        """ 
     51            Find readers in a given directory 
     52             
     53            @param dir: directory to search into 
     54            @return: number of readers found 
     55        """ 
     56        readers_found = 0 
     57        for item in os.listdir(dir): 
     58            full_path = os.path.join(dir, item) 
     59            if os.path.isfile(full_path) and item.endswith('.py'): 
     60                toks = os.path.splitext(os.path.basename(item)) 
    2761                name = toks[0] 
    2862                path = [os.path.abspath(dir)] 
     
    3367                    if hasattr(module, "Reader"): 
    3468                        try: 
    35                             plugins.append(module.Reader()) 
     69                            # Find supported extensions 
     70                            loader = module.Reader() 
     71                            for ext in loader.ext: 
     72                                if ext not in self.loaders: 
     73                                    self.loaders[ext] = [] 
     74                                self.loaders[ext].insert(0,loader.read) 
     75                            readers_found += 1 
     76                             
     77                            # Check whether writing is supported 
     78                            if hasattr(loader, 'write'): 
     79                                for ext in loader.ext: 
     80                                    if ext not in self.writers: 
     81                                        self.writers[ext] = [] 
     82                                    self.writers[ext].insert(0,loader.write) 
    3683                        except: 
    37                             logging.error("Error accessing Reader in %s\n  %s" % (name, sys.exc_value)) 
     84                            logging.error("Loader: Error accessing Reader in %s\n  %s" % (name, sys.exc_value)) 
    3885                except : 
    39                     logging.error("Error importing %s\n  %s" % (name, sys.exc_value)) 
     86                    logging.error("Loader: Error importing %s\n  %s" % (name, sys.exc_value)) 
    4087                finally: 
    4188                    if not file==None: 
    4289                        file.close() 
    43     except: 
    44         # Should raise and catch at a higher level and display error on status bar 
    45         pass    
    46     return plugins 
     90        return readers_found  
    4791 
     92    def lookup_writers(self, path): 
     93        """ 
     94        Return the loader associated with the file type of path. 
     95         
     96        Raises ValueError if file type is not known. 
     97        """         
     98        # Find matching extensions 
     99        extlist = [ext for ext in self.extensions() if path.endswith(ext)] 
     100        # Sort matching extensions by decreasing order of length 
     101        extlist.sort(lambda a,b: len(a)<len(b)) 
     102        # Combine loaders for matching extensions into one big list 
     103        writers = [] 
     104        for L in [self.writers[ext] for ext in extlist]: 
     105            writers.extend(L) 
     106        # Remove duplicates if they exist 
     107        if len(writers) != len(set(writers)): 
     108            result = [] 
     109            for L in writers: 
     110                if L not in result: result.append(L) 
     111            writers = L 
     112        # Raise an error if there are no matching extensions 
     113        if len(writers) == 0: 
     114            raise ValueError, "Unknown file type for "+path 
     115        # All done 
     116        return writers 
    48117 
     118    def save(self, path, data, format=None): 
     119        """ 
     120        Call the writer for the file type of path. 
     121 
     122        Raises ValueError if no writer is available. 
     123        Raises KeyError if format is not available. 
     124        May raise a writer-defined exception if writer fails.         
     125        """ 
     126        if format is None: 
     127            writers = self.lookup_writers(path) 
     128        else: 
     129            writers = self.writers[format] 
     130        for fn in writers: 
     131            try: 
     132                return fn(path, data) 
     133            except: 
     134                pass # give other loaders a chance to succeed 
     135        # If we get here it is because all loaders failed 
     136        raise # reraises last exception 
     137 
     138         
    49139class Loader(object): 
    50140    """ 
    51         Loader class extracts data from a given file. 
    52         This provides routines for opening files based on extension, 
    53         and readers built-in file extensions. 
    54         It uses functionalities for class Load 
    55         @note: For loader to operate properly each readers used should  
    56         contain a class name "Reader" that contains a field call ext. 
    57         Can be used as follow: 
    58         L=Loader() 
    59         self.assertEqual(l.__contains__('.tiff'),True) 
    60         #Recieves data  
    61         data=L.load(path) 
     141        Utility class to use the Registry as a singleton. 
    62142    """ 
    63     #Store instance of class Load 
    64     __load = None 
     143    ## Registry instance 
     144    __registry = Registry() 
    65145     
     146    def load(self, file, format=None): 
     147        """ 
     148            Load a file 
     149             
     150            @param file: file name (path) 
     151            @param format: specified format to use (optional) 
     152            @return: DataInfo object 
     153        """ 
     154        return self.__registry.load(file, format) 
    66155     
    67     class Load(object): 
     156    def save(self, file, data, format): 
     157        """ 
     158            Save a DataInfo object to file 
     159            @param file: file name (path) 
     160            @param data: DataInfo object 
     161            @param format: format to write the data in  
     162        """ 
     163        return self.__registry.save(file, data, format) 
     164         
     165    def _get_registry_creation_time(self): 
     166        """ 
     167            Internal method used to test the uniqueness 
     168            of the registry object 
     169        """ 
     170        return self.__registry._created 
    68171     
    69         def __init__(self): 
    70             #Dictionary containing readers and extension as keys 
    71             self.readers = {} 
    72             #Load all readers in plugins 
    73              
    74             #TODO: misuse of __setitem__ 
    75             #TODO: this bad call is done twice: here, and in Loader.__init__ 
    76             #self.__setitem__() 
    77              
    78              
    79         def __setitem__(self,dir=None, ext=None, reader=None): 
    80             """ 
    81                 __setitem__  sets in a dictionary(self.readers) a given reader 
    82                 with a file extension that it can read. 
    83                 @param ext: extension given of type string 
    84                 @param reader:instance Reader class 
    85                 @param dir: directory name where plugins readers will be saved 
    86                 @raise : ValueError will be raise if a "plugins" directory is not found 
    87                 and the user didn't add a reader as parameter or if the user didn't  
    88                 add a reader as a parameter and plugins directory doesn't contain 
    89                 plugin reader. 
    90                 if an extension is not specified and a reader does not contain a field 
    91                 ext , a warning is printed in test_log.txt file. 
    92                 @note: when called without parameters __setitem__ will try to load 
    93                 readers inside a "readers" directory  
    94                 if call with a directory name will try find readers  
    95                 from that directory "dir" 
    96             """ 
    97             if dir==None: 
    98                 dir = 'readers' 
    99                  
    100             #TODO Probably name the new path something else... 
    101              
    102             #TODO: The whole concept of plug-ins was missed here. 
    103             # First we want to always load the reader we have (in 'readers') 
    104             # and THEN we want to add any additional readers found in 
    105             # a pre-defined plug-in path (that path should be a variable). 
    106             dir=os.path.join(os.path.dirname(os.path.abspath(__file__)),dir) 
    107              
    108             if (reader==None and  ext==None) or dir:#1st load 
    109                 plugReader=None 
    110                 if os.path.isdir(dir): 
    111                     plugReader=_findReaders(dir)# import all module in plugins 
    112                  
    113                 #TODO The following just doesn't make sense 
    114                 # ../C:\Python25\lib... ???? 
    115                 if os.path.isdir('../'+dir): 
    116                     plugReader=_findReaders('../'+dir) 
    117   
    118                  
    119                 if plugReader !=None: 
    120                     list=[] 
    121                     for preader in plugReader:# for each modules takes list of extensions 
    122                         #TODO should use hasattr rather than a try/except block 
    123                         try: 
    124                             list=preader.ext 
    125                         except AttributeError,msg: 
    126                             logging.warning(msg) 
    127                             pass 
    128                             #raise  AttributeError," %s instance has no attribute 'ext'"\ 
    129                             #%(preader.__class__) 
    130                         if list !=[]: 
    131                             for item in list: 
    132                                 ext=item 
    133                                 if ext not in self.readers:#assign extension with its reader 
    134                                     self.readers[ext] = [] 
    135                                 self.readers[ext].insert(0,preader) 
    136             #Reader and extension are given 
    137             elif reader !=None and  ext !=None: 
    138                 if ext not in self.readers: 
    139                     self.readers[ext] = [] 
    140                 self.readers[ext].insert(0,reader) 
    141             elif reader!=None: 
    142                 #only reader is receive try to find a field ext 
    143                 try: 
    144                     list=preader.ext 
    145                 except: 
    146                     raise AttributeError," Reader instance has no attribute 'ext'" 
    147                 for item in list: 
    148                  
    149                     ext=item 
    150                     if ext not in self.readers:#assign extension with its reader 
    151                         self.readers[ext] = [] 
    152                     self.readers[ext].insert(0,reader) 
    153  
    154             else: 
    155                 raise ValueError,"missing reader" 
    156                  
    157              
    158         def __getitem__(self, ext): 
    159             """ 
    160                 __getitem__ get a list of readers that can read a file with that extension 
    161                 @param ext: file extension 
    162                 @return self.readers[ext]:list of readers that can read a file  
    163                 with that extension 
    164             """ 
    165             return self.readers[ext] 
    166              
    167         def __contains__(self, ext): 
    168             """ 
    169                 @param ext:file extension 
    170                 @return: True or False whether there is a reader file with that extension 
    171             """ 
    172             return ext in self.readers 
     172    def find_plugins(self, dir): 
     173        """ 
     174            Find plugins in a given directory 
     175            @param dir: directory to look into to find new readers/writers 
     176        """ 
     177        return self.__registry.find_plugins(dir) 
     178     
     179         
     180if __name__ == "__main__":  
     181    logging.basicConfig(level=logging.INFO, 
     182                        format='%(asctime)s %(levelname)s %(message)s', 
     183                        filename='loader.log', 
     184                        filemode='w') 
     185    l = Loader() 
     186    data = l.load('test/cansas1d.xml') 
     187    l.save('test_file.xml', data) 
    173188         
    174189         
    175         def formats(self, name=True, ext=False): 
    176             """ 
    177             Return a list of the registered formats.  If name=True then 
    178             named formats are returned.  If ext=True then extensions 
    179             are returned. 
    180             """ 
    181             names = [a for a in self.readers.keys() if not a.startswith('.')] 
    182             exts = [a for a in self.readers.keys() if a.startswith('.')] 
    183             names.sort() 
    184             exts.sort() 
    185             ret = [] 
    186             if name: ret += names 
    187             if ext: ret += exts 
    188             return ret 
    189              
    190         def lookup(self, path): 
    191             """ 
    192             Return the loader associated with the file type of path. 
    193             """         
    194             file = os.path.basename(path) 
    195             idx = file.find('.') 
    196             ext = file[idx:] if idx >= 0 else '' 
    197             
    198             try: 
    199                 return self.readers[ext] 
    200             except: 
    201                 logging.warning("Unknown file type '%s'"%ext) 
    202                 raise RuntimeError, "Unknown file type '%s'"%ext 
    203                  
    204         
    205          
    206         def load(self, path, format=None): 
    207             """ 
    208                 Call reader for the file type of path. 
    209                 @param path: path to file to load 
    210                 @param format: extension of file to load 
    211                 @return Data if sucessful 
    212                   or None is not reader was able to read that file 
    213                 Raises ValueError if no reader is available. 
    214                 May raise a loader-defined exception if loader fails. 
    215             """ 
    216             try: 
    217                 os.path.isfile( os.path.abspath(path))  
    218             except: 
    219                 raise ValueError," file path unknown" 
    220              
    221             if format is None: 
    222                 try: 
    223                     readers = self.lookup(path) 
    224                 except : 
    225                     raise  
    226             else: 
    227                 readers = self.readers[format] 
    228             if readers!=None: 
    229                 for fn in readers: 
    230                     try: 
    231                         value=fn.read(path) 
    232                         return value 
    233                     except: 
    234                         logging.error("Load Error: %s"% (sys.exc_value)) 
    235             else: 
    236                 raise ValueError,"Loader contains no reader" 
    237                          
    238                           
    239     def __init__(self): 
    240         """ Create singleton instance """ 
    241         # Check whether we already have an instance 
    242         if Loader.__load is None: 
    243             # Create and remember instance 
    244             Loader.__load = Loader.Load() 
    245             Loader.__load.__setitem__() 
    246         # Store instance reference as the only member in the handle 
    247         self.__dict__['_Loader__load'] = Loader.__load 
    248  
    249     def __getattr__(self, attr): 
    250         """ Delegate access to implementation """ 
    251         return getattr(self.__load, attr) 
    252  
    253     def __setattr__(self, attr, value): 
    254         """ Delegate access to implementation """ 
    255         return setattr(self.__load, attr, value) 
     190     
  • DataLoader/readers/ascii_reader.py

    r99d1af6 rdaa56d0  
    1313from DataLoader.data_info import Data1D 
    1414 
     15# Check whether we have a converter available 
    1516has_converter = True 
    1617try: 
     
    116117                # Sanity check 
    117118                if has_error == True and not len(y) == len(dy): 
    118                     raise ValueError, "ascii_reader: y and dy have different length" 
     119                    raise RuntimeError, "ascii_reader: y and dy have different length" 
    119120 
    120121                # If the data length is zero, consider this as 
    121122                # though we were not able to read the file. 
    122123                if len(x)==0: 
    123                     raise ValueError, "ascii_reader: could not load file" 
     124                    raise RuntimeError, "ascii_reader: could not load file" 
    124125                
    125126                output.x = x 
  • DataLoader/readers/tiff_reader.py

    r8bd8ea4 rdaa56d0  
     1""" 
     2    Image reader. Untested.  
     3""" 
    14 
    2 import math,logging 
     5""" 
     6This software was developed by the University of Tennessee as part of the 
     7Distributed Data Analysis of Neutron Scattering Experiments (DANSE) 
     8project funded by the US National Science Foundation.  
    39 
     10See the license text in license.txt 
     11 
     12copyright 2008, University of Tennessee 
     13""" 
     14#TODO: load and check data and orientation of the image (needs rendering) 
     15 
     16import math, logging, os 
     17import numpy 
     18from DataLoader.data_info import Data2D 
    419     
    520class Reader: 
     
    823    """ 
    924    ## File type 
    10     type = [] 
     25    type = ["TIF files (*.tif)|*.tif", 
     26            "JPG files (*.jpg)|*.jpg", 
     27            "JPEG files (*.jpeg)|*.jpeg", 
     28            "PNG files (*.png)|*.png", 
     29            "TIFF files (*.tiff)|*.tiff", 
     30            "BMP files (*.bmp)|*.bmp", 
     31            "GIF files (*.gif)|*.gif", 
     32            ] 
    1133    ## Extension 
    12     ext  = ['tif', 'jpg', '.png', 'jpeg', '.tiff', 'gif', 'bmp']     
     34    ext  = ['.tif', '.jpg', '.png', '.jpeg', '.tiff', '.gif', '.bmp']     
    1335         
    1436    def read(self, filename=None): 
    15         import Image 
    16         print "in tiff" 
    1737        """ 
    1838            Open and read the data in a file 
    1939            @param file: path of the file 
    2040        """ 
     41        try: 
     42            import Image 
     43        except: 
     44            raise RuntimeError, "tiff_reader: could not load file. Missing Image module." 
    2145         
    22         read_it = False 
    23         for item in self.ext: 
    24             if filename.lower().find(item)>=0: 
    25                 read_it = True 
     46        # Instantiate data object 
     47        output = Data2D() 
     48        output.filename = os.path.basename(filename) 
     49             
     50        # Read in the image 
     51        try: 
     52            im = Image.open(filename) 
     53        except : 
     54            raise  RuntimeError,"cannot open %s"%(filename) 
     55        data = im.getdata() 
     56         
     57        # Initiazed the output data object 
     58        output.data = numpy.zeros([im.size[0],im.size[1]]) 
     59         
     60        # Initialize  
     61        x_vals = [] 
     62        y_vals = []  
     63 
     64        # x and y vectors 
     65        for i_x in range(im.size[0]): 
     66            x_vals.append(i_x) 
     67             
     68        itot = 0 
     69        for i_y in range(im.size[1]): 
     70            y_vals.append(i_y) 
     71 
     72        for val in data: 
     73            try: 
     74                value = float(val) 
     75            except: 
     76                logging.error("tiff_reader: had to skip a non-float point") 
     77                continue 
     78             
     79            # Get bin number 
     80            if math.fmod(itot, im.size[0])==0: 
     81                i_x = 0 
     82                i_y += 1 
     83            else: 
     84                i_x += 1 
    2685                 
    27         if read_it: 
    28             import Image 
    29             import pylab 
    30             import copy 
    31             import numpy 
     86            output.data[im.size[1]-1-i_y][i_x] = value 
    3287             
    33             wavelength, distance, center_x, center_y, pixel = 10.0, 11.0, 65, 65, 1.0 
    34              
    35              
    36              
    37             # Initialize  
    38             x_vals = [] 
    39             y_vals = []  
    40             ymin = None 
    41             ymax = None 
    42             xmin = None 
    43             xmax = None 
    44             Z = None 
     88            itot += 1 
     89                 
     90        output.xbins      = im.size[0] 
     91        output.ybins      = im.size[1] 
     92        output.x_bins     = x_vals 
     93        output.y_bins     = y_vals 
     94        output.xmin       = 0 
     95        output.xmax       = im.size[0]-1 
     96        output.ymin       = 0 
     97        output.ymax       = im.size[0]-1 
    4598         
    46             try: 
    47                 im = Image.open(filename) 
    48             except : 
    49                 raise  RuntimeError,"cannot open %s"%(filename) 
    50             # Detector size should be 128x128, the file is 190x190 
    51             print "-> Image size:", im.size, im.format, im.mode 
    52             data = im.getdata() 
    53             x = numpy.zeros(im.size[0]) 
    54             y = numpy.zeros(im.size[1]) 
    55             X, Y = pylab.meshgrid(x, y) 
    56             Z = copy.deepcopy(X) 
    57             itot = 0 
    58             i_x = 0 
    59             i_y = 0 
    60              
    61             # Qx and Qy vectors 
    62             for i_x in range(im.size[0]): 
    63                 theta = (i_x-center_x+1)*pixel / distance / 100.0 
    64                 qx = 4.0*math.pi/wavelength * math.sin(theta/2.0) 
    65                 x_vals.append(qx) 
    66                 if xmin==None or qx<xmin: 
    67                     xmin = qx 
    68                 if xmax==None or qx>xmax: 
    69                     xmax = qx 
    70              
    71             ymin = None 
    72             ymax = None 
    73             for i_y in range(im.size[1]): 
    74                 theta = (i_y-center_y+1)*pixel / distance / 100.0 
    75                 qy = 4.0*math.pi/wavelength * math.sin(theta/2.0) 
    76                 y_vals.append(qy) 
    77                 if ymin==None or qy<ymin: 
    78                     ymin = qy 
    79                 if ymax==None or qy>ymax: 
    80                     ymax = qy 
    81              
    82             for val in data: 
    83                  
    84                 try: 
    85                     value = float(val) 
    86                 except: 
    87                     continue 
    88                  
    89                 # Get bin number 
    90                 if math.fmod(itot, im.size[0])==0: 
    91                     i_x = 0 
    92                     i_y += 1 
    93                 else: 
    94                     i_x += 1 
    95                      
    96                 Z[im.size[1]-1-i_y][i_x] = value 
    97                  
    98                 itot += 1 
    99             from readInfo import ReaderInfo       
    100             output = ReaderInfo() 
    101             output.wavelength = wavelength 
    102             output.xbins      = im.size[0] 
    103             output.ybins      = im.size[1] 
    104             output.center_x   = center_x 
    105             output.center_y   = center_y 
    106             output.distance   = distance 
    107             output.x_vals     = x_vals 
    108             output.y_vals     = y_vals 
    109             output.xmin       = xmin 
    110             output.xmax       = xmax 
    111             output.ymin       = ymin 
    112             output.ymax       = ymax 
    113             output.image      = Z 
    114             output.pixel_size = pixel 
    115             output.x          = x_vals 
    116             output.y          = y_vals 
    117             output.type       ="2D" 
    118             logging.info("tiff_reader reading %s"%(filename)) 
    119              
    120             return output 
     99        return output 
    121100         
    122         return None 
    123101 
    124102 
  • DataLoader/test/error_conditions.py

    rf9474b5 rdaa56d0  
    99        """ 
    1010            self.s.load('blah.mat') on an unknown type 
    11             should raise a runtime exception 
     11            should raise a ValueError exception (thrown by data_util.registry) 
    1212        """ 
    13         self.assertRaises(RuntimeError, self.s.load, 'angles_flat.mat') 
     13        self.assertRaises(ValueError, self.s.load, 'angles_flat.mat') 
    1414         
    1515    def test_corrupt(self): 
  • DataLoader/test/sequence_tests.py

    rb99ac227 rdaa56d0  
    2929    single_igor() 
    3030    single_abs() 
     31    print "Test passed" 
  • DataLoader/test/testLoad.py

    rb99ac227 rdaa56d0  
    1616import DataLoader 
    1717from DataLoader.loader import  Loader 
    18   
     18 
     19# Check whether we should test image loading on this system  
     20HAS_IMAGE = False 
     21try: 
     22    import Image 
     23    HAS_IMAGE = True 
     24except: 
     25    print "IMAGE TESTS WILL NOT BE PERFORMED: MISSING PIL MODULE" 
     26     
    1927import os.path 
    2028 
     
    2432        self.loader = Loader() 
    2533         
    26          
    2734    def test_singleton(self): 
    2835        """ 
    2936            Testing whether Loader is truly a singleton 
    3037        """ 
    31         # Set a new data member 
    32         self.loader._test_data_member = 1.45 
    33          
    3438        # Create a 'new' Loader 
    3539        b = Loader() 
    36          
    37         # Test that the new loader has the new data member 
    38         self.assertEqual(b._test_data_member, self.loader._test_data_member) 
     40        self.assertEqual(self.loader._get_registry_creation_time(), 
     41                         b._get_registry_creation_time()) 
    3942 
    4043class testLoader(unittest.TestCase): 
     
    5356    def testLoad0(self): 
    5457        """test reading empty file""" 
    55         self.assertEqual(self.L.load('empty.txt'),None) 
     58        self.assertRaises(RuntimeError, self.L.load, 'empty.txt') 
    5659         
    5760    def testLoad1(self): 
     
    8790            self.assertEqual(output.dy[i],dy[i]) 
    8891        
     92    def testLoad2_uppercase(self): 
     93        """Testing loading a txt file of 3 columns""" 
     94        output= self.L.load('test_3_columns.TXT')  
     95        x=[0,0.204082,0.408163,0.612245,0.816327,1.02041,1.22449]     
     96        y=[2.83954,3.44938,5.82026,5.27591,5.2781,5.22531,7.47487] 
     97        dx=[] 
     98        dy=[0.6,0.676531,0.753061,0.829592,0.906122,0.982653,1.05918] 
     99        self.assertEqual(len(output.x),len(x)) 
     100        self.assertEqual(len(output.y),len(y)) 
     101        self.assertEqual(len(output.dy),len(dy)) 
     102        for i in range(len(x)): 
     103            self.assertEqual(output.x[i],x[i]) 
     104            self.assertEqual(output.y[i],y[i]) 
     105            self.assertEqual(output.dy[i],dy[i]) 
     106        
    89107     
    90108    def testload3(self): 
     
    92110        #tested good file.asc 
    93111        output= self.L.load('MAR07232_rest.ASC')  
     112        self.assertEqual(output.xmin,-0.018558945804750416) 
     113        self.assertEqual(output.xmax, 0.016234058202440633,) 
     114        self.assertEqual(output.ymin,-0.01684257151702391) 
     115        self.assertEqual(output.ymax,0.017950440578015116) 
     116        
     117        #tested corrupted file.asc 
     118        try:self.L.load('AR07232_rest.ASC') 
     119        except ValueError,msg: 
     120           #logging.log(10,str(msg)) 
     121           logging.error(str(msg)) 
     122 
     123    def testload3_lowercase(self): 
     124        """ Testing loading Igor data""" 
     125        #tested good file.asc 
     126        output= self.L.load('MAR07232_rest.asc')  
    94127        self.assertEqual(output.xmin,-0.018558945804750416) 
    95128        self.assertEqual(output.xmax, 0.016234058202440633,) 
     
    118151    def testload5(self): 
    119152        """ Testing loading image file""" 
    120         output=self.L.load('angles_flat.png') 
    121         self.assertEqual(output.xbins ,200) 
     153        if HAS_IMAGE: 
     154            output=self.L.load('angles_flat.png') 
     155            self.assertEqual(output.xbins ,200) 
    122156         
    123157    def testload6(self): 
    124158        """test file with unknown extension""" 
    125         try:self.L.load('hello.missing') 
    126         except RuntimeError,msg: 
    127            self.assertEqual( str(msg),"Unknown file type '.missing'") 
    128         else: raise ValueError,"No error raised for missing extension" 
     159        self.assertRaises(ValueError, self.L.load, 'hello.missing') 
    129160         
    130         #self.L.lookup('hello.missing') 
    131         try: self.L.lookup('hello.missing') 
    132         except RuntimeError,msg: 
    133            self.assertEqual( str(msg),"Unknown file type '.missing'") 
    134         else: raise ValueError,"No error raised for missing extension" 
     161        # Lookup is not supported as a public method 
     162        #self.assertRaises(ValueError, self.L.lookup, 'hello.missing') 
     163         
    135164         
    136165    def testload7(self): 
    137166        """ test file containing an image but as extension .txt""" 
    138         self.assertEqual(self.L.load('angles_flat.txt'),None) 
     167        self.assertRaises(RuntimeError, self.L.load, 'angles_flat.txt') 
    139168 
    140169if __name__ == '__main__': 
  • DataLoader/test/testplugings.py

    r4c00964 rdaa56d0  
    44 
    55import unittest 
    6 import math 
    7 import DataLoader 
    8 from DataLoader.loader import  Loader 
    9 from DataLoader.readers import TXT3_Reader,TXT2_Reader 
    10 from DataLoader.readers import IgorReader,danse_reader,tiff_reader 
    11 import os.path 
    12 import os  
    13 import logging 
    14 logging.basicConfig(level=logging.DEBUG, 
    15                     format='%(asctime)s %(levelname)s %(message)s', 
    16                     filename='test_log.txt', 
    17                     filemode='w') 
     6from DataLoader.loader import  Loader, Registry 
    187class testLoader(unittest.TestCase): 
    198     
    20     try:L=Loader() 
    21     except AttributeError,msg: 
    22         logging.warning(msg) 
     9    def setUp(self): 
     10        self.L=Loader() 
     11        self.L.find_plugins('../plugins') 
     12             
    2313    def testplugin(self): 
    24         """ test loading with readers""" 
     14        """  
     15            test loading with a test reader only  
     16            found in the plugins directory 
     17        """ 
     18        output = self.L.load('test_data.test') 
     19        self.assertEqual(output.x[0], 1234.) 
    2520         
    26         self.assertEqual(self.L.__contains__('.tiff'),True) 
    27         self.assertEqual(self.L.__contains__('.png'),True) 
    28         self.assertEqual(self.L.__contains__('.txt'),True) 
    29          #tested corrupted file.asc 
    30         try:self.L.load('MAR07232_rest.ASC') 
    31         except AttributeError,msg: 
    32            #logging.log(10,str(msg)) 
    33            logging.warning(str(msg)) 
    34     def testplugin1(self): 
    35         """ test loading with plugging""" 
    36         self.L.__setitem__(dir='plugins') 
    37         read3=IgorReader.Reader() 
    38         self.L.__setitem__('plugins','.ASC',read3) 
    39         self.assertEqual(self.L.__contains__('.ASC'),True) 
    40         #Testing loading a txt file of 2 columns, the only reader should be read1  
    41         output=self.L.load('test_2_columns.txt')  
    42         x=[2.83954,0.204082,0.408163,0.612245,0.816327,1.02041,1.22449,1.42857,1.63265] 
    43         y=[0.6,3.44938, 5.82026,5.27591,5.2781,5.22531,7.47487,7.85852,10.2278] 
    44         dx=[] 
    45         dy=[] 
    46         self.assertEqual(len(output.x),len(x)) 
    47         self.assertEqual(len(output.y),len(y)) 
     21class testRegistry(unittest.TestCase): 
     22     
     23    def setUp(self): 
     24        self.L=Registry() 
     25        self.L.find_plugins('../plugins') 
     26             
     27    def testplugin(self): 
     28        """  
     29            test loading with a test reader only  
     30            found in the plugins directory 
     31        """ 
     32        output = self.L.load('test_data.test') 
     33        self.assertEqual(output.x[0], 1234.) 
     34        self.assertTrue(self.L.loaders.has_key('.test')) 
    4835         
    49         for i in range(len(x)): 
    50             self.assertEqual(output.x[i],x[i]) 
    51             self.assertEqual(output.y[i],y[i]) 
    52  
    53 # How about actually executing the tests... 
    5436if __name__ == '__main__': 
    5537    unittest.main() 
Note: See TracChangeset for help on using the changeset viewer.