Changeset 41e0a3b in sasview for src/sas/sascalc/dataloader/readers


Ignore:
Timestamp:
Apr 4, 2017 1:04:32 PM (7 years ago)
Author:
Adam Washington <adam.washington@…>
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.2.2, ticket-1009, ticket-1094-headless, ticket-1242-2d-resolution, ticket-1243, ticket-1249, ticket885, unittest-saveload
Children:
35009a0
Parents:
2d866370 (diff), dd11014 (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the (diff) links above to see all the changes relative to each parent.
Message:

Merge branch 'master' of github.com:SasView/sasview

Location:
src/sas/sascalc/dataloader/readers
Files:
8 edited

Legend:

Unmodified
Added
Removed
  • src/sas/sascalc/dataloader/readers/IgorReader.py

    rb699768 rdd11014  
    1313############################################################################# 
    1414import os 
    15 import numpy 
    16 import math 
    17 #import logging 
     15 
    1816from sas.sascalc.dataloader.data_info import Data2D 
    1917from sas.sascalc.dataloader.data_info import Detector 
    2018from sas.sascalc.dataloader.manipulations import reader2D_converter 
     19import numpy as np 
    2120 
    2221# Look for unit converter 
     
    4039        """ Read file """ 
    4140        if not os.path.isfile(filename): 
    42             raise ValueError, \ 
    43             "Specified file %s is not a regular file" % filename 
    44          
    45         # Read file 
    46         f = open(filename, 'r') 
    47         buf = f.read() 
    48          
    49         # Instantiate data object 
     41            raise ValueError("Specified file %s is not a regular " 
     42                             "file" % filename) 
     43         
    5044        output = Data2D() 
     45 
    5146        output.filename = os.path.basename(filename) 
    5247        detector = Detector() 
    53         if len(output.detector) > 0: 
    54             print str(output.detector[0]) 
     48        if len(output.detector): 
     49            print(str(output.detector[0])) 
    5550        output.detector.append(detector) 
    56                  
    57         # Get content 
    58         dataStarted = False 
    59          
    60         lines = buf.split('\n') 
    61         itot = 0 
    62         x = [] 
    63         y = [] 
    64          
    65         ncounts = 0 
    66          
    67         xmin = None 
    68         xmax = None 
    69         ymin = None 
    70         ymax = None 
    71          
    72         i_x = 0 
    73         i_y = -1 
    74         i_tot_row = 0 
    75          
    76         isInfo = False 
    77         isCenter = False 
    78         
    79         data_conv_q = None 
    80         data_conv_i = None 
    81          
    82         if has_converter == True and output.Q_unit != '1/A': 
     51 
     52        data_conv_q = data_conv_i = None 
     53         
     54        if has_converter and output.Q_unit != '1/A': 
    8355            data_conv_q = Converter('1/A') 
    8456            # Test it 
    8557            data_conv_q(1.0, output.Q_unit) 
    8658             
    87         if has_converter == True and output.I_unit != '1/cm': 
     59        if has_converter and output.I_unit != '1/cm': 
    8860            data_conv_i = Converter('1/cm') 
    8961            # Test it 
    9062            data_conv_i(1.0, output.I_unit) 
    91           
    92         for line in lines: 
    93              
    94             # Find setup info line 
    95             if isInfo: 
    96                 isInfo = False 
    97                 line_toks = line.split() 
    98                 # Wavelength in Angstrom 
    99                 try: 
    100                     wavelength = float(line_toks[1]) 
    101                 except: 
    102                     msg = "IgorReader: can't read this file, missing wavelength" 
    103                     raise ValueError, msg 
    104                  
    105             #Find # of bins in a row assuming the detector is square. 
    106             if dataStarted == True: 
    107                 try: 
    108                     value = float(line) 
    109                 except: 
    110                     # Found a non-float entry, skip it 
    111                     continue 
    112                  
    113                 # Get total bin number 
    114                  
    115             i_tot_row += 1 
    116         i_tot_row = math.ceil(math.sqrt(i_tot_row)) - 1 
    117         #print "i_tot", i_tot_row 
    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]) 
    122       
    123         #Read Header and 2D data 
    124         for line in lines: 
    125             # Find setup info line 
    126             if isInfo: 
    127                 isInfo = False 
    128                 line_toks = line.split() 
    129                 # Wavelength in Angstrom 
    130                 try: 
    131                     wavelength = float(line_toks[1]) 
    132                 except: 
    133                     msg = "IgorReader: can't read this file, missing wavelength" 
    134                     raise ValueError, msg 
    135                 # Distance in meters 
    136                 try: 
    137                     distance = float(line_toks[3]) 
    138                 except: 
    139                     msg = "IgorReader: can't read this file, missing distance" 
    140                     raise ValueError, msg 
    141                  
    142                 # Distance in meters 
    143                 try: 
    144                     transmission = float(line_toks[4]) 
    145                 except: 
    146                     msg = "IgorReader: can't read this file, " 
    147                     msg += "missing transmission" 
    148                     raise ValueError, msg 
    149                                              
    150             if line.count("LAMBDA") > 0: 
    151                 isInfo = True 
    152                  
    153             # Find center info line 
    154             if isCenter: 
    155                 isCenter = False 
    156                 line_toks = line.split() 
    157                  
    158                 # Center in bin number: Must substrate 1 because 
    159                 #the index starts from 1 
    160                 center_x = float(line_toks[0]) - 1 
    161                 center_y = float(line_toks[1]) - 1 
    162  
    163             if line.count("BCENT") > 0: 
    164                 isCenter = True 
    165                  
    166             # Find data start 
    167             if line.count("***")>0: 
    168                 dataStarted = True 
    169                  
    170                 # Check that we have all the info 
    171                 if wavelength == None \ 
    172                     or distance == None \ 
    173                     or center_x == None \ 
    174                     or center_y == None: 
    175                     msg = "IgorReader:Missing information in data file" 
    176                     raise ValueError, msg 
    177                  
    178             if dataStarted == True: 
    179                 try: 
    180                     value = float(line) 
    181                 except: 
    182                     # Found a non-float entry, skip it 
    183                     continue 
    184                  
    185                 # Get bin number 
    186                 if math.fmod(itot, i_tot_row) == 0: 
    187                     i_x = 0 
    188                     i_y += 1 
    189                 else: 
    190                     i_x += 1 
    191                      
    192                 output.data[i_y][i_x] = value 
    193                 ncounts += 1 
    194                  
    195                 # Det 640 x 640 mm 
    196                 # Q = 4pi/lambda sin(theta/2) 
    197                 # Bin size is 0.5 cm  
    198                 #REmoved +1 from theta = (i_x-center_x+1)*0.5 / distance 
    199                 # / 100.0 and  
    200                 #REmoved +1 from theta = (i_y-center_y+1)*0.5 / 
    201                 # distance / 100.0 
    202                 #ToDo: Need  complete check if the following 
    203                 # covert process is consistent with fitting.py. 
    204                 theta = (i_x - center_x) * 0.5 / distance / 100.0 
    205                 qx = 4.0 * math.pi / wavelength * math.sin(theta/2.0) 
    206  
    207                 if has_converter == True and output.Q_unit != '1/A': 
    208                     qx = data_conv_q(qx, units=output.Q_unit) 
    209  
    210                 if xmin == None or qx < xmin: 
    211                     xmin = qx 
    212                 if xmax == None or qx > xmax: 
    213                     xmax = qx 
    214                  
    215                 theta = (i_y - center_y) * 0.5 / distance / 100.0 
    216                 qy = 4.0 * math.pi / wavelength * math.sin(theta / 2.0) 
    217  
    218                 if has_converter == True and output.Q_unit != '1/A': 
    219                     qy = data_conv_q(qy, units=output.Q_unit) 
    220                  
    221                 if ymin == None or qy < ymin: 
    222                     ymin = qy 
    223                 if ymax == None or qy > ymax: 
    224                     ymax = qy 
    225                  
    226                 if not qx in x: 
    227                     x.append(qx) 
    228                 if not qy in y: 
    229                     y.append(qy) 
    230                  
    231                 itot += 1 
    232                    
    233                    
     63 
     64        data_row = 0 
     65        wavelength = distance = center_x = center_y = None 
     66        dataStarted = isInfo = isCenter = False 
     67 
     68        with open(filename, 'r') as f: 
     69            for line in f: 
     70                data_row += 1 
     71                # Find setup info line 
     72                if isInfo: 
     73                    isInfo = False 
     74                    line_toks = line.split() 
     75                    # Wavelength in Angstrom 
     76                    try: 
     77                        wavelength = float(line_toks[1]) 
     78                    except ValueError: 
     79                        msg = "IgorReader: can't read this file, missing wavelength" 
     80                        raise ValueError(msg) 
     81                    # Distance in meters 
     82                    try: 
     83                        distance = float(line_toks[3]) 
     84                    except ValueError: 
     85                        msg = "IgorReader: can't read this file, missing distance" 
     86                        raise ValueError(msg) 
     87 
     88                    # Distance in meters 
     89                    try: 
     90                        transmission = float(line_toks[4]) 
     91                    except: 
     92                        msg = "IgorReader: can't read this file, " 
     93                        msg += "missing transmission" 
     94                        raise ValueError(msg) 
     95 
     96                if line.count("LAMBDA"): 
     97                    isInfo = True 
     98 
     99                # Find center info line 
     100                if isCenter: 
     101                    isCenter = False 
     102                    line_toks = line.split() 
     103 
     104                    # Center in bin number: Must subtract 1 because 
     105                    # the index starts from 1 
     106                    center_x = float(line_toks[0]) - 1 
     107                    center_y = float(line_toks[1]) - 1 
     108 
     109                if line.count("BCENT"): 
     110                    isCenter = True 
     111 
     112                # Find data start 
     113                if line.count("***"): 
     114                    # now have to continue to blank line 
     115                    dataStarted = True 
     116 
     117                    # Check that we have all the info 
     118                    if (wavelength is None 
     119                            or distance is None 
     120                            or center_x is None 
     121                            or center_y is None): 
     122                        msg = "IgorReader:Missing information in data file" 
     123                        raise ValueError(msg) 
     124 
     125                if dataStarted: 
     126                    if len(line.rstrip()): 
     127                        continue 
     128                    else: 
     129                        break 
     130 
     131        # The data is loaded in row major order (last index changing most 
     132        # rapidly). However, the original data is in column major order (first 
     133        # index changing most rapidly). The swap to column major order is done 
     134        # in reader2D_converter at the end of this method. 
     135        data = np.loadtxt(filename, skiprows=data_row) 
     136        size_x = size_y = int(np.rint(np.sqrt(data.size))) 
     137        output.data = np.reshape(data, (size_x, size_y)) 
     138        output.err_data = np.zeros_like(output.data) 
     139 
     140        # Det 640 x 640 mm 
     141        # Q = 4 * pi/lambda * sin(theta/2) 
     142        # Bin size is 0.5 cm 
     143        # Removed +1 from theta = (i_x - center_x + 1)*0.5 / distance 
     144        # / 100.0 and 
     145        # Removed +1 from theta = (i_y - center_y + 1)*0.5 / 
     146        # distance / 100.0 
     147        # ToDo: Need  complete check if the following 
     148        # convert process is consistent with fitting.py. 
     149 
     150        # calculate qx, qy bin centers of each pixel in the image 
     151        theta = (np.arange(size_x) - center_x) * 0.5 / distance / 100. 
     152        qx = 4 * np.pi / wavelength * np.sin(theta/2) 
     153 
     154        theta = (np.arange(size_y) - center_y) * 0.5 / distance / 100. 
     155        qy = 4 * np.pi / wavelength * np.sin(theta/2) 
     156 
     157        if has_converter and output.Q_unit != '1/A': 
     158            qx = data_conv_q(qx, units=output.Q_unit) 
     159            qy = data_conv_q(qx, units=output.Q_unit) 
     160 
     161        xmax = np.max(qx) 
     162        xmin = np.min(qx) 
     163        ymax = np.max(qy) 
     164        ymin = np.min(qy) 
     165 
     166        # calculate edge offset in q. 
    234167        theta = 0.25 / distance / 100.0 
    235         xstep = 4.0 * math.pi / wavelength * math.sin(theta / 2.0) 
     168        xstep = 4.0 * np.pi / wavelength * np.sin(theta / 2.0) 
    236169         
    237170        theta = 0.25 / distance / 100.0 
    238         ystep = 4.0 * math.pi/ wavelength * math.sin(theta / 2.0) 
     171        ystep = 4.0 * np.pi/ wavelength * np.sin(theta / 2.0) 
    239172         
    240173        # Store all data ###################################### 
    241174        # Store wavelength 
    242         if has_converter == True and output.source.wavelength_unit != 'A': 
     175        if has_converter and output.source.wavelength_unit != 'A': 
    243176            conv = Converter('A') 
    244177            wavelength = conv(wavelength, units=output.source.wavelength_unit) 
     
    246179 
    247180        # Store distance 
    248         if has_converter == True and detector.distance_unit != 'm': 
     181        if has_converter and detector.distance_unit != 'm': 
    249182            conv = Converter('m') 
    250183            distance = conv(distance, units=detector.distance_unit) 
     
    254187        output.sample.transmission = transmission 
    255188         
    256         # Store pixel size 
     189        # Store pixel size (mm) 
    257190        pixel = 5.0 
    258         if has_converter == True and detector.pixel_size_unit != 'mm': 
     191        if has_converter and detector.pixel_size_unit != 'mm': 
    259192            conv = Converter('mm') 
    260193            pixel = conv(pixel, units=detector.pixel_size_unit) 
     
    267200         
    268201        # Store limits of the image (2D array) 
    269         xmin = xmin - xstep / 2.0 
    270         xmax = xmax + xstep / 2.0 
    271         ymin = ymin - ystep / 2.0 
    272         ymax = ymax + ystep / 2.0 
    273         if has_converter == True and output.Q_unit != '1/A': 
     202        xmin -= xstep / 2.0 
     203        xmax += xstep / 2.0 
     204        ymin -= ystep / 2.0 
     205        ymax += ystep / 2.0 
     206        if has_converter and output.Q_unit != '1/A': 
    274207            xmin = data_conv_q(xmin, units=output.Q_unit) 
    275208            xmax = data_conv_q(xmax, units=output.Q_unit) 
     
    282215         
    283216        # Store x and y axis bin centers 
    284         output.x_bins = x 
    285         output.y_bins = y 
     217        output.x_bins = qx.tolist() 
     218        output.y_bins = qy.tolist() 
    286219         
    287220        # Units 
  • src/sas/sascalc/dataloader/readers/abs_reader.py

    rb699768 r9a5097c  
    99###################################################################### 
    1010 
    11 import numpy 
     11import numpy as np 
    1212import os 
    1313from sas.sascalc.dataloader.data_info import Data1D 
     
    5353                buff = input_f.read() 
    5454                lines = buff.split('\n') 
    55                 x  = numpy.zeros(0) 
    56                 y  = numpy.zeros(0) 
    57                 dy = numpy.zeros(0) 
    58                 dx = numpy.zeros(0) 
     55                x  = np.zeros(0) 
     56                y  = np.zeros(0) 
     57                dy = np.zeros(0) 
     58                dx = np.zeros(0) 
    5959                output = Data1D(x, y, dy=dy, dx=dx) 
    6060                detector = Detector() 
     
    204204                                _dy = data_conv_i(_dy, units=output.y_unit) 
    205205                            
    206                             x = numpy.append(x, _x) 
    207                             y = numpy.append(y, _y) 
    208                             dy = numpy.append(dy, _dy) 
    209                             dx = numpy.append(dx, _dx) 
     206                            x = np.append(x, _x) 
     207                            y = np.append(y, _y) 
     208                            dy = np.append(dy, _dy) 
     209                            dx = np.append(dx, _dx) 
    210210                             
    211211                        except: 
  • src/sas/sascalc/dataloader/readers/ascii_reader.py

    rd2471870 r9a5097c  
    1414 
    1515 
    16 import numpy 
     16import numpy as np 
    1717import os 
    1818from sas.sascalc.dataloader.data_info import Data1D 
     
    6969 
    7070                # Arrays for data storage 
    71                 tx = numpy.zeros(0) 
    72                 ty = numpy.zeros(0) 
    73                 tdy = numpy.zeros(0) 
    74                 tdx = numpy.zeros(0) 
     71                tx = np.zeros(0) 
     72                ty = np.zeros(0) 
     73                tdy = np.zeros(0) 
     74                tdx = np.zeros(0) 
    7575 
    7676                # The first good line of data will define whether 
     
    140140                            is_data == False: 
    141141                            try: 
    142                                 tx = numpy.zeros(0) 
    143                                 ty = numpy.zeros(0) 
    144                                 tdy = numpy.zeros(0) 
    145                                 tdx = numpy.zeros(0) 
     142                                tx = np.zeros(0) 
     143                                ty = np.zeros(0) 
     144                                tdy = np.zeros(0) 
     145                                tdx = np.zeros(0) 
    146146                            except: 
    147147                                pass 
    148148 
    149149                        if has_error_dy == True: 
    150                             tdy = numpy.append(tdy, _dy) 
     150                            tdy = np.append(tdy, _dy) 
    151151                        if has_error_dx == True: 
    152                             tdx = numpy.append(tdx, _dx) 
    153                         tx = numpy.append(tx, _x) 
    154                         ty = numpy.append(ty, _y) 
     152                            tdx = np.append(tdx, _dx) 
     153                        tx = np.append(tx, _x) 
     154                        ty = np.append(ty, _y) 
    155155 
    156156                        #To remember the # of columns on the current line 
     
    188188                #Let's re-order the data to make cal. 
    189189                # curve look better some cases 
    190                 ind = numpy.lexsort((ty, tx)) 
    191                 x = numpy.zeros(len(tx)) 
    192                 y = numpy.zeros(len(ty)) 
    193                 dy = numpy.zeros(len(tdy)) 
    194                 dx = numpy.zeros(len(tdx)) 
     190                ind = np.lexsort((ty, tx)) 
     191                x = np.zeros(len(tx)) 
     192                y = np.zeros(len(ty)) 
     193                dy = np.zeros(len(tdy)) 
     194                dx = np.zeros(len(tdx)) 
    195195                output = Data1D(x, y, dy=dy, dx=dx) 
    196196                self.filename = output.filename = basename 
     
    212212                output.y = y[x != 0] 
    213213                output.dy = dy[x != 0] if has_error_dy == True\ 
    214                     else numpy.zeros(len(output.y)) 
     214                    else np.zeros(len(output.y)) 
    215215                output.dx = dx[x != 0] if has_error_dx == True\ 
    216                     else numpy.zeros(len(output.x)) 
     216                    else np.zeros(len(output.x)) 
    217217 
    218218                output.xaxis("\\rm{Q}", 'A^{-1}') 
  • src/sas/sascalc/dataloader/readers/danse_reader.py

    rb699768 r9a5097c  
    1515import os 
    1616import sys 
    17 import numpy 
     17import numpy as np 
    1818import logging 
    1919from sas.sascalc.dataloader.data_info import Data2D, Detector 
     
    7979            output.detector.append(detector) 
    8080             
    81             output.data = numpy.zeros([size_x,size_y]) 
    82             output.err_data = numpy.zeros([size_x, size_y]) 
     81            output.data = np.zeros([size_x,size_y]) 
     82            output.err_data = np.zeros([size_x, size_y]) 
    8383             
    8484            data_conv_q = None 
  • src/sas/sascalc/dataloader/readers/hfir1d_reader.py

    rb699768 r9a5097c  
    99#copyright 2008, University of Tennessee 
    1010###################################################################### 
    11 import numpy 
     11import numpy as np 
    1212import os 
    1313from sas.sascalc.dataloader.data_info import Data1D 
     
    5252                buff = input_f.read() 
    5353                lines = buff.split('\n') 
    54                 x = numpy.zeros(0) 
    55                 y = numpy.zeros(0) 
    56                 dx = numpy.zeros(0) 
    57                 dy = numpy.zeros(0) 
     54                x = np.zeros(0) 
     55                y = np.zeros(0) 
     56                dx = np.zeros(0) 
     57                dy = np.zeros(0) 
    5858                output = Data1D(x, y, dx=dx, dy=dy) 
    5959                self.filename = output.filename = basename 
     
    8888                            _dy = data_conv_i(_dy, units=output.y_unit) 
    8989                                                     
    90                         x = numpy.append(x, _x) 
    91                         y = numpy.append(y, _y) 
    92                         dx = numpy.append(dx, _dx) 
    93                         dy = numpy.append(dy, _dy) 
     90                        x = np.append(x, _x) 
     91                        y = np.append(y, _y) 
     92                        dx = np.append(dx, _dx) 
     93                        dy = np.append(dy, _dy) 
    9494                    except: 
    9595                        # Couldn't parse this line, skip it  
  • src/sas/sascalc/dataloader/readers/red2d_reader.py

    rb699768 r9a5097c  
    1010###################################################################### 
    1111import os 
    12 import numpy 
     12import numpy as np 
    1313import math 
    1414from sas.sascalc.dataloader.data_info import Data2D, Detector 
     
    198198                break 
    199199        # Make numpy array to remove header lines using index 
    200         lines_array = numpy.array(lines) 
     200        lines_array = np.array(lines) 
    201201 
    202202        # index for lines_array 
    203         lines_index = numpy.arange(len(lines)) 
     203        lines_index = np.arange(len(lines)) 
    204204         
    205205        # get the data lines 
     
    225225 
    226226        # numpy array form 
    227         data_array = numpy.array(data_list1) 
     227        data_array = np.array(data_list1) 
    228228        # Redimesion based on the row_num and col_num, 
    229229        #otherwise raise an error. 
     
    235235        ## Get the all data: Let's HARDcoding; Todo find better way 
    236236        # Defaults 
    237         dqx_data = numpy.zeros(0) 
    238         dqy_data = numpy.zeros(0) 
    239         err_data = numpy.ones(row_num) 
    240         qz_data = numpy.zeros(row_num) 
    241         mask = numpy.ones(row_num, dtype=bool) 
     237        dqx_data = np.zeros(0) 
     238        dqy_data = np.zeros(0) 
     239        err_data = np.ones(row_num) 
     240        qz_data = np.zeros(row_num) 
     241        mask = np.ones(row_num, dtype=bool) 
    242242        # Get from the array 
    243243        qx_data = data_point[0] 
     
    254254            dqy_data = data_point[(5 + ver)] 
    255255        #if col_num > (6 + ver): mask[data_point[(6 + ver)] < 1] = False 
    256         q_data = numpy.sqrt(qx_data*qx_data+qy_data*qy_data+qz_data*qz_data) 
     256        q_data = np.sqrt(qx_data*qx_data+qy_data*qy_data+qz_data*qz_data) 
    257257            
    258258        # Extra protection(it is needed for some data files):  
     
    262262   
    263263        # Store limits of the image in q space 
    264         xmin = numpy.min(qx_data) 
    265         xmax = numpy.max(qx_data) 
    266         ymin = numpy.min(qy_data) 
    267         ymax = numpy.max(qy_data) 
     264        xmin = np.min(qx_data) 
     265        xmax = np.max(qx_data) 
     266        ymin = np.min(qy_data) 
     267        ymax = np.max(qy_data) 
    268268 
    269269        # units 
     
    287287         
    288288        # store x and y axis bin centers in q space 
    289         x_bins = numpy.arange(xmin, xmax + xstep, xstep) 
    290         y_bins = numpy.arange(ymin, ymax + ystep, ystep) 
     289        x_bins = np.arange(xmin, xmax + xstep, xstep) 
     290        y_bins = np.arange(ymin, ymax + ystep, ystep) 
    291291        
    292292        # get the limits of q values 
     
    300300        output.data = data 
    301301        if (err_data == 1).all(): 
    302             output.err_data = numpy.sqrt(numpy.abs(data)) 
     302            output.err_data = np.sqrt(np.abs(data)) 
    303303            output.err_data[output.err_data == 0.0] = 1.0 
    304304        else: 
     
    335335                # tranfer the comp. to cartesian coord. for newer version. 
    336336                if ver != 1: 
    337                     diag = numpy.sqrt(qx_data * qx_data + qy_data * qy_data) 
     337                    diag = np.sqrt(qx_data * qx_data + qy_data * qy_data) 
    338338                    cos_th = qx_data / diag 
    339339                    sin_th = qy_data / diag 
    340                     output.dqx_data = numpy.sqrt((dqx_data * cos_th) * \ 
     340                    output.dqx_data = np.sqrt((dqx_data * cos_th) * \ 
    341341                                                 (dqx_data * cos_th) \ 
    342342                                                 + (dqy_data * sin_th) * \ 
    343343                                                  (dqy_data * sin_th)) 
    344                     output.dqy_data = numpy.sqrt((dqx_data * sin_th) * \ 
     344                    output.dqy_data = np.sqrt((dqx_data * sin_th) * \ 
    345345                                                 (dqx_data * sin_th) \ 
    346346                                                 + (dqy_data * cos_th) * \ 
  • src/sas/sascalc/dataloader/readers/tiff_reader.py

    rb699768 r9a5097c  
    1313import logging 
    1414import os 
    15 import numpy 
     15import numpy as np 
    1616from sas.sascalc.dataloader.data_info import Data2D 
    1717from sas.sascalc.dataloader.manipulations import reader2D_converter 
     
    5656 
    5757        # 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]]) 
    60         output.mask = numpy.ones([im.size[0], im.size[1]], dtype=bool) 
     58        output.data = np.zeros([im.size[0], im.size[1]]) 
     59        output.err_data = np.zeros([im.size[0], im.size[1]]) 
     60        output.mask = np.ones([im.size[0], im.size[1]], dtype=bool) 
    6161         
    6262        # Initialize 
     
    9494        output.x_bins = x_vals 
    9595        output.y_bins = y_vals 
    96         output.qx_data = numpy.array(x_vals) 
    97         output.qy_data = numpy.array(y_vals) 
     96        output.qx_data = np.array(x_vals) 
     97        output.qy_data = np.array(y_vals) 
    9898        output.xmin = 0 
    9999        output.xmax = im.size[0] - 1 
  • src/sas/sascalc/dataloader/readers/sesans_reader.py

    r9a5097c r2d866370  
    11""" 
    22    SESANS reader (based on ASCII reader) 
    3      
     3 
    44    Reader for .ses or .sesans file format 
    5      
    6     Jurrian Bakker  
     5 
     6    Jurrian Bakker 
    77""" 
    88import numpy as np 
     
    1818_ZERO = 1e-16 
    1919 
     20 
    2021class Reader: 
    2122    """ 
    2223    Class to load sesans files (6 columns). 
    2324    """ 
    24     ## File type 
     25    # File type 
    2526    type_name = "SESANS" 
    26      
    27     ## Wildcards 
     27 
     28    # Wildcards 
    2829    type = ["SESANS files (*.ses)|*.ses", 
    2930            "SESANS files (*..sesans)|*.sesans"] 
    30     ## List of allowed extensions 
     31    # List of allowed extensions 
    3132    ext = ['.ses', '.SES', '.sesans', '.SESANS'] 
    32      
    33     ## Flag to bypass extension check 
     33 
     34    # Flag to bypass extension check 
    3435    allow_all = True 
    35      
     36 
    3637    def read(self, path): 
    37          
    38 #        print "reader triggered" 
    39          
    4038        """ 
    4139        Load data file 
    42          
     40 
    4341        :param path: file path 
    44          
     42 
    4543        :return: SESANSData1D object, or None 
    46          
     44 
    4745        :raise RuntimeError: when the file can't be opened 
    4846        :raise ValueError: when the length of the data vectors are inconsistent 
     
    5250            _, extension = os.path.splitext(basename) 
    5351            if self.allow_all or extension.lower() in self.ext: 
    54                 try: 
     52                with open(path, 'r') as input_f: 
    5553                    # Read in binary mode since GRASP frequently has no-ascii 
    5654                    # characters that brakes the open operation 
    57                     input_f = open(path,'rb') 
    58                 except: 
    59                     raise  RuntimeError, "sesans_reader: cannot open %s" % path 
    60                 buff = input_f.read() 
    61                 lines = buff.splitlines() 
    62                 x  = np.zeros(0) 
    63                 y  = np.zeros(0) 
    64                 dy = np.zeros(0) 
    65                 lam  = np.zeros(0) 
    66                 dlam = np.zeros(0) 
    67                 dx = np.zeros(0) 
    68                  
    69                #temp. space to sort data 
    70                 tx  = np.zeros(0) 
    71                 ty  = np.zeros(0) 
    72                 tdy = np.zeros(0) 
    73                 tlam  = np.zeros(0) 
    74                 tdlam = np.zeros(0) 
    75                 tdx = np.zeros(0) 
    76                 output = Data1D(x=x, y=y, lam=lam, dy=dy, dx=dx, dlam=dlam, isSesans=True) 
    77                 self.filename = output.filename = basename 
     55                    line = input_f.readline() 
     56                    params = {} 
     57                    while line.strip() != "": 
     58                        if line.strip() == "": 
     59                            break 
     60                        terms = line.strip().split("\t") 
     61                        params[terms[0].strip()] = " ".join(terms[1:]).strip() 
     62                        line = input_f.readline() 
     63                    headers_temp = input_f.readline().strip().split("\t") 
     64                    headers = {} 
     65                    for h in headers_temp: 
     66                        temp = h.strip().split() 
     67                        headers[h[:-1].strip()] = temp[-1][1:-1] 
     68                    data = np.loadtxt(input_f) 
     69                    x = data[:, 0] 
     70                    dx = data[:, 3] 
     71                    lam = data[:, 4] 
     72                    dlam = data[:, 5] 
     73                    y = data[:, 1] 
     74                    dy = data[:, 2] 
    7875 
    79                 paramnames=[] 
    80                 paramvals=[] 
    81                 zvals=[] 
    82                 dzvals=[] 
    83                 lamvals=[] 
    84                 dlamvals=[] 
    85                 Pvals=[] 
    86                 dPvals=[] 
     76                    lam_unit = self._header_fetch(headers, "wavelength") 
     77                    if lam_unit == "AA": 
     78                        lam_unit = "A" 
    8779 
    88                 for line in lines: 
    89                     # Initial try for CSV (split on ,) 
    90                     line=line.strip() 
    91                     toks = line.split('\t') 
    92                     if len(toks)==2: 
    93                         paramnames.append(toks[0]) 
    94                         paramvals.append(toks[1]) 
    95                     if len(toks)>5: 
    96                         zvals.append(toks[0]) 
    97                         dzvals.append(toks[3]) 
    98                         lamvals.append(toks[4]) 
    99                         dlamvals.append(toks[5]) 
    100                         Pvals.append(toks[1]) 
    101                         dPvals.append(toks[2]) 
    102                     else: 
    103                         continue 
     80                    x, x_unit = self._unit_conversion( 
     81                        x, lam_unit, 
     82                        self._fetch_unit(headers, "spin echo length")) 
     83                    dx, dx_unit = self._unit_conversion( 
     84                        dx, lam_unit, 
     85                        self._fetch_unit(headers, "error SEL")) 
     86                    dlam, dlam_unit = self._unit_conversion( 
     87                        dlam, lam_unit, 
     88                        self._fetch_unit(headers, "error wavelength")) 
     89                    y_unit = r'\AA^{-2} cm^{-1}' 
    10490 
    105                 x=[] 
    106                 y=[] 
    107                 lam=[] 
    108                 dx=[] 
    109                 dy=[] 
    110                 dlam=[] 
    111                 lam_header = lamvals[0].split() 
    112                 data_conv_z = None 
    113                 default_z_unit = "A" 
    114                 data_conv_P = None 
    115                 default_p_unit = " " # Adjust unit for axis (L^-3) 
    116                 lam_unit = lam_header[1].replace("[","").replace("]","") 
    117                 if lam_unit == 'AA': 
    118                     lam_unit = 'A' 
    119                 varheader=[zvals[0],dzvals[0],lamvals[0],dlamvals[0],Pvals[0],dPvals[0]] 
    120                 valrange=range(1, len(zvals)) 
    121                 for i in valrange: 
    122                     x.append(float(zvals[i])) 
    123                     y.append(float(Pvals[i])) 
    124                     lam.append(float(lamvals[i])) 
    125                     dy.append(float(dPvals[i])) 
    126                     dx.append(float(dzvals[i])) 
    127                     dlam.append(float(dlamvals[i])) 
     91                    output = Data1D(x=x, y=y, lam=lam, dy=dy, dx=dx, dlam=dlam, 
     92                                    isSesans=True) 
     93                    self.filename = output.filename = basename 
     94                    output.xaxis(r"\rm{z}", x_unit) 
     95                    # Adjust label to ln P/(lam^2 t), remove lam column refs 
     96                    output.yaxis(r"\rm{ln(P)/(t \lambda^2)}", y_unit) 
     97                    # Store loading process information 
     98                    output.meta_data['loader'] = self.type_name 
     99                    output.sample.name = params["Sample"] 
     100                    output.sample.ID = params["DataFileTitle"] 
    128101 
    129                 x,y,lam,dy,dx,dlam = [ 
    130                     np.asarray(v, 'double') 
    131                    for v in (x,y,lam,dy,dx,dlam) 
    132                 ] 
     102                    output.sample.zacceptance = ( 
     103                        float(self._header_fetch(params, "Q_zmax")), 
     104                        self._fetch_unit(params, "Q_zmax")) 
    133105 
    134                 input_f.close() 
    135  
    136                 output.x, output.x_unit = self._unit_conversion(x, lam_unit, default_z_unit) 
    137                 output.y = y 
    138                 output.y_unit = r'\AA^{-2} cm^{-1}'  # output y_unit added 
    139                 output.dx, output.dx_unit = self._unit_conversion(dx, lam_unit, default_z_unit) 
    140                 output.dy = dy 
    141                 output.lam, output.lam_unit = self._unit_conversion(lam, lam_unit, default_z_unit) 
    142                 output.dlam, output.dlam_unit = self._unit_conversion(dlam, lam_unit, default_z_unit) 
    143                  
    144                 output.xaxis(r"\rm{z}", output.x_unit) 
    145                 output.yaxis(r"\rm{ln(P)/(t \lambda^2)}", output.y_unit)  # Adjust label to ln P/(lam^2 t), remove lam column refs 
    146  
    147                 # Store loading process information 
    148                 output.meta_data['loader'] = self.type_name 
    149                 #output.sample.thickness = float(paramvals[6]) 
    150                 output.sample.name = paramvals[1] 
    151                 output.sample.ID = paramvals[0] 
    152                 zaccept_unit_split = paramnames[7].split("[") 
    153                 zaccept_unit = zaccept_unit_split[1].replace("]","") 
    154                 if zaccept_unit.strip() == r'\AA^-1' or zaccept_unit.strip() == r'\A^-1': 
    155                     zaccept_unit = "1/A" 
    156                 output.sample.zacceptance=(float(paramvals[7]),zaccept_unit) 
    157                 output.vars = varheader 
     106                    output.sample.yacceptance = ( 
     107                        float(self._header_fetch(params, "Q_ymax")), 
     108                        self._fetch_unit(params, "Q_ymax")) 
    158109 
    159110                if len(output.x) < 1: 
    160                     raise RuntimeError, "%s is empty" % path 
     111                    raise RuntimeError("%s is empty" % path) 
    161112                return output 
    162113 
    163114        else: 
    164             raise RuntimeError, "%s is not a file" % path 
     115            raise RuntimeError("%s is not a file" % path) 
    165116        return None 
    166117 
    167     def _unit_conversion(self, value, value_unit, default_unit): 
    168         if has_converter == True and value_unit != default_unit: 
     118    @staticmethod 
     119    def _unit_conversion(value, value_unit, default_unit): 
     120        """ 
     121        Performs unit conversion on a measurement. 
     122 
     123        :param value: The magnitude of the measurement 
     124        :type value: Number 
     125        :param value_unit: a string containing the final desired unit 
     126        :type value_unit: String 
     127        :param default_unit: a string containing the units of the original measurement 
     128        :type default_unit: String 
     129        :return: The magnitude of the measurement in the new units 
     130        """ 
     131        if has_converter and value_unit != default_unit: 
    169132            data_conv_q = Converter(value_unit) 
    170133            value = data_conv_q(value, units=default_unit) 
     
    173136            new_unit = value_unit 
    174137        return value, new_unit 
     138 
     139    @staticmethod 
     140    def _header_fetch(headers, key): 
     141        """ 
     142        Pull the value of a unit defined header from a dict. Example:: 
     143 
     144         d = {"Length [m]": 17} 
     145         self._header_fetch(d, "Length") == 17 
     146 
     147        :param header: A dictionary of values 
     148        :type header: Dictionary 
     149        :param key: A string which is a prefix for one of the keys in the dict 
     150        :type key: String 
     151        :return: The value of the dictionary for the specified key 
     152        """ 
     153        index = [k for k in headers.keys() 
     154                 if k.startswith(key)][0] 
     155        return headers[index] 
     156 
     157    @staticmethod 
     158    def _fetch_unit(params, key): 
     159        """ 
     160        Pull the unit off of a dictionary header. Example:: 
     161 
     162         d = {"Length [m]": 17} 
     163         self._fetch_unit(d, "Length") == "m" 
     164 
     165        :param header: A dictionary of values, where the keys are strings 
     166        with the units for the values appended onto the string within square 
     167        brackets (See the example above) 
     168        :type header: Dictionary 
     169        :param key: A string with the prefix of the dictionary key whose unit 
     170        is being fetched 
     171        :type key: String 
     172        :return: A string containing the unit specifed in the header 
     173        """ 
     174        index = [k for k in params.keys() 
     175                 if k.startswith(key)][0] 
     176        unit = index.strip().split()[-1][1:-1] 
     177        if unit.startswith(r"\A"): 
     178            unit = "1/A" 
     179        return unit 
Note: See TracChangeset for help on using the changeset viewer.