Changes in / [dd11014:41e0a3b] in sasview
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
src/sas/sascalc/dataloader/readers/sesans_reader.py
r9a5097c r2d866370 1 1 """ 2 2 SESANS reader (based on ASCII reader) 3 3 4 4 Reader for .ses or .sesans file format 5 6 Jurrian Bakker 5 6 Jurrian Bakker 7 7 """ 8 8 import numpy as np … … 18 18 _ZERO = 1e-16 19 19 20 20 21 class Reader: 21 22 """ 22 23 Class to load sesans files (6 columns). 23 24 """ 24 # #File type25 # File type 25 26 type_name = "SESANS" 26 27 # #Wildcards27 28 # Wildcards 28 29 type = ["SESANS files (*.ses)|*.ses", 29 30 "SESANS files (*..sesans)|*.sesans"] 30 # #List of allowed extensions31 # List of allowed extensions 31 32 ext = ['.ses', '.SES', '.sesans', '.SESANS'] 32 33 # #Flag to bypass extension check33 34 # Flag to bypass extension check 34 35 allow_all = True 35 36 36 37 def read(self, path): 37 38 # print "reader triggered"39 40 38 """ 41 39 Load data file 42 40 43 41 :param path: file path 44 42 45 43 :return: SESANSData1D object, or None 46 44 47 45 :raise RuntimeError: when the file can't be opened 48 46 :raise ValueError: when the length of the data vectors are inconsistent … … 52 50 _, extension = os.path.splitext(basename) 53 51 if self.allow_all or extension.lower() in self.ext: 54 try:52 with open(path, 'r') as input_f: 55 53 # Read in binary mode since GRASP frequently has no-ascii 56 54 # 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] 78 75 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" 87 79 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}' 104 90 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"] 128 101 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")) 133 105 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")) 158 109 159 110 if len(output.x) < 1: 160 raise RuntimeError , "%s is empty" % path111 raise RuntimeError("%s is empty" % path) 161 112 return output 162 113 163 114 else: 164 raise RuntimeError , "%s is not a file" % path115 raise RuntimeError("%s is not a file" % path) 165 116 return None 166 117 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: 169 132 data_conv_q = Converter(value_unit) 170 133 value = data_conv_q(value, units=default_unit) … … 173 136 new_unit = value_unit 174 137 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.