Changeset 7d6351e in sasview


Ignore:
Timestamp:
Apr 27, 2012 11:22:31 AM (12 years ago)
Author:
Mathieu Doucet <doucetm@…>
Branches:
master, ESS_GUI, ESS_GUI_Docs, ESS_GUI_batch_fitting, ESS_GUI_bumps_abstraction, ESS_GUI_iss1116, ESS_GUI_iss879, ESS_GUI_iss959, ESS_GUI_opencl, ESS_GUI_ordering, ESS_GUI_sync_sascalc, costrafo411, magnetic_scatt, release-4.1.1, release-4.1.2, release-4.2.2, release_4.0.1, ticket-1009, ticket-1094-headless, ticket-1242-2d-resolution, ticket-1243, ticket-1249, ticket885, unittest-saveload
Children:
4a96b8b
Parents:
f60a8c2
Message:

Pep-8-ification

Location:
sansdataloader/src/sans/dataloader/readers
Files:
9 edited

Legend:

Unmodified
Added
Removed
  • sansdataloader/src/sans/dataloader/readers/IgorReader.py

    rad8034f r7d6351e  
    1  
     1""" 
     2    IGOR 2D reduced file reader 
     3""" 
    24############################################################################ 
    35#This software was developed by the University of Tennessee as part of the 
     
    1012#copyright 2008, University of Tennessee 
    1113############################################################################# 
    12  
    13 """ 
    14     IGOR 2D reduced file reader 
    15 """ 
    16  
    1714import os 
    18 #import sys 
    1915import numpy 
    2016import math 
     
    3127    has_converter = False 
    3228 
     29 
    3330class Reader: 
    3431    """ Simple data reader for Igor data files """ 
    3532    ## File type 
    36     type_name = "IGOR 2D"    
     33    type_name = "IGOR 2D" 
    3734    ## Wildcards 
    3835    type = ["IGOR 2D files (*.ASC)|*.ASC"] 
     
    4037    ext=['.ASC', '.asc'] 
    4138 
    42     def read(self,filename=None): 
     39    def read(self, filename=None): 
    4340        """ Read file """ 
    4441        if not os.path.isfile(filename): 
     
    4744         
    4845        # Read file 
    49         f = open(filename,'r') 
     46        f = open(filename, 'r') 
    5047        buf = f.read() 
    5148         
     
    5451        output.filename = os.path.basename(filename) 
    5552        detector = Detector() 
    56         if len(output.detector)>0: print str(output.detector[0]) 
     53        if len(output.detector) > 0: 
     54            print str(output.detector[0]) 
    5755        output.detector.append(detector) 
    5856                 
    5957        # Get content 
    6058        dataStarted = False 
    61          
    6259         
    6360        lines = buf.split('\n') 
     
    9188            data_conv_i = Converter('1/cm') 
    9289            # Test it 
    93             data_conv_i(1.0, output.I_unit)             
     90            data_conv_i(1.0, output.I_unit) 
    9491          
    9592        for line in lines: 
     
    117114                 
    118115            i_tot_row += 1 
    119         i_tot_row=math.ceil(math.sqrt(i_tot_row))-1  
     116        i_tot_row = math.ceil(math.sqrt(i_tot_row)) - 1 
    120117        #print "i_tot", i_tot_row 
    121         size_x = i_tot_row#192#128 
    122         size_y = i_tot_row#192#128 
    123         output.data = numpy.zeros([size_x,size_y]) 
    124         output.err_data = numpy.zeros([size_x,size_y]) 
     118        size_x = i_tot_row  # 192#128 
     119        size_y = i_tot_row  # 192#128 
     120        output.data = numpy.zeros([size_x, size_y]) 
     121        output.err_data = numpy.zeros([size_x, size_y]) 
    125122      
    126123        #Read Header and 2D data 
     
    151148                    raise ValueError, msg 
    152149                                             
    153             if line.count("LAMBDA")>0: 
     150            if line.count("LAMBDA") > 0: 
    154151                isInfo = True 
    155152                 
    156153            # Find center info line 
    157154            if isCenter: 
    158                 isCenter = False                 
     155                isCenter = False 
    159156                line_toks = line.split() 
    160157                 
    161                 # Center in bin number: Must substrate 1 because  
     158                # Center in bin number: Must substrate 1 because 
    162159                #the index starts from 1 
    163                 center_x = float(line_toks[0])-1 
    164                 center_y = float(line_toks[1])-1 
    165  
    166             if line.count("BCENT")>0: 
     160                center_x = float(line_toks[0]) - 1 
     161                center_y = float(line_toks[1]) - 1 
     162 
     163            if line.count("BCENT") > 0: 
    167164                isCenter = True 
    168165                 
    169          
    170166            # Find data start 
    171167            if line.count("***")>0: 
     
    188184                 
    189185                # Get bin number 
    190                 if math.fmod(itot, i_tot_row)==0: 
     186                if math.fmod(itot, i_tot_row) == 0: 
    191187                    i_x = 0 
    192188                    i_y += 1 
     
    195191                     
    196192                output.data[i_y][i_x] = value 
    197                 ncounts += 1  
     193                ncounts += 1 
    198194                 
    199195                # Det 640 x 640 mm 
    200196                # Q = 4pi/lambda sin(theta/2) 
    201197                # Bin size is 0.5 cm  
    202                 #REmoved +1 from theta = (i_x-center_x+1)*0.5 / distance  
     198                #REmoved +1 from theta = (i_x-center_x+1)*0.5 / distance 
    203199                # / 100.0 and  
    204200                #REmoved +1 from theta = (i_y-center_y+1)*0.5 / 
     
    206202                #ToDo: Need  complete check if the following 
    207203                # covert process is consistent with fitting.py. 
    208                 theta = (i_x-center_x)*0.5 / distance / 100.0 
    209                 qx = 4.0*math.pi/wavelength * math.sin(theta/2.0) 
     204                theta = (i_x - center_x) * 0.5 / distance / 100.0 
     205                qx = 4.0 * math.pi / wavelength * math.sin(theta/2.0) 
    210206 
    211207                if has_converter == True and output.Q_unit != '1/A': 
    212208                    qx = data_conv_q(qx, units=output.Q_unit) 
    213209 
    214                 if xmin==None or qx<xmin: 
     210                if xmin == None or qx < xmin: 
    215211                    xmin = qx 
    216                 if xmax==None or qx>xmax: 
     212                if xmax == None or qx > xmax: 
    217213                    xmax = qx 
    218214                 
    219                 theta = (i_y-center_y)*0.5 / distance / 100.0 
    220                 qy = 4.0*math.pi/wavelength * math.sin(theta/2.0) 
     215                theta = (i_y - center_y) * 0.5 / distance / 100.0 
     216                qy = 4.0 * math.pi / wavelength * math.sin(theta / 2.0) 
    221217 
    222218                if has_converter == True and output.Q_unit != '1/A': 
    223219                    qy = data_conv_q(qy, units=output.Q_unit) 
    224220                 
    225                 if ymin==None or qy<ymin: 
     221                if ymin == None or qy < ymin: 
    226222                    ymin = qy 
    227                 if ymax==None or qy>ymax: 
     223                if ymax == None or qy > ymax: 
    228224                    ymax = qy 
    229225                 
     
    237233                   
    238234        theta = 0.25 / distance / 100.0 
    239         xstep = 4.0*math.pi/wavelength * math.sin(theta/2.0) 
     235        xstep = 4.0 * math.pi / wavelength * math.sin(theta / 2.0) 
    240236         
    241237        theta = 0.25 / distance / 100.0 
    242         ystep = 4.0*math.pi/wavelength * math.sin(theta/2.0) 
     238        ystep = 4.0 * math.pi/ wavelength * math.sin(theta / 2.0) 
    243239         
    244240        # Store all data ###################################### 
    245241        # Store wavelength 
    246         if has_converter==True and output.source.wavelength_unit != 'A': 
     242        if has_converter == True and output.source.wavelength_unit != 'A': 
    247243            conv = Converter('A') 
    248244            wavelength = conv(wavelength, units=output.source.wavelength_unit) 
     
    250246 
    251247        # Store distance 
    252         if has_converter==True and detector.distance_unit != 'm': 
     248        if has_converter == True and detector.distance_unit != 'm': 
    253249            conv = Converter('m') 
    254250            distance = conv(distance, units=detector.distance_unit) 
     
    260256        # Store pixel size 
    261257        pixel = 5.0 
    262         if has_converter==True and detector.pixel_size_unit != 'mm': 
     258        if has_converter == True and detector.pixel_size_unit != 'mm': 
    263259            conv = Converter('mm') 
    264260            pixel = conv(pixel, units=detector.pixel_size_unit) 
     
    267263   
    268264        # Store beam center in distance units 
    269         detector.beam_center.x = center_x*pixel 
    270         detector.beam_center.y = center_y*pixel 
    271    
     265        detector.beam_center.x = center_x * pixel 
     266        detector.beam_center.y = center_y * pixel 
    272267         
    273268        # Store limits of the image (2D array) 
    274         xmin    =xmin-xstep/2.0 
    275         xmax    =xmax+xstep/2.0 
    276         ymin    =ymin-ystep/2.0 
    277         ymax    =ymax+ystep/2.0 
     269        xmin = xmin - xstep / 2.0 
     270        xmax = xmax + xstep / 2.0 
     271        ymin = ymin - ystep / 2.0 
     272        ymax = ymax + ystep / 2.0 
    278273        if has_converter == True and output.Q_unit != '1/A': 
    279274            xmin = data_conv_q(xmin, units=output.Q_unit) 
     
    287282         
    288283        # Store x and y axis bin centers 
    289         output.x_bins     = x 
    290         output.y_bins     = y 
     284        output.x_bins = x 
     285        output.y_bins = y 
    291286         
    292287        # Units 
     
    301296            output.zaxis("\\rm{Intensity}", output.I_unit) 
    302297        else: 
    303             output.zaxis("\\rm{Intensity}","cm^{-1}") 
     298            output.zaxis("\\rm{Intensity}", "cm^{-1}") 
    304299     
    305300        # Store loading process information 
     
    308303 
    309304        return output 
    310      
    311 if __name__ == "__main__":  
    312     reader = Reader() 
    313     print reader.read("../test/MAR07232_rest.ASC")  
    314      
  • sansdataloader/src/sans/dataloader/readers/abs_reader.py

    raac129aa r7d6351e  
    44#This software was developed by the University of Tennessee as part of the 
    55#Distributed Data Analysis of Neutron Scattering Experiments (DANSE) 
    6 #project funded by the US National Science Foundation.  
     6#project funded by the US National Science Foundation. 
    77#See the license text in license.txt 
    88#copyright 2008, University of Tennessee 
     
    2020    has_converter = False 
    2121     
     22     
    2223class Reader: 
    2324    """ 
     
    2526    """ 
    2627    ## File type 
    27     type_name = "IGOR 1D"    
     28    type_name = "IGOR 1D" 
    2829    ## Wildcards 
    2930    type = ["IGOR 1D files (*.abs)|*.abs"] 
    3031    ## List of allowed extensions 
    31     ext = ['.abs', '.ABS']   
     32    ext = ['.abs', '.ABS'] 
    3233     
    3334    def read(self, path): 
     
    4344        """ 
    4445        if os.path.isfile(path): 
    45             basename  = os.path.basename(path) 
     46            basename = os.path.basename(path) 
    4647            root, extension = os.path.splitext(basename) 
    4748            if extension.lower() in self.ext: 
    4849                try: 
    49                     input_f =  open(path,'r') 
    50                 except : 
     50                    input_f = open(path,'r') 
     51                except: 
    5152                    raise  RuntimeError, "abs_reader: cannot open %s" % path 
    5253                buff = input_f.read() 
     
    9192                                output.source.wavelength_unit != 'A': 
    9293                                conv = Converter('A') 
    93                                 output.source.wavelength = conv(value,  
     94                                output.source.wavelength = conv(value, 
    9495                                        units=output.source.wavelength_unit) 
    9596                            else: 
     
    99100                            msg = "abs_reader: cannot open %s" % path 
    100101                            raise  RuntimeError, msg 
    101                             #raise ValueError,"IgorReader: can't read this file, 
    102                             # missing wavelength" 
    103102                         
    104103                        # Distance in meters 
     
    108107                                detector.distance_unit != 'm': 
    109108                                conv = Converter('m') 
    110                                 detector.distance = conv(value,  
     109                                detector.distance = conv(value, 
    111110                                                units=detector.distance_unit) 
    112111                            else: 
     
    116115                            msg = "abs_reader: cannot open %s" % path 
    117116                            raise  RuntimeError, msg 
    118                         # Transmission  
     117                        # Transmission 
    119118                        try: 
    120119                            output.sample.transmission = float(line_toks[4]) 
     
    129128                                output.sample.thickness_unit != 'cm': 
    130129                                conv = Converter('cm') 
    131                                 output.sample.thickness = conv(value,  
     130                                output.sample.thickness = conv(value, 
    132131                                            units=output.sample.thickness_unit) 
    133132                            else: 
     
    144143                    # Find center info line 
    145144                    if is_center == True: 
    146                         is_center = False                 
     145                        is_center = False 
    147146                        line_toks = line.split() 
    148147                        # Center in bin number 
     
    154153                            detector.pixel_size_unit != 'mm': 
    155154                            conv = Converter('mm') 
    156                             detector.pixel_size.x = conv(5.0,  
     155                            detector.pixel_size.x = conv(5.0, 
    157156                                                units=detector.pixel_size_unit) 
    158157                            detector.pixel_size.y = conv(5.0, 
     
    164163                        # Store beam center in distance units 
    165164                        # Det 640 x 640 mm 
    166                         if has_converter==True and \ 
     165                        if has_converter == True and \ 
    167166                            detector.beam_center_unit != 'mm': 
    168167                            conv = Converter('mm') 
    169168                            detector.beam_center.x = conv(center_x * 5.0, 
    170169                                             units=detector.beam_center_unit) 
    171                             detector.beam_center.y = conv(center_y * 5.0,  
     170                            detector.beam_center.y = conv(center_y * 5.0, 
    172171                                            units=detector.beam_center_unit) 
    173172                        else: 
     
    182181                            pass 
    183182                     
    184                     #BCENT(X,Y)   A1(mm)   A2(mm)   A1A2DIST(m)   DL/L  
    185                     #  BSTOP(mm)   DET_TYP  
     183                    #BCENT(X,Y)   A1(mm)   A2(mm)   A1A2DIST(m)   DL/L 
     184                    #  BSTOP(mm)   DET_TYP 
    186185                    if line.count("BCENT") > 0: 
    187186                        is_center = True 
     
    191190                        toks = line.split() 
    192191 
    193                         try:   
     192                        try: 
    194193                            _x  = float(toks[0]) 
    195                             _y  = float(toks[1])  
     194                            _y  = float(toks[1]) 
    196195                            _dy = float(toks[2]) 
    197196                            _dx = float(toks[3]) 
     
    205204                                _dy = data_conv_i(_dy, units=output.y_unit) 
    206205                            
    207                             x  = numpy.append(x,   _x)  
    208                             y  = numpy.append(y,  _y) 
     206                            x = numpy.append(x, _x) 
     207                            y = numpy.append(y, _y) 
    209208                            dy = numpy.append(dy, _dy) 
    210                             dx  = numpy.append(dx, _dx) 
     209                            dx = numpy.append(dx, _dx) 
    211210                             
    212211                        except: 
     
    218217                    #The 6 columns are | Q (1/A) | I(Q) (1/cm) | std. dev. 
    219218                    # I(Q) (1/cm) | sigmaQ | meanQ | ShadowFactor| 
    220                     if line.count("The 6 columns")>0: 
     219                    if line.count("The 6 columns") > 0: 
    221220                        is_data_started = True 
    222221             
     
    230229                    raise ValueError, "ascii_reader: could not load file" 
    231230                 
    232                 output.x = x[x!=0] 
    233                 output.y = y[x!=0] 
    234                 output.dy = dy[x!=0] 
    235                 output.dx = dx[x!=0] 
     231                output.x = x[x != 0] 
     232                output.y = y[x != 0] 
     233                output.dy = dy[x != 0] 
     234                output.dx = dx[x != 0] 
    236235                if data_conv_q is not None: 
    237236                    output.xaxis("\\rm{Q}", output.x_unit) 
     
    241240                    output.yaxis("\\rm{Intensity}", output.y_unit) 
    242241                else: 
    243                     output.yaxis("\\rm{Intensity}","cm^{-1}") 
     242                    output.yaxis("\\rm{Intensity}", "cm^{-1}") 
    244243                     
    245244                # Store loading process information 
    246                 output.meta_data['loader'] = self.type_name                        
     245                output.meta_data['loader'] = self.type_name 
    247246                return output 
    248247        else: 
    249248            raise RuntimeError, "%s is not a file" % path 
    250249        return None 
    251      
    252 if __name__ == "__main__":  
    253     reader = Reader() 
    254     print reader.read("../test/jan08002.ABS") 
    255      
    256      
    257              
  • sansdataloader/src/sans/dataloader/readers/ascii_reader.py

    r9cd0baa r7d6351e  
    1  
    2  
     1""" 
     2    ASCII reader 
     3""" 
    34############################################################################ 
    45#This software was developed by the University of Tennessee as part of the 
    56#Distributed Data Analysis of Neutron Scattering Experiments (DANSE) 
    67#project funded by the US National Science Foundation.  
    7 #If you use DANSE applications to do scientific research that leads to  
    8 #publication, we ask that you acknowledge the use of the software with the  
     8#If you use DANSE applications to do scientific research that leads to 
     9#publication, we ask that you acknowledge the use of the software with the 
    910#following sentence: 
    10 #This work benefited from DANSE software developed under NSF award DMR-0520547.  
     11#This work benefited from DANSE software developed under NSF award DMR-0520547. 
    1112#copyright 2008, University of Tennessee 
    1213############################################################################# 
     
    2425    has_converter = False 
    2526_ZERO = 1e-16 
     27 
    2628 
    2729class Reader: 
     
    3840            "CSV files (*.csv)|*.csv"] 
    3941    ## List of allowed extensions 
    40     ext = ['.txt', '.TXT', '.dat', '.DAT', '.abs', '.ABS', 'csv', 'CSV']   
     42    ext = ['.txt', '.TXT', '.dat', '.DAT', '.abs', '.ABS', 'csv', 'CSV'] 
    4143     
    4244    ## Flag to bypass extension check 
     
    4446     
    4547    def read(self, path): 
    46         """  
     48        """ 
    4749        Load data file 
    4850         
     
    5557        """ 
    5658        if os.path.isfile(path): 
    57             basename  = os.path.basename(path) 
     59            basename = os.path.basename(path) 
    5860            _, extension = os.path.splitext(basename) 
    5961            if self.allow_all or extension.lower() in self.ext: 
     
    6163                    # Read in binary mode since GRASP frequently has no-ascii 
    6264                    # characters that brakes the open operation 
    63                     input_f =  open(path,'rb') 
    64                 except : 
     65                    input_f = open(path,'rb') 
     66                except: 
    6567                    raise  RuntimeError, "ascii_reader: cannot open %s" % path 
    6668                buff = input_f.read() 
    6769                lines = buff.split('\n') 
    6870                 
    69                 #Jae could not find python universal line spliter:  
     71                #Jae could not find python universal line spliter: 
    7072                #keep the below for now 
    7173                # some ascii data has \r line separator, 
    7274                # try it when the data is on only one long line 
    73                 if len(lines) < 2 :  
     75                if len(lines) < 2 : 
    7476                    lines = buff.split('\r') 
    7577                  
     
    101103                    data_conv_i(1.0, output.y_unit) 
    102104            
    103                  
    104105                # The first good line of data will define whether 
    105106                # we have 2-column or 3-column ascii 
     
    108109                 
    109110                #Initialize counters for data lines and header lines. 
    110                 is_data = False #Has more than 5 lines 
     111                is_data = False  # Has more than 5 lines 
    111112                # More than "5" lines of data is considered as actual 
    112113                # data unless that is the only data 
    113                 mum_data_lines = 5  
     114                mum_data_lines = 5 
    114115                # To count # of current data candidate lines 
    115                 i = -1   
    116                 # To count total # of previous data candidate lines           
    117                 i1 = -1  
    118                 # To count # of header lines           
     116                i = -1 
     117                # To count total # of previous data candidate lines 
     118                i1 = -1 
     119                # To count # of header lines 
    119120                j = -1 
    120                 # Helps to count # of header lines             
     121                # Helps to count # of header lines 
    121122                j1 = -1 
    122                 #minimum required number of columns of data; ( <= 4).            
    123                 lentoks = 2      
     123                #minimum required number of columns of data; ( <= 4). 
     124                lentoks = 2 
    124125                for line in lines: 
    125126                    toks = line.split(',') 
     
    146147                             
    147148                        if data_conv_i is not None: 
    148                             _y = data_conv_i(_y, units=output.y_unit)                         
     149                            _y = data_conv_i(_y, units=output.y_unit) 
    149150                         
    150151                        # If we have an extra token, check 
     
    186187                            has_error_dx = False if _dx == None else True 
    187188                         
    188                         #After talked with PB, we decided to take care of only  
     189                        #After talked with PB, we decided to take care of only 
    189190                        # 4 columns of data for now. 
    190191                        #number of columns in the current line 
    191                         #To remember the # of columns in the current  
     192                        #To remember the # of columns in the current 
    192193                        #line of data 
    193194                        new_lentoks = len(toks) 
    194195                         
    195                         #If the previous columns not equal to the current,  
    196                         #mark the previous as non-data and reset the dependents.   
    197                         if lentoks != new_lentoks : 
     196                        #If the previous columns not equal to the current, 
     197                        #mark the previous as non-data and reset the dependents. 
     198                        if lentoks != new_lentoks: 
    198199                            if is_data == True: 
    199200                                break 
     
    203204                                j = -1 
    204205                                j1 = -1 
    205                              
    206206                             
    207207                        #Delete the previously stored lines of data candidates 
     
    215215                                pass 
    216216                             
    217                         x  = numpy.append(x,  _x)  
    218                         y  = numpy.append(y,  _y) 
     217                        x = numpy.append(x, _x)  
     218                        y = numpy.append(y, _y) 
    219219                         
    220220                        if has_error_dy == True: 
     
    224224                                is_data == False: 
    225225                                try: 
    226                                     dy = numpy.zeros(0)   
     226                                    dy = numpy.zeros(0) 
    227227                                except: 
    228                                     pass                                                                
     228                                    pass 
    229229                            dy = numpy.append(dy, _dy) 
    230230                             
     
    235235                                is_data == False: 
    236236                                try: 
    237                                     dx = numpy.zeros(0)                             
     237                                    dx = numpy.zeros(0) 
    238238                                except: 
    239                                     pass                                                                
     239                                    pass 
    240240                            dx = numpy.append(dx, _dx) 
    241241                             
     
    249249                                ty = numpy.zeros(0) 
    250250                            except: 
    251                                 pass                                                            
    252  
    253                         tx  = numpy.append(tx,   _x)  
    254                         ty  = numpy.append(ty,  _y) 
     251                                pass 
     252 
     253                        tx = numpy.append(tx, _x) 
     254                        ty = numpy.append(ty, _y) 
    255255                         
    256256                        if has_error_dy == True: 
     
    262262                                    tdy = numpy.zeros(0) 
    263263                                except: 
    264                                     pass                                                                                                                 
     264                                    pass 
    265265                            tdy = numpy.append(tdy, _dy) 
    266266                        if has_error_dx == True: 
     
    272272                                    tdx = numpy.zeros(0) 
    273273                                except: 
    274                                     pass                                                                                                           
     274                                    pass 
    275275                            tdx = numpy.append(tdx, _dx) 
    276276 
     
    278278                        if lentoks < new_lentoks: 
    279279                            if is_data == False: 
    280                                 i1 = -1                             
     280                                i1 = -1 
    281281                        #To remember the # of columns on the current line 
    282282                        # for the next line of data 
    283283                        lentoks = len(toks) 
    284284                         
    285                         #Reset # of header lines and counts #  
    286                         # of data candidate lines     
     285                        #Reset # of header lines and counts # 
     286                        # of data candidate lines 
    287287                        if j == 0 and j1 == 0: 
    288                             i1 = i + 1                             
     288                            i1 = i + 1 
    289289                        i += 1 
    290290                    except: 
     
    292292                        # It is data and meet non - number, then stop reading 
    293293                        if is_data == True: 
    294                             break     
     294                            break 
    295295                        lentoks = 2 
    296                         #Counting # of header lines                     
     296                        #Counting # of header lines 
    297297                        j += 1 
    298298                        if j == j1 + 1: 
    299                             j1 = j                             
    300                         else:                             
     299                            j1 = j 
     300                        else: 
    301301                            j = -1 
    302302                        #Reset # of lines of data candidates 
    303303                        i = -1 
    304304                         
    305                         # Couldn't parse this line, skip it  
     305                        # Couldn't parse this line, skip it 
    306306                        pass 
    307307                     
    308                 input_f.close()      
     308                input_f.close() 
    309309                # Sanity check 
    310310                if has_error_dy == True and not len(y) == len(dy): 
     
    329329                    if has_error_dx == True: 
    330330                        dx[i] = tdx[ind[i]] 
    331                 # Zeros in dx, dy  
     331                # Zeros in dx, dy 
    332332                if has_error_dx: 
    333                     dx[dx==0] = _ZERO 
     333                    dx[dx == 0] = _ZERO 
    334334                if has_error_dy: 
    335                     dy[dy==0] = _ZERO 
    336                 #Data     
    337                 output.x = x[x!=0] 
    338                 output.y = y[x!=0] 
    339                 output.dy = dy[x!=0] if has_error_dy == True else numpy.zeros(len(output.y)) 
    340                 output.dx = dx[x!=0] if has_error_dx == True else numpy.zeros(len(output.x)) 
     335                    dy[dy == 0] = _ZERO 
     336                #Data 
     337                output.x = x[x != 0] 
     338                output.y = y[x != 0] 
     339                output.dy = dy[x != 0] if has_error_dy == True\ 
     340                    else numpy.zeros(len(output.y)) 
     341                output.dx = dx[x != 0] if has_error_dx == True\ 
     342                    else numpy.zeros(len(output.x)) 
    341343                                 
    342344                if data_conv_q is not None: 
     
    347349                    output.yaxis("\\rm{Intensity}", output.y_unit) 
    348350                else: 
    349                     output.yaxis("\\rm{Intensity}","cm^{-1}") 
     351                    output.yaxis("\\rm{Intensity}", "cm^{-1}") 
    350352                     
    351353                # Store loading process information 
    352                 output.meta_data['loader'] = self.type_name     
     354                output.meta_data['loader'] = self.type_name 
    353355                     
    354356                return output 
     
    357359            raise RuntimeError, "%s is not a file" % path 
    358360        return None 
    359      
    360 if __name__ == "__main__":  
    361     reader = Reader() 
    362     #print reader.read("../test/test_3_columns.txt") 
    363     print reader.read("../test/empty.txt") 
    364      
    365      
    366                          
  • sansdataloader/src/sans/dataloader/readers/associations.py

    rf576de0 r7d6351e  
    1  
    2  
    3 ############################################################################ 
    4 #This software was developed by the University of Tennessee as part of the 
    5 #Distributed Data Analysis of Neutron Scattering Experiments (DANSE) 
    6 #project funded by the US National Science Foundation.  
    7 #If you use DANSE applications to do scientific research that leads to  
    8 #publication, we ask that you acknowledge the use of the software with the  
    9 #following sentence: 
    10 #This work benefited from DANSE software developed under NSF award DMR-0520547.  
    11 #copyright 2009, University of Tennessee 
    12 ############################################################################# 
    13  
    14  
    151""" 
    162Module to associate default readers to file extensions. 
     
    184The readers are tried in order they appear when reading a file. 
    195""" 
    20  
     6############################################################################ 
     7#This software was developed by the University of Tennessee as part of the 
     8#Distributed Data Analysis of Neutron Scattering Experiments (DANSE) 
     9#project funded by the US National Science Foundation. 
     10#If you use DANSE applications to do scientific research that leads to 
     11#publication, we ask that you acknowledge the use of the software with the 
     12#following sentence: 
     13#This work benefited from DANSE software developed under NSF award DMR-0520547. 
     14#copyright 2009, University of Tennessee 
     15############################################################################# 
    2116import os 
    2217import sys 
    2318import logging 
    24 from lxml import etree  
     19from lxml import etree 
    2520# Py2exe compatibility: import _elementpath to ensure that py2exe finds it 
    26 from lxml import _elementpath   
     21from lxml import _elementpath 
    2722 
    2823## Format version for the XML settings file 
    2924VERSION = 'sansloader/1.0' 
     25 
    3026 
    3127def read_associations(loader, settings='defaults.xml'): 
     
    5450         
    5551        # Check the format version number 
    56         # Specifying the namespace will take care of the file format version  
     52        # Specifying the namespace will take care of the file format version 
    5753        root = tree.getroot() 
    5854         
     
    6460        for entry in entry_list: 
    6561            reader = entry.get('reader') 
    66             ext    = entry.get('extension') 
     62            ext = entry.get('extension') 
    6763             
    6864            if reader is not None and ext is not None: 
    6965                # Associate the extension with a particular reader 
    70                 # TODO: Modify the Register code to be case-insensitive  
     66                # TODO: Modify the Register code to be case-insensitive 
    7167                # and remove the extra line below. 
    7268                try: 
     
    114110    registry_function(tiff_reader) 
    115111     
    116     return True             
    117  
    118  
    119 if __name__ == "__main__":  
    120     logging.basicConfig(level=logging.INFO, 
    121                         format='%(asctime)s %(levelname)s %(message)s', 
    122                         filename='logger.log', 
    123                         filemode='w') 
    124     from sans.dataloader.loader import Loader 
    125     l = Loader() 
    126     read_associations(l) 
    127      
    128      
    129     print l.get_wildcards() 
    130      
    131      
     112    return True 
  • sansdataloader/src/sans/dataloader/readers/cansas_reader.py

    r5a0dac1f r7d6351e  
    1  
    2  
     1""" 
     2    CanSAS data reader 
     3""" 
    34############################################################################ 
    45#This software was developed by the University of Tennessee as part of the 
     
    2526#      Process notes have the same problem. 
    2627#TODO: Unit conversion is not complete (temperature units are missing) 
    27  
    2828 
    2929import logging 
     
    4747CANSAS_NS = "cansas1d/1.0" 
    4848ALLOW_ALL = True 
     49 
    4950 
    5051def write_node(doc, parent, name, value, attr={}): 
     
    6768    return False 
    6869 
     70 
    6971def get_content(location, node): 
    7072    """ 
     
    7880    nodes = node.xpath(location, namespaces={'ns': CANSAS_NS}) 
    7981     
    80     if len(nodes)>0: 
     82    if len(nodes) > 0: 
    8183        return nodes[0] 
    8284    else: 
    8385        return None 
    8486 
     87 
    8588def get_float(location, node): 
    8689    """ 
    87     Get the content of a node as a float  
     90    Get the content of a node as a float 
    8891     
    8992    :param location: xpath location 
     
    9699    if len(nodes) > 0: 
    97100        try: 
    98             value = float(nodes[0].text)    
     101            value = float(nodes[0].text) 
    99102        except: 
    100103            # Could not pass, skip and return None 
     
    124127 
    125128    ## List of allowed extensions 
    126     ext = ['.xml', '.XML', '.avex', '.AVEx', '.absx', 'ABSx']   
     129    ext = ['.xml', '.XML', '.avex', '.AVEx', '.absx', 'ABSx'] 
    127130     
    128131    def __init__(self): 
     
    131134     
    132135    def read(self, path): 
    133         """  
     136        """ 
    134137        Load data file 
    135138         
     
    145148        output = [] 
    146149        if os.path.isfile(path): 
    147             basename  = os.path.basename(path) 
     150            basename = os.path.basename(path) 
    148151            root, extension = os.path.splitext(basename) 
    149152            if ALLOW_ALL or extension.lower() in self.ext: 
     
    152155                    # Check the format version number 
    153156                    # Specifying the namespace will take care of the file 
    154                     # format version  
     157                    # format version 
    155158                    root = tree.getroot() 
    156159                     
     
    173176        # Return output consistent with the loader's api 
    174177        if len(output) == 0: 
    175             #cannot return none when it cannot read  
     178            #cannot return none when it cannot read 
    176179            #return None 
    177180            raise RuntimeError, "%s cannot be read \n" % path 
     
    179182            return output[0] 
    180183        else: 
    181             return output                 
     184            return output 
    182185                 
    183186    def _parse_entry(self, dom): 
     
    194197        data_info = Data1D(x, y) 
    195198         
    196         # Look up title       
     199        # Look up title 
    197200        self._store_content('ns:Title', dom, 'title', data_info) 
    198201         
    199         # Look up run number    
     202        # Look up run number 
    200203        nodes = dom.xpath('ns:Run', namespaces={'ns': CANSAS_NS}) 
    201         for item in nodes:     
     204        for item in nodes: 
    202205            if item.text is not None: 
    203206                value = item.text.strip() 
     
    207210                        data_info.run_name[value] = item.get('name') 
    208211                            
    209         # Look up instrument name               
     212        # Look up instrument name 
    210213        self._store_content('ns:SASinstrument/ns:name', dom, 'instrument', 
    211214                             data_info) 
     
    230233            data_info.sample.name = entry.get('name') 
    231234             
    232         self._store_content('ns:SASsample/ns:ID',  
    233                      dom, 'ID', data_info.sample)                     
    234         self._store_float('ns:SASsample/ns:thickness',  
     235        self._store_content('ns:SASsample/ns:ID', 
     236                     dom, 'ID', data_info.sample) 
     237        self._store_float('ns:SASsample/ns:thickness', 
    235238                     dom, 'thickness', data_info.sample) 
    236         self._store_float('ns:SASsample/ns:transmission',  
     239        self._store_float('ns:SASsample/ns:transmission', 
    237240                     dom, 'transmission', data_info.sample) 
    238         self._store_float('ns:SASsample/ns:temperature',  
     241        self._store_float('ns:SASsample/ns:temperature', 
    239242                     dom, 'temperature', data_info.sample) 
    240243         
    241         nodes = dom.xpath('ns:SASsample/ns:details',  
     244        nodes = dom.xpath('ns:SASsample/ns:details', 
    242245                          namespaces={'ns': CANSAS_NS}) 
    243246        for item in nodes: 
     
    254257         
    255258        # Position (as a vector) 
    256         self._store_float('ns:SASsample/ns:position/ns:x',  
    257                      dom, 'position.x', data_info.sample)           
    258         self._store_float('ns:SASsample/ns:position/ns:y',  
    259                      dom, 'position.y', data_info.sample)           
    260         self._store_float('ns:SASsample/ns:position/ns:z',  
    261                      dom, 'position.z', data_info.sample)           
     259        self._store_float('ns:SASsample/ns:position/ns:x', 
     260                     dom, 'position.x', data_info.sample) 
     261        self._store_float('ns:SASsample/ns:position/ns:y', 
     262                     dom, 'position.y', data_info.sample) 
     263        self._store_float('ns:SASsample/ns:position/ns:z', 
     264                     dom, 'position.z', data_info.sample) 
    262265         
    263266        # Orientation (as a vector) 
    264         self._store_float('ns:SASsample/ns:orientation/ns:roll',  
    265                      dom, 'orientation.x', data_info.sample)           
    266         self._store_float('ns:SASsample/ns:orientation/ns:pitch',  
    267                      dom, 'orientation.y', data_info.sample)           
    268         self._store_float('ns:SASsample/ns:orientation/ns:yaw',  
    269                      dom, 'orientation.z', data_info.sample)           
     267        self._store_float('ns:SASsample/ns:orientation/ns:roll', 
     268                     dom, 'orientation.x', data_info.sample) 
     269        self._store_float('ns:SASsample/ns:orientation/ns:pitch', 
     270                     dom, 'orientation.y', data_info.sample) 
     271        self._store_float('ns:SASsample/ns:orientation/ns:yaw', 
     272                     dom, 'orientation.z', data_info.sample) 
    270273        
    271274        # Source info ################### 
     
    274277            data_info.source.name = entry.get('name') 
    275278         
    276         self._store_content('ns:SASinstrument/ns:SASsource/ns:radiation',  
    277                      dom, 'radiation', data_info.source)                     
    278         self._store_content('ns:SASinstrument/ns:SASsource/ns:beam_shape',  
    279                      dom, 'beam_shape', data_info.source)                     
    280         self._store_float('ns:SASinstrument/ns:SASsource/ns:wavelength',  
    281                      dom, 'wavelength', data_info.source)           
    282         self._store_float('ns:SASinstrument/ns:SASsource/ns:wavelength_min',  
    283                      dom, 'wavelength_min', data_info.source)           
    284         self._store_float('ns:SASinstrument/ns:SASsource/ns:wavelength_max',  
    285                      dom, 'wavelength_max', data_info.source)           
    286         self._store_float('ns:SASinstrument/ns:SASsource/ns:wavelength_spread',  
    287                      dom, 'wavelength_spread', data_info.source)     
     279        self._store_content('ns:SASinstrument/ns:SASsource/ns:radiation', 
     280                     dom, 'radiation', data_info.source) 
     281        self._store_content('ns:SASinstrument/ns:SASsource/ns:beam_shape', 
     282                     dom, 'beam_shape', data_info.source) 
     283        self._store_float('ns:SASinstrument/ns:SASsource/ns:wavelength', 
     284                     dom, 'wavelength', data_info.source) 
     285        self._store_float('ns:SASinstrument/ns:SASsource/ns:wavelength_min', 
     286                     dom, 'wavelength_min', data_info.source) 
     287        self._store_float('ns:SASinstrument/ns:SASsource/ns:wavelength_max', 
     288                     dom, 'wavelength_max', data_info.source) 
     289        self._store_float('ns:SASinstrument/ns:SASsource/ns:wavelength_spread', 
     290                     dom, 'wavelength_spread', data_info.source) 
    288291         
    289292        # Beam size (as a vector)    
     
    292295            data_info.source.beam_size_name = entry.get('name') 
    293296             
    294         self._store_float('ns:SASinstrument/ns:SASsource/ns:beam_size/ns:x',  
    295                      dom, 'beam_size.x', data_info.source)     
    296         self._store_float('ns:SASinstrument/ns:SASsource/ns:beam_size/ns:y',  
    297                      dom, 'beam_size.y', data_info.source)     
    298         self._store_float('ns:SASinstrument/ns:SASsource/ns:beam_size/ns:z',  
    299                      dom, 'beam_size.z', data_info.source)     
     297        self._store_float('ns:SASinstrument/ns:SASsource/ns:beam_size/ns:x', 
     298                     dom, 'beam_size.x', data_info.source) 
     299        self._store_float('ns:SASinstrument/ns:SASsource/ns:beam_size/ns:y', 
     300                     dom, 'beam_size.y', data_info.source) 
     301        self._store_float('ns:SASinstrument/ns:SASsource/ns:beam_size/ns:z', 
     302                     dom, 'beam_size.z', data_info.source) 
    300303         
    301304        # Collimation info ################### 
    302         nodes = dom.xpath('ns:SASinstrument/ns:SAScollimation',  
     305        nodes = dom.xpath('ns:SASinstrument/ns:SAScollimation', 
    303306                          namespaces={'ns': CANSAS_NS}) 
    304307        for item in nodes: 
     
    306309            if item.get('name') is not None: 
    307310                collim.name = item.get('name') 
    308             self._store_float('ns:length', item, 'length', collim)   
     311            self._store_float('ns:length', item, 'length', collim) 
    309312             
    310313            # Look for apertures 
    311314            apert_list = item.xpath('ns:aperture', namespaces={'ns': CANSAS_NS}) 
    312315            for apert in apert_list: 
    313                 aperture =  Aperture() 
     316                aperture = Aperture() 
    314317                 
    315318                # Get the name and type of the aperture 
     
    317320                aperture.type = apert.get('type') 
    318321                     
    319                 self._store_float('ns:distance', apert, 'distance', aperture)     
     322                self._store_float('ns:distance', apert, 'distance', aperture) 
    320323                 
    321324                entry = get_content('ns:size', apert) 
     
    323326                    aperture.size_name = entry.get('name') 
    324327                 
    325                 self._store_float('ns:size/ns:x', apert, 'size.x', aperture)     
    326                 self._store_float('ns:size/ns:y', apert, 'size.y', aperture)     
     328                self._store_float('ns:size/ns:x', apert, 'size.x', aperture) 
     329                self._store_float('ns:size/ns:y', apert, 'size.y', aperture) 
    327330                self._store_float('ns:size/ns:z', apert, 'size.z', aperture) 
    328331                 
     
    339342             
    340343            self._store_content('ns:name', item, 'name', detector) 
    341             self._store_float('ns:SDD', item, 'distance', detector)     
     344            self._store_float('ns:SDD', item, 'distance', detector) 
    342345             
    343346            # Detector offset (as a vector) 
    344             self._store_float('ns:offset/ns:x', item, 'offset.x', detector)     
    345             self._store_float('ns:offset/ns:y', item, 'offset.y', detector)     
    346             self._store_float('ns:offset/ns:z', item, 'offset.z', detector)     
     347            self._store_float('ns:offset/ns:x', item, 'offset.x', detector) 
     348            self._store_float('ns:offset/ns:y', item, 'offset.y', detector) 
     349            self._store_float('ns:offset/ns:z', item, 'offset.z', detector) 
    347350             
    348351            # Detector orientation (as a vector) 
    349             self._store_float('ns:orientation/ns:roll',  item, 'orientation.x', 
    350                                detector)     
     352            self._store_float('ns:orientation/ns:roll', item, 'orientation.x', 
     353                               detector) 
    351354            self._store_float('ns:orientation/ns:pitch', item, 'orientation.y', 
    352                                detector)     
    353             self._store_float('ns:orientation/ns:yaw',   item, 'orientation.z', 
    354                                detector)     
     355                               detector) 
     356            self._store_float('ns:orientation/ns:yaw', item, 'orientation.z', 
     357                               detector) 
    355358             
    356359            # Beam center (as a vector) 
    357360            self._store_float('ns:beam_center/ns:x', item, 'beam_center.x', 
    358                                detector)     
    359             self._store_float('ns:beam_center/ns:y', item, 'beam_center.y',  
    360                               detector)     
     361                               detector) 
     362            self._store_float('ns:beam_center/ns:y', item, 'beam_center.y', 
     363                              detector) 
    361364            self._store_float('ns:beam_center/ns:z', item, 'beam_center.z', 
    362                                detector)     
     365                               detector) 
    363366             
    364367            # Pixel size (as a vector) 
    365368            self._store_float('ns:pixel_size/ns:x', item, 'pixel_size.x', 
    366                                detector)     
     369                               detector) 
    367370            self._store_float('ns:pixel_size/ns:y', item, 'pixel_size.y', 
    368                                detector)     
     371                               detector) 
    369372            self._store_float('ns:pixel_size/ns:z', item, 'pixel_size.z', 
    370                                detector)     
     373                               detector) 
    371374             
    372375            self._store_float('ns:slit_length', item, 'slit_length', detector) 
    373376             
    374             data_info.detector.append(detector)     
     377            data_info.detector.append(detector) 
    375378 
    376379        # Processes info ###################### 
     
    397400                    logging.error(err_mess) 
    398401             
    399             note_list = item.xpath('ns:SASprocessnote',  
     402            note_list = item.xpath('ns:SASprocessnote', 
    400403                                   namespaces={'ns': CANSAS_NS}) 
    401404            for note in note_list: 
     
    404407             
    405408            data_info.process.append(process) 
    406              
    407409             
    408410        # Data info ###################### 
     
    415417        nodes = dom.xpath('ns:SASdata/ns:Idata', namespaces={'ns': CANSAS_NS}) 
    416418 
    417         x  = numpy.zeros(0) 
    418         y  = numpy.zeros(0) 
     419        x = numpy.zeros(0) 
     420        y = numpy.zeros(0) 
    419421        dx = numpy.zeros(0) 
    420422        dy = numpy.zeros(0) 
     
    434436                _dxw = 0.0 
    435437                 
    436             if attr.has_key('unit') and \ 
     438            if 'unit' in attr and \ 
    437439                attr['unit'].lower() != data_info.x_unit.lower(): 
    438440                if HAS_CONVERTER == True: 
     
    441443                        _x = data_conv_q(_x, units=data_info.x_unit) 
    442444                    except: 
    443                         msg =  "CanSAS reader: could not convert " 
     445                        msg = "CanSAS reader: could not convert " 
    444446                        msg += "Q unit [%s]; " % attr['unit'], 
    445                         msg += "expecting [%s]\n  %s" % (data_info.x_unit,  
     447                        msg += "expecting [%s]\n  %s" % (data_info.x_unit, 
    446448                                                         sys.exc_value) 
    447449                        raise ValueError, msg 
     
    454456                         
    455457            # Error in Q 
    456             if attr_d.has_key('unit') and \ 
     458            if 'unit' in attr_d and \ 
    457459                attr_d['unit'].lower() != data_info.x_unit.lower(): 
    458460                if HAS_CONVERTER == True: 
     
    463465                        msg = "CanSAS reader: could not convert dQ unit [%s]; "\ 
    464466                        % attr['unit'] 
    465                         msg += " expecting "  
     467                        msg += " expecting " 
    466468                        msg += "[%s]\n  %s" % (data_info.x_unit, sys.exc_value) 
    467469                        raise ValueError, msg 
     
    471473                    % attr['unit'] 
    472474                    msg += "expecting [%s]" % data_info.x_unit 
    473                     raise ValueError,  msg 
     475                    raise ValueError, msg 
    474476                         
    475477            # Slit length 
    476             if attr_l.has_key('unit') and \ 
     478            if 'unit' in attr_l and \ 
    477479                attr_l['unit'].lower() != data_info.x_unit.lower(): 
    478480                if HAS_CONVERTER == True: 
     
    483485                        msg = "CanSAS reader: could not convert dQl unit [%s];"\ 
    484486                        % attr['unit'] 
    485                         msg += " expecting [%s]\n  %s" % (data_info.x_unit,  
     487                        msg += " expecting [%s]\n  %s" % (data_info.x_unit, 
    486488                                                          sys.exc_value) 
    487                         raise ValueError, msg 
    488                          
     489                        raise ValueError, msg  
    489490                else: 
    490491                    msg = "CanSAS reader: unrecognized dQl unit [%s];"\ 
     
    494495                         
    495496            # Slit width 
    496             if attr_w.has_key('unit') and \ 
     497            if 'unit' in attr_w and \ 
    497498            attr_w['unit'].lower() != data_info.x_unit.lower(): 
    498499                if HAS_CONVERTER == True: 
     
    503504                        msg = "CanSAS reader: could not convert dQw unit [%s];"\ 
    504505                        % attr['unit'] 
    505                         msg += " expecting [%s]\n  %s" % (data_info.x_unit,  
     506                        msg += " expecting [%s]\n  %s" % (data_info.x_unit, 
    506507                                                          sys.exc_value) 
    507508                        raise ValueError, msg 
     
    511512                    % attr['unit'] 
    512513                    msg += " expecting [%s]" % data_info.x_unit 
    513                     raise ValueError, msg    
     514                    raise ValueError, msg 
    514515            _y, attr = get_float('ns:I', item) 
    515516            _dy, attr_d = get_float('ns:Idev', item) 
    516517            if _dy == None: 
    517518                _dy = 0.0 
    518             if attr.has_key('unit') and \ 
     519            if 'unit' in attr and \ 
    519520            attr['unit'].lower() != data_info.y_unit.lower(): 
    520521                if HAS_CONVERTER == True: 
     
    537538                    raise ValueError, msg  
    538539                         
    539             if attr_d.has_key('unit') and \ 
     540            if 'unit' in attr_d and \ 
    540541            attr_d['unit'].lower() != data_info.y_unit.lower(): 
    541542                if HAS_CONVERTER == True: 
     
    545546                    except: 
    546547                        if attr_d['unit'].lower() == 'count': 
    547                             pass  
     548                            pass 
    548549                        else: 
    549550                            msg = "CanSAS reader: could not convert dI(q) unit " 
    550                             msg += "[%s]; expecting [%s]\n  %s"  % (attr_d['unit'], 
     551                            msg += "[%s]; expecting [%s]\n  %s" % (attr_d['unit'], 
    551552                                                 data_info.y_unit, sys.exc_value) 
    552553                            raise ValueError, msg 
     
    558559                 
    559560            if _x is not None and _y is not None: 
    560                 x  = numpy.append(x, _x) 
    561                 y  = numpy.append(y, _y) 
     561                x = numpy.append(x, _x) 
     562                y = numpy.append(y, _y) 
    562563                dx = numpy.append(dx, _dx) 
    563564                dy = numpy.append(dy, _dy) 
    564565                dxl = numpy.append(dxl, _dxl) 
    565566                dxw = numpy.append(dxw, _dxw) 
    566         # Zeros in dx, dy  
    567         if not numpy.all(dx==0): 
    568             dx[dx==0] = _ZERO 
    569         if not numpy.all(dy==0): 
    570             dy[dy==0] = _ZERO 
     567        # Zeros in dx, dy 
     568        if not numpy.all(dx == 0): 
     569            dx[dx == 0] = _ZERO 
     570        if not numpy.all(dy == 0): 
     571            dy[dy == 0] = _ZERO 
    571572        
    572         data_info.x = x[x!=0] 
    573         data_info.y = y[x!=0] 
    574         data_info.dx = dx[x!=0] 
    575          
    576         data_info.dy = dy[x!=0] 
    577         data_info.dxl = dxl[x!=0] 
    578         data_info.dxw = dxw[x!=0] 
     573        data_info.x = x[x != 0] 
     574        data_info.y = y[x != 0] 
     575        data_info.dx = dx[x != 0] 
     576         
     577        data_info.dy = dy[x != 0] 
     578        data_info.dxl = dxl[x != 0] 
     579        data_info.dxw = dxw[x != 0] 
    579580         
    580581        data_conv_q = None 
     
    589590            data_conv_i = Converter('1/cm') 
    590591            # Test it 
    591             data_conv_i(1.0, output.I_unit)                     
     592            data_conv_i(1.0, output.I_unit) 
    592593                 
    593594        if data_conv_q is not None: 
     
    598599            data_info.yaxis("\\rm{Intensity}", data_info.y_unit) 
    599600        else: 
    600             data_info.yaxis("\\rm{Intensity}","cm^{-1}") 
     601            data_info.yaxis("\\rm{Intensity}", "cm^{-1}") 
    601602 
    602603        return data_info 
     
    629630        for item in datainfo.run: 
    630631            runname = {} 
    631             if datainfo.run_name.has_key(item) and \ 
    632             len(str(datainfo.run_name[item]))>1: 
    633                 runname = {'name': datainfo.run_name[item] } 
     632            if item in datainfo.run_name and \ 
     633            len(str(datainfo.run_name[item])) > 1: 
     634                runname = {'name': datainfo.run_name[item]} 
    634635            write_node(doc, entry_node, "Run", item, runname) 
    635636         
     
    641642            pt = doc.createElement("Idata") 
    642643            node.appendChild(pt) 
    643             write_node(doc, pt, "Q", datainfo.x[i], {'unit':datainfo.x_unit}) 
    644             if len(datainfo.y)>=i: 
     644            write_node(doc, pt, "Q", datainfo.x[i], {'unit': datainfo.x_unit}) 
     645            if len(datainfo.y) >= i: 
    645646                write_node(doc, pt, "I", datainfo.y[i], 
    646                             {'unit':datainfo.y_unit}) 
     647                            {'unit': datainfo.y_unit}) 
    647648            if datainfo.dx != None and len(datainfo.dx) >= i: 
    648649                write_node(doc, pt, "Qdev", datainfo.dx[i], 
    649                             {'unit':datainfo.x_unit}) 
     650                            {'unit': datainfo.x_unit}) 
    650651            if datainfo.dxl != None and len(datainfo.dxl) >= i: 
    651652                write_node(doc, pt, "dQl", datainfo.dxl[i], 
    652                             {'unit':datainfo.x_unit})     
     653                            {'unit': datainfo.x_unit}) 
    653654            if datainfo.dxw != None and len(datainfo.dxw) >= i: 
    654655                write_node(doc, pt, "dQw", datainfo.dxw[i], 
    655                             {'unit':datainfo.x_unit})               
     656                            {'unit': datainfo.x_unit}) 
    656657            if datainfo.dy != None and len(datainfo.dy) >= i: 
    657658                write_node(doc, pt, "Idev", datainfo.dy[i], 
    658                             {'unit':datainfo.y_unit}) 
    659  
    660          
     659                            {'unit': datainfo.y_unit}) 
     660 
    661661        # Sample info 
    662662        sample = doc.createElement("SASsample") 
     
    666666        write_node(doc, sample, "ID", str(datainfo.sample.ID)) 
    667667        write_node(doc, sample, "thickness", datainfo.sample.thickness, 
    668                    {"unit":datainfo.sample.thickness_unit}) 
     668                   {"unit": datainfo.sample.thickness_unit}) 
    669669        write_node(doc, sample, "transmission", datainfo.sample.transmission) 
    670670        write_node(doc, sample, "temperature", datainfo.sample.temperature, 
    671                    {"unit":datainfo.sample.temperature_unit}) 
     671                   {"unit": datainfo.sample.temperature_unit}) 
    672672         
    673673        for item in datainfo.sample.details: 
     
    676676        pos = doc.createElement("position") 
    677677        written = write_node(doc, pos, "x", datainfo.sample.position.x, 
    678                              {"unit":datainfo.sample.position_unit}) 
     678                             {"unit": datainfo.sample.position_unit}) 
    679679        written = written | write_node(doc, pos, "y", 
    680680                                       datainfo.sample.position.y, 
    681                                        {"unit":datainfo.sample.position_unit}) 
     681                                       {"unit": datainfo.sample.position_unit}) 
    682682        written = written | write_node(doc, pos, "z", 
    683683                                       datainfo.sample.position.z, 
    684                                        {"unit":datainfo.sample.position_unit}) 
     684                                       {"unit": datainfo.sample.position_unit}) 
    685685        if written == True: 
    686686            sample.appendChild(pos) 
     
    689689        written = write_node(doc, ori, "roll", 
    690690                             datainfo.sample.orientation.x, 
    691                              {"unit":datainfo.sample.orientation_unit}) 
     691                             {"unit": datainfo.sample.orientation_unit}) 
    692692        written = written | write_node(doc, ori, "pitch", 
    693693                                       datainfo.sample.orientation.y, 
    694                                     {"unit":datainfo.sample.orientation_unit}) 
     694                                    {"unit": datainfo.sample.orientation_unit}) 
    695695        written = written | write_node(doc, ori, "yaw", 
    696696                                       datainfo.sample.orientation.z, 
    697                                     {"unit":datainfo.sample.orientation_unit}) 
     697                                    {"unit": datainfo.sample.orientation_unit}) 
    698698        if written == True: 
    699699            sample.appendChild(ori) 
     
    717717            size.setAttribute("name", str(datainfo.source.beam_size_name)) 
    718718        written = write_node(doc, size, "x", datainfo.source.beam_size.x, 
    719                              {"unit":datainfo.source.beam_size_unit}) 
     719                             {"unit": datainfo.source.beam_size_unit}) 
    720720        written = written | write_node(doc, size, "y", 
    721721                                       datainfo.source.beam_size.y, 
    722                                        {"unit":datainfo.source.beam_size_unit}) 
     722                                       {"unit": datainfo.source.beam_size_unit}) 
    723723        written = written | write_node(doc, size, "z", 
    724724                                       datainfo.source.beam_size.z, 
    725                                        {"unit":datainfo.source.beam_size_unit}) 
     725                                       {"unit": datainfo.source.beam_size_unit}) 
    726726        if written == True: 
    727727            source.appendChild(size) 
     
    729729        write_node(doc, source, "wavelength", 
    730730                   datainfo.source.wavelength, 
    731                    {"unit":datainfo.source.wavelength_unit}) 
     731                   {"unit": datainfo.source.wavelength_unit}) 
    732732        write_node(doc, source, "wavelength_min", 
    733733                   datainfo.source.wavelength_min, 
    734                    {"unit":datainfo.source.wavelength_min_unit}) 
     734                   {"unit": datainfo.source.wavelength_min_unit}) 
    735735        write_node(doc, source, "wavelength_max", 
    736736                   datainfo.source.wavelength_max, 
    737                    {"unit":datainfo.source.wavelength_max_unit}) 
     737                   {"unit": datainfo.source.wavelength_max_unit}) 
    738738        write_node(doc, source, "wavelength_spread", 
    739739                   datainfo.source.wavelength_spread, 
    740                    {"unit":datainfo.source.wavelength_spread_unit}) 
     740                   {"unit": datainfo.source.wavelength_spread_unit}) 
    741741         
    742742        #   Collimation 
     
    748748             
    749749            write_node(doc, coll, "length", item.length, 
    750                        {"unit":item.length_unit}) 
     750                       {"unit": item.length_unit}) 
    751751             
    752752            for apert in item.aperture: 
     
    759759                 
    760760                write_node(doc, ap, "distance", apert.distance, 
    761                            {"unit":apert.distance_unit}) 
     761                           {"unit": apert.distance_unit}) 
    762762                 
    763763                size = doc.createElement("size") 
     
    765765                    size.setAttribute("name", str(apert.size_name)) 
    766766                written = write_node(doc, size, "x", apert.size.x, 
    767                                      {"unit":apert.size_unit}) 
     767                                     {"unit": apert.size_unit}) 
    768768                written = written | write_node(doc, size, "y", apert.size.y, 
    769                                                {"unit":apert.size_unit}) 
     769                                               {"unit": apert.size_unit}) 
    770770                written = written | write_node(doc, size, "z", apert.size.z, 
    771                                                {"unit":apert.size_unit}) 
     771                                               {"unit": apert.size_unit}) 
    772772                if written == True: 
    773773                    ap.appendChild(size) 
     
    778778            written = write_node(doc, det, "name", item.name) 
    779779            written = written | write_node(doc, det, "SDD", item.distance, 
    780                                            {"unit":item.distance_unit}) 
     780                                           {"unit": item.distance_unit}) 
    781781            written = written | write_node(doc, det, "slit_length", 
    782782                                           item.slit_length, 
    783                                            {"unit":item.slit_length_unit}) 
     783                                           {"unit": item.slit_length_unit}) 
    784784            if written == True: 
    785785                instr.appendChild(det) 
     
    787787            off = doc.createElement("offset") 
    788788            written = write_node(doc, off, "x", item.offset.x, 
    789                                  {"unit":item.offset_unit}) 
     789                                 {"unit": item.offset_unit}) 
    790790            written = written | write_node(doc, off, "y", item.offset.y, 
    791                                            {"unit":item.offset_unit}) 
     791                                           {"unit": item.offset_unit}) 
    792792            written = written | write_node(doc, off, "z", item.offset.z, 
    793                                            {"unit":item.offset_unit}) 
     793                                           {"unit": item.offset_unit}) 
    794794            if written == True: 
    795795                det.appendChild(off) 
     
    797797            center = doc.createElement("beam_center") 
    798798            written = write_node(doc, center, "x", item.beam_center.x, 
    799                                  {"unit":item.beam_center_unit}) 
     799                                 {"unit": item.beam_center_unit}) 
    800800            written = written | write_node(doc, center, "y", 
    801801                                           item.beam_center.y, 
    802                                            {"unit":item.beam_center_unit}) 
     802                                           {"unit": item.beam_center_unit}) 
    803803            written = written | write_node(doc, center, "z", 
    804804                                           item.beam_center.z, 
    805                                            {"unit":item.beam_center_unit}) 
     805                                           {"unit": item.beam_center_unit}) 
    806806            if written == True: 
    807807                det.appendChild(center) 
     
    809809            pix = doc.createElement("pixel_size") 
    810810            written = write_node(doc, pix, "x", item.pixel_size.x, 
    811                                  {"unit":item.pixel_size_unit}) 
     811                                 {"unit": item.pixel_size_unit}) 
    812812            written = written | write_node(doc, pix, "y", item.pixel_size.y, 
    813                                            {"unit":item.pixel_size_unit}) 
     813                                           {"unit": item.pixel_size_unit}) 
    814814            written = written | write_node(doc, pix, "z", item.pixel_size.z, 
    815                                            {"unit":item.pixel_size_unit}) 
     815                                           {"unit": item.pixel_size_unit}) 
    816816            if written == True: 
    817817                det.appendChild(pix) 
    818818                 
    819819            ori = doc.createElement("orientation") 
    820             written = write_node(doc, ori, "roll",  item.orientation.x, 
    821                                  {"unit":item.orientation_unit}) 
     820            written = write_node(doc, ori, "roll", item.orientation.x, 
     821                                 {"unit": item.orientation_unit}) 
    822822            written = written | write_node(doc, ori, "pitch", 
    823823                                           item.orientation.y, 
    824                                            {"unit":item.orientation_unit}) 
     824                                           {"unit": item.orientation_unit}) 
    825825            written = written | write_node(doc, ori, "yaw", 
    826826                                           item.orientation.z, 
    827                                            {"unit":item.orientation_unit}) 
     827                                           {"unit": item.orientation_unit}) 
    828828            if written == True: 
    829829                det.appendChild(ori) 
    830830                 
    831          
    832831        # Processes info 
    833832        for item in datainfo.process: 
     
    857856        """ 
    858857        # Create XML document 
    859         doc, sasentry = self._to_xml_doc(datainfo) 
     858        doc, _ = self._to_xml_doc(datainfo) 
    860859        # Write the file 
    861860        fd = open(filename, 'w') 
     
    877876        :param variable: name of the data member to store it in [string] 
    878877        :param storage: data object that has the 'variable' data member 
    879         :param optional: if True, no exception will be raised  
     878        :param optional: if True, no exception will be raised 
    880879            if unit conversion can't be done 
    881880 
     
    895894                toks = variable.split('.') 
    896895                exec "local_unit = storage.%s_unit" % toks[0] 
    897                 if units.lower()!=local_unit.lower(): 
     896                if units.lower() != local_unit.lower(): 
    898897                    if HAS_CONVERTER == True: 
    899898                        try: 
     
    909908                                logging.info(err_mess) 
    910909                            else: 
    911                                 raise ValueError, err_mess  
     910                                raise ValueError, err_mess 
    912911                    else: 
    913912                        err_mess = "CanSAS reader: unrecognized %s unit [%s];"\ 
     
    942941        if entry is not None and entry.text is not None: 
    943942            exec "storage.%s = entry.text.strip()" % variable 
    944  
    945              
    946              
    947 if __name__ == "__main__":  
    948     logging.basicConfig(level=logging.ERROR, 
    949                         format='%(asctime)s %(levelname)s %(message)s', 
    950                         filename='cansas_reader.log', 
    951                         filemode='w') 
    952     reader = Reader() 
    953     print reader.read("../test/cansas1d.xml") 
    954     #print reader.read("../test/latex_smeared.xml") 
    955      
    956      
    957                          
  • sansdataloader/src/sans/dataloader/readers/danse_reader.py

    rad8034f r7d6351e  
    1  
    2  
     1""" 
     2    DANSE/SANS file reader 
     3""" 
    34############################################################################ 
    45#This software was developed by the University of Tennessee as part of the 
    56#Distributed Data Analysis of Neutron Scattering Experiments (DANSE) 
    67#project funded by the US National Science Foundation.  
    7 #If you use DANSE applications to do scientific research that leads to  
    8 #publication, we ask that you acknowledge the use of the software with the  
     8#If you use DANSE applications to do scientific research that leads to 
     9#publication, we ask that you acknowledge the use of the software with the 
    910#following sentence: 
    10 #This work benefited from DANSE software developed under NSF award DMR-0520547.  
     11#This work benefited from DANSE software developed under NSF award DMR-0520547. 
    1112#copyright 2008, University of Tennessee 
    1213############################################################################# 
    13  
    14 """ 
    15     DANSE/SANS file reader 
    16 """ 
    17  
    1814import math 
    1915import os 
     
    3127    has_converter = False 
    3228 
     29 
    3330class Reader: 
    3431    """ 
     
    3633    """ 
    3734    ## File type 
    38     type_name = "DANSE"    
     35    type_name = "DANSE" 
    3936    ## Wildcards 
    4037    type = ["DANSE files (*.sans)|*.sans"] 
    4138    ## Extension 
    42     ext  = ['.sans', '.SANS']     
     39    ext  = ['.sans', '.SANS'] 
    4340         
    4441    def read(self, filename=None): 
     
    5653            try: 
    5754                datafile = open(filename, 'r') 
    58             except : 
     55            except: 
    5956                raise  RuntimeError,"danse_reader cannot open %s" % (filename) 
    6057         
     
    9693                data_conv_i = Converter('1/cm') 
    9794                # Test it 
    98                 data_conv_i(1.0, output.I_unit)             
     95                data_conv_i(1.0, output.I_unit) 
    9996         
    10097            read_on = True 
     
    107104                if toks[0] == "FORMATVERSION": 
    108105                    fversion = float(toks[1]) 
    109                 if toks[0] == "WAVELENGTH":     
    110                     wavelength = float(toks[1])                 
     106                if toks[0] == "WAVELENGTH": 
     107                    wavelength = float(toks[1]) 
    111108                elif toks[0] == "DISTANCE": 
    112109                    distance = float(toks[1]) 
     
    145142                            error.append(err) 
    146143                        except: 
    147                             logging.info("Skipping line:%s,%s" %( data_str, 
     144                            logging.info("Skipping line:%s,%s" %(data_str, 
    148145                                                                sys.exc_value)) 
    149146             
    150             # Initialize  
     147            # Initialize 
    151148            x_vals = [] 
    152             y_vals = []  
     149            y_vals = [] 
    153150            ymin = None 
    154151            ymax = None 
     
    158155            # Qx and Qy vectors 
    159156            theta = pixel / distance / 100.0 
    160             stepq = 4.0 * math.pi/wavelength * math.sin(theta/2.0)  
     157            stepq = 4.0 * math.pi / wavelength * math.sin(theta / 2.0) 
    161158            for i_x in range(size_x): 
    162159                theta = (i_x - center_x + 1) * pixel / distance / 100.0 
    163                 qx = 4.0 * math.pi / wavelength * math.sin(theta/2.0) 
     160                qx = 4.0 * math.pi / wavelength * math.sin(theta / 2.0) 
    164161                 
    165162                if has_converter == True and output.Q_unit != '1/A': 
     
    176173            for i_y in range(size_y): 
    177174                theta = (i_y - center_y + 1) * pixel / distance / 100.0 
    178                 qy = 4.0 * math.pi/wavelength * math.sin(theta/2.0) 
     175                qy = 4.0 * math.pi / wavelength * math.sin(theta/2.0) 
    179176                 
    180177                if has_converter == True and output.Q_unit != '1/A': 
     
    188185             
    189186            # Store the data in the 2D array 
    190             itot = 0 
    191             i_x  = 0 
    192             i_y  = -1 
     187            i_x = 0 
     188            i_y = -1 
    193189             
    194190            for i_pt in range(len(data)): 
     
    198194                    # For version 1.0, the data were still 
    199195                    # stored as strings at this point. 
    200                     msg = "Skipping entry (v1.0):%s,%s" %(str(data[i_pt]), 
     196                    msg = "Skipping entry (v1.0):%s,%s" % (str(data[i_pt]), 
    201197                                                           sys.exc_value) 
    202198                    logging.info(msg) 
     
    209205                    i_x += 1 
    210206                     
    211                 output.data[i_y][i_x] = value        
    212                 #output.data[size_y-1-i_y][i_x] = value 
     207                output.data[i_y][i_x] = value 
    213208                if fversion>1.0: 
    214209                    output.err_data[i_y][i_x] = error[i_pt] 
    215                     #output.err_data[size_y-1-i_y][i_x] = error[i_pt] 
    216                  
    217  
    218             # Store all data  
     210                 
     211            # Store all data 
    219212            # Store wavelength 
    220213            if has_converter == True and output.source.wavelength_unit != 'A': 
     
    238231 
    239232            # Store beam center in distance units 
    240             detector.beam_center.x = center_x*pixel 
    241             detector.beam_center.y = center_y*pixel 
     233            detector.beam_center.x = center_x * pixel 
     234            detector.beam_center.y = center_y * pixel 
    242235             
    243236            # Store limits of the image (2D array) 
    244237            xmin = xmin - stepq / 2.0 
    245238            xmax = xmax + stepq / 2.0 
    246             ymin = ymin - stepq  /2.0 
     239            ymin = ymin - stepq /2.0 
    247240            ymax = ymax + stepq / 2.0 
    248241             
     
    258251             
    259252            # Store x and y axis bin centers 
    260             output.x_bins     = x_vals 
    261             output.y_bins     = y_vals 
     253            output.x_bins = x_vals 
     254            output.y_bins = y_vals 
    262255            
    263256            # Units 
     
    272265                output.zaxis("\\rm{Intensity}", output.I_unit) 
    273266            else: 
    274                 output.zaxis("\\rm{Intensity}","cm^{-1}") 
     267                output.zaxis("\\rm{Intensity}", "cm^{-1}") 
    275268            
    276269            if not fversion >= 1.0: 
     
    281274             
    282275            # Store loading process information 
    283             output.meta_data['loader'] = self.type_name     
     276            output.meta_data['loader'] = self.type_name 
    284277            output = reader2D_converter(output) 
    285278            return output 
    286279         
    287280        return None 
    288  
    289 if __name__ == "__main__":  
    290     reader = Reader() 
    291     print reader.read("../test/MP_New.sans") 
    292      
  • sansdataloader/src/sans/dataloader/readers/hfir1d_reader.py

    rad8034f r7d6351e  
    1  
     1""" 
     2    HFIR 1D 4-column data reader 
     3""" 
    24##################################################################### 
    35#This software was developed by the University of Tennessee as part of the 
    46#Distributed Data Analysis of Neutron Scattering Experiments (DANSE) 
    5 #project funded by the US National Science Foundation.  
     7#project funded by the US National Science Foundation. 
    68#See the license text in license.txt 
    79#copyright 2008, University of Tennessee 
    810###################################################################### 
    9  
    1011import numpy 
    1112import os 
     
    2425    """ 
    2526    ## File type 
    26     type_name = "HFIR 1D"    
     27    type_name = "HFIR 1D" 
    2728    ## Wildcards 
    2829    type = ["HFIR 1D files (*.d1d)|*.d1d"] 
    2930    ## List of allowed extensions 
    30     ext = ['.d1d']   
     31    ext = ['.d1d'] 
    3132     
    3233    def read(self, path): 
     
    4243        """ 
    4344        if os.path.isfile(path): 
    44             basename  = os.path.basename(path) 
     45            basename = os.path.basename(path) 
    4546            root, extension = os.path.splitext(basename) 
    4647            if extension.lower() in self.ext: 
    4748                try: 
    48                     input_f =  open(path,'r') 
    49                 except : 
     49                    input_f = open(path,'r') 
     50                except: 
    5051                    raise  RuntimeError, "hfir1d_reader: cannot open %s" % path 
    5152                buff = input_f.read() 
    5253                lines = buff.split('\n') 
    53                 x  = numpy.zeros(0) 
    54                 y  = numpy.zeros(0) 
     54                x = numpy.zeros(0) 
     55                y = numpy.zeros(0) 
    5556                dx = numpy.zeros(0) 
    5657                dy = numpy.zeros(0) 
     
    8485                             
    8586                        if data_conv_i is not None: 
    86                             _y = data_conv_i(_y, units=output.y_unit)                         
    87                             _dy = data_conv_i(_dy, units=output.y_unit)                         
     87                            _y = data_conv_i(_y, units=output.y_unit) 
     88                            _dy = data_conv_i(_dy, units=output.y_unit) 
    8889                                                     
    89                         x   = numpy.append(x, _x)  
    90                         y   = numpy.append(y, _y) 
    91                         dx  = numpy.append(dx, _dx) 
    92                         dy  = numpy.append(dy, _dy)                         
     90                        x = numpy.append(x, _x) 
     91                        y = numpy.append(y, _y) 
     92                        dx = numpy.append(dx, _dx) 
     93                        dy = numpy.append(dy, _dy) 
    9394                    except: 
    9495                        # Couldn't parse this line, skip it  
    9596                        pass 
    9697                          
    97                       
    9898                # Sanity check 
    9999                if not len(y) == len(dy): 
     
    120120                    output.yaxis("\\rm{Intensity}", output.y_unit) 
    121121                else: 
    122                     output.yaxis("\\rm{Intensity}","cm^{-1}") 
     122                    output.yaxis("\\rm{Intensity}", "cm^{-1}") 
    123123                 
    124124                # Store loading process information 
    125                 output.meta_data['loader'] = self.type_name    
     125                output.meta_data['loader'] = self.type_name 
    126126                return output 
    127127        else: 
    128128            raise RuntimeError, "%s is not a file" % path 
    129129        return None 
    130      
    131 if __name__ == "__main__":  
    132     reader = Reader() 
    133     print reader.read("../test/S2-30dq.d1d") 
    134      
    135      
    136                          
  • sansdataloader/src/sans/dataloader/readers/red2d_reader.py

    rad8034f r7d6351e  
    1  
     1""" 
     2    TXT/IGOR 2D Q Map file reader 
     3""" 
    24##################################################################### 
    35#This software was developed by the University of Tennessee as part of the 
     
    79#copyright 2008, University of Tennessee 
    810###################################################################### 
    9  
    10 """ 
    11     TXT/IGOR 2D Q Map file reader 
    12 """ 
    13  
    14  
    1511import os 
    16 #import sys 
    1712import numpy 
    1813import math 
    19 #import logging 
    2014from sans.dataloader.data_info import Data2D, Detector 
    2115 
     
    2620except: 
    2721    has_converter = False 
     22     
    2823     
    2924def check_point(x_point): 
     
    3631    except: 
    3732        return 0 
     33       
    3834         
    3935class Reader: 
    4036    """ Simple data reader for Igor data files """ 
    4137    ## File type 
    42     type_name = "IGOR/DAT 2D Q_map"    
     38    type_name = "IGOR/DAT 2D Q_map" 
    4339    ## Wildcards 
    4440    type = ["IGOR/DAT 2D file in Q_map (*.dat)|*.DAT"] 
    4541    ## Extension 
    46     ext=['.DAT', '.dat'] 
     42    ext = ['.DAT', '.dat'] 
    4743     
    4844    def write(self, filename, data): 
     
    5147         
    5248        :param filename: file name to write 
    53         :param data: data2D  
     49        :param data: data2D 
    5450        """ 
    5551        import time 
    56         st = time.time() 
    5752        # Write the file 
    5853        fd = open(filename, 'w') 
     
    6661        # write qx qy I values 
    6762        for i in range(len(data.data)): 
    68             fd.write("%g  %g  %g\n" % (data.qx_data[i],  
     63            fd.write("%g  %g  %g\n" % (data.qx_data[i], 
    6964                                        data.qy_data[i], 
    7065                                       data.data[i])) 
    7166        # close 
    72         fd.close()                  
    73  
    74     def read(self,filename=None): 
     67        fd.close() 
     68 
     69    def read(self, filename=None): 
    7570        """ Read file """ 
    7671        if not os.path.isfile(filename): 
     
    7974 
    8075        # Read file 
    81         f = open(filename,'r') 
     76        f = open(filename, 'r') 
    8277        buf = f.read() 
    83         f.close()      
     78        f.close() 
    8479        # Instantiate data object 
    8580        output = Data2D() 
    8681        output.filename = os.path.basename(filename) 
    8782        detector = Detector() 
    88         if len(output.detector)>0: print str(output.detector[0]) 
     83        if len(output.detector) > 0: 
     84            print str(output.detector[0]) 
    8985        output.detector.append(detector) 
    9086                 
     
    9288        dataStarted = False 
    9389         
    94         ## Defaults       
     90        ## Defaults 
    9591        lines = buf.split('\n') 
    96         itot = 0 
    9792        x = [] 
    9893        y = [] 
    9994         
    100         ncounts = 0 
    101          
    102         wavelength   = None 
    103         distance     = None 
     95        wavelength = None 
     96        distance = None 
    10497        transmission = None 
    10598         
     
    107100        pixel_y = None 
    108101         
    109         i_x    = 0 
    110         i_y    = -1 
    111         pixels = 0 
    112          
    113         isInfo   = False 
     102        isInfo = False 
    114103        isCenter = False 
    115104 
     
    126115            data_conv_i = Converter('1/cm') 
    127116            # Test it 
    128             data_conv_i(1.0, output.I_unit)             
     117            data_conv_i(1.0, output.I_unit) 
    129118         
    130119               
     
    132121        # to calculate the exact number of data points 
    133122        count = 0 
    134         while (len(lines[len(lines)-(count+1)].lstrip().rstrip()) < 1): 
    135             del lines[len(lines)-(count+1)] 
     123        while (len(lines[len(lines) - (count + 1)].lstrip().rstrip()) < 1): 
     124            del lines[len(lines) - (count + 1)] 
    136125            count = count + 1 
    137126 
     
    140129        # Old version NIST files: 0 
    141130        ver = 0 
    142         for line in lines:       
     131        for line in lines: 
    143132            line_num += 1 
    144133            ## Reading the header applies only to IGOR/NIST 2D q_map data files 
     
    182171            # Find center info line 
    183172            if isCenter: 
    184                 isCenter = False                 
     173                isCenter = False 
    185174                line_toks = line.split() 
    186175                # Center in bin number 
     
    199188                continue 
    200189 
    201             ## Read and get data.    
     190            ## Read and get data. 
    202191            if dataStarted == True: 
    203                 line_toks = line.split()               
     192                line_toks = line.split() 
    204193                if len(line_toks) == 0: 
    205194                    #empty line 
     
    223212        data_list = data_list.split() 
    224213  
    225         # Check if the size is consistent with data, otherwise  
     214        # Check if the size is consistent with data, otherwise 
    226215        #try the tab(\t) separator 
    227         # (this may be removed once get the confidence  
     216        # (this may be removed once get the confidence 
    228217        #the former working all cases). 
    229218        if len(data_list) != (len(data_lines)) * col_num: 
     
    233222        # Change it(string) into float 
    234223        #data_list = map(float,data_list) 
    235         data_list1 = map(check_point,data_list) 
     224        data_list1 = map(check_point, data_list) 
    236225 
    237226        # numpy array form 
    238227        data_array = numpy.array(data_list1) 
    239         # Redimesion based on the row_num and col_num,  
     228        # Redimesion based on the row_num and col_num, 
    240229        #otherwise raise an error. 
    241230        try: 
     
    250239        err_data = numpy.ones(row_num) 
    251240        qz_data = numpy.zeros(row_num) 
    252         mask = numpy.ones(row_num,dtype=bool) 
     241        mask = numpy.ones(row_num, dtype=bool) 
    253242        # Get from the array 
    254243        qx_data = data_point[0] 
     
    256245        data = data_point[2] 
    257246        if ver == 1: 
    258             if col_num > (2 + ver): err_data = data_point[(2 + ver)] 
    259         if col_num > (3 + ver): qz_data = data_point[(3 + ver)] 
    260         if col_num > (4 + ver): dqx_data = data_point[(4 + ver)] 
    261         if col_num > (5 + ver): dqy_data = data_point[(5 + ver)] 
     247            if col_num > (2 + ver): 
     248                err_data = data_point[(2 + ver)] 
     249        if col_num > (3 + ver): 
     250            qz_data = data_point[(3 + ver)] 
     251        if col_num > (4 + ver): 
     252            dqx_data = data_point[(4 + ver)] 
     253        if col_num > (5 + ver): 
     254            dqy_data = data_point[(5 + ver)] 
    262255        #if col_num > (6 + ver): mask[data_point[(6 + ver)] < 1] = False 
    263256        q_data = numpy.sqrt(qx_data*qx_data+qy_data*qy_data+qz_data*qz_data) 
     
    265258        # Extra protection(it is needed for some data files):  
    266259        # If all mask elements are False, put all True 
    267         if not mask.any(): mask[mask==False] = True    
     260        if not mask.any(): 
     261            mask[mask == False] = True 
    268262   
    269263        # Store limits of the image in q space 
    270         xmin    = numpy.min(qx_data) 
    271         xmax    = numpy.max(qx_data) 
    272         ymin    = numpy.min(qy_data) 
    273         ymax    = numpy.max(qy_data) 
     264        xmin = numpy.min(qx_data) 
     265        xmax = numpy.max(qx_data) 
     266        ymin = numpy.min(qy_data) 
     267        ymax = numpy.max(qy_data) 
    274268 
    275269        # units 
     
    286280        # calculate the number of pixels in the each axes 
    287281        npix_y = math.floor(math.sqrt(len(data))) 
    288         npix_x = math.floor(len(data)/npix_y) 
    289          
    290         # calculate the size of bins       
    291         xstep = x_size/(npix_x-1) 
    292         ystep = y_size/(npix_y-1) 
     282        npix_x = math.floor(len(data) / npix_y) 
     283         
     284        # calculate the size of bins 
     285        xstep = x_size / (npix_x - 1) 
     286        ystep = y_size / (npix_y - 1) 
    293287         
    294288        # store x and y axis bin centers in q space 
    295         x_bins  = numpy.arange(xmin,xmax+xstep,xstep) 
    296         y_bins  = numpy.arange(ymin,ymax+ystep,ystep) 
     289        x_bins = numpy.arange(xmin, xmax + xstep, xstep) 
     290        y_bins = numpy.arange(ymin, ymax + ystep, ystep) 
    297291        
    298292        # get the limits of q values 
    299         xmin = xmin - xstep/2 
    300         xmax = xmax + xstep/2 
    301         ymin = ymin - ystep/2 
    302         ymax = ymax + ystep/2 
    303          
    304         #Store data in outputs   
    305         #TODO: Check the lengths  
    306         output.data     = data 
     293        xmin = xmin - xstep / 2 
     294        xmax = xmax + xstep / 2 
     295        ymin = ymin - ystep / 2 
     296        ymax = ymax + ystep / 2 
     297         
     298        #Store data in outputs 
     299        #TODO: Check the lengths 
     300        output.data = data 
    307301        if (err_data == 1).all(): 
    308302            output.err_data = numpy.sqrt(numpy.abs(data)) 
     
    311305            output.err_data = err_data 
    312306             
    313         output.qx_data  = qx_data 
    314         output.qy_data  = qy_data              
    315         output.q_data   = q_data 
    316         output.mask     = mask  
     307        output.qx_data = qx_data 
     308        output.qy_data = qy_data 
     309        output.q_data = q_data 
     310        output.mask = mask 
    317311         
    318312        output.x_bins = x_bins 
     
    334328         
    335329        # optional data: if all of dq data == 0, do not pass to output 
    336         if len(dqx_data) == len(qx_data) and dqx_data.any()!=0:  
     330        if len(dqx_data) == len(qx_data) and dqx_data.any() != 0: 
    337331            # if no dqx_data, do not pass dqy_data. 
    338332            #(1 axis dq is not supported yet). 
    339             if len(dqy_data) == len(qy_data) and dqy_data.any()!=0: 
     333            if len(dqy_data) == len(qy_data) and dqy_data.any() != 0: 
    340334                # Currently we do not support dq parr, perp. 
    341335                # tranfer the comp. to cartesian coord. for newer version. 
     
    346340                    output.dqx_data = numpy.sqrt((dqx_data * cos_th) * \ 
    347341                                                 (dqx_data * cos_th) \ 
    348                                                  + ( dqy_data * sin_th) * \ 
    349                                                   ( dqy_data * sin_th)) 
     342                                                 + (dqy_data * sin_th) * \ 
     343                                                  (dqy_data * sin_th)) 
    350344                    output.dqy_data = numpy.sqrt((dqx_data * sin_th) * \ 
    351345                                                 (dqx_data * sin_th) \ 
    352                                                  + ( dqy_data * cos_th) * \ 
    353                                                   ( dqy_data * cos_th)) 
     346                                                 + (dqy_data * cos_th) * \ 
     347                                                  (dqy_data * cos_th)) 
    354348                else: 
    355349                    output.dqx_data = dqx_data 
     
    362356        else: 
    363357            output.xaxis("\\rm{Q_{x}}", 'A^{-1}') 
    364             output.yaxis("\\rm{Q_{y}}", 'A^{-1}')             
     358            output.yaxis("\\rm{Q_{y}}", 'A^{-1}') 
    365359        if data_conv_i is not None: 
    366360            output.zaxis("\\rm{Intensity}", output.I_unit) 
    367361        else: 
    368             output.zaxis("\\rm{Intensity}","cm^{-1}") 
     362            output.zaxis("\\rm{Intensity}", "cm^{-1}") 
    369363     
    370364        # Store loading process information 
     
    372366 
    373367        return output 
    374      
    375 if __name__ == "__main__":  
    376     reader = Reader() 
    377     print reader.read("../test/exp18_14_igor_2dqxqy.dat")  
    378          
    379  
  • sansdataloader/src/sans/dataloader/readers/tiff_reader.py

    rad8034f r7d6351e  
    1  
    2  
    31##################################################################### 
    42#This software was developed by the University of Tennessee as part of the 
     
    97###################################################################### 
    108""" 
    11     Image reader. Untested.  
     9    Image reader. Untested. 
    1210""" 
    13  
    14  
    1511#TODO: load and check data and orientation of the image (needs rendering) 
    16  
    17 import math, logging, os 
     12import math 
     13import logging 
     14import os 
    1815import numpy 
    1916from sans.dataloader.data_info import Data2D 
     17     
    2018     
    2119class Reader: 
     
    2422    """ 
    2523    ## File type 
    26     type_name = "TIF"    
     24    type_name = "TIF" 
    2725    ## Wildcards 
    2826    type = ["TIF files (*.tif)|*.tif", 
     
    3028            ] 
    3129    ## Extension 
    32     ext  = ['.tif', '.tiff']     
     30    ext = ['.tif', '.tiff'] 
    3331         
    3432    def read(self, filename=None): 
     
    5149        try: 
    5250            im = Image.open(filename) 
    53         except : 
    54             raise  RuntimeError,"cannot open %s"%(filename) 
     51        except: 
     52            raise  RuntimeError, "cannot open %s"%(filename) 
    5553        data = im.getdata() 
    5654 
    5755        # Initiazed the output data object 
    58         output.data = numpy.zeros([im.size[0],im.size[1]]) 
    59         output.err_data = numpy.zeros([im.size[0],im.size[1]]) 
     56        output.data = numpy.zeros([im.size[0], im.size[1]]) 
     57        output.err_data = numpy.zeros([im.size[0], im.size[1]]) 
    6058         
    61         # Initialize  
     59        # Initialize 
    6260        x_vals = [] 
    63         y_vals = []  
     61        y_vals = [] 
    6462 
    6563        # x and y vectors 
     
    7977             
    8078            # Get bin number 
    81             if math.fmod(itot, im.size[0])==0: 
     79            if math.fmod(itot, im.size[0]) == 0: 
    8280                i_x = 0 
    8381                i_y += 1 
     
    8583                i_x += 1 
    8684                 
    87             output.data[im.size[1]-1-i_y][i_x] = value 
     85            output.data[im.size[1] - 1 - i_y][i_x] = value 
    8886             
    8987            itot += 1 
    9088                 
    91         output.xbins      = im.size[0] 
    92         output.ybins      = im.size[1] 
    93         output.x_bins     = x_vals 
    94         output.y_bins     = y_vals 
    95         output.xmin       = 0 
    96         output.xmax       = im.size[0]-1 
    97         output.ymin       = 0 
    98         output.ymax       = im.size[0]-1 
     89        output.xbins = im.size[0] 
     90        output.ybins = im.size[1] 
     91        output.x_bins = x_vals 
     92        output.y_bins = y_vals 
     93        output.xmin = 0 
     94        output.xmax = im.size[0] - 1 
     95        output.ymin = 0 
     96        output.ymax = im.size[0] - 1 
    9997         
    10098        # Store loading process information 
    101         output.meta_data['loader'] = self.type_name  
     99        output.meta_data['loader'] = self.type_name 
    102100        return output 
    103          
    104  
    105 if __name__ == "__main__":  
    106     reader = Reader() 
    107     print reader.read("../test/MP_New.sans") 
    108      
    109  
Note: See TracChangeset for help on using the changeset viewer.