Changeset a7a5886 in sasview


Ignore:
Timestamp:
Nov 2, 2010 5:02:56 PM (13 years ago)
Author:
Gervaise Alina <gervyh@…>
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:
da9ac4e6
Parents:
44148f0
Message:

working pylint

Location:
DataLoader
Files:
13 edited

Legend:

Unmodified
Added
Removed
  • DataLoader/data_info.py

    r0997158f ra7a5886  
    3333    Data1D is a place holder for 1D plottables. 
    3434    """ 
    35     # The presence of these should be mutually exclusive with the presence of Qdev (dx) 
     35    # The presence of these should be mutually 
     36    # exclusive with the presence of Qdev (dx) 
    3637    x = None 
    3738    y = None 
     
    4950    _yunit = '' 
    5051     
    51     def __init__(self,x,y,dx=None,dy=None,dxl=None,dxw=None): 
     52    def __init__(self, x, y, dx=None, dy=None, dxl=None, dxw=None): 
    5253        self.x = numpy.asarray(x) 
    5354        self.y = numpy.asarray(y) 
    54         if dx is not None: self.dx = numpy.asarray(dx) 
    55         if dy is not None: self.dy = numpy.asarray(dy) 
    56         if dxl is not None: self.dxl = numpy.asarray(dxl) 
    57         if dxw is not None: self.dxw = numpy.asarray(dxw) 
     55        if dx is not None: 
     56             self.dx = numpy.asarray(dx) 
     57        if dy is not None:  
     58            self.dy = numpy.asarray(dy) 
     59        if dxl is not None:  
     60            self.dxl = numpy.asarray(dxl) 
     61        if dxw is not None:  
     62            self.dxw = numpy.asarray(dxw) 
    5863 
    5964    def xaxis(self, label, unit): 
     65        """ 
     66        set the x axis label and unit 
     67        """ 
    6068        self._xaxis = label 
    6169        self._xunit = unit 
    6270         
    6371    def yaxis(self, label, unit): 
     72        """ 
     73        set the y axis label and unit 
     74        """ 
    6475        self._yaxis = label 
    6576        self._yunit = unit 
     
    90101    _zunit = '' 
    91102     
    92     def __init__(self, data=None, err_data=None, qx_data=None, qy_data=None, q_data=None,mask=None, dqx_data=None, dqy_data=None): 
     103    def __init__(self, data=None, err_data=None, qx_data=None, 
     104                  qy_data=None, q_data=None, mask=None, 
     105                   dqx_data=None, dqy_data=None): 
    93106        self.data = numpy.asarray(data) 
    94107        self.qx_data = numpy.asarray(qx_data) 
     
    101114                
    102115    def xaxis(self, label, unit): 
     116        """ 
     117        set the x axis label and unit 
     118        """ 
    103119        self._xaxis = label 
    104120        self._xunit = unit 
    105121         
    106122    def yaxis(self, label, unit): 
     123        """ 
     124        set the y axis label and unit 
     125        """ 
    107126        self._yaxis = label 
    108127        self._yunit = unit 
    109128             
    110129    def zaxis(self, label, unit): 
     130        """ 
     131        set the z axis label and unit 
     132        """ 
    111133        self._zaxis = label 
    112134        self._zunit = unit 
     
    139161         
    140162    def __str__(self): 
    141         return "x = %s\ty = %s\tz = %s" % (str(self.x), str(self.y), str(self.z)) 
     163        msg = "x = %s\ty = %s\tz = %s" % (str(self.x), str(self.y), str(self.z)) 
     164        return msg 
    142165         
    143166 
     
    151174    distance = None 
    152175    distance_unit = 'mm' 
    153     ## Offset of this detector position in X, Y, (and Z if necessary) [Vector] [mm]  
     176    ## Offset of this detector position in X, Y,  
     177    #(and Z if necessary) [Vector] [mm]  
    154178    offset = None 
    155179    offset_unit = 'm' 
    156     ## Orientation (rotation) of this detector in roll, pitch, and yaw [Vector] [degrees] 
     180    ## Orientation (rotation) of this detector in roll, 
     181    # pitch, and yaw [Vector] [degrees] 
    157182    orientation = None 
    158183    orientation_unit = 'degree' 
    159     ## Center of the beam on the detector in X and Y (and Z if necessary) [Vector] [mm] 
     184    ## Center of the beam on the detector in X and Y  
     185    #(and Z if necessary) [Vector] [mm] 
    160186    beam_center = None 
    161187    beam_center_unit = 'mm' 
     
    352378    name = '' 
    353379    date = '' 
    354     description= '' 
     380    description = '' 
    355381    term = None 
    356382    notes = None 
     
    460486    # but should be implemented for each data class inherited from DataInfo 
    461487    # that holds actual data (ex.: Data1D) 
    462     def _perform_operation(self, other, operation): return NotImplemented 
     488    def _perform_operation(self, other, operation):  
     489        """ 
     490        Private method to perform operation. Not implemented for DataInfo, 
     491        but should be implemented for each data class inherited from DataInfo 
     492        that holds actual data (ex.: Data1D) 
     493        """ 
     494        return NotImplemented 
    463495 
    464496    def __add__(self, other): 
     
    470502        :raise ValueError: raised when two data sets are incompatible 
    471503        """ 
    472         def operation(a, b): return a+b 
     504        def operation(a, b): 
     505            return a + b 
    473506        return self._perform_operation(other, operation) 
    474507         
     
    484517         
    485518        """ 
    486         def operation(a, b): return b+a 
     519        def operation(a, b): 
     520            return b + a 
    487521        return self._perform_operation(other, operation) 
    488522         
     
    498532         
    499533        """ 
    500         def operation(a, b): return a-b 
     534        def operation(a, b): 
     535            return a - b 
    501536        return self._perform_operation(other, operation) 
    502537         
     
    512547         
    513548        """ 
    514         def operation(a, b): return b-a 
     549        def operation(a, b): 
     550            return b - a 
    515551        return self._perform_operation(other, operation) 
    516552         
     
    526562         
    527563        """ 
    528         def operation(a, b): return a*b 
     564        def operation(a, b): 
     565            return a * b 
    529566        return self._perform_operation(other, operation) 
    530567         
     
    539576        :raise ValueError: raised when two data sets are incompatible 
    540577        """ 
    541         def operation(a, b): return b*a 
     578        def operation(a, b): 
     579            return b * a 
    542580        return self._perform_operation(other, operation) 
    543581         
     
    553591         
    554592        """ 
    555         def operation(a, b): return a/b 
     593        def operation(a, b): 
     594            return a/b 
    556595        return self._perform_operation(other, operation) 
    557596         
     
    567606         
    568607        """ 
    569         def operation(a, b): return b/a 
     608        def operation(a, b): 
     609            return b/a 
    570610        return self._perform_operation(other, operation)             
    571611             
     
    604644        """ 
    605645        def _check(v):             
    606             if (v.__class__==list or v.__class__==numpy.ndarray) \ 
    607                 and len(v)>0 and min(v)>0: 
     646            if (v.__class__ == list or v.__class__ == numpy.ndarray) \ 
     647                and len(v) > 0 and min(v) > 0: 
    608648                return True 
    609649             
     
    664704            if len(self.x) != len(other.x) or \ 
    665705                len(self.y) != len(other.y): 
    666                 raise ValueError, "Unable to perform operation: data length are not equal" 
     706                msg =  "Unable to perform operation: data length are not equal" 
     707                raise ValueError, msg 
    667708             
    668709            # Here we could also extrapolate between data points 
    669710            for i in range(len(self.x)): 
    670711                if self.x[i] != other.x[i]: 
    671                     raise ValueError, "Incompatible data sets: x-values do not match" 
     712                    msg = "Incompatible data sets: x-values do not match" 
     713                    raise ValueError, msg 
    672714             
    673715            # Check that the other data set has errors, otherwise 
    674716            # create zero vector 
    675717            dy_other = other.dy 
    676             if other.dy==None or (len(other.dy) != len(other.y)): 
     718            if other.dy == None or (len(other.dy) != len(other.y)): 
    677719                dy_other = numpy.zeros(len(other.y)) 
    678720             
    679721        # Check that we have errors, otherwise create zero vector 
    680722        dy = self.dy 
    681         if self.dy==None or (len(self.dy) != len(self.y)): 
     723        if self.dy == None or (len(self.dy) != len(self.y)): 
    682724            dy = numpy.zeros(len(self.y))             
    683725             
     
    693735        for i in range(len(self.x)): 
    694736            result.x[i] = self.x[i] 
    695             if self.dx is not None and len(self.x)==len(self.dx): 
     737            if self.dx is not None and len(self.x) == len(self.dx): 
    696738                result.dx[i] = self.dx[i] 
    697739             
     
    724766     
    725767     
    726     def __init__(self, data=None, err_data=None, qx_data=None, qy_data=None, q_data=None, mask=None, dqx_data=None, dqy_data=None): 
     768    def __init__(self, data=None, err_data=None, qx_data=None, 
     769                  qy_data=None, q_data=None, mask=None,  
     770                  dqx_data=None, dqy_data=None): 
    727771        self.y_bins = [] 
    728772        self.x_bins = [] 
    729773        DataInfo.__init__(self) 
    730         plottable_2D.__init__(self, data, err_data, qx_data, qy_data, q_data,mask, dqx_data, dqy_data) 
    731         if len(self.detector)>0: 
     774        plottable_2D.__init__(self, data, err_data, qx_data, 
     775                              qy_data, q_data,mask, dqx_data, dqy_data) 
     776        if len(self.detector) > 0: 
    732777            raise RuntimeError, "Data2D: Detector bank already filled at init" 
    733778 
     
    739784        _str += "   X- & Y-axis:  %s\t[%s]\n" % (self._yaxis, self._yunit) 
    740785        _str += "   Z-axis:       %s\t[%s]\n" % (self._zaxis, self._zunit) 
    741         leny = 0 
    742         if len(self.data)>0: 
    743             leny = len(self.data) 
     786        #leny = 0 
     787        #if len(self.data) > 0: 
     788        #    leny = len(self.data) 
    744789        _str += "   Length:       %g \n" % (len(self.data)) 
    745790         
     
    766811            dqx_data = None 
    767812            dqy_data = None 
    768             clone = Data2D(data, err_data, qx_data, qy_data, q_data,mask, dqx_data=dqx_data, dqy_data=dqy_data) 
     813            clone = Data2D(data, err_data, qx_data, qy_data, 
     814                            q_data,mask, dqx_data=dqx_data, dqy_data=dqy_data) 
    769815 
    770816        clone.title       = self.title 
     
    802848            # Check that data lengths are the same 
    803849            if numpy.size(self.data) != numpy.size(other.data): 
    804                 raise ValueError, "Unable to perform operation: data length are not equal" 
     850                msg = "Unable to perform operation: data length are not equal" 
     851                raise ValueError, msg 
    805852                
    806853            # Check that the scales match 
     
    811858            #TODO: test this 
    812859            err_other = other.err_data 
    813             if other.err_data==None or (numpy.size(other.err_data) != numpy.size(other.data)): 
    814                 err_other = numpy.zeros([numpy.size(other.data,0), numpy.size(other.data,1)]) 
     860            if other.err_data == None or \ 
     861                (numpy.size(other.err_data) != numpy.size(other.data)): 
     862                err_other = numpy.zeros([numpy.size(other.data, 0), 
     863                                          numpy.size(other.data, 1)]) 
    815864             
    816865        # Check that we have errors, otherwise create zero vector 
    817866        err = self.err_data 
    818         if self.err_data==None or (numpy.size(self.err_data) != numpy.size(self.data)): 
    819             err = numpy.zeros([numpy.size(self.data,0), numpy.size(self.data,1)]) 
     867        if self.err_data == None or \ 
     868            (numpy.size(self.err_data) != numpy.size(self.data)): 
     869            err = numpy.zeros([numpy.size(self.data, 0), 
     870                                numpy.size(self.data, 1)]) 
    820871             
    821872        return err, err_other 
     
    833884        dy, dy_other = self._validity_check(other) 
    834885     
    835         result = self.clone_without_data([numpy.size(self.data,0), numpy.size(self.data,1)]) 
    836          
    837         for i in range(numpy.size(self.data,0)): 
    838             for j in range(numpy.size(self.data,1)): 
     886        result = self.clone_without_data([numpy.size(self.data, 0),  
     887                                          numpy.size(self.data, 1)]) 
     888         
     889        for i in range(numpy.size(self.data, 0)): 
     890            for j in range(numpy.size(self.data, 1)): 
    839891                result.data[i][j] = self.data[i][j] 
    840                 if self.err_data is not None and numpy.size(self.data)==numpy.size(self.err_data): 
     892                if self.err_data is not None and \ 
     893                    numpy.size(self.data) == numpy.size(self.err_data): 
    841894                    result.err_data[i][j] = self.err_data[i][j] 
    842895                 
  • DataLoader/loader.py

    rf118fe2f ra7a5886  
    2323""" 
    2424 
    25 from data_util.registry import ExtensionRegistry 
    2625import os  
    2726import sys 
     
    2928import time 
    3029from zipfile import ZipFile 
    31  
     30from data_util.registry import ExtensionRegistry 
    3231# Default readers are defined in the readers sub-module 
    3332import readers 
    34 from readers import ascii_reader,cansas_reader 
     33from readers import ascii_reader 
     34from readers import cansas_reader 
    3535 
    3636class Registry(ExtensionRegistry): 
     
    5555        readers.read_associations(self) 
    5656         
    57         #TODO: remove the following line when ready to switch to the new default readers 
     57        #TODO: remove the following line when ready to switch to  
     58        #the new default readers 
    5859        #readers.register_readers(self._identify_plugin) 
    5960         
     
    6768 
    6869        :param path: file path 
    69         :param format: explicit extension, to force the use of a particular reader 
     70        :param format: explicit extension, to force the use  
     71            of a particular reader 
    7072 
    7173        Defaults to the ascii (multi-column) reader 
     
    8385                cansas_loader = cansas_reader.Reader() 
    8486                return cansas_loader.read(path) 
     87             
    8588    def find_plugins(self, dir): 
    8689        """ 
     
    112115                        if self._identify_plugin(module): 
    113116                            readers_found += 1 
    114                     except : 
    115                         logging.error("Loader: Error importing %s\n  %s" % (item, sys.exc_value)) 
     117                    except: 
     118                        msg = "Loader: Error importing " 
     119                        msg += "%s\n  %s" % (item, sys.exc_value) 
     120                        logging.error(msg) 
    116121                             
    117122                # Process zip files 
     
    128133                                fullname = mfile.replace('/', '.') 
    129134                                fullname = os.path.splitext(fullname)[0] 
    130                                 module = __import__(fullname, globals(), locals(), [""]) 
     135                                module = __import__(fullname, globals(), 
     136                                                     locals(), [""]) 
    131137                                if self._identify_plugin(module): 
    132138                                    readers_found += 1 
    133139                            except: 
    134                                 logging.error("Loader: Error importing %s\n  %s" % (mfile, sys.exc_value)) 
     140                                msg = "Loader: Error importing" 
     141                                msg += " %s\n  %s" % (mfile, sys.exc_value) 
     142                                logging.error(msg) 
    135143                             
    136144                    except: 
    137                         logging.error("Loader: Error importing %s\n  %s" % (item, sys.exc_value)) 
     145                        msg = "Loader: Error importing " 
     146                        msg += " %s\n  %s" % (item, sys.exc_value) 
     147                        logging.error(msg) 
    138148                      
    139149        return readers_found  
     
    166176                    type_name = loader.type_name 
    167177                     
    168                 wcard = "%s files (*%s)|*%s" % (type_name, ext.lower(), ext.lower()) 
     178                wcard = "%s files (*%s)|*%s" % (type_name, ext.lower(), 
     179                                                 ext.lower()) 
    169180                if wcard not in self.wildcards: 
    170181                    self.wildcards.append(wcard) 
     
    178189                         
    179190            except: 
    180                 logging.error("Loader: Error accessing Reader in %s\n  %s" % (module.__name__, sys.exc_value)) 
     191                msg = "Loader: Error accessing" 
     192                msg += " Reader in %s\n  %s" % (module.__name__, sys.exc_value) 
     193                logging.error(msg) 
    181194        return reader_found 
    182195 
     
    203216                type_name = loader.type_name 
    204217                 
    205                 wcard = "%s files (*%s)|*%s" % (type_name, ext.lower(), ext.lower()) 
     218                wcard = "%s files (*%s)|*%s" % (type_name, ext.lower(),  
     219                                                ext.lower()) 
    206220                if wcard not in self.wildcards: 
    207221                    self.wildcards.append(wcard) 
    208222                  
    209223        except: 
    210             logging.error("Loader: Error accessing Reader in %s\n  %s" % (module.__name__, sys.exc_value)) 
     224            msg = "Loader: Error accessing Reader " 
     225            msg += "in %s\n  %s" % (module.__name__, sys.exc_value) 
     226            logging.error(msg) 
    211227        return reader_found 
    212228 
     
    229245                    if ext not in self.loaders: 
    230246                        self.loaders[ext] = [] 
    231                     # When finding a reader at run time, treat this reader as the new  
    232                     # default 
    233                     self.loaders[ext].insert(0,loader.read) 
     247                    # When finding a reader at run time, 
     248                    # treat this reader as the new default 
     249                    self.loaders[ext].insert(0, loader.read) 
    234250 
    235251                    reader_found = True 
     
    239255                    if hasattr(loader, 'type_name'): 
    240256                        type_name = loader.type_name 
    241                     wcard = "%s files (*%s)|*%s" % (type_name, ext.lower(), ext.lower()) 
     257                    wcard = "%s files (*%s)|*%s" % (type_name, ext.lower(), 
     258                                                     ext.lower()) 
    242259                    if wcard not in self.wildcards: 
    243260                        self.wildcards.append(wcard) 
     
    251268                         
    252269            except: 
    253                 logging.error("Loader: Error accessing Reader in %s\n  %s" % (module.__name__, sys.exc_value)) 
     270                msg = "Loader: Error accessing Reader" 
     271                msg += " in %s\n  %s" % (module.__name__, sys.exc_value) 
     272                logging.error(msg) 
    254273        return reader_found 
    255274 
     
    263282        extlist = [ext for ext in self.extensions() if path.endswith(ext)] 
    264283        # Sort matching extensions by decreasing order of length 
    265         extlist.sort(lambda a,b: len(a)<len(b)) 
     284        extlist.sort(lambda a, b: len(a) < len(b)) 
    266285        # Combine loaders for matching extensions into one big list 
    267286        writers = [] 
     
    276295        # Raise an error if there are no matching extensions 
    277296        if len(writers) == 0: 
    278             raise ValueError, "Unknown file type for "+path 
     297            raise ValueError, "Unknown file type for " + path 
    279298        # All done 
    280299        return writers 
     
    372391                        filemode='w') 
    373392    l = Loader() 
    374     data = l.load('test/cansas1d.xml') 
    375     l.save('test_file.xml', data, '.xml') 
     393    test_data = l.load('test/cansas1d.xml') 
     394    l.save('test_file.xml', test_data, '.xml') 
    376395     
    377396    print l.get_wildcards() 
  • DataLoader/manipulations.py

    r0997158f ra7a5886  
    99 
    1010""" 
    11     Data manipulations for 2D data sets. 
    12     Using the meta data information, various types of averaging 
    13     are performed in Q-space  
     11Data manipulations for 2D data sets. 
     12Using the meta data information, various types of averaging 
     13are performed in Q-space  
    1414""" 
    15  
    16  
    1715#TODO: copy the meta data from the 2D object to the resulting 1D object 
    18  
    19 from data_info import plottable_2D, Data1D 
    2016import math 
    2117import numpy 
     18 
     19#from data_info import plottable_2D 
     20from data_info import Data1D 
     21 
    2222 
    2323def get_q(dx, dy, det_dist, wavelength): 
     
    3131    plane_dist = math.sqrt(dx*dx + dy*dy) 
    3232    # Half of the scattering angle 
    33     theta      = 0.5*math.atan(plane_dist/det_dist) 
    34     return (4.0*math.pi/wavelength)*math.sin(theta) 
    35  
    36 def get_q_compo(dx, dy, det_dist, wavelength,compo=None): 
     33    theta = 0.5 * math.atan(plane_dist/det_dist) 
     34    return (4.0 * math.pi/wavelength) * math.sin(theta) 
     35 
     36def get_q_compo(dx, dy, det_dist, wavelength, compo=None): 
    3737    """ 
    3838    This reduces tiny error at very large q. 
    3939    Implementation of this func is not started yet.<--ToDo 
    4040    """ 
    41     if dy==0: 
    42         if dx>=0: 
    43             angle_xy=0 
     41    if dy == 0: 
     42        if dx >= 0: 
     43            angle_xy = 0 
    4444        else: 
    45             angle_xy=math.pi 
     45            angle_xy = math.pi 
    4646    else: 
    47         angle_xy=math.atan(dx/dy) 
    48          
    49     if compo=="x": 
    50         out=get_q(dx, dy, det_dist, wavelength)*cos(angle_xy) 
    51     elif compo=="y": 
    52         out=get_q(dx, dy, det_dist, wavelength)*sin(angle_xy) 
     47        angle_xy = math.atan(dx/dy) 
     48         
     49    if compo == "x": 
     50        out = get_q(dx, dy, det_dist, wavelength) * math.cos(angle_xy) 
     51    elif compo == "y": 
     52        out = get_q(dx, dy, det_dist, wavelength) * math.sin(angle_xy) 
    5353    else: 
    54         out=get_q(dx, dy, det_dist, wavelength) 
     54        out = get_q(dx, dy, det_dist, wavelength) 
    5555    return out 
    5656 
     
    6363    Pi = math.pi 
    6464    if phi < 0: 
    65         phi_out = phi  + 2*Pi 
    66     elif phi > 2*Pi: 
    67         phi_out = phi  - 2*Pi 
     65        phi_out = phi  + (2 * Pi) 
     66    elif phi > (2 * Pi): 
     67        phi_out = phi  - (2 * Pi) 
    6868    else: 
    6969        phi_out = phi  
     
    7272def reader2D_converter(data2d=None): 
    7373    """ 
    74     convert old 2d format opened by IhorReader or danse_reader to new Data2D format 
     74    convert old 2d format opened by IhorReader or danse_reader 
     75    to new Data2D format 
    7576     
    7677    :param data2d: 2d array of Data2D object 
     
    7980     
    8081    """ 
    81     if data2d.data==None or data2d.x_bins==None or data2d.y_bins==None: 
    82         raise ValueError,"Can't convert this data: data=None..." 
     82    if data2d.data == None or data2d.x_bins == None or data2d.y_bins == None: 
     83        raise ValueError, "Can't convert this data: data=None..." 
    8384     
    8485    from DataLoader.data_info import Data2D 
    8586 
    86     new_x = numpy.tile(data2d.x_bins, (len(data2d.y_bins),1)) 
    87     new_y = numpy.tile(data2d.y_bins, (len(data2d.x_bins),1)) 
    88     new_y = new_y.swapaxes(0,1) 
     87    new_x = numpy.tile(data2d.x_bins, (len(data2d.y_bins), 1)) 
     88    new_y = numpy.tile(data2d.y_bins, (len(data2d.x_bins), 1)) 
     89    new_y = new_y.swapaxes(0, 1) 
    8990 
    9091    new_data = data2d.data.flatten() 
    9192    qx_data = new_x.flatten() 
    9293    qy_data = new_y.flatten() 
    93     q_data = numpy.sqrt(qx_data*qx_data+qy_data*qy_data) 
    94     if data2d.err_data == None or numpy.any(data2d.err_data<=0):  
     94    q_data = numpy.sqrt(qx_data*qx_data + qy_data*qy_data) 
     95    if data2d.err_data == None or numpy.any(data2d.err_data <= 0):  
    9596        new_err_data = numpy.sqrt(numpy.abs(new_data)) 
    9697    else: 
    9798        new_err_data = data2d.err_data.flatten() 
    98     mask    = numpy.ones(len(new_data), dtype = bool) 
     99    mask    = numpy.ones(len(new_data), dtype=bool) 
    99100 
    100101    output = Data2D() 
     
    113114    Compute average I(Q) for a region of interest 
    114115    """ 
    115     def __init__(self, x_min=0.0, x_max=0.0, y_min=0.0, y_max=0.0, bin_width=0.001): 
     116    def __init__(self, x_min=0.0, x_max=0.0, y_min=0.0, 
     117                 y_max=0.0, bin_width=0.001): 
    116118        # Minimum Qx value [A-1] 
    117119        self.x_min = x_min 
     
    124126        # Bin width (step size) [A-1] 
    125127        self.bin_width = bin_width 
    126         # If True, I(|Q|) will be return, otherwise, negative q-values are allowed 
     128        # If True, I(|Q|) will be return, otherwise, 
     129        # negative q-values are allowed 
    127130        self.fold = False 
    128131         
    129     def __call__(self, data2D): return NotImplemented 
     132    def __call__(self, data2D): 
     133        return NotImplemented 
    130134         
    131135    def _avg(self, data2D, maj): 
     
    141145        """ 
    142146        if len(data2D.detector) != 1: 
    143             raise RuntimeError, "_Slab._avg: invalid number of detectors: %g" % len(data2D.detector) 
     147            msg = "_Slab._avg: invalid number of " 
     148            msg += " detectors: %g" % len(data2D.detector) 
     149            raise RuntimeError, msg 
    144150         
    145151        # Get data  
     
    151157              
    152158        # Build array of Q intervals 
    153         if maj=='x': 
    154             if self.fold: x_min = 0      
     159        if maj == 'x': 
     160            if self.fold: 
     161                x_min = 0      
    155162            else:  x_min = self.x_min 
    156             nbins = int(math.ceil((self.x_max-x_min)/self.bin_width)) 
    157             qbins = self.bin_width*numpy.arange(nbins)+ x_min 
    158         elif maj=='y': 
     163            nbins = int(math.ceil((self.x_max - x_min)/self.bin_width)) 
     164            qbins = self.bin_width * numpy.arange(nbins) + x_min 
     165        elif maj == 'y': 
    159166            if self.fold: y_min = 0      
    160167            else:  y_min = self.y_min 
    161             nbins = int(math.ceil((self.y_max-y_min)/self.bin_width)) 
    162             qbins = self.bin_width*numpy.arange(nbins)+ y_min           
     168            nbins = int(math.ceil((self.y_max - y_min)/self.bin_width)) 
     169            qbins = self.bin_width * numpy.arange(nbins) + y_min           
    163170        else: 
    164171            raise RuntimeError, "_Slab._avg: unrecognized axis %s" % str(maj) 
     
    179186            if self.y_min <= qy_data[npts] and self.y_max > qy_data[npts]: 
    180187                frac_y = 1 
    181              
    182188            frac = frac_x * frac_y 
    183189             
    184             if frac == 0: continue 
    185  
     190            if frac == 0: 
     191                continue 
    186192            # binning: find axis of q 
    187             if maj=='x':  
     193            if maj == 'x':  
    188194                q_value = qx_data[npts] 
    189195                min = x_min  
    190             if maj=='y':  
     196            if maj == 'y':  
    191197                q_value = qy_data[npts]  
    192198                min = y_min  
    193             if self.fold and q_value<0: q_value = -q_value    
    194              
     199            if self.fold and q_value < 0: 
     200                q_value = -q_value    
    195201            # bin 
    196             i_q = int(math.ceil((q_value-min)/self.bin_width)) - 1 
     202            i_q = int(math.ceil((q_value - min)/self.bin_width)) - 1 
    197203             
    198204            # skip outside of max bins 
    199             if i_q<0 or i_q>=nbins: continue 
     205            if i_q < 0 or i_q >= nbins: 
     206                continue 
    200207             
    201208            # give it full weight 
     
    203210             
    204211            #TODO: find better definition of x[i_q] based on q_data 
    205             x[i_q]         = min +(i_q+1)*self.bin_width/2.0 
    206             y[i_q]         += frac * data[npts] 
    207              
    208             if err_data == None or err_data[npts]==0.0: 
    209                 if data[npts] <0: data[npts] = -data[npts] 
     212            x[i_q] = min + (i_q + 1) * self.bin_width / 2.0 
     213            y[i_q] += frac * data[npts] 
     214             
     215            if err_data == None or err_data[npts] == 0.0: 
     216                if data[npts] < 0: data[npts] = -data[npts] 
    210217                err_y[i_q] += frac * frac * data[npts] 
    211218            else: 
     
    217224            err_y[n] = math.sqrt(err_y[n]) 
    218225           
    219         err_y = err_y/y_counts 
    220         y    = y/y_counts 
    221          
    222         idx = (numpy.isfinite(y)& numpy.isfinite(x))  
     226        err_y = err_y / y_counts 
     227        y    = y / y_counts 
     228         
     229        idx = (numpy.isfinite(y) & numpy.isfinite(x))  
    223230         
    224231        if not idx.any():  
    225             raise ValueError, "Average Error: No points inside ROI to average..."  
    226         elif len(y[idx])!= nbins: 
    227             print "resulted",nbins- len(y[idx]),"empty bin(s) due to tight binning..." 
     232            msg = "Average Error: No points inside ROI to average..."  
     233            raise ValueError, msg 
     234        #elif len(y[idx])!= nbins: 
     235        #    msg = "empty bin(s) due to tight binning..." 
     236        #    print "resulted",nbins- len(y[idx]), msg 
    228237        return Data1D(x=x[idx], y=y[idx], dy=err_y[idx]) 
    229238         
     
    283292         
    284293        # Average the sums 
    285         counts = 0 if y_counts==0 else y 
    286         error  = 0 if y_counts==0 else math.sqrt(err_y) 
     294        counts = 0 if y_counts == 0 else y 
     295        error  = 0 if y_counts == 0 else math.sqrt(err_y) 
    287296         
    288297        return counts, error 
     
    294303        :param data2D: Data2D object 
    295304         
    296         :return: number of counts, error on number of counts, number of entries summed 
     305        :return: number of counts,  
     306            error on number of counts, number of entries summed 
    297307         
    298308        """ 
    299309        if len(data2D.detector) != 1: 
    300             raise RuntimeError, "Circular averaging: invalid number of detectors: %g" % len(data2D.detector) 
    301          
     310            msg = "Circular averaging: invalid number " 
     311            msg += "of detectors: %g" % len(data2D.detector) 
     312            raise RuntimeError, msg 
    302313        # Get data  
    303314        data = data2D.data[numpy.isfinite(data2D.data)] 
     
    326337            if self.y_min <= qy and self.y_max > qy: 
    327338                frac_y = 1 
    328                  
    329339            #Find the fraction along each directions             
    330340            frac = frac_x * frac_y 
    331             if frac == 0: continue 
    332  
     341            if frac == 0: 
     342                continue 
    333343            y += frac * data[npts] 
    334             if err_data == None or err_data[npts]==0.0: 
    335                 if data[npts] <0: data[npts] = -data[npts] 
     344            if err_data == None or err_data[npts] == 0.0: 
     345                if data[npts] < 0: 
     346                    data[npts] = -data[npts] 
    336347                err_y += frac * frac * data[npts] 
    337348            else: 
    338349                err_y += frac * frac * err_data[npts] * err_data[npts] 
    339             y_counts += frac 
    340                 
     350            y_counts += frac      
    341351        return y, err_y, y_counts 
    342352 
     
    348358    """ 
    349359    def __init__(self, x_min=0.0, x_max=0.0, y_min=0.0, y_max=0.0): 
    350         super(Boxavg, self).__init__(x_min=x_min, x_max=x_max, y_min=y_min, y_max=y_max) 
     360        super(Boxavg, self).__init__(x_min=x_min, x_max=x_max, 
     361                                      y_min=y_min, y_max=y_max) 
    351362 
    352363    def __call__(self, data2D): 
     
    362373         
    363374        # Average the sums 
    364         counts = 0 if y_counts==0 else y/y_counts 
    365         error  = 0 if y_counts==0 else math.sqrt(err_y)/y_counts 
     375        counts = 0 if y_counts == 0 else y/y_counts 
     376        error  = 0 if y_counts == 0 else math.sqrt(err_y)/y_counts 
    366377         
    367378        return counts, error 
     
    384395     
    385396    """ 
    386     if x<=xmin: 
     397    if x <= xmin: 
    387398        return 0.0 
    388     if x>xmin and x<xmax: 
    389         return (x-xmin)/(xmax-xmin) 
     399    if x > xmin and x < xmax: 
     400        return (x - xmin) / (xmax - xmin) 
    390401    else: 
    391402        return 1.0 
     
    423434 
    424435        if len(data2D.q_data) == None: 
    425             raise RuntimeError, "Circular averaging: invalid q_data: %g" % data2D.q_data 
     436            msg = "Circular averaging: invalid q_data: %g" % data2D.q_data 
     437            raise RuntimeError, msg 
    426438 
    427439        # Build array of Q intervals 
    428         nbins = int(math.ceil((self.r_max-self.r_min)/self.bin_width)) 
    429         qbins = self.bin_width*numpy.arange(nbins)+self.r_min 
     440        nbins = int(math.ceil((self.r_max - self.r_min) / self.bin_width)) 
     441        qbins = self.bin_width * numpy.arange(nbins) + self.r_min 
    430442 
    431443        x  = numpy.zeros(nbins) 
     
    438450             
    439451            # q-value at the pixel (j,i) 
    440             q_value = q_data[npt] 
    441                  
     452            q_value = q_data[npt]  
    442453            data_n = data[npt]                 
    443454             
    444455            ## No need to calculate the frac when all data are within range 
    445456            if self.r_min >= self.r_max: 
    446                 raise ValueError, "Limit Error: min > max ???"  
    447              
    448             if self.r_min <= q_value and q_value <= self.r_max: frac = 1                        
    449  
    450             if frac == 0: continue 
    451                        
    452             i_q = int(math.floor((q_value-self.r_min)/self.bin_width))     
     457                raise ValueError, "Limit Error: min > max"  
     458             
     459            if self.r_min <= q_value and q_value <= self.r_max: 
     460                frac = 1                        
     461            if frac == 0: 
     462                continue  
     463            i_q = int(math.floor((q_value - self.r_min) / self.bin_width))     
    453464 
    454465            # Take care of the edge case at phi = 2pi.  
    455466            if i_q == nbins:   
    456                 i_q = nbins -1  
    457                                      
     467                i_q = nbins -1               
    458468            y[i_q] += frac * data_n 
    459469 
    460             if err_data == None or err_data[npt]==0.0: 
    461                 if data_n <0: data_n = -data_n 
     470            if err_data == None or err_data[npt] == 0.0: 
     471                if data_n < 0: 
     472                    data_n = -data_n 
    462473                err_y[i_q] += frac * frac * data_n 
    463474            else: 
     
    466477         
    467478        ## x should be the center value of each bins         
    468         x = qbins+self.bin_width/ 
     479        x = qbins + self.bin_width /  
    469480         
    470481        # Average the sums        
    471482        for n in range(nbins): 
    472             if err_y[n] <0: err_y[n] = -err_y[n] 
     483            if err_y[n] < 0: err_y[n] = -err_y[n] 
    473484            err_y[n] = math.sqrt(err_y[n]) 
    474485                       
    475         err_y = err_y/y_counts 
    476         y    = y/y_counts 
    477         idx = (numpy.isfinite(y))&(numpy.isfinite(x))  
     486        err_y = err_y / y_counts 
     487        y    = y / y_counts 
     488        idx = (numpy.isfinite(y)) & (numpy.isfinite(x))  
    478489         
    479490        if not idx.any():  
    480             raise ValueError, "Average Error: No points inside ROI to average..."  
    481         elif len(y[idx])!= nbins: 
    482             print "resulted",nbins- len(y[idx]),"empty bin(s) due to tight binning..." 
    483          
     491            msg = "Average Error: No points inside ROI to average..."  
     492            raise ValueError, msg 
     493        #elif len(y[idx])!= nbins: 
     494        #    print "resulted",nbins- len(y[idx]) 
     495        #,"empty bin(s) due to tight binning..." 
    484496        return Data1D(x=x[idx], y=y[idx], dy=err_y[idx]) 
    485497     
     
    498510    """ 
    499511    #Todo: remove center. 
    500     def __init__(self, r_min=0, r_max=0, center_x=0, center_y=0,nbins=20 ): 
     512    def __init__(self, r_min=0, r_max=0, center_x=0, center_y=0, nbins=20): 
    501513        # Minimum radius 
    502514        self.r_min = r_min 
     
    541553        for npt in range(len(data)):           
    542554            frac = 0 
    543              
    544555            # q-value at the point (npt) 
    545556            q_value = q_data[npt] 
    546                  
    547557            data_n = data[npt]     
    548558                         
    549559            # phi-value at the point (npt) 
    550             phi_value=math.atan2(qy_data[npt],qx_data[npt])+Pi 
    551              
    552             if self.r_min <= q_value and q_value <= self.r_max: frac = 1                        
    553  
    554             if frac == 0: continue 
    555              
     560            phi_value = math.atan2(qy_data[npt], qx_data[npt]) + Pi 
     561             
     562            if self.r_min <= q_value and q_value <= self.r_max: 
     563                frac = 1                        
     564            if frac == 0: 
     565                continue 
    556566            # binning            
    557             i_phi = int(math.floor((self.nbins_phi)*phi_value/(2*Pi))) 
     567            i_phi = int(math.floor((self.nbins_phi) * phi_value / (2 * Pi))) 
    558568             
    559569            # Take care of the edge case at phi = 2pi.  
    560570            if i_phi == self.nbins_phi:   
    561                 i_phi =  self.nbins_phi -1  
    562                                               
     571                i_phi =  self.nbins_phi - 1                             
    563572            phi_bins[i_phi] += frac * data[npt] 
    564573             
    565             if err_data == None or err_data[npt] ==0.0: 
    566                 if data_n <0: data_n = -data_n 
     574            if err_data == None or err_data[npt] == 0.0: 
     575                if data_n < 0: 
     576                    data_n = -data_n 
    567577                phi_err[i_phi] += frac * frac * math.fabs(data_n) 
    568578            else: 
    569                 phi_err[i_phi] += frac * frac *err_data[npt]*err_data[npt] 
     579                phi_err[i_phi] += frac * frac * err_data[npt] * err_data[npt] 
    570580            phi_counts[i_phi] += frac 
    571581                           
     
    573583            phi_bins[i] = phi_bins[i] / phi_counts[i] 
    574584            phi_err[i] = math.sqrt(phi_err[i]) / phi_counts[i] 
    575             phi_values[i] = 2.0*math.pi/self.nbins_phi*(1.0*i + 0.5) 
     585            phi_values[i] = 2.0 * math.pi / self.nbins_phi * (1.0 * i + 0.5) 
    576586             
    577587        idx = (numpy.isfinite(phi_bins))  
    578588 
    579         if not idx.any():  
    580             raise ValueError, "Average Error: No points inside ROI to average..."  
    581         elif len(phi_bins[idx])!= self.nbins_phi: 
    582             print "resulted",self.nbins_phi- len(phi_bins[idx]),"empty bin(s) due to tight binning..." 
     589        if not idx.any(): 
     590            msg = "Average Error: No points inside ROI to average..."  
     591            raise ValueError, msg 
     592        #elif len(phi_bins[idx])!= self.nbins_phi: 
     593        #    print "resulted",self.nbins_phi- len(phi_bins[idx]) 
     594        #,"empty bin(s) due to tight binning..." 
    583595        return Data1D(x=phi_values[idx], y=phi_bins[idx], dy=phi_err[idx]) 
    584596     
     
    600612     
    601613    """ 
    602      
    603614    # y side for x = minx 
    604615    x_0 = get_intercept(qmax, q_00, q_01) 
     
    615626     
    616627    if x_0 and x_1: 
    617         frac_max = (x_0+x_1)/2.0 
    618      
     628        frac_max = (x_0 + x_1) / 2.0 
    619629    elif y_0 and y_1: 
    620         frac_max = (y_0+y_1)/2.0 
    621      
     630        frac_max = (y_0 + y_1) / 2.0 
    622631    elif x_0 and y_0: 
    623632        if q_00 < q_10: 
    624             frac_max = x_0*y_0/2.0 
     633            frac_max = x_0 * y_0 / 2.0 
    625634        else: 
    626             frac_max = 1.0-x_0*y_0/2.0 
    627      
     635            frac_max = 1.0 - x_0 * y_0 / 2.0 
    628636    elif x_0 and y_1: 
    629637        if q_00 < q_10: 
    630             frac_max = x_0*y_1/2.0 
     638            frac_max = x_0 * y_1 / 2.0 
    631639        else: 
    632             frac_max = 1.0-x_0*y_1/2.0 
    633      
     640            frac_max = 1.0 - x_0 * y_1 / 2.0 
    634641    elif x_1 and y_0: 
    635642        if q_00 > q_10: 
    636             frac_max = x_1*y_0/2.0 
     643            frac_max = x_1 * y_0 / 2.0 
    637644        else: 
    638             frac_max = 1.0-x_1*y_0/2.0 
    639      
     645            frac_max = 1.0 - x_1 * y_0 / 2.0 
    640646    elif x_1 and y_1: 
    641647        if q_00 < q_10: 
    642             frac_max = 1.0 - (1.0-x_1)*(1.0-y_1)/2.0 
     648            frac_max = 1.0 - (1.0 - x_1) * (1.0 - y_1) / 2.0 
    643649        else: 
    644             frac_max = (1.0-x_1)*(1.0-y_1)/2.0 
     650            frac_max = (1.0 - x_1) * (1.0 - y_1) / 2.0 
    645651             
    646652    # If we make it here, there is no intercept between 
    647653    # this pixel and the constant-q ring. We only need 
    648654    # to know if we have to include it or exclude it. 
    649     elif (q_00+q_01+q_10+q_11)/4.0 < qmax: 
     655    elif (q_00 + q_01 + q_10 + q_11)/4.0 < qmax: 
    650656        frac_max = 1.0 
    651657 
     
    671677    if q_1 > q_0: 
    672678        if (q > q_0 and q <= q_1): 
    673             return (q-q_0)/(q_1 - q_0)     
     679            return (q - q_0)/(q_1 - q_0)     
    674680    else: 
    675681        if (q > q_1 and q <= q_0): 
    676             return (q-q_1)/(q_0 - q_1) 
     682            return (q - q_1)/(q_0 - q_1) 
    677683    return None 
    678684      
     
    682688    The sector is defined by r_min, r_max, phi_min, phi_max, 
    683689    and the position of the center of the ring  
    684     where phi_min and phi_max are defined by the right and left lines wrt central line 
     690    where phi_min and phi_max are defined by the right 
     691    and left lines wrt central line 
    685692    and phi_max could be less than phi_min.  
    686693    
    687     Phi is defined between 0 and 2*pi in anti-clockwise starting from the x- axis on the left-hand side 
    688     """ 
    689     def __init__(self, r_min, r_max, phi_min=0, phi_max=2*math.pi,nbins=20): 
     694    Phi is defined between 0 and 2*pi in anti-clockwise  
     695    starting from the x- axis on the left-hand side 
     696    """ 
     697    def __init__(self, r_min, r_max, phi_min=0, phi_max=2*math.pi, nbins=20): 
    690698        self.r_min = r_min 
    691699        self.r_max = r_max 
     
    728736                       
    729737        for n in range(len(data)):      
    730                 frac = 0 
     738            frac = 0 
     739             
     740            # q-value at the pixel (j,i) 
     741            q_value = q_data[n] 
     742            data_n = data[n] 
     743             
     744            # Is pixel within range? 
     745            is_in = False 
     746             
     747            # phi-value of the pixel (j,i) 
     748            phi_value = math.atan2(qy_data[n], qx_data[n]) + Pi  
     749             
     750            ## No need to calculate the frac when all data are within range 
     751            if self.r_min <= q_value and q_value <= self.r_max: 
     752                frac = 1                        
     753            if frac == 0: 
     754                continue 
     755            #In case of two ROIs (symmetric major and minor regions)(for 'q2') 
     756            if run.lower()=='q2': 
     757                ## For minor sector wing  
     758                # Calculate the minor wing phis 
     759                phi_min_minor = flip_phi(phi_min - Pi) 
     760                phi_max_minor = flip_phi(phi_max - Pi) 
     761                # Check if phis of the minor ring is within 0 to 2pi 
     762                if phi_min_minor > phi_max_minor: 
     763                    is_in = (phi_value > phi_min_minor or \ 
     764                              phi_value < phi_max_minor) 
     765                else: 
     766                    is_in = (phi_value > phi_min_minor and \ 
     767                              phi_value < phi_max_minor) 
     768 
     769            #For all cases(i.e.,for 'q', 'q2', and 'phi')  
     770            #Find pixels within ROI   
     771            if phi_min > phi_max:  
     772                is_in = is_in or (phi_value > phi_min or \ 
     773                                   phi_value < phi_max)          
     774            else: 
     775                is_in = is_in or (phi_value >= phi_min  and \ 
     776                                    phi_value < phi_max) 
     777             
     778            if not is_in: 
     779                frac = 0                                                         
     780            if frac == 0: 
     781                continue 
     782            # Check which type of averaging we need 
     783            if run.lower() == 'phi':  
     784                temp_x = (self.nbins) * (phi_value - self.phi_min) 
     785                temp_y = (self.phi_max - self.phi_min) 
     786                i_bin = int(math.floor(temp_x / temp_y)) 
     787            else: 
     788                temp_x = (self.nbins) * (q_value - self.r_min) 
     789                tem_y = (self.r_max - self.r_min) 
     790                i_bin = int(math.floor(temp_x / temp_y)) 
     791 
     792            # Take care of the edge case at phi = 2pi.  
     793            if i_bin == self.nbins:   
     794                i_bin =  self.nbins - 1 
    731795                 
    732                 # q-value at the pixel (j,i) 
    733                 q_value = q_data[n] 
    734                  
    735      
    736                 data_n = data[n] 
    737                  
    738                 # Is pixel within range? 
    739                 is_in = False 
    740                  
    741                 # phi-value of the pixel (j,i) 
    742                 phi_value=math.atan2(qy_data[n],qx_data[n])+Pi  
    743                  
    744                 ## No need to calculate the frac when all data are within range 
    745                 if self.r_min <= q_value and q_value <= self.r_max: frac = 1                        
    746  
    747                 if frac == 0: continue 
    748    
    749                 #In case of two ROIs (symmetric major and minor regions)(for 'q2') 
    750                 if run.lower()=='q2': 
    751                     ## For minor sector wing  
    752                     # Calculate the minor wing phis 
    753                     phi_min_minor = flip_phi(phi_min-Pi) 
    754                     phi_max_minor = flip_phi(phi_max-Pi) 
    755                     # Check if phis of the minor ring is within 0 to 2pi 
    756                     if phi_min_minor > phi_max_minor: 
    757                         is_in = (phi_value > phi_min_minor or phi_value < phi_max_minor) 
    758                     else: 
    759                         is_in = (phi_value > phi_min_minor and phi_value < phi_max_minor) 
    760  
    761                 #For all cases(i.e.,for 'q', 'q2', and 'phi')  
    762                 #Find pixels within ROI   
    763                 if phi_min > phi_max:  
    764                     is_in = is_in or (phi_value > phi_min or phi_value < phi_max)          
    765                 else: 
    766                     is_in = is_in or (phi_value>= phi_min  and  phi_value <phi_max) 
    767                  
    768                 if not is_in: frac = 0                                                         
    769                 if frac == 0: continue 
    770                  
    771                 # Check which type of averaging we need 
    772                 if run.lower()=='phi':  
    773                     i_bin    = int(math.floor((self.nbins)*(phi_value-self.phi_min)\ 
    774                                               /(self.phi_max-self.phi_min))) 
    775                 else: 
    776                     i_bin = int(math.floor((self.nbins)*(q_value-self.r_min)/(self.r_max-self.r_min))) 
    777  
    778                 # Take care of the edge case at phi = 2pi.  
    779                 if i_bin == self.nbins:   
    780                     i_bin =  self.nbins -1 
    781                      
    782                 ## Get the total y           
    783                 y[i_bin] += frac * data_n 
    784  
    785                 if err_data == None or err_data[n] ==0.0: 
    786                     if data_n<0: data_n= -data_n 
    787                     y_err[i_bin] += frac * frac * data_n 
    788                 else: 
    789                     y_err[i_bin] += frac * frac * err_data[n]*err_data[n] 
    790                 y_counts[i_bin] += frac 
    791         
     796            ## Get the total y           
     797            y[i_bin] += frac * data_n 
     798 
     799            if err_data == None or err_data[n] == 0.0: 
     800                if data_n < 0: 
     801                    data_n = -data_n 
     802                y_err[i_bin] += frac * frac * data_n 
     803            else: 
     804                y_err[i_bin] += frac * frac * err_data[n] * err_data[n] 
     805            y_counts[i_bin] += frac 
     806    
    792807        # Organize the results 
    793808        for i in range(self.nbins): 
     
    797812            # The type of averaging: phi,q2, or q 
    798813            # Calculate x[i]should be at the center of the bin 
    799             if run.lower()=='phi':                
    800                 x[i] = (self.phi_max-self.phi_min)/self.nbins*(1.0*i + 0.5)+self.phi_min 
     814            if run.lower() == 'phi':  
     815                temp = self.nbins * (1.0 * i + 0.5) + self.phi_min               
     816                x[i] = (self.phi_max - self.phi_min) / temp 
    801817            else: 
    802                 x[i] = (self.r_max-self.r_min)/self.nbins*(1.0*i + 0.5)+self.r_min 
     818                temp = self.nbins * (1.0 * i + 0.5) + self.r_min 
     819                x[i] = (self.r_max - self.r_min) / temp 
    803820                 
    804         idx = (numpy.isfinite(y)& numpy.isfinite(y_err)) 
    805          
    806         if not idx.any():  
    807             raise ValueError, "Average Error: No points inside sector of ROI to average..."  
    808         elif len(y[idx])!= self.nbins: 
    809             print "resulted",self.nbins- len(y[idx]),"empty bin(s) due to tight binning..." 
     821        idx = (numpy.isfinite(y) & numpy.isfinite(y_err)) 
     822         
     823        if not idx.any(): 
     824            msg = "Average Error: No points inside sector of ROI to average..."  
     825            raise ValueError, msg 
     826        #elif len(y[idx])!= self.nbins: 
     827        #    print "resulted",self.nbins- len(y[idx]), 
     828        #"empty bin(s) due to tight binning..." 
    810829        return Data1D(x=x[idx], y=y[idx], dy=y_err[idx]) 
    811830                 
     
    885904        qy_data = data2D.qy_data 
    886905        mask = data2D.mask 
    887         q_data = numpy.sqrt(qx_data*qx_data+qy_data*qy_data) 
     906        q_data = numpy.sqrt(qx_data * qx_data + qy_data * qy_data) 
    888907        #q_data_max = numpy.max(q_data) 
    889908 
     
    946965    Defines a sector (major + minor) region on a 2D data set. 
    947966    The sector is defined by phi_min, phi_max, 
    948     where phi_min and phi_max are defined by the right and left lines wrt central line.  
     967    where phi_min and phi_max are defined by the right  
     968    and left lines wrt central line.  
    949969    
    950970    Phi_min and phi_max are given in units of radian  
    951971    and (phi_max-phi_min) should not be larger than pi 
    952972    """ 
    953     def __init__(self,phi_min=0, phi_max=math.pi): 
     973    def __init__(self, phi_min=0, phi_max=math.pi): 
    954974        self.phi_min = phi_min 
    955975        self.phi_max = phi_max 
     
    9911011         
    9921012        # Get the min and max into the region: -pi <= phi < Pi 
    993         phi_min_major = flip_phi(self.phi_min+Pi)-Pi 
    994         phi_max_major = flip_phi(self.phi_max+Pi)-Pi   
     1013        phi_min_major = flip_phi(self.phi_min + Pi) - Pi 
     1014        phi_max_major = flip_phi(self.phi_max + Pi) - Pi   
    9951015        # check for major sector 
    9961016        if phi_min_major > phi_max_major: 
     
    10011021        # minor sector 
    10021022        # Get the min and max into the region: -pi <= phi < Pi 
    1003         phi_min_minor = flip_phi(self.phi_min)-Pi 
    1004         phi_max_minor = flip_phi(self.phi_max)-Pi 
     1023        phi_min_minor = flip_phi(self.phi_min) - Pi 
     1024        phi_max_minor = flip_phi(self.phi_max) - Pi 
    10051025               
    10061026        # check for minor sector 
    10071027        if phi_min_minor > phi_max_minor: 
    1008             out_minor= (phi_min_minor <= phi_data) + (phi_max_minor>= phi_data)  
     1028            out_minor = (phi_min_minor <= phi_data) + \ 
     1029                            (phi_max_minor >= phi_data)  
    10091030        else: 
    1010             out_minor = (phi_min_minor <= phi_data) & (phi_max_minor >= phi_data)  
     1031            out_minor = (phi_min_minor <= phi_data) & \ 
     1032                            (phi_max_minor >= phi_data)  
    10111033        out = out_major + out_minor 
    10121034         
  • DataLoader/qsmearing.py

    r023c8e2 ra7a5886  
    77#copyright 2008, University of Tennessee 
    88###################################################################### 
    9  
     9import numpy 
     10#import math 
     11import logging 
     12import sys 
    1013import DataLoader.extensions.smearer as smearer 
    11 import numpy 
    12 import math 
    13 import logging, sys 
    1414from DataLoader.smearing_2d import Smearer2D 
    1515 
     
    4040        return Smearer2D(data1D) 
    4141     
    42     if  not hasattr(data1D, "dx") and not hasattr(data1D, "dxl") and not hasattr(data1D, "dxw"): 
     42    if  not hasattr(data1D, "dx") and not hasattr(data1D, "dxl")\ 
     43         and not hasattr(data1D, "dxw"): 
    4344        return None 
    4445     
    4546    # Look for resolution smearing data 
    4647    _found_resolution = False 
    47     if data1D.dx is not None and len(data1D.dx)==len(data1D.x): 
     48    if data1D.dx is not None and len(data1D.dx) == len(data1D.x): 
    4849         
    4950        # Check that we have non-zero data 
    50         if data1D.dx[0]>0.0: 
     51        if data1D.dx[0] > 0.0: 
    5152            _found_resolution = True 
    5253            #print "_found_resolution",_found_resolution 
     
    5859    # Look for slit smearing data 
    5960    _found_slit = False 
    60     if data1D.dxl is not None and len(data1D.dxl)==len(data1D.x) \ 
    61         and data1D.dxw is not None and len(data1D.dxw)==len(data1D.x): 
     61    if data1D.dxl is not None and len(data1D.dxl) == len(data1D.x) \ 
     62        and data1D.dxw is not None and len(data1D.dxw) == len(data1D.x): 
    6263         
    6364        # Check that we have non-zero data 
    64         if data1D.dxl[0]>0.0 or data1D.dxw[0]>0.0: 
     65        if data1D.dxl[0] > 0.0 or data1D.dxw[0] > 0.0: 
    6566            _found_slit = True 
    6667         
     
    7879    if _found_slit == True: 
    7980        return SlitSmearer(data1D) 
    80      
    8181    return None 
    8282             
     
    101101        return result 
    102102 
    103          
    104     def _compute_matrix(self): return NotImplemented 
     103    def _compute_matrix(self): 
     104        """ 
     105        """ 
     106        return NotImplemented 
    105107 
    106108    def get_bin_range(self, q_min=None, q_max=None): 
     
    115117        if not self._init_complete: 
    116118            self._initialize_smearer() 
    117              
    118119        if q_min == None: 
    119120            q_min = self.min 
    120          
    121121        if q_max == None: 
    122122            q_max = self.max 
    123          
    124         _qmin_unsmeared, _qmax_unsmeared = self.get_unsmeared_range(q_min, q_max) 
    125          
     123        _qmin_unsmeared, _qmax_unsmeared = self.get_unsmeared_range(q_min, 
     124                                                                     q_max) 
    126125        _first_bin = None 
    127126        _last_bin  = None 
    128127 
    129         step = (self.max-self.min)/(self.nbins-1.0) 
     128        step = (self.max - self.min) / (self.nbins - 1.0) 
    130129        try: 
    131130            for i in range(self.nbins): 
     
    138137                        _last_bin  = i 
    139138        except: 
    140             raise RuntimeError, "_BaseSmearer.get_bin_range: error getting range\n  %s" % sys.exc_value 
     139            msg = "_BaseSmearer.get_bin_range: " 
     140            msg += " error getting range\n  %s" % sys.exc_value 
     141            raise RuntimeError, msg 
    141142                
    142143        return _first_bin, _last_bin 
     
    152153              
    153154        # Get the max value for the last bin 
    154         if last_bin is None or last_bin>=len(iq_in): 
    155             last_bin = len(iq_in)-1 
     155        if last_bin is None or last_bin >= len(iq_in): 
     156            last_bin = len(iq_in) - 1 
    156157        # Check that the first bin is positive 
    157         if first_bin<0: 
     158        if first_bin < 0: 
    158159            first_bin = 0 
    159160             
    160161        # Sanity check 
    161162        if len(iq_in) != self.nbins: 
    162             raise RuntimeError, "Invalid I(q) vector: inconsistent array length %d != %s" % (len(iq_in), str(self.nbins)) 
     163            msg = "Invalid I(q) vector: inconsistent array " 
     164            msg += " length %d != %s" % (len(iq_in), str(self.nbins)) 
     165            raise RuntimeError, msg 
    163166              
    164167        # Storage for smeared I(q)    
    165168        iq_out = numpy.zeros(self.nbins) 
    166         smear_output = smearer.smear(self._smearer, iq_in, iq_out, first_bin, last_bin) 
     169        smear_output = smearer.smear(self._smearer, iq_in, iq_out, 
     170                                      first_bin, last_bin) 
    167171        if smear_output < 0: 
    168             raise RuntimeError, "_BaseSmearer: could not smear, code = %g" % smear_output 
     172            msg = "_BaseSmearer: could not smear, code = %g" % smear_output 
     173            raise RuntimeError, msg 
    169174        return iq_out 
     175     
     176    def _initialize_smearer(self): 
     177        """ 
     178        """ 
     179        return NotImplemented 
    170180     
    171181class _SlitSmearer(_BaseSmearer): 
     
    207217        This method HAS to be called before smearing 
    208218        """ 
    209         #self._smearer = smearer.new_slit_smearer(self.width, self.height, self.min, self.max, self.nbins) 
    210         self._smearer = smearer.new_slit_smearer_with_q(self.width, self.height, self.qvalues) 
     219        #self._smearer = smearer.new_slit_smearer(self.width, 
     220        # self.height, self.min, self.max, self.nbins) 
     221        self._smearer = smearer.new_slit_smearer_with_q(self.width,  
     222                                                    self.height, self.qvalues) 
    211223        self._init_complete = True 
    212224 
     
    241253        ## Slit width 
    242254        self.width = 0 
    243         if data1D.dxw is not None and len(data1D.dxw)==len(data1D.x): 
     255        if data1D.dxw is not None and len(data1D.dxw) == len(data1D.x): 
    244256            self.width = data1D.dxw[0] 
    245257            # Sanity check 
    246258            for value in data1D.dxw: 
    247259                if value != self.width: 
    248                     raise RuntimeError, "Slit smearing parameters must be the same for all data" 
    249                  
     260                    msg = "Slit smearing parameters must " 
     261                    msg += " be the same for all data" 
     262                    raise RuntimeError, msg 
    250263        ## Slit height 
    251264        self.height = 0 
    252         if data1D.dxl is not None and len(data1D.dxl)==len(data1D.x): 
     265        if data1D.dxl is not None and len(data1D.dxl) == len(data1D.x): 
    253266            self.height = data1D.dxl[0] 
    254267            # Sanity check 
    255268            for value in data1D.dxl: 
    256269                if value != self.height: 
    257                     raise RuntimeError, "Slit smearing parameters must be the same for all data" 
     270                    msg = "Slit smearing parameters must be" 
     271                    msg += " the same for all data" 
     272                    raise RuntimeError, msg 
    258273         
    259274        ## Number of Q bins 
     
    283298        _BaseSmearer.__init__(self) 
    284299        ## Standard deviation in Q [A-1] 
    285         self.width  = width 
     300        self.width = width 
    286301        ## Q_min (Min Q-value for I(q)) 
    287         self.min    = min 
     302        self.min = min 
    288303        ## Q_max (Max Q_value for I(q)) 
    289         self.max    = max 
     304        self.max = max 
    290305        ## Number of Q bins  
    291         self.nbins  = nbins 
     306        self.nbins = nbins 
    292307        ## Smearing matrix 
    293308        self._weights = None 
     
    299314        This method HAS to be called before smearing 
    300315        """ 
    301         #self._smearer = smearer.new_q_smearer(numpy.asarray(self.width), self.min, self.max, self.nbins) 
    302         self._smearer = smearer.new_q_smearer_with_q(numpy.asarray(self.width), self.qvalues) 
     316        #self._smearer = smearer.new_q_smearer(numpy.asarray(self.width), 
     317        # self.min, self.max, self.nbins) 
     318        self._smearer = smearer.new_q_smearer_with_q(numpy.asarray(self.width), 
     319                                                      self.qvalues) 
    303320        self._init_complete = True 
    304321         
     
    313330        _qmax_unsmeared = q_max  
    314331        try: 
    315             offset = 3.0*max(self.width) 
    316             _qmin_unsmeared = max([self.min, q_min-offset]) 
    317             _qmax_unsmeared = min([self.max, q_max+offset]) 
     332            offset = 3.0 * max(self.width) 
     333            _qmin_unsmeared = max([self.min, q_min - offset]) 
     334            _qmax_unsmeared = min([self.max, q_max + offset]) 
    318335        except: 
    319336            logging.error("_QSmearer.get_bin_range: %s" % sys.exc_value) 
     
    336353        ## Resolution 
    337354        self.width = numpy.zeros(len(data1D.x)) 
    338         if data1D.dx is not None and len(data1D.dx)==len(data1D.x): 
     355        if data1D.dx is not None and len(data1D.dx) == len(data1D.x): 
    339356            self.width = data1D.dx 
    340357         
     
    350367 
    351368if __name__ == '__main__': 
    352     x = 0.001*numpy.arange(1,11) 
    353     y = 12.0-numpy.arange(1,11) 
     369    x = 0.001 * numpy.arange(1, 11) 
     370    y = 12.0 - numpy.arange(1, 11) 
    354371    print x 
    355372    #for i in range(10): print i, 0.001 + i*0.008/9.0  
    356373    #for i in range(100): print i, int(math.floor( (i/ (100/9.0)) ))  
    357  
    358      
    359374    s = _SlitSmearer(nbins=10, width=0.0, height=0.005, min=0.001, max=0.010) 
    360375    #s = _QSmearer(nbins=10, width=0.001, min=0.001, max=0.010) 
     
    366381    if True: 
    367382        for i in range(10): 
    368             print x[i],y[i], sy[i] 
     383            print x[i], y[i], sy[i] 
    369384            #print q, ' : ', s.weight(q), s._compute_iq(q)  
    370385            #print q, ' : ', s(q), s._compute_iq(q)  
  • DataLoader/readers/IgorReader.py

    r0997158f ra7a5886  
    1515""" 
    1616 
    17 import os, sys 
     17import os 
     18#import sys 
    1819import numpy 
    19 import math, logging 
    20 from DataLoader.data_info import Data2D, Detector 
     20import math 
     21#import logging 
     22from DataLoader.data_info import Data2D 
     23from DataLoader.data_info import Detector 
    2124from DataLoader.manipulations import reader2D_converter 
    2225 
     
    100103                    wavelength = float(line_toks[1]) 
    101104                except: 
    102                     raise ValueError,"IgorReader: can't read this file, missing wavelength" 
     105                    msg = "IgorReader: can't read this file, missing wavelength" 
     106                    raise ValueError, msg 
    103107                 
    104108            #Find # of bins in a row assuming the detector is square. 
     
    130134                    wavelength = float(line_toks[1]) 
    131135                except: 
    132                     raise ValueError,"IgorReader: can't read this file, missing wavelength" 
     136                    msg = "IgorReader: can't read this file, missing wavelength" 
     137                    raise ValueError, msg 
    133138                # Distance in meters 
    134139                try: 
    135140                    distance = float(line_toks[3]) 
    136141                except: 
    137                     raise ValueError,"IgorReader: can't read this file, missing distance" 
     142                    msg = "IgorReader: can't read this file, missing distance" 
     143                    raise ValueError, msg 
    138144                 
    139145                # Distance in meters 
     
    141147                    transmission = float(line_toks[4]) 
    142148                except: 
    143                     raise ValueError,"IgorReader: can't read this file, missing transmission" 
     149                    msg = "IgorReader: can't read this file, " 
     150                    msg += "missing transmission" 
     151                    raise ValueError, msg 
    144152                                             
    145153            if line.count("LAMBDA")>0: 
     
    151159                line_toks = line.split() 
    152160                 
    153                 # Center in bin number: Must substrate 1 because the index starts from 1 
     161                # Center in bin number: Must substrate 1 because  
     162                #the index starts from 1 
    154163                center_x = float(line_toks[0])-1 
    155164                center_y = float(line_toks[1])-1 
     
    168177                    or center_x == None \ 
    169178                    or center_y == None: 
    170                     raise ValueError, "IgorReader:Missing information in data file" 
     179                    msg = "IgorReader:Missing information in data file" 
     180                    raise ValueError, msg 
    171181                 
    172182            if dataStarted == True: 
     
    190200                # Q = 4pi/lambda sin(theta/2) 
    191201                # Bin size is 0.5 cm  
    192                 #REmoved +1 from theta = (i_x-center_x+1)*0.5 / distance / 100.0 and  
    193                 #REmoved +1 from theta = (i_y-center_y+1)*0.5 / distance / 100.0 
    194                 #ToDo: Need  complete check if the following covert process is consistent with fitting.py. 
     202                #REmoved +1 from theta = (i_x-center_x+1)*0.5 / distance  
     203                # / 100.0 and  
     204                #REmoved +1 from theta = (i_y-center_y+1)*0.5 / 
     205                # distance / 100.0 
     206                #ToDo: Need  complete check if the following 
     207                # covert process is consistent with fitting.py. 
    195208                theta = (i_x-center_x)*0.5 / distance / 100.0 
    196209                qx = 4.0*math.pi/wavelength * math.sin(theta/2.0) 
  • DataLoader/readers/abs_reader.py

    r0997158f ra7a5886  
     1""" 
     2""" 
    13##################################################################### 
    24#This software was developed by the University of Tennessee as part of the 
     
    911import numpy 
    1012import os 
    11 from DataLoader.data_info import Data1D, Detector 
     13from DataLoader.data_info import Data1D 
     14from DataLoader.data_info import Detector 
    1215 
    1316has_converter = True 
     
    2629    type = ["IGOR 1D files (*.abs)|*.abs"] 
    2730    ## List of allowed extensions 
    28     ext=['.abs', '.ABS']   
     31    ext = ['.abs', '.ABS']   
    2932     
    3033    def read(self, path): 
     
    7881                     
    7982                    # Information line 1 
    80                     if is_info==True: 
     83                    if is_info == True: 
    8184                        is_info = False 
    8285                        line_toks = line.split() 
     
    8588                        try: 
    8689                            value = float(line_toks[1]) 
    87                             if has_converter==True and output.source.wavelength_unit != 'A': 
     90                            if has_converter == True and \ 
     91                                output.source.wavelength_unit != 'A': 
    8892                                conv = Converter('A') 
    89                                 output.source.wavelength = conv(value, units=output.source.wavelength_unit) 
     93                                output.source.wavelength = conv(value,  
     94                                        units=output.source.wavelength_unit) 
    9095                            else: 
    9196                                output.source.wavelength = value 
    9297                        except: 
    9398                            #goes to ASC reader 
    94                             raise  RuntimeError, "abs_reader: cannot open %s" % path 
    95                             #raise ValueError,"IgorReader: can't read this file, missing wavelength" 
     99                            msg = "abs_reader: cannot open %s" % path 
     100                            raise  RuntimeError, msg 
     101                            #raise ValueError,"IgorReader: can't read this file, 
     102                            # missing wavelength" 
    96103                         
    97104                        # Distance in meters 
    98105                        try: 
    99106                            value = float(line_toks[3]) 
    100                             if has_converter==True and detector.distance_unit != 'm': 
     107                            if has_converter == True and \ 
     108                                detector.distance_unit != 'm': 
    101109                                conv = Converter('m') 
    102                                 detector.distance = conv(value, units=detector.distance_unit) 
     110                                detector.distance = conv(value,  
     111                                                units=detector.distance_unit) 
    103112                            else: 
    104113                                detector.distance = value 
    105114                        except: 
    106115                            #goes to ASC reader 
    107                             raise  RuntimeError, "abs_reader: cannot open %s" % path 
    108                          
     116                            msg = "abs_reader: cannot open %s" % path 
     117                            raise  RuntimeError, msg 
    109118                        # Transmission  
    110119                        try: 
     
    117126                        try: 
    118127                            value = float(line_toks[5]) 
    119                             if has_converter==True and output.sample.thickness_unit != 'cm': 
     128                            if has_converter == True and \ 
     129                                output.sample.thickness_unit != 'cm': 
    120130                                conv = Converter('cm') 
    121                                 output.sample.thickness = conv(value, units=output.sample.thickness_unit) 
     131                                output.sample.thickness = conv(value,  
     132                                            units=output.sample.thickness_unit) 
    122133                            else: 
    123134                                output.sample.thickness = value 
     
    126137                            pass 
    127138                     
    128                     #MON CNT   LAMBDA   DET ANG   DET DIST   TRANS   THICK   AVE   STEP 
    129                     if line.count("LAMBDA")>0: 
     139                    #MON CNT   LAMBDA   DET ANG   DET DIST   TRANS   THICK  
     140                    #  AVE   STEP 
     141                    if line.count("LAMBDA") > 0: 
    130142                        is_info = True 
    131143                         
    132144                    # Find center info line 
    133                     if is_center==True: 
     145                    if is_center == True: 
    134146                        is_center = False                 
    135147                        line_toks = line.split() 
     
    139151                         
    140152                        # Bin size 
    141                         if has_converter==True and detector.pixel_size_unit != 'mm': 
     153                        if has_converter == True and \ 
     154                            detector.pixel_size_unit != 'mm': 
    142155                            conv = Converter('mm') 
    143                             detector.pixel_size.x = conv(5.0, units=detector.pixel_size_unit) 
    144                             detector.pixel_size.y = conv(5.0, units=detector.pixel_size_unit) 
     156                            detector.pixel_size.x = conv(5.0,  
     157                                                units=detector.pixel_size_unit) 
     158                            detector.pixel_size.y = conv(5.0, 
     159                                                units=detector.pixel_size_unit) 
    145160                        else: 
    146161                            detector.pixel_size.x = 5.0 
     
    149164                        # Store beam center in distance units 
    150165                        # Det 640 x 640 mm 
    151                         if has_converter==True and detector.beam_center_unit != 'mm': 
     166                        if has_converter==True and \ 
     167                            detector.beam_center_unit != 'mm': 
    152168                            conv = Converter('mm') 
    153                             detector.beam_center.x = conv(center_x*5.0, units=detector.beam_center_unit) 
    154                             detector.beam_center.y = conv(center_y*5.0, units=detector.beam_center_unit) 
     169                            detector.beam_center.x = conv(center_x * 5.0, 
     170                                             units=detector.beam_center_unit) 
     171                            detector.beam_center.y = conv(center_y * 5.0,  
     172                                            units=detector.beam_center_unit) 
    155173                        else: 
    156                             detector.beam_center.x = center_x*5.0 
    157                             detector.beam_center.y = center_y*5.0 
     174                            detector.beam_center.x = center_x * 5.0 
     175                            detector.beam_center.y = center_y * 5.0 
    158176                         
    159177                        # Detector type 
     
    164182                            pass 
    165183                     
    166                     #BCENT(X,Y)   A1(mm)   A2(mm)   A1A2DIST(m)   DL/L   BSTOP(mm)   DET_TYP  
    167                     if line.count("BCENT")>0: 
     184                    #BCENT(X,Y)   A1(mm)   A2(mm)   A1A2DIST(m)   DL/L  
     185                    #  BSTOP(mm)   DET_TYP  
     186                    if line.count("BCENT") > 0: 
    168187                        is_center = True 
    169188                         
    170189                    # Parse the data 
    171                     if is_data_started==True: 
     190                    if is_data_started == True: 
    172191                        toks = line.split() 
    173192 
     
    197216                            pass 
    198217                             
    199                     #The 6 columns are | Q (1/A) | I(Q) (1/cm) | std. dev. I(Q) (1/cm) | sigmaQ | meanQ | ShadowFactor| 
     218                    #The 6 columns are | Q (1/A) | I(Q) (1/cm) | std. dev. 
     219                    # I(Q) (1/cm) | sigmaQ | meanQ | ShadowFactor| 
    200220                    if line.count("The 6 columns")>0: 
    201221                        is_data_started = True 
     
    203223                # Sanity check 
    204224                if not len(y) == len(dy): 
    205                     raise ValueError, "abs_reader: y and dy have different length" 
    206  
     225                    msg = "abs_reader: y and dy have different length" 
     226                    raise ValueError, msg 
    207227                # If the data length is zero, consider this as 
    208228                # though we were not able to read the file. 
    209                 if len(x)==0: 
     229                if len(x) == 0: 
    210230                    raise ValueError, "ascii_reader: could not load file" 
    211                 
    212231                output.x = x 
    213232                output.y = y 
  • DataLoader/readers/ascii_reader.py

    rfca90f82 ra7a5886  
    3636            "ASCII files (*.abs)|*.abs"] 
    3737    ## List of allowed extensions 
    38     ext=['.txt', '.TXT', '.dat', '.DAT', '.abs', '.ABS']   
     38    ext = ['.txt', '.TXT', '.dat', '.DAT', '.abs', '.ABS']   
    3939     
    4040    ## Flag to bypass extension check 
     
    5454        if os.path.isfile(path): 
    5555            basename  = os.path.basename(path) 
    56             root, extension = os.path.splitext(basename) 
     56            _, extension = os.path.splitext(basename) 
    5757            if self.allow_all or extension.lower() in self.ext: 
    5858                try: 
     
    6363                lines = buff.split('\n') 
    6464                 
    65                 #Jae could not find python universal line spliter: keep the below for now 
    66                 # some ascii data has \r line separator, try it when the data is on only one long line 
     65                #Jae could not find python universal line spliter:  
     66                #keep the below for now 
     67                # some ascii data has \r line separator, 
     68                # try it when the data is on only one long line 
    6769                if len(lines) < 2 :  
    6870                    lines = buff.split('\r') 
     
    103105                #Initialize counters for data lines and header lines. 
    104106                is_data = False #Has more than 5 lines 
    105                 mum_data_lines = 5 # More than "5" lines of data is considered as actual data unless that is the only data 
    106  
    107                 i=-1            # To count # of current data candidate lines 
    108                 i1=-1           # To count total # of previous data candidate lines 
    109                 j=-1            # To count # of header lines 
    110                 j1=-1           # Helps to count # of header lines 
    111                 lentoks = 2     # minimum required number of columns of data; ( <= 4). 
    112                  
     107                # More than "5" lines of data is considered as actual 
     108                # data unless that is the only data 
     109                mum_data_lines = 5  
     110                # To count # of current data candidate lines 
     111                i = -1   
     112                # To count total # of previous data candidate lines           
     113                i1 = -1  
     114                # To count # of header lines           
     115                j = -1 
     116                # Helps to count # of header lines             
     117                j1 = -1 
     118                #minimum required number of columns of data; ( <= 4).            
     119                lentoks = 2      
    113120                for line in lines: 
    114121                    toks = line.split() 
    115                      
    116122                    try: 
    117123                        #Make sure that all columns are numbers. 
     
    140146                        # third column. 
    141147                        _dy = None 
    142                         if len(toks)>2: 
     148                        if len(toks) > 2: 
    143149                            try: 
    144150                                _dy = float(toks[2]) 
     
    158164                        #Check for dx 
    159165                        _dx = None 
    160                         if len(toks)>3: 
     166                        if len(toks) > 3: 
    161167                            try: 
    162168                                _dx = float(toks[3]) 
     
    174180                            has_error_dx = False if _dx == None else True 
    175181                         
    176                         #After talked with PB, we decided to take care of only 4 columns of data for now. 
     182                        #After talked with PB, we decided to take care of only  
     183                        # 4 columns of data for now. 
    177184                        #number of columns in the current line 
    178                         #To remember the # of columns in the current line of data 
     185                        #To remember the # of columns in the current  
     186                        #line of data 
    179187                        new_lentoks = len(toks) 
    180188                         
    181                         #If the previous columns not equal to the current, mark the previous as non-data and reset the dependents.   
     189                        #If the previous columns not equal to the current,  
     190                        #mark the previous as non-data and reset the dependents.   
    182191                        if lentoks != new_lentoks : 
    183192                            if is_data == True: 
     
    190199                             
    191200                             
    192                         #Delete the previously stored lines of data candidates if is not data. 
    193                         if i < 0 and -1< i1 < mum_data_lines and is_data == False: 
     201                        #Delete the previously stored lines of data candidates 
     202                        # if is not data. 
     203                        if i < 0 and -1 < i1 < mum_data_lines and \ 
     204                            is_data == False: 
    194205                            try: 
    195                                 x= numpy.zeros(0) 
    196                                 y= numpy.zeros(0) 
    197                                  
     206                                x = numpy.zeros(0) 
     207                                y = numpy.zeros(0) 
    198208                            except: 
    199209                                pass 
     
    203213                         
    204214                        if has_error_dy == True: 
    205                             #Delete the previously stored lines of data candidates if is not data. 
    206                             if i < 0 and -1< i1 < mum_data_lines and is_data== False: 
     215                            #Delete the previously stored lines of 
     216                            # data candidates if is not data. 
     217                            if i < 0 and -1 < i1 < mum_data_lines and \ 
     218                                is_data == False: 
    207219                                try: 
    208220                                    dy = numpy.zeros(0)   
     
    212224                             
    213225                        if has_error_dx == True: 
    214                             #Delete the previously stored lines of data candidates if is not data. 
    215                             if i < 0 and -1< i1 < mum_data_lines and is_data== False: 
     226                            #Delete the previously stored lines of 
     227                            # data candidates if is not data. 
     228                            if i < 0 and -1 < i1 < mum_data_lines and \ 
     229                                is_data == False: 
    216230                                try: 
    217231                                    dx = numpy.zeros(0)                             
     
    221235                             
    222236                        #Same for temp. 
    223                         #Delete the previously stored lines of data candidates if is not data. 
    224                         if i < 0 and -1< i1 < mum_data_lines and is_data== False: 
     237                        #Delete the previously stored lines of data candidates 
     238                        # if is not data. 
     239                        if i < 0 and -1 < i1 < mum_data_lines and\ 
     240                            is_data == False: 
    225241                            try: 
    226242                                tx = numpy.zeros(0) 
    227243                                ty = numpy.zeros(0) 
    228244                            except: 
    229                                 pass                                                                
     245                                pass                                                            
    230246 
    231247                        tx  = numpy.append(tx,   _x)  
     
    233249                         
    234250                        if has_error_dy == True: 
    235                             #Delete the previously stored lines of data candidates if is not data. 
    236                             if i < 0 and -1<i1 < mum_data_lines and is_data== False: 
     251                            #Delete the previously stored lines of 
     252                            # data candidates if is not data. 
     253                            if i < 0 and -1 < i1 < mum_data_lines and \ 
     254                                is_data == False: 
    237255                                try: 
    238256                                    tdy = numpy.zeros(0) 
     
    241259                            tdy = numpy.append(tdy, _dy) 
    242260                        if has_error_dx == True: 
    243                             #Delete the previously stored lines of data candidates if is not data. 
    244                             if i < 0 and -1< i1 < mum_data_lines and is_data== False: 
     261                            #Delete the previously stored lines of 
     262                            # data candidates if is not data. 
     263                            if i < 0 and -1 < i1 < mum_data_lines and \ 
     264                                is_data == False: 
    245265                                try: 
    246266                                    tdx = numpy.zeros(0) 
    247267                                except: 
    248                                     pass                                                                                                              
     268                                    pass                                                                                                           
    249269                            tdx = numpy.append(tdx, _dx) 
    250270 
    251271                        #reset i1 and flag lentoks for the next 
    252                         if lentoks < new_lentoks : 
     272                        if lentoks < new_lentoks: 
    253273                            if is_data == False: 
    254274                                i1 = -1                             
    255                         #To remember the # of columns on the current line for the next line of data 
     275                        #To remember the # of columns on the current line 
     276                        # for the next line of data 
    256277                        lentoks = len(toks) 
    257278                         
    258                         #Reset # of header lines and counts # of data candidate lines     
    259                         if j == 0 and j1 ==0: 
     279                        #Reset # of header lines and counts #  
     280                        # of data candidate lines     
     281                        if j == 0 and j1 == 0: 
    260282                            i1 = i + 1                             
    261                         i+=1 
    262                          
     283                        i += 1 
    263284                    except: 
    264285 
     
    268289                        lentoks = 2 
    269290                        #Counting # of header lines                     
    270                         j+=1 
    271                         if j == j1+1: 
     291                        j += 1 
     292                        if j == j1 + 1: 
    272293                            j1 = j                             
    273294                        else:                             
     
    279300                        pass 
    280301                     
    281      
    282302                input_f.close()      
    283303                # Sanity check 
    284304                if has_error_dy == True and not len(y) == len(dy): 
    285                     raise RuntimeError, "ascii_reader: y and dy have different length" 
     305                    msg = "ascii_reader: y and dy have different length" 
     306                    raise RuntimeError, msg 
    286307                if has_error_dx == True and not len(x) == len(dx): 
    287                     raise RuntimeError, "ascii_reader: y and dy have different length" 
    288  
     308                    msg = "ascii_reader: y and dy have different length" 
     309                    raise RuntimeError, msg 
    289310                # If the data length is zero, consider this as 
    290311                # though we were not able to read the file. 
    291                 if len(x)==0: 
     312                if len(x) == 0: 
    292313                    raise RuntimeError, "ascii_reader: could not load file" 
    293314                 
    294                 #Let's re-order the data to make cal. curve look better some cases 
    295                 ind = numpy.lexsort((ty,tx)) 
     315                #Let's re-order the data to make cal. 
     316                # curve look better some cases 
     317                ind = numpy.lexsort((ty, tx)) 
    296318                for i in ind: 
    297319                    x[i] = tx[ind[i]] 
     
    301323                    if has_error_dx == True: 
    302324                        dx[i] = tdx[ind[i]] 
    303                  
    304                  
    305325                #Data     
    306326                output.x = x 
  • DataLoader/readers/associations.py

    r0997158f ra7a5886  
    1919""" 
    2020 
    21 import os, sys 
     21import os 
     22import sys 
    2223import logging 
    2324from lxml import etree  
     
    5253         
    5354        # Read in the file extension associations 
    54         entry_list = root.xpath('/ns:SansLoader/ns:FileType', namespaces={'ns': VERSION}) 
     55        entry_list = root.xpath('/ns:SansLoader/ns:FileType', 
     56                                 namespaces={'ns': VERSION}) 
    5557 
    5658        # For each FileType entry, get the associated reader and extension 
     
    6163            if reader is not None and ext is not None: 
    6264                # Associate the extension with a particular reader 
    63                 # TODO: Modify the Register code to be case-insensitive and remove the 
    64                 #       extra line below. 
     65                # TODO: Modify the Register code to be case-insensitive  
     66                # and remove the extra line below. 
    6567                try: 
    6668                    exec "import %s" % reader 
    67                     exec "loader.associate_file_type('%s', %s)" % (ext.lower(), reader) 
    68                     exec "loader.associate_file_type('%s', %s)" % (ext.upper(), reader) 
     69                    exec "loader.associate_file_type('%s', %s)" % (ext.lower(), 
     70                                                                    reader) 
     71                    exec "loader.associate_file_type('%s', %s)" % (ext.upper(), 
     72                                                                    reader) 
    6973                except: 
    70                     logging.error("read_associations: skipping association for %s\n  %s" % (attr['extension'], sys.exc_value)) 
     74                    msg = "read_associations: skipping association" 
     75                    msg += " for %s\n  %s" % (attr['extension'], sys.exc_value) 
     76                    logging.error(msg) 
    7177          
    7278          
  • DataLoader/readers/cansas_reader.py

    r7406040 ra7a5886  
    1515# within a single SASentry. Will raise a runtime error. 
    1616 
    17 #TODO: check that all vectors are written only if they have at least one non-empty value 
    18 #TODO: Writing only allows one SASentry per file. Would be best to allow multiple entries. 
     17#TODO: check that all vectors are written only if they have at  
     18#    least one non-empty value 
     19#TODO: Writing only allows one SASentry per file. 
     20#     Would be best to allow multiple entries. 
    1921#TODO: Store error list 
    2022#TODO: Allow for additional meta data for each section 
    21 #TODO: Notes need to be implemented. They can be any XML structure in version 1.0 
     23#TODO: Notes need to be implemented. They can be any XML  
     24#    structure in version 1.0 
    2225#      Process notes have the same problem. 
    2326#TODO: Unit conversion is not complete (temperature units are missing) 
     
    2629import logging 
    2730import numpy 
    28 import os, sys 
    29 from DataLoader.data_info import Data1D, Collimation, Detector, Process, Aperture 
     31import os 
     32import sys 
     33from DataLoader.data_info import Data1D 
     34from DataLoader.data_info import Collimation 
     35from DataLoader.data_info import Detector 
     36from DataLoader.data_info import Process 
     37from DataLoader.data_info import Aperture 
    3038from lxml import etree 
    3139import xml.dom.minidom 
     
    8593    value = None 
    8694    attr = {} 
    87      
    88     if len(nodes)>0: 
     95    if len(nodes) > 0: 
    8996        try: 
    9097            value = float(nodes[0].text)    
    9198        except: 
    9299            # Could not pass, skip and return None 
    93             logging.error("cansas_reader.get_float: could not convert '%s' to float" % nodes[0].text) 
    94          
     100            msg = "cansas_reader.get_float: could not " 
     101            msg += " convert '%s' to float" % nodes[0].text 
     102            logging.error(msg) 
    95103        if nodes[0].get('unit') is not None: 
    96104            attr['unit'] = nodes[0].get('unit') 
    97              
    98105    return value, attr 
    99106 
    100107             
    101  
    102108class Reader: 
    103109    """ 
     
    117123 
    118124    ## List of allowed extensions 
    119     ext=['.xml', '.XML','.avex', '.AVEx', '.absx', 'ABSx']   
     125    ext = ['.xml', '.XML','.avex', '.AVEx', '.absx', 'ABSx']   
    120126     
    121127    def __init__(self): 
     
    144150                tree = etree.parse(path, parser=etree.ETCompatXMLParser()) 
    145151                # Check the format version number 
    146                 # Specifying the namespace will take care of the file format version  
     152                # Specifying the namespace will take care of the file 
     153                # format version  
    147154                root = tree.getroot() 
    148155                 
    149                 entry_list = root.xpath('/ns:SASroot/ns:SASentry', namespaces={'ns': CANSAS_NS}) 
     156                entry_list = root.xpath('/ns:SASroot/ns:SASentry', 
     157                                         namespaces={'ns': CANSAS_NS}) 
    150158                 
    151159                for entry in entry_list: 
     
    196204                            
    197205        # Look up instrument name               
    198         self._store_content('ns:SASinstrument/ns:name', dom, 'instrument', data_info) 
     206        self._store_content('ns:SASinstrument/ns:name', dom, 'instrument', 
     207                             data_info) 
    199208 
    200209        # Notes 
     
    207216                        data_info.notes.append(note_value) 
    208217            except: 
    209                 err_mess = "cansas_reader.read: error processing entry notes\n  %s" % sys.exc_value 
     218                err_mess = "cansas_reader.read: error processing" 
     219                err_mess += " entry notes\n  %s" % sys.exc_value 
    210220                self.errors.append(err_mess) 
    211221                logging.error(err_mess) 
     
    225235                     dom, 'temperature', data_info.sample) 
    226236         
    227         nodes = dom.xpath('ns:SASsample/ns:details', namespaces={'ns': CANSAS_NS}) 
     237        nodes = dom.xpath('ns:SASsample/ns:details',  
     238                          namespaces={'ns': CANSAS_NS}) 
    228239        for item in nodes: 
    229240            try: 
     
    233244                        data_info.sample.details.append(detail_value) 
    234245            except: 
    235                 err_mess = "cansas_reader.read: error processing sample details\n  %s" % sys.exc_value 
     246                err_mess = "cansas_reader.read: error processing " 
     247                err_mess += " sample details\n  %s" % sys.exc_value 
    236248                self.errors.append(err_mess) 
    237249                logging.error(err_mess) 
     
    284296         
    285297        # Collimation info ################### 
    286         nodes = dom.xpath('ns:SASinstrument/ns:SAScollimation', namespaces={'ns': CANSAS_NS}) 
     298        nodes = dom.xpath('ns:SASinstrument/ns:SAScollimation',  
     299                          namespaces={'ns': CANSAS_NS}) 
    287300        for item in nodes: 
    288301            collim = Collimation() 
     
    315328         
    316329        # Detector info ###################### 
    317         nodes = dom.xpath('ns:SASinstrument/ns:SASdetector', namespaces={'ns': CANSAS_NS}) 
     330        nodes = dom.xpath('ns:SASinstrument/ns:SASdetector', 
     331                           namespaces={'ns': CANSAS_NS}) 
    318332        for item in nodes: 
    319333             
     
    329343             
    330344            # Detector orientation (as a vector) 
    331             self._store_float('ns:orientation/ns:roll',  item, 'orientation.x', detector)     
    332             self._store_float('ns:orientation/ns:pitch', item, 'orientation.y', detector)     
    333             self._store_float('ns:orientation/ns:yaw',   item, 'orientation.z', detector)     
     345            self._store_float('ns:orientation/ns:roll',  item, 'orientation.x', 
     346                               detector)     
     347            self._store_float('ns:orientation/ns:pitch', item, 'orientation.y', 
     348                               detector)     
     349            self._store_float('ns:orientation/ns:yaw',   item, 'orientation.z', 
     350                               detector)     
    334351             
    335352            # Beam center (as a vector) 
    336             self._store_float('ns:beam_center/ns:x', item, 'beam_center.x', detector)     
    337             self._store_float('ns:beam_center/ns:y', item, 'beam_center.y', detector)     
    338             self._store_float('ns:beam_center/ns:z', item, 'beam_center.z', detector)     
     353            self._store_float('ns:beam_center/ns:x', item, 'beam_center.x', 
     354                               detector)     
     355            self._store_float('ns:beam_center/ns:y', item, 'beam_center.y',  
     356                              detector)     
     357            self._store_float('ns:beam_center/ns:z', item, 'beam_center.z', 
     358                               detector)     
    339359             
    340360            # Pixel size (as a vector) 
    341             self._store_float('ns:pixel_size/ns:x', item, 'pixel_size.x', detector)     
    342             self._store_float('ns:pixel_size/ns:y', item, 'pixel_size.y', detector)     
    343             self._store_float('ns:pixel_size/ns:z', item, 'pixel_size.z', detector)     
     361            self._store_float('ns:pixel_size/ns:x', item, 'pixel_size.x', 
     362                               detector)     
     363            self._store_float('ns:pixel_size/ns:y', item, 'pixel_size.y', 
     364                               detector)     
     365            self._store_float('ns:pixel_size/ns:z', item, 'pixel_size.z', 
     366                               detector)     
    344367             
    345368            self._store_float('ns:slit_length', item, 'slit_length', detector) 
     
    365388                        process.term.append(term_attr) 
    366389                except: 
    367                     err_mess = "cansas_reader.read: error processing process term\n  %s" % sys.exc_value 
     390                    err_mess = "cansas_reader.read: error processing " 
     391                    err_mess += " process term\n  %s" % sys.exc_value 
    368392                    self.errors.append(err_mess) 
    369393                    logging.error(err_mess) 
    370394             
    371             note_list = item.xpath('ns:SASprocessnote', namespaces={'ns': CANSAS_NS}) 
     395            note_list = item.xpath('ns:SASprocessnote',  
     396                                   namespaces={'ns': CANSAS_NS}) 
    372397            for note in note_list: 
    373398                if note.text is not None: 
     
    379404        # Data info ###################### 
    380405        nodes = dom.xpath('ns:SASdata', namespaces={'ns': CANSAS_NS}) 
    381         if len(nodes)>1: 
    382             raise RuntimeError, "CanSAS reader is not compatible with multiple SASdata entries" 
     406        if len(nodes) > 1: 
     407            msg = "CanSAS reader is not compatible with multiple" 
     408            msg += " SASdata entries" 
     409            raise RuntimeError, msg 
    383410         
    384411        nodes = dom.xpath('ns:SASdata/ns:Idata', namespaces={'ns': CANSAS_NS}) 
     
    403430                _dxw = 0.0 
    404431                 
    405             if attr.has_key('unit') and attr['unit'].lower() != data_info.x_unit.lower(): 
     432            if attr.has_key('unit') and \ 
     433                attr['unit'].lower() != data_info.x_unit.lower(): 
    406434                if has_converter==True: 
    407435                    try: 
     
    409437                        _x = data_conv_q(_x, units=data_info.x_unit) 
    410438                    except: 
    411                         raise ValueError, "CanSAS reader: could not convert Q unit [%s]; expecting [%s]\n  %s" \ 
    412                         % (attr['unit'], data_info.x_unit, sys.exc_value) 
     439                        msg =  "CanSAS reader: could not convert " 
     440                        msg += "Q unit [%s]; "  
     441                        msg += "expecting [%s]\n  %s" % (attr['unit'],  
     442                                  data_info.x_unit, sys.exc_value) 
     443                        raise ValueError, msg 
     444                         
    413445                else: 
    414                     raise ValueError, "CanSAS reader: unrecognized Q unit [%s]; expecting [%s]" \ 
    415                         % (attr['unit'], data_info.x_unit) 
     446                    msg = "CanSAS reader: unrecognized Q unit [%s]; " 
     447                    msg += "expecting [%s]" % (attr['unit'], data_info.x_unit) 
     448                    raise ValueError, msg 
     449                         
    416450            # Error in Q 
    417             if attr_d.has_key('unit') and attr_d['unit'].lower() != data_info.x_unit.lower(): 
     451            if attr_d.has_key('unit') and \ 
     452                attr_d['unit'].lower() != data_info.x_unit.lower(): 
    418453                if has_converter==True: 
    419454                    try: 
     
    421456                        _dx = data_conv_q(_dx, units=data_info.x_unit) 
    422457                    except: 
    423                         raise ValueError, "CanSAS reader: could not convert dQ unit [%s]; expecting [%s]\n  %s" \ 
    424                         % (attr['unit'], data_info.x_unit, sys.exc_value) 
     458                        msg = "CanSAS reader: could not convert dQ unit [%s];" 
     459                        msg += " expecting "  
     460                        msg += "[%s]\n  %s" % (attr['unit'], 
     461                                                data_info.x_unit, sys.exc_value) 
     462                        raise ValueError, msg 
     463                         
    425464                else: 
    426                     raise ValueError, "CanSAS reader: unrecognized dQ unit [%s]; expecting [%s]" \ 
    427                         % (attr['unit'], data_info.x_unit) 
     465                    msg = "CanSAS reader: unrecognized dQ unit [%s]; " 
     466                    msg += "expecting [%s]" % (attr['unit'], data_info.x_unit) 
     467                    raise ValueError,  msg 
     468                         
    428469            # Slit length 
    429             if attr_l.has_key('unit') and attr_l['unit'].lower() != data_info.x_unit.lower(): 
    430                 if has_converter==True: 
     470            if attr_l.has_key('unit') and \ 
     471                attr_l['unit'].lower() != data_info.x_unit.lower(): 
     472                if has_converter == True: 
    431473                    try: 
    432474                        data_conv_q = Converter(attr_l['unit']) 
    433475                        _dxl = data_conv_q(_dxl, units=data_info.x_unit) 
    434476                    except: 
    435                         raise ValueError, "CanSAS reader: could not convert dQl unit [%s]; expecting [%s]\n  %s" \ 
    436                         % (attr['unit'], data_info.x_unit, sys.exc_value) 
     477                        msg = "CanSAS reader: could not convert dQl unit [%s];" 
     478                        msg += " expecting [%s]\n  %s" % (attr['unit'], 
     479                                             data_info.x_unit, sys.exc_value) 
     480                        raise ValueError, msg 
     481                         
    437482                else: 
    438                     raise ValueError, "CanSAS reader: unrecognized dQl unit [%s]; expecting [%s]" \ 
    439                         % (attr['unit'], data_info.x_unit) 
     483                    msg = "CanSAS reader: unrecognized dQl unit [%s];" 
     484                    msg += " expecting [%s]" % (attr['unit'], data_info.x_unit) 
     485                    raise ValueError, msg 
     486                         
    440487            # Slit width 
    441             if attr_w.has_key('unit') and attr_w['unit'].lower() != data_info.x_unit.lower(): 
    442                 if has_converter==True: 
     488            if attr_w.has_key('unit') and \ 
     489            attr_w['unit'].lower() != data_info.x_unit.lower(): 
     490                if has_converter == True: 
    443491                    try: 
    444492                        data_conv_q = Converter(attr_w['unit']) 
    445493                        _dxw = data_conv_q(_dxw, units=data_info.x_unit) 
    446494                    except: 
    447                         raise ValueError, "CanSAS reader: could not convert dQw unit [%s]; expecting [%s]\n  %s" \ 
    448                         % (attr['unit'], data_info.x_unit, sys.exc_value) 
     495                        msg = "CanSAS reader: could not convert dQw unit [%s];" 
     496                        msg += " expecting [%s]\n  %s" % (attr['unit'],  
     497                                                data_info.x_unit, sys.exc_value) 
     498                        raise ValueError, msg 
     499                         
    449500                else: 
    450                     raise ValueError, "CanSAS reader: unrecognized dQw unit [%s]; expecting [%s]" \ 
    451                         % (attr['unit'], data_info.x_unit) 
    452                      
     501                    msg = "CanSAS reader: unrecognized dQw unit [%s];" 
     502                    msg += " expecting [%s]" % (attr['unit'], data_info.x_unit) 
     503                    raise ValueError, msg    
    453504            _y, attr = get_float('ns:I', item) 
    454505            _dy, attr_d = get_float('ns:Idev', item) 
    455506            if _dy == None: 
    456507                _dy = 0.0 
    457             if attr.has_key('unit') and attr['unit'].lower() != data_info.y_unit.lower(): 
     508            if attr.has_key('unit') and \ 
     509            attr['unit'].lower() != data_info.y_unit.lower(): 
    458510                if has_converter==True: 
    459511                    try: 
     
    461513                        _y = data_conv_i(_y, units=data_info.y_unit) 
    462514                    except: 
    463                         raise ValueError, "CanSAS reader: could not convert I(q) unit [%s]; expecting [%s]\n  %s" \ 
    464                         % (attr['unit'], data_info.y_unit, sys.exc_value) 
     515                        msg = "CanSAS reader: could not convert I(q) unit [%s];" 
     516                        msg += " expecting [%s]\n  %s" % (attr['unit'],  
     517                                            data_info.y_unit, sys.exc_value) 
     518                        raise ValueError, msg 
    465519                else: 
    466                     raise ValueError, "CanSAS reader: unrecognized I(q) unit [%s]; expecting [%s]" \ 
    467                         % (attr['unit'], data_info.y_unit) 
    468             if attr_d.has_key('unit') and attr_d['unit'].lower() != data_info.y_unit.lower(): 
     520                    msg = "CanSAS reader: unrecognized I(q) unit [%s];" 
     521                    msg += " expecting [%s]" % (attr['unit'], data_info.y_unit) 
     522                    raise ValueError, msg  
     523                         
     524            if attr_d.has_key('unit') and \ 
     525            attr_d['unit'].lower() != data_info.y_unit.lower(): 
    469526                if has_converter==True: 
    470527                    try: 
     
    472529                        _dy = data_conv_i(_dy, units=data_info.y_unit) 
    473530                    except: 
    474                         raise ValueError, "CanSAS reader: could not convert dI(q) unit [%s]; expecting [%s]\n  %s" \ 
    475                         % (attr_d['unit'], data_info.y_unit, sys.exc_value) 
     531                        msg = "CanSAS reader: could not convert dI(q) unit " 
     532                        msg += "[%s]; expecting [%s]\n  %s"  % (attr_d['unit'], 
     533                                             data_info.y_unit, sys.exc_value) 
     534                        raise ValueError, msg 
    476535                else: 
    477                     raise ValueError, "CanSAS reader: unrecognized dI(q) unit [%s]; expecting [%s]" \ 
    478                         % (attr_d['unit'], data_info.y_unit) 
     536                    msg = "CanSAS reader: unrecognized dI(q) unit [%s]; " 
     537                    msg += "expecting [%s]" % (attr_d['unit'], data_info.y_unit) 
     538                    raise ValueError, msg 
    479539                 
    480540            if _x is not None and _y is not None: 
     
    486546                dxw = numpy.append(dxw, _dxw) 
    487547                 
    488              
    489548        data_info.x = x 
    490549        data_info.y = y 
     
    532591        main_node.setAttribute("version", self.version) 
    533592        main_node.setAttribute("xmlns", "cansas1d/%s" % self.version) 
    534         main_node.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance") 
    535         main_node.setAttribute("xsi:schemaLocation", "cansas1d/%s http://svn.smallangles.net/svn/canSAS/1dwg/trunk/cansas1d.xsd" % self.version) 
     593        main_node.setAttribute("xmlns:xsi", 
     594                               "http://www.w3.org/2001/XMLSchema-instance") 
     595        main_node.setAttribute("xsi:schemaLocation", 
     596                               "cansas1d/%s http://svn.smallangles.net/svn/canSAS/1dwg/trunk/cansas1d.xsd" % self.version) 
    536597         
    537598        doc.appendChild(main_node) 
     
    543604        for item in datainfo.run: 
    544605            runname = {} 
    545             if datainfo.run_name.has_key(item) and len(str(datainfo.run_name[item]))>1: 
     606            if datainfo.run_name.has_key(item) and \ 
     607            len(str(datainfo.run_name[item]))>1: 
    546608                runname = {'name': datainfo.run_name[item] } 
    547609            write_node(doc, entry_node, "Run", item, runname) 
     
    556618            write_node(doc, pt, "Q", datainfo.x[i], {'unit':datainfo.x_unit}) 
    557619            if len(datainfo.y)>=i: 
    558                 write_node(doc, pt, "I", datainfo.y[i], {'unit':datainfo.y_unit}) 
     620                write_node(doc, pt, "I", datainfo.y[i], 
     621                            {'unit':datainfo.y_unit}) 
    559622            if datainfo.dx !=None and len(datainfo.dx)>=i: 
    560                 write_node(doc, pt, "Qdev", datainfo.dx[i], {'unit':datainfo.x_unit}) 
     623                write_node(doc, pt, "Qdev", datainfo.dx[i], 
     624                            {'unit':datainfo.x_unit}) 
    561625            if datainfo.dy !=None and len(datainfo.dy)>=i: 
    562                 write_node(doc, pt, "Idev", datainfo.dy[i], {'unit':datainfo.y_unit}) 
     626                write_node(doc, pt, "Idev", datainfo.dy[i], 
     627                            {'unit':datainfo.y_unit}) 
    563628 
    564629         
     
    569634        entry_node.appendChild(sample) 
    570635        write_node(doc, sample, "ID", str(datainfo.sample.ID)) 
    571         write_node(doc, sample, "thickness", datainfo.sample.thickness, {"unit":datainfo.sample.thickness_unit}) 
     636        write_node(doc, sample, "thickness", datainfo.sample.thickness, 
     637                   {"unit":datainfo.sample.thickness_unit}) 
    572638        write_node(doc, sample, "transmission", datainfo.sample.transmission) 
    573         write_node(doc, sample, "temperature", datainfo.sample.temperature, {"unit":datainfo.sample.temperature_unit}) 
     639        write_node(doc, sample, "temperature", datainfo.sample.temperature, 
     640                   {"unit":datainfo.sample.temperature_unit}) 
    574641         
    575642        for item in datainfo.sample.details: 
     
    577644         
    578645        pos = doc.createElement("position") 
    579         written = write_node(doc, pos, "x", datainfo.sample.position.x, {"unit":datainfo.sample.position_unit}) 
    580         written = written | write_node(doc, pos, "y", datainfo.sample.position.y, {"unit":datainfo.sample.position_unit}) 
    581         written = written | write_node(doc, pos, "z", datainfo.sample.position.z, {"unit":datainfo.sample.position_unit}) 
     646        written = write_node(doc, pos, "x", datainfo.sample.position.x, 
     647                             {"unit":datainfo.sample.position_unit}) 
     648        written = written | write_node(doc, pos, "y", 
     649                                       datainfo.sample.position.y, 
     650                                       {"unit":datainfo.sample.position_unit}) 
     651        written = written | write_node(doc, pos, "z", 
     652                                       datainfo.sample.position.z, 
     653                                       {"unit":datainfo.sample.position_unit}) 
    582654        if written == True: 
    583655            sample.appendChild(pos) 
    584656         
    585657        ori = doc.createElement("orientation") 
    586         written = write_node(doc, ori, "roll",  datainfo.sample.orientation.x, {"unit":datainfo.sample.orientation_unit}) 
    587         written = written | write_node(doc, ori, "pitch", datainfo.sample.orientation.y, {"unit":datainfo.sample.orientation_unit}) 
    588         written = written | write_node(doc, ori, "yaw",   datainfo.sample.orientation.z, {"unit":datainfo.sample.orientation_unit}) 
     658        written = write_node(doc, ori, "roll", 
     659                             datainfo.sample.orientation.x, 
     660                             {"unit":datainfo.sample.orientation_unit}) 
     661        written = written | write_node(doc, ori, "pitch", 
     662                                       datainfo.sample.orientation.y, 
     663                                    {"unit":datainfo.sample.orientation_unit}) 
     664        written = written | write_node(doc, ori, "yaw", 
     665                                       datainfo.sample.orientation.z, 
     666                                    {"unit":datainfo.sample.orientation_unit}) 
    589667        if written == True: 
    590668            sample.appendChild(ori) 
     
    607685        if datainfo.source.beam_size_name is not None: 
    608686            size.setAttribute("name", str(datainfo.source.beam_size_name)) 
    609         written = write_node(doc, size, "x", datainfo.source.beam_size.x, {"unit":datainfo.source.beam_size_unit}) 
    610         written = written | write_node(doc, size, "y", datainfo.source.beam_size.y, {"unit":datainfo.source.beam_size_unit}) 
    611         written = written | write_node(doc, size, "z", datainfo.source.beam_size.z, {"unit":datainfo.source.beam_size_unit}) 
     687        written = write_node(doc, size, "x", datainfo.source.beam_size.x, 
     688                             {"unit":datainfo.source.beam_size_unit}) 
     689        written = written | write_node(doc, size, "y", 
     690                                       datainfo.source.beam_size.y, 
     691                                       {"unit":datainfo.source.beam_size_unit}) 
     692        written = written | write_node(doc, size, "z", 
     693                                       datainfo.source.beam_size.z, 
     694                                       {"unit":datainfo.source.beam_size_unit}) 
    612695        if written == True: 
    613696            source.appendChild(size) 
    614697             
    615         write_node(doc, source, "wavelength", datainfo.source.wavelength, {"unit":datainfo.source.wavelength_unit}) 
    616         write_node(doc, source, "wavelength_min", datainfo.source.wavelength_min, {"unit":datainfo.source.wavelength_min_unit}) 
    617         write_node(doc, source, "wavelength_max", datainfo.source.wavelength_max, {"unit":datainfo.source.wavelength_max_unit}) 
    618         write_node(doc, source, "wavelength_spread", datainfo.source.wavelength_spread, {"unit":datainfo.source.wavelength_spread_unit}) 
     698        write_node(doc, source, "wavelength", 
     699                   datainfo.source.wavelength, 
     700                   {"unit":datainfo.source.wavelength_unit}) 
     701        write_node(doc, source, "wavelength_min", 
     702                   datainfo.source.wavelength_min, 
     703                   {"unit":datainfo.source.wavelength_min_unit}) 
     704        write_node(doc, source, "wavelength_max", 
     705                   datainfo.source.wavelength_max, 
     706                   {"unit":datainfo.source.wavelength_max_unit}) 
     707        write_node(doc, source, "wavelength_spread", 
     708                   datainfo.source.wavelength_spread, 
     709                   {"unit":datainfo.source.wavelength_spread_unit}) 
    619710         
    620711        #   Collimation 
     
    625716            instr.appendChild(coll) 
    626717             
    627             write_node(doc, coll, "length", item.length, {"unit":item.length_unit}) 
     718            write_node(doc, coll, "length", item.length, 
     719                       {"unit":item.length_unit}) 
    628720             
    629721            for apert in item.aperture: 
     
    635727                coll.appendChild(ap) 
    636728                 
    637                 write_node(doc, ap, "distance", apert.distance, {"unit":apert.distance_unit}) 
     729                write_node(doc, ap, "distance", apert.distance, 
     730                           {"unit":apert.distance_unit}) 
    638731                 
    639732                size = doc.createElement("size") 
    640733                if apert.size_name is not None: 
    641734                    size.setAttribute("name", str(apert.size_name)) 
    642                 written = write_node(doc, size, "x", apert.size.x, {"unit":apert.size_unit}) 
    643                 written = written | write_node(doc, size, "y", apert.size.y, {"unit":apert.size_unit}) 
    644                 written = written | write_node(doc, size, "z", apert.size.z, {"unit":apert.size_unit}) 
     735                written = write_node(doc, size, "x", apert.size.x, 
     736                                     {"unit":apert.size_unit}) 
     737                written = written | write_node(doc, size, "y", apert.size.y, 
     738                                               {"unit":apert.size_unit}) 
     739                written = written | write_node(doc, size, "z", apert.size.z, 
     740                                               {"unit":apert.size_unit}) 
    645741                if written == True: 
    646742                    ap.appendChild(size) 
     
    650746            det = doc.createElement("SASdetector") 
    651747            written = write_node(doc, det, "name", item.name) 
    652             written = written | write_node(doc, det, "SDD", item.distance, {"unit":item.distance_unit}) 
    653             written = written | write_node(doc, det, "slit_length", item.slit_length, {"unit":item.slit_length_unit}) 
     748            written = written | write_node(doc, det, "SDD", item.distance, 
     749                                           {"unit":item.distance_unit}) 
     750            written = written | write_node(doc, det, "slit_length", 
     751                                           item.slit_length, 
     752                                           {"unit":item.slit_length_unit}) 
    654753            if written == True: 
    655754                instr.appendChild(det) 
    656755             
    657756            off = doc.createElement("offset") 
    658             written = write_node(doc, off, "x", item.offset.x, {"unit":item.offset_unit}) 
    659             written = written | write_node(doc, off, "y", item.offset.y, {"unit":item.offset_unit}) 
    660             written = written | write_node(doc, off, "z", item.offset.z, {"unit":item.offset_unit}) 
     757            written = write_node(doc, off, "x", item.offset.x, 
     758                                 {"unit":item.offset_unit}) 
     759            written = written | write_node(doc, off, "y", item.offset.y, 
     760                                           {"unit":item.offset_unit}) 
     761            written = written | write_node(doc, off, "z", item.offset.z, 
     762                                           {"unit":item.offset_unit}) 
    661763            if written == True: 
    662764                det.appendChild(off) 
    663765             
    664766            center = doc.createElement("beam_center") 
    665             written = write_node(doc, center, "x", item.beam_center.x, {"unit":item.beam_center_unit}) 
    666             written = written | write_node(doc, center, "y", item.beam_center.y, {"unit":item.beam_center_unit}) 
    667             written = written | write_node(doc, center, "z", item.beam_center.z, {"unit":item.beam_center_unit}) 
     767            written = write_node(doc, center, "x", item.beam_center.x, 
     768                                 {"unit":item.beam_center_unit}) 
     769            written = written | write_node(doc, center, "y", 
     770                                           item.beam_center.y, 
     771                                           {"unit":item.beam_center_unit}) 
     772            written = written | write_node(doc, center, "z", 
     773                                           item.beam_center.z, 
     774                                           {"unit":item.beam_center_unit}) 
    668775            if written == True: 
    669776                det.appendChild(center) 
    670777                 
    671778            pix = doc.createElement("pixel_size") 
    672             written = write_node(doc, pix, "x", item.pixel_size.x, {"unit":item.pixel_size_unit}) 
    673             written = written | write_node(doc, pix, "y", item.pixel_size.y, {"unit":item.pixel_size_unit}) 
    674             written = written | write_node(doc, pix, "z", item.pixel_size.z, {"unit":item.pixel_size_unit}) 
     779            written = write_node(doc, pix, "x", item.pixel_size.x, 
     780                                 {"unit":item.pixel_size_unit}) 
     781            written = written | write_node(doc, pix, "y", item.pixel_size.y, 
     782                                           {"unit":item.pixel_size_unit}) 
     783            written = written | write_node(doc, pix, "z", item.pixel_size.z, 
     784                                           {"unit":item.pixel_size_unit}) 
    675785            if written == True: 
    676786                det.appendChild(pix) 
    677787                 
    678788            ori = doc.createElement("orientation") 
    679             written = write_node(doc, ori, "roll",  item.orientation.x, {"unit":item.orientation_unit}) 
    680             written = written | write_node(doc, ori, "pitch", item.orientation.y, {"unit":item.orientation_unit}) 
    681             written = written | write_node(doc, ori, "yaw",   item.orientation.z, {"unit":item.orientation_unit}) 
     789            written = write_node(doc, ori, "roll",  item.orientation.x, 
     790                                 {"unit":item.orientation_unit}) 
     791            written = written | write_node(doc, ori, "pitch", 
     792                                           item.orientation.y, 
     793                                           {"unit":item.orientation_unit}) 
     794            written = written | write_node(doc, ori, "yaw", 
     795                                           item.orientation.z, 
     796                                           {"unit":item.orientation_unit}) 
    682797            if written == True: 
    683798                det.appendChild(ori) 
     
    731846        :param variable: name of the data member to store it in [string] 
    732847        :param storage: data object that has the 'variable' data member 
    733         :param optional: if True, no exception will be raised if unit conversion can't be done 
     848        :param optional: if True, no exception will be raised  
     849            if unit conversion can't be done 
    734850 
    735851        :raise ValueError: raised when the units are not recognized 
     
    752868                        try: 
    753869                            conv = Converter(units) 
    754                             exec "storage.%s = %g" % (variable, conv(value, units=local_unit)) 
     870                            exec "storage.%s = %g" % (variable, 
     871                                            conv(value, units=local_unit)) 
    755872                        except: 
    756                             err_mess = "CanSAS reader: could not convert %s unit [%s]; expecting [%s]\n  %s" \ 
     873                            err_mess = "CanSAS reader: could not convert" 
     874                            err_mess += " %s unit [%s]; expecting [%s]\n  %s" \ 
    757875                                % (variable, units, local_unit, sys.exc_value) 
    758876                            self.errors.append(err_mess) 
     
    762880                                raise ValueError, err_mess  
    763881                    else: 
    764                         err_mess = "CanSAS reader: unrecognized %s unit [%s]; expecting [%s]" \ 
    765                             % (variable, units, local_unit) 
     882                        err_mess = "CanSAS reader: unrecognized %s unit [%s];" 
     883                        err_mess += " expecting [%s]" % (variable,  
     884                                                         units, local_unit) 
    766885                        self.errors.append(err_mess) 
    767886                        if optional: 
  • DataLoader/readers/danse_reader.py

    r0997158f ra7a5886  
    1818import math 
    1919import os 
    20 import copy 
     20#import copy 
    2121import numpy 
    2222import logging 
     
    5050        read_it = False 
    5151        for item in self.ext: 
    52             if filename.lower().find(item)>=0: 
     52            if filename.lower().find(item) >= 0: 
    5353                read_it = True 
    5454                 
    5555        if read_it: 
    5656            try: 
    57                  datafile = open(filename, 'r') 
     57                datafile = open(filename, 'r') 
    5858            except : 
    59                 raise  RuntimeError,"danse_reader cannot open %s"%(filename) 
    60              
    61              
     59                raise  RuntimeError,"danse_reader cannot open %s" % (filename) 
     60         
    6261            # defaults 
    6362            # wavelength in Angstrom 
     
    8483             
    8584            output.data = numpy.zeros([size_x,size_y]) 
    86             output.err_data = numpy.zeros([size_x,size_y]) 
     85            output.err_data = numpy.zeros([size_x, size_y]) 
    8786             
    8887            data_conv_q = None 
     
    102101            while read_on: 
    103102                line = datafile.readline() 
    104                 if line.find("DATA:")>=0: 
     103                if line.find("DATA:") >= 0: 
    105104                    read_on = False 
    106105                    break 
    107106                toks = line.split(':') 
    108                 if toks[0]=="FORMATVERSION": 
     107                if toks[0] == "FORMATVERSION": 
    109108                    fversion = float(toks[1]) 
    110                 if toks[0]=="WAVELENGTH":     
     109                if toks[0] == "WAVELENGTH":     
    111110                    wavelength = float(toks[1])                 
    112                 elif toks[0]=="DISTANCE": 
     111                elif toks[0] == "DISTANCE": 
    113112                    distance = float(toks[1]) 
    114                 elif toks[0]=="CENTER_X": 
     113                elif toks[0] == "CENTER_X": 
    115114                    center_x = float(toks[1]) 
    116                 elif toks[0]=="CENTER_Y": 
     115                elif toks[0] == "CENTER_Y": 
    117116                    center_y = float(toks[1]) 
    118                 elif toks[0]=="PIXELSIZE": 
     117                elif toks[0] == "PIXELSIZE": 
    119118                    pixel = float(toks[1]) 
    120                 elif toks[0]=="SIZE_X": 
     119                elif toks[0] == "SIZE_X": 
    121120                    size_x = int(toks[1]) 
    122                 elif toks[0]=="SIZE_Y": 
     121                elif toks[0] == "SIZE_Y": 
    123122                    size_y = int(toks[1]) 
    124123             
     
    126125            data = [] 
    127126            error = [] 
    128             if fversion==1.0: 
     127            if fversion == 1.0: 
    129128                data_str = datafile.readline() 
    130129                data = data_str.split(' ') 
     
    133132                while read_on: 
    134133                    data_str = datafile.readline() 
    135                     if len(data_str)==0: 
     134                    if len(data_str) == 0: 
    136135                        read_on = False 
    137136                    else: 
     
    146145                            error.append(err) 
    147146                        except: 
    148                             logging.info("Skipping line:%s,%s" %( data_str,sys.exc_value)) 
     147                            logging.info("Skipping line:%s,%s" %( data_str, 
     148                                                                sys.exc_value)) 
    149149             
    150150            # Initialize  
     
    158158            # Qx and Qy vectors 
    159159            theta = pixel / distance / 100.0 
    160             stepq = 4.0*math.pi/wavelength * math.sin(theta/2.0)  
     160            stepq = 4.0 * math.pi/wavelength * math.sin(theta/2.0)  
    161161            for i_x in range(size_x): 
    162                 theta = (i_x-center_x+1)*pixel / distance / 100.0 
    163                 qx = 4.0*math.pi/wavelength * math.sin(theta/2.0) 
     162                theta = (i_x - center_x + 1) * pixel / distance / 100.0 
     163                qx = 4.0 * math.pi / wavelength * math.sin(theta/2.0) 
    164164                 
    165165                if has_converter == True and output.Q_unit != '1/A': 
     
    167167                 
    168168                x_vals.append(qx) 
    169                 if xmin==None or qx<xmin: 
     169                if xmin == None or qx < xmin: 
    170170                    xmin = qx 
    171                 if xmax==None or qx>xmax: 
     171                if xmax == None or qx > xmax: 
    172172                    xmax = qx 
    173173             
     
    175175            ymax = None 
    176176            for i_y in range(size_y): 
    177                 theta = (i_y-center_y+1)*pixel / distance / 100.0 
    178                 qy = 4.0*math.pi/wavelength * math.sin(theta/2.0) 
     177                theta = (i_y - center_y + 1) * pixel / distance / 100.0 
     178                qy = 4.0 * math.pi/wavelength * math.sin(theta/2.0) 
    179179                 
    180180                if has_converter == True and output.Q_unit != '1/A': 
     
    182182                 
    183183                y_vals.append(qy) 
    184                 if ymin==None or qy<ymin: 
     184                if ymin == None or qy < ymin: 
    185185                    ymin = qy 
    186                 if ymax==None or qy>ymax: 
     186                if ymax == None or qy > ymax: 
    187187                    ymax = qy 
    188188             
     
    198198                    # For version 1.0, the data were still 
    199199                    # stored as strings at this point. 
    200                     logging.info("Skipping entry (v1.0):%s,%s" %(str(data[i_pt]), sys.exc_value)) 
     200                    msg = "Skipping entry (v1.0):%s,%s" %(str(data[i_pt]), 
     201                                                           sys.exc_value) 
     202                    logging.info(msg) 
    201203                 
    202204                # Get bin number 
    203                 if math.fmod(i_pt, size_x)==0: 
     205                if math.fmod(i_pt, size_x) == 0: 
    204206                    i_x = 0 
    205207                    i_y += 1 
     
    213215                    #output.err_data[size_y-1-i_y][i_x] = error[i_pt] 
    214216                 
    215                  
     217 
    216218            # Store all data  
    217219            # Store wavelength 
    218             if has_converter==True and output.source.wavelength_unit != 'A': 
     220            if has_converter == True and output.source.wavelength_unit != 'A': 
    219221                conv = Converter('A') 
    220                 wavelength = conv(wavelength, units=output.source.wavelength_unit) 
     222                wavelength = conv(wavelength, 
     223                                  units=output.source.wavelength_unit) 
    221224            output.source.wavelength = wavelength 
    222225                 
    223226            # Store distance 
    224             if has_converter==True and detector.distance_unit != 'm': 
     227            if has_converter == True and detector.distance_unit != 'm': 
    225228                conv = Converter('m') 
    226229                distance = conv(distance, units=detector.distance_unit) 
     
    228231             
    229232            # Store pixel size 
    230             if has_converter==True and detector.pixel_size_unit != 'mm': 
     233            if has_converter == True and detector.pixel_size_unit != 'mm': 
    231234                conv = Converter('mm') 
    232235                pixel = conv(pixel, units=detector.pixel_size_unit) 
     
    239242             
    240243            # Store limits of the image (2D array) 
    241             xmin    =xmin-stepq/2.0 
    242             xmax    =xmax+stepq/2.0 
    243             ymin    =ymin-stepq/2.0 
    244             ymax    =ymax+stepq/2.0 
     244            xmin = xmin - stepq / 2.0 
     245            xmax = xmax + stepq / 2.0 
     246            ymin = ymin - stepq  /2.0 
     247            ymax = ymax + stepq / 2.0 
    245248             
    246249            if has_converter == True and output.Q_unit != '1/A': 
     
    271274                output.zaxis("\\rm{Intensity}","cm^{-1}") 
    272275            
    273             if not fversion>=1.0: 
    274                 raise ValueError,"Danse_reader can't read this file %s"%filename 
    275             else: 
    276                 logging.info("Danse_reader Reading %s \n"%filename) 
     276            if not fversion >= 1.0: 
     277                msg = "Danse_reader can't read this file %s" % filename 
     278                raise ValueError, msg 
     279            else: 
     280                logging.info("Danse_reader Reading %s \n" % filename) 
    277281             
    278282            # Store loading process information 
  • DataLoader/readers/hfir1d_reader.py

    r0997158f ra7a5886  
    2828    type = ["HFIR 1D files (*.d1d)|*.d1d"] 
    2929    ## List of allowed extensions 
    30     ext=['.d1d']   
     30    ext = ['.d1d']   
    3131     
    3232    def read(self, path): 
     
    8787                            _dy = data_conv_i(_dy, units=output.y_unit)                         
    8888                                                     
    89  
    9089                        x   = numpy.append(x, _x)  
    9190                        y   = numpy.append(y, _y) 
     
    9998                # Sanity check 
    10099                if not len(y) == len(dy): 
    101                     raise RuntimeError, "hfir1d_reader: y and dy have different length" 
     100                    msg = "hfir1d_reader: y and dy have different length" 
     101                    raise RuntimeError, msg 
    102102                if not len(x) == len(dx): 
    103                     raise RuntimeError, "hfir1d_reader: x and dx have different length" 
     103                    msg = "hfir1d_reader: x and dx have different length" 
     104                    raise RuntimeError, msg 
    104105 
    105106                # If the data length is zero, consider this as 
    106107                # though we were not able to read the file. 
    107                 if len(x)==0: 
     108                if len(x) == 0: 
    108109                    raise RuntimeError, "hfir1d_reader: could not load file" 
    109110                
  • DataLoader/readers/red2d_reader.py

    rd2539aa ra7a5886  
    1313 
    1414 
    15 import os, sys 
     15import os 
     16#import sys 
    1617import numpy 
    17 import math, logging 
     18import math 
     19#import logging 
    1820from DataLoader.data_info import Data2D, Detector 
    1921 
     
    121123                    wavelength = float(line_toks[1]) 
    122124                    # Units 
    123                     if has_converter==True and output.source.wavelength_unit != 'A': 
     125                    if has_converter == True and \ 
     126                    output.source.wavelength_unit != 'A': 
    124127                        conv = Converter('A') 
    125                         wavelength = conv(wavelength, units=output.source.wavelength_unit) 
     128                        wavelength = conv(wavelength, 
     129                                          units=output.source.wavelength_unit) 
    126130                except: 
    127131                    #Not required 
     
    131135                    distance = float(line_toks[3]) 
    132136                    # Units 
    133                     if has_converter==True and detector.distance_unit != 'm': 
     137                    if has_converter == True and detector.distance_unit != 'm': 
    134138                        conv = Converter('m') 
    135139                        distance = conv(distance, units=detector.distance_unit) 
     
    145149                    pass 
    146150                                             
    147             if line.count("LAMBDA")>0: 
     151            if line.count("LAMBDA") > 0: 
    148152                isInfo = True 
    149153                 
     
    156160                center_y = float(line_toks[1]) 
    157161 
    158             if line.count("BCENT")>0: 
     162            if line.count("BCENT") > 0: 
    159163                isCenter = True 
    160164                        
    161165            # Find data start 
    162             if line.count("Data columns") or line.count("ASCII data")>0: 
     166            if line.count("Data columns") or line.count("ASCII data") > 0: 
    163167                dataStarted = True 
    164168                continue 
     
    173177                col_num = len(line_toks) 
    174178                break 
    175  
    176          
    177179        # Make numpy array to remove header lines using index 
    178180        lines_array = numpy.array(lines) 
     
    182184         
    183185        # get the data lines 
    184         data_lines = lines_array[lines_index>=(line_num-1)] 
     186        data_lines = lines_array[lines_index >= (line_num - 1)] 
    185187        # Now we get the total number of rows (i.e., # of data points) 
    186188        row_num = len(data_lines) 
     
    190192        data_list = data_list.split() 
    191193  
    192         # Check if the size is consistent with data, otherwise try the tab(\t) separator 
    193         # (this may be removed once get the confidence the former working all cases). 
     194        # Check if the size is consistent with data, otherwise  
     195        #try the tab(\t) separator 
     196        # (this may be removed once get the confidence  
     197        #the former working all cases). 
    194198        if len(data_list) != (len(data_lines)) * col_num: 
    195199            data_list = "\t".join(data_lines.tolist()) 
     
    202206        # numpy array form 
    203207        data_array = numpy.array(data_list1) 
    204         # Redimesion based on the row_num and col_num, otherwise raise an error. 
     208        # Redimesion based on the row_num and col_num,  
     209        #otherwise raise an error. 
    205210        try: 
    206             data_point = data_array.reshape(row_num,col_num).transpose() 
     211            data_point = data_array.reshape(row_num, col_num).transpose() 
    207212        except: 
    208             raise ValueError, "red2d_reader: Can't read this file: Not a proper file format" 
     213            msg = "red2d_reader: Can't read this file: Not a proper file format" 
     214            raise ValueError, msg 
    209215         
    210216        ## Get the all data: Let's HARDcoding; Todo find better way 
     
    218224        qy_data = data_point[1] 
    219225        data = data_point[2] 
    220         if col_num >3: qz_data = data_point[3] 
    221         if col_num >4: dqx_data = data_point[4] 
    222         if col_num >5: dqy_data = data_point[5] 
    223         if col_num >6: mask[data_point[6]<1] = False 
     226        if col_num > 3: qz_data = data_point[3] 
     227        if col_num > 4: dqx_data = data_point[4] 
     228        if col_num > 5: dqy_data = data_point[5] 
     229        if col_num > 6: mask[data_point[6] < 1] = False 
    224230        q_data = numpy.sqrt(qx_data*qx_data+qy_data*qy_data+qz_data*qz_data) 
    225231            
     
    291297        # optional data: if all of dq data == 0, do not pass to output 
    292298        if len(dqx_data) == len(qx_data) and dqx_data.any()!=0:  
    293             # if no dqx_data, do not pass dqy_data.(1 axis dq is not supported yet). 
     299            # if no dqx_data, do not pass dqy_data. 
     300            #(1 axis dq is not supported yet). 
    294301            if len(dqy_data) == len(qy_data) and dqy_data.any()!=0: 
    295302                output.dqx_data = dqx_data 
  • DataLoader/readers/tiff_reader.py

    r0997158f ra7a5886  
    4141            import Image 
    4242        except: 
    43             raise RuntimeError, "tiff_reader: could not load file. Missing Image module." 
     43            msg = "tiff_reader: could not load file. Missing Image module." 
     44            raise RuntimeError, msg 
    4445         
    4546        # Instantiate data object 
Note: See TracChangeset for help on using the changeset viewer.