1 | """ |
---|
2 | SESANS reader (based on ASCII reader) |
---|
3 | |
---|
4 | Reader for .ses or .sesans file format |
---|
5 | |
---|
6 | Jurrian Bakker |
---|
7 | """ |
---|
8 | import numpy as np |
---|
9 | import os |
---|
10 | from sas.sascalc.dataloader.data_info import Data1D |
---|
11 | |
---|
12 | # Check whether we have a converter available |
---|
13 | has_converter = True |
---|
14 | try: |
---|
15 | from sas.sascalc.data_util.nxsunit import Converter |
---|
16 | except: |
---|
17 | has_converter = False |
---|
18 | _ZERO = 1e-16 |
---|
19 | |
---|
20 | |
---|
21 | class Reader: |
---|
22 | """ |
---|
23 | Class to load sesans files (6 columns). |
---|
24 | """ |
---|
25 | # File type |
---|
26 | type_name = "SESANS" |
---|
27 | |
---|
28 | # Wildcards |
---|
29 | type = ["SESANS files (*.ses)|*.ses", |
---|
30 | "SESANS files (*..sesans)|*.sesans"] |
---|
31 | # List of allowed extensions |
---|
32 | ext = ['.ses', '.SES', '.sesans', '.SESANS'] |
---|
33 | |
---|
34 | # Flag to bypass extension check |
---|
35 | allow_all = True |
---|
36 | |
---|
37 | def read(self, path): |
---|
38 | """ |
---|
39 | Load data file |
---|
40 | |
---|
41 | :param path: file path |
---|
42 | |
---|
43 | :return: SESANSData1D object, or None |
---|
44 | |
---|
45 | :raise RuntimeError: when the file can't be opened |
---|
46 | :raise ValueError: when the length of the data vectors are inconsistent |
---|
47 | """ |
---|
48 | if os.path.isfile(path): |
---|
49 | basename = os.path.basename(path) |
---|
50 | _, extension = os.path.splitext(basename) |
---|
51 | if self.allow_all or extension.lower() in self.ext: |
---|
52 | with open(path, 'r') as input_f: |
---|
53 | # Read in binary mode since GRASP frequently has no-ascii |
---|
54 | # characters that brakes the open operation |
---|
55 | line = input_f.readline() |
---|
56 | params = {} |
---|
57 | while line.strip() != "": |
---|
58 | terms = line.strip().split("\t") |
---|
59 | params[terms[0].strip()] = " ".join(terms[1:]).strip() |
---|
60 | line = input_f.readline() |
---|
61 | headers_temp = input_f.readline().strip().split("\t") |
---|
62 | headers = {} |
---|
63 | for h in headers_temp: |
---|
64 | temp = h.strip().split() |
---|
65 | headers[h[:-1].strip()] = temp[-1][1:-1] |
---|
66 | data = np.loadtxt(input_f) |
---|
67 | if data.size < 1: |
---|
68 | raise RuntimeError("{} is empty".format(path)) |
---|
69 | x = data[:, 0] |
---|
70 | dx = data[:, 3] |
---|
71 | lam = data[:, 4] |
---|
72 | dlam = data[:, 5] |
---|
73 | y = data[:, 1] |
---|
74 | dy = data[:, 2] |
---|
75 | |
---|
76 | lam_unit = self._header_fetch(headers, "wavelength") |
---|
77 | if lam_unit == "AA": |
---|
78 | lam_unit = "A" |
---|
79 | |
---|
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}' |
---|
90 | |
---|
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"] |
---|
101 | |
---|
102 | output.sample.zacceptance = ( |
---|
103 | float(self._header_fetch(params, "Q_zmax")), |
---|
104 | self._fetch_unit(params, "Q_zmax")) |
---|
105 | |
---|
106 | output.sample.yacceptance = ( |
---|
107 | float(self._header_fetch(params, "Q_ymax")), |
---|
108 | self._fetch_unit(params, "Q_ymax")) |
---|
109 | return output |
---|
110 | |
---|
111 | else: |
---|
112 | raise RuntimeError("%s is not a file" % path) |
---|
113 | return None |
---|
114 | |
---|
115 | @staticmethod |
---|
116 | def _unit_conversion(value, value_unit, default_unit): |
---|
117 | """ |
---|
118 | Performs unit conversion on a measurement. |
---|
119 | |
---|
120 | :param value: The magnitude of the measurement |
---|
121 | :param value_unit: a string containing the final desired unit |
---|
122 | :param default_unit: a string containing the units of the original measurement |
---|
123 | :return: The magnitude of the measurement in the new units |
---|
124 | """ |
---|
125 | # (float, string, string) -> float |
---|
126 | if has_converter and value_unit != default_unit: |
---|
127 | data_conv_q = Converter(value_unit) |
---|
128 | value = data_conv_q(value, units=default_unit) |
---|
129 | new_unit = default_unit |
---|
130 | else: |
---|
131 | new_unit = value_unit |
---|
132 | return value, new_unit |
---|
133 | |
---|
134 | @staticmethod |
---|
135 | def _header_fetch(headers, key): |
---|
136 | """ |
---|
137 | Pull the value of a unit defined header from a dict. Example:: |
---|
138 | |
---|
139 | d = {"Length [m]": 17} |
---|
140 | self._header_fetch(d, "Length") == 17 |
---|
141 | |
---|
142 | :param header: A dictionary of values |
---|
143 | :param key: A string which is a prefix for one of the keys in the dict |
---|
144 | :return: The value of the dictionary for the specified key |
---|
145 | """ |
---|
146 | # (dict<string, x>, string) -> x |
---|
147 | index = [k for k in headers.keys() |
---|
148 | if k.startswith(key)][0] |
---|
149 | return headers[index] |
---|
150 | |
---|
151 | @staticmethod |
---|
152 | def _fetch_unit(params, key): |
---|
153 | """ |
---|
154 | Pull the unit off of a dictionary header. Example:: |
---|
155 | |
---|
156 | d = {"Length [m]": 17} |
---|
157 | self._fetch_unit(d, "Length") == "m" |
---|
158 | |
---|
159 | :param header: A dictionary of values, where the keys are strings |
---|
160 | with the units for the values appended onto the string within square |
---|
161 | brackets (See the example above) |
---|
162 | :param key: A string with the prefix of the dictionary key whose unit |
---|
163 | is being fetched |
---|
164 | :return: A string containing the unit specifed in the header |
---|
165 | """ |
---|
166 | # (dict<string, _>, string) -> string |
---|
167 | index = [k for k in params.keys() |
---|
168 | if k.startswith(key)][0] |
---|
169 | unit = index.strip().split()[-1][1:-1] |
---|
170 | if unit.startswith(r"\A"): |
---|
171 | unit = "1/A" |
---|
172 | return unit |
---|