1 | import logging |
---|
2 | import numpy as np |
---|
3 | import os |
---|
4 | import sys |
---|
5 | import datetime |
---|
6 | import inspect |
---|
7 | # For saving individual sections of data |
---|
8 | from sas.sascalc.dataloader.data_info import Data1D, Data2D, DataInfo, \ |
---|
9 | plottable_1D, plottable_2D |
---|
10 | from sas.sascalc.dataloader.data_info import Collimation, TransmissionSpectrum, \ |
---|
11 | Detector, Process, Aperture |
---|
12 | from sas.sascalc.dataloader.data_info import \ |
---|
13 | combine_data_info_with_plottable as combine_data |
---|
14 | import sas.sascalc.dataloader.readers.xml_reader as xml_reader |
---|
15 | from sas.sascalc.dataloader.readers.xml_reader import XMLreader |
---|
16 | from sas.sascalc.dataloader.readers.cansas_constants import CansasConstants, CurrentLevel |
---|
17 | from sas.sascalc.dataloader.loader_exceptions import FileContentsException, \ |
---|
18 | DefaultReaderException, DataReaderException |
---|
19 | |
---|
20 | # The following 2 imports *ARE* used. Do not remove either. |
---|
21 | import xml.dom.minidom |
---|
22 | from xml.dom.minidom import parseString |
---|
23 | |
---|
24 | from lxml import etree |
---|
25 | |
---|
26 | logger = logging.getLogger(__name__) |
---|
27 | |
---|
28 | PREPROCESS = "xmlpreprocess" |
---|
29 | ENCODING = "encoding" |
---|
30 | RUN_NAME_DEFAULT = "None" |
---|
31 | INVALID_SCHEMA_PATH_1_1 = "{0}/sas/sascalc/dataloader/readers/schema/cansas1d_invalid_v1_1.xsd" |
---|
32 | INVALID_SCHEMA_PATH_1_0 = "{0}/sas/sascalc/dataloader/readers/schema/cansas1d_invalid_v1_0.xsd" |
---|
33 | INVALID_XML = "\n\nThe loaded xml file, {0} does not fully meet the CanSAS v1.x specification. SasView loaded " + \ |
---|
34 | "as much of the data as possible.\n\n" |
---|
35 | HAS_CONVERTER = True |
---|
36 | try: |
---|
37 | from sas.sascalc.data_util.nxsunit import Converter |
---|
38 | except ImportError: |
---|
39 | HAS_CONVERTER = False |
---|
40 | |
---|
41 | CONSTANTS = CansasConstants() |
---|
42 | CANSAS_FORMAT = CONSTANTS.format |
---|
43 | CANSAS_NS = CONSTANTS.names |
---|
44 | ALLOW_ALL = True |
---|
45 | |
---|
46 | class Reader(XMLreader): |
---|
47 | cansas_version = "1.0" |
---|
48 | base_ns = "{cansas1d/1.0}" |
---|
49 | cansas_defaults = None |
---|
50 | type_name = "canSAS" |
---|
51 | invalid = True |
---|
52 | frm = "" |
---|
53 | # Log messages and errors |
---|
54 | logging = None |
---|
55 | errors = set() |
---|
56 | # Namespace hierarchy for current xml_file object |
---|
57 | names = None |
---|
58 | ns_list = None |
---|
59 | # Temporary storage location for loading multiple data sets in a single file |
---|
60 | current_data1d = None |
---|
61 | data = None |
---|
62 | # Wildcards |
---|
63 | type = ["XML files (*.xml)|*.xml", "SasView Save Files (*.svs)|*.svs"] |
---|
64 | # List of allowed extensions |
---|
65 | ext = ['.xml', '.XML', '.svs', '.SVS'] |
---|
66 | # Flag to bypass extension check |
---|
67 | allow_all = True |
---|
68 | |
---|
69 | def reset_state(self): |
---|
70 | """ |
---|
71 | Resets the class state to a base case when loading a new data file so previous |
---|
72 | data files do not appear a second time |
---|
73 | """ |
---|
74 | self.current_datainfo = None |
---|
75 | self.current_dataset = None |
---|
76 | self.current_data1d = None |
---|
77 | self.data = [] |
---|
78 | self.process = Process() |
---|
79 | self.transspectrum = TransmissionSpectrum() |
---|
80 | self.aperture = Aperture() |
---|
81 | self.collimation = Collimation() |
---|
82 | self.detector = Detector() |
---|
83 | self.names = [] |
---|
84 | self.cansas_defaults = {} |
---|
85 | self.output = [] |
---|
86 | self.ns_list = None |
---|
87 | self.logging = [] |
---|
88 | self.encoding = None |
---|
89 | |
---|
90 | def read(self, xml_file, schema_path="", invalid=True): |
---|
91 | if schema_path != "" or invalid != True: |
---|
92 | # read has been called from self.get_file_contents because xml file doens't conform to schema |
---|
93 | _, self.extension = os.path.splitext(os.path.basename(xml_file)) |
---|
94 | return self.get_file_contents(xml_file=xml_file, schema_path=schema_path, invalid=invalid) |
---|
95 | |
---|
96 | # Otherwise, read has been called by the data loader - file_reader_base_class handles this |
---|
97 | return super(XMLreader, self).read(xml_file) |
---|
98 | |
---|
99 | def get_file_contents(self, xml_file=None, schema_path="", invalid=True): |
---|
100 | # Reset everything since we're loading a new file |
---|
101 | self.reset_state() |
---|
102 | self.invalid = invalid |
---|
103 | if xml_file is None: |
---|
104 | xml_file = self.f_open.name |
---|
105 | # We don't sure f_open since lxml handles opnening/closing files |
---|
106 | if not self.f_open.closed: |
---|
107 | self.f_open.close() |
---|
108 | |
---|
109 | basename, _ = os.path.splitext(os.path.basename(xml_file)) |
---|
110 | |
---|
111 | try: |
---|
112 | # Raises FileContentsException |
---|
113 | self.load_file_and_schema(xml_file, schema_path) |
---|
114 | self.current_datainfo = DataInfo() |
---|
115 | # Raises FileContentsException if file doesn't meet CanSAS schema |
---|
116 | self.is_cansas(self.extension) |
---|
117 | self.invalid = False # If we reach this point then file must be valid CanSAS |
---|
118 | |
---|
119 | # Parse each SASentry |
---|
120 | entry_list = self.xmlroot.xpath('/ns:SASroot/ns:SASentry', namespaces={ |
---|
121 | 'ns': self.cansas_defaults.get("ns") |
---|
122 | }) |
---|
123 | # Look for a SASentry |
---|
124 | self.names.append("SASentry") |
---|
125 | self.set_processing_instructions() |
---|
126 | |
---|
127 | for entry in entry_list: |
---|
128 | self.current_datainfo.filename = basename + self.extension |
---|
129 | self.current_datainfo.meta_data["loader"] = "CanSAS XML 1D" |
---|
130 | self.current_datainfo.meta_data[PREPROCESS] = self.processing_instructions |
---|
131 | self._parse_entry(entry) |
---|
132 | self.data_cleanup() |
---|
133 | except FileContentsException as fc_exc: |
---|
134 | # File doesn't meet schema - try loading with a less strict schema |
---|
135 | base_name = xml_reader.__file__ |
---|
136 | base_name = base_name.replace("\\", "/") |
---|
137 | base = base_name.split("/sas/")[0] |
---|
138 | if self.cansas_version == "1.1": |
---|
139 | invalid_schema = INVALID_SCHEMA_PATH_1_1.format(base, self.cansas_defaults.get("schema")) |
---|
140 | else: |
---|
141 | invalid_schema = INVALID_SCHEMA_PATH_1_0.format(base, self.cansas_defaults.get("schema")) |
---|
142 | self.set_schema(invalid_schema) |
---|
143 | if self.invalid: |
---|
144 | try: |
---|
145 | # Load data with less strict schema |
---|
146 | self.read(xml_file, invalid_schema, False) |
---|
147 | |
---|
148 | # File can still be read but doesn't match schema, so raise exception |
---|
149 | self.load_file_and_schema(xml_file) # Reload strict schema so we can find where error are in file |
---|
150 | invalid_xml = self.find_invalid_xml() |
---|
151 | if invalid_xml != "": |
---|
152 | invalid_xml = INVALID_XML.format(basename + self.extension) + invalid_xml |
---|
153 | raise DataReaderException(invalid_xml) # Handled by base class |
---|
154 | except FileContentsException as fc_exc: |
---|
155 | msg = "CanSAS Reader could not load the file {}".format(xml_file) |
---|
156 | if fc_exc.message is not None: # Propagate error messages from earlier |
---|
157 | msg = fc_exc.message |
---|
158 | if not self.extension in self.ext: # If the file has no associated loader |
---|
159 | raise DefaultReaderException(msg) |
---|
160 | raise FileContentsException(msg) |
---|
161 | pass |
---|
162 | else: |
---|
163 | raise fc_exc |
---|
164 | except Exception as e: # Convert all other exceptions to FileContentsExceptions |
---|
165 | raise FileContentsException(e.message) |
---|
166 | |
---|
167 | |
---|
168 | def load_file_and_schema(self, xml_file, schema_path=""): |
---|
169 | base_name = xml_reader.__file__ |
---|
170 | base_name = base_name.replace("\\", "/") |
---|
171 | base = base_name.split("/sas/")[0] |
---|
172 | |
---|
173 | # Try and parse the XML file |
---|
174 | try: |
---|
175 | self.set_xml_file(xml_file) |
---|
176 | except etree.XMLSyntaxError: # File isn't valid XML so can't be loaded |
---|
177 | msg = "SasView cannot load {}.\nInvalid XML syntax".format(xml_file) |
---|
178 | raise FileContentsException(msg) |
---|
179 | |
---|
180 | self.cansas_version = self.xmlroot.get("version", "1.0") |
---|
181 | self.cansas_defaults = CANSAS_NS.get(self.cansas_version, "1.0") |
---|
182 | |
---|
183 | if schema_path == "": |
---|
184 | schema_path = "{}/sas/sascalc/dataloader/readers/schema/{}".format( |
---|
185 | base, self.cansas_defaults.get("schema").replace("\\", "/") |
---|
186 | ) |
---|
187 | self.set_schema(schema_path) |
---|
188 | |
---|
189 | def is_cansas(self, ext="xml"): |
---|
190 | """ |
---|
191 | Checks to see if the XML file is a CanSAS file |
---|
192 | |
---|
193 | :param ext: The file extension of the data file |
---|
194 | :raises FileContentsException: Raised if XML file isn't valid CanSAS |
---|
195 | """ |
---|
196 | if self.validate_xml(): # Check file is valid XML |
---|
197 | name = "{http://www.w3.org/2001/XMLSchema-instance}schemaLocation" |
---|
198 | value = self.xmlroot.get(name) |
---|
199 | # Check schema CanSAS version matches file CanSAS version |
---|
200 | if CANSAS_NS.get(self.cansas_version).get("ns") == value.rsplit(" ")[0]: |
---|
201 | return True |
---|
202 | if ext == "svs": |
---|
203 | return True # Why is this required? |
---|
204 | # If we get to this point then file isn't valid CanSAS |
---|
205 | logger.warning("File doesn't meet CanSAS schema. Trying to load anyway.") |
---|
206 | raise FileContentsException("The file is not valid CanSAS") |
---|
207 | |
---|
208 | def _parse_entry(self, dom, recurse=False): |
---|
209 | if not self._is_call_local() and not recurse: |
---|
210 | self.reset_state() |
---|
211 | self.data = [] |
---|
212 | self.current_datainfo = DataInfo() |
---|
213 | self.names.append("SASentry") |
---|
214 | self.parent_class = "SASentry" |
---|
215 | # Create an empty dataset if no data has been passed to the reader |
---|
216 | if self.current_dataset is None: |
---|
217 | self.current_dataset = plottable_1D(np.empty(0), np.empty(0), |
---|
218 | np.empty(0), np.empty(0)) |
---|
219 | self.base_ns = "{" + CANSAS_NS.get(self.cansas_version).get("ns") + "}" |
---|
220 | |
---|
221 | # Loop through each child in the parent element |
---|
222 | for node in dom: |
---|
223 | attr = node.attrib |
---|
224 | name = attr.get("name", "") |
---|
225 | type = attr.get("type", "") |
---|
226 | # Get the element name and set the current names level |
---|
227 | tagname = node.tag.replace(self.base_ns, "") |
---|
228 | tagname_original = tagname |
---|
229 | # Skip this iteration when loading in save state information |
---|
230 | if tagname == "fitting_plug_in" or tagname == "pr_inversion" or tagname == "invariant": |
---|
231 | continue |
---|
232 | # Get where to store content |
---|
233 | self.names.append(tagname_original) |
---|
234 | self.ns_list = CONSTANTS.iterate_namespace(self.names) |
---|
235 | # If the element is a child element, recurse |
---|
236 | if len(node.getchildren()) > 0: |
---|
237 | self.parent_class = tagname_original |
---|
238 | if tagname == 'SASdata': |
---|
239 | self._initialize_new_data_set(node) |
---|
240 | if isinstance(self.current_dataset, plottable_2D): |
---|
241 | x_bins = attr.get("x_bins", "") |
---|
242 | y_bins = attr.get("y_bins", "") |
---|
243 | if x_bins is not "" and y_bins is not "": |
---|
244 | self.current_dataset.shape = (x_bins, y_bins) |
---|
245 | else: |
---|
246 | self.current_dataset.shape = () |
---|
247 | # Recurse to access data within the group |
---|
248 | self._parse_entry(node, recurse=True) |
---|
249 | if tagname == "SASsample": |
---|
250 | self.current_datainfo.sample.name = name |
---|
251 | elif tagname == "beam_size": |
---|
252 | self.current_datainfo.source.beam_size_name = name |
---|
253 | elif tagname == "SAScollimation": |
---|
254 | self.collimation.name = name |
---|
255 | elif tagname == "aperture": |
---|
256 | self.aperture.name = name |
---|
257 | self.aperture.type = type |
---|
258 | self._add_intermediate() |
---|
259 | else: |
---|
260 | if isinstance(self.current_dataset, plottable_2D): |
---|
261 | data_point = node.text |
---|
262 | unit = attr.get('unit', '') |
---|
263 | else: |
---|
264 | data_point, unit = self._get_node_value(node, tagname) |
---|
265 | |
---|
266 | # If this is a dataset, store the data appropriately |
---|
267 | if tagname == 'Run': |
---|
268 | self.current_datainfo.run_name[data_point] = name |
---|
269 | self.current_datainfo.run.append(data_point) |
---|
270 | elif tagname == 'Title': |
---|
271 | self.current_datainfo.title = data_point |
---|
272 | elif tagname == 'SASnote': |
---|
273 | self.current_datainfo.notes.append(data_point) |
---|
274 | |
---|
275 | # I and Q points |
---|
276 | elif tagname == 'I' and isinstance(self.current_dataset, plottable_1D): |
---|
277 | self.current_dataset.yaxis("Intensity", unit) |
---|
278 | self.current_dataset.y = np.append(self.current_dataset.y, data_point) |
---|
279 | elif tagname == 'Idev' and isinstance(self.current_dataset, plottable_1D): |
---|
280 | self.current_dataset.dy = np.append(self.current_dataset.dy, data_point) |
---|
281 | elif tagname == 'Q': |
---|
282 | self.current_dataset.xaxis("Q", unit) |
---|
283 | self.current_dataset.x = np.append(self.current_dataset.x, data_point) |
---|
284 | elif tagname == 'Qdev': |
---|
285 | self.current_dataset.dx = np.append(self.current_dataset.dx, data_point) |
---|
286 | elif tagname == 'dQw': |
---|
287 | self.current_dataset.dxw = np.append(self.current_dataset.dxw, data_point) |
---|
288 | elif tagname == 'dQl': |
---|
289 | self.current_dataset.dxl = np.append(self.current_dataset.dxl, data_point) |
---|
290 | elif tagname == 'Qmean': |
---|
291 | pass |
---|
292 | elif tagname == 'Shadowfactor': |
---|
293 | pass |
---|
294 | elif tagname == 'Sesans': |
---|
295 | self.current_datainfo.isSesans = bool(data_point) |
---|
296 | self.current_dataset.xaxis(attr.get('x_axis'), |
---|
297 | attr.get('x_unit')) |
---|
298 | self.current_dataset.yaxis(attr.get('y_axis'), |
---|
299 | attr.get('y_unit')) |
---|
300 | elif tagname == 'yacceptance': |
---|
301 | self.current_datainfo.sample.yacceptance = (data_point, unit) |
---|
302 | elif tagname == 'zacceptance': |
---|
303 | self.current_datainfo.sample.zacceptance = (data_point, unit) |
---|
304 | |
---|
305 | # I and Qx, Qy - 2D data |
---|
306 | elif tagname == 'I' and isinstance(self.current_dataset, plottable_2D): |
---|
307 | self.current_dataset.yaxis("Intensity", unit) |
---|
308 | self.current_dataset.data = np.fromstring(data_point, dtype=float, sep=",") |
---|
309 | elif tagname == 'Idev' and isinstance(self.current_dataset, plottable_2D): |
---|
310 | self.current_dataset.err_data = np.fromstring(data_point, dtype=float, sep=",") |
---|
311 | elif tagname == 'Qx': |
---|
312 | self.current_dataset.xaxis("Qx", unit) |
---|
313 | self.current_dataset.qx_data = np.fromstring(data_point, dtype=float, sep=",") |
---|
314 | elif tagname == 'Qy': |
---|
315 | self.current_dataset.yaxis("Qy", unit) |
---|
316 | self.current_dataset.qy_data = np.fromstring(data_point, dtype=float, sep=",") |
---|
317 | elif tagname == 'Qxdev': |
---|
318 | self.current_dataset.xaxis("Qxdev", unit) |
---|
319 | self.current_dataset.dqx_data = np.fromstring(data_point, dtype=float, sep=",") |
---|
320 | elif tagname == 'Qydev': |
---|
321 | self.current_dataset.yaxis("Qydev", unit) |
---|
322 | self.current_dataset.dqy_data = np.fromstring(data_point, dtype=float, sep=",") |
---|
323 | elif tagname == 'Mask': |
---|
324 | inter = [item == "1" for item in data_point.split(",")] |
---|
325 | self.current_dataset.mask = np.asarray(inter, dtype=bool) |
---|
326 | |
---|
327 | # Sample Information |
---|
328 | elif tagname == 'ID' and self.parent_class == 'SASsample': |
---|
329 | self.current_datainfo.sample.ID = data_point |
---|
330 | elif tagname == 'Title' and self.parent_class == 'SASsample': |
---|
331 | self.current_datainfo.sample.name = data_point |
---|
332 | elif tagname == 'thickness' and self.parent_class == 'SASsample': |
---|
333 | self.current_datainfo.sample.thickness = data_point |
---|
334 | self.current_datainfo.sample.thickness_unit = unit |
---|
335 | elif tagname == 'transmission' and self.parent_class == 'SASsample': |
---|
336 | self.current_datainfo.sample.transmission = data_point |
---|
337 | elif tagname == 'temperature' and self.parent_class == 'SASsample': |
---|
338 | self.current_datainfo.sample.temperature = data_point |
---|
339 | self.current_datainfo.sample.temperature_unit = unit |
---|
340 | elif tagname == 'details' and self.parent_class == 'SASsample': |
---|
341 | self.current_datainfo.sample.details.append(data_point) |
---|
342 | elif tagname == 'x' and self.parent_class == 'position': |
---|
343 | self.current_datainfo.sample.position.x = data_point |
---|
344 | self.current_datainfo.sample.position_unit = unit |
---|
345 | elif tagname == 'y' and self.parent_class == 'position': |
---|
346 | self.current_datainfo.sample.position.y = data_point |
---|
347 | self.current_datainfo.sample.position_unit = unit |
---|
348 | elif tagname == 'z' and self.parent_class == 'position': |
---|
349 | self.current_datainfo.sample.position.z = data_point |
---|
350 | self.current_datainfo.sample.position_unit = unit |
---|
351 | elif tagname == 'roll' and self.parent_class == 'orientation' and 'SASsample' in self.names: |
---|
352 | self.current_datainfo.sample.orientation.x = data_point |
---|
353 | self.current_datainfo.sample.orientation_unit = unit |
---|
354 | elif tagname == 'pitch' and self.parent_class == 'orientation' and 'SASsample' in self.names: |
---|
355 | self.current_datainfo.sample.orientation.y = data_point |
---|
356 | self.current_datainfo.sample.orientation_unit = unit |
---|
357 | elif tagname == 'yaw' and self.parent_class == 'orientation' and 'SASsample' in self.names: |
---|
358 | self.current_datainfo.sample.orientation.z = data_point |
---|
359 | self.current_datainfo.sample.orientation_unit = unit |
---|
360 | |
---|
361 | # Instrumental Information |
---|
362 | elif tagname == 'name' and self.parent_class == 'SASinstrument': |
---|
363 | self.current_datainfo.instrument = data_point |
---|
364 | |
---|
365 | # Detector Information |
---|
366 | elif tagname == 'name' and self.parent_class == 'SASdetector': |
---|
367 | self.detector.name = data_point |
---|
368 | elif tagname == 'SDD' and self.parent_class == 'SASdetector': |
---|
369 | self.detector.distance = data_point |
---|
370 | self.detector.distance_unit = unit |
---|
371 | elif tagname == 'slit_length' and self.parent_class == 'SASdetector': |
---|
372 | self.detector.slit_length = data_point |
---|
373 | self.detector.slit_length_unit = unit |
---|
374 | elif tagname == 'x' and self.parent_class == 'offset': |
---|
375 | self.detector.offset.x = data_point |
---|
376 | self.detector.offset_unit = unit |
---|
377 | elif tagname == 'y' and self.parent_class == 'offset': |
---|
378 | self.detector.offset.y = data_point |
---|
379 | self.detector.offset_unit = unit |
---|
380 | elif tagname == 'z' and self.parent_class == 'offset': |
---|
381 | self.detector.offset.z = data_point |
---|
382 | self.detector.offset_unit = unit |
---|
383 | elif tagname == 'x' and self.parent_class == 'beam_center': |
---|
384 | self.detector.beam_center.x = data_point |
---|
385 | self.detector.beam_center_unit = unit |
---|
386 | elif tagname == 'y' and self.parent_class == 'beam_center': |
---|
387 | self.detector.beam_center.y = data_point |
---|
388 | self.detector.beam_center_unit = unit |
---|
389 | elif tagname == 'z' and self.parent_class == 'beam_center': |
---|
390 | self.detector.beam_center.z = data_point |
---|
391 | self.detector.beam_center_unit = unit |
---|
392 | elif tagname == 'x' and self.parent_class == 'pixel_size': |
---|
393 | self.detector.pixel_size.x = data_point |
---|
394 | self.detector.pixel_size_unit = unit |
---|
395 | elif tagname == 'y' and self.parent_class == 'pixel_size': |
---|
396 | self.detector.pixel_size.y = data_point |
---|
397 | self.detector.pixel_size_unit = unit |
---|
398 | elif tagname == 'z' and self.parent_class == 'pixel_size': |
---|
399 | self.detector.pixel_size.z = data_point |
---|
400 | self.detector.pixel_size_unit = unit |
---|
401 | elif tagname == 'roll' and self.parent_class == 'orientation' and 'SASdetector' in self.names: |
---|
402 | self.detector.orientation.x = data_point |
---|
403 | self.detector.orientation_unit = unit |
---|
404 | elif tagname == 'pitch' and self.parent_class == 'orientation' and 'SASdetector' in self.names: |
---|
405 | self.detector.orientation.y = data_point |
---|
406 | self.detector.orientation_unit = unit |
---|
407 | elif tagname == 'yaw' and self.parent_class == 'orientation' and 'SASdetector' in self.names: |
---|
408 | self.detector.orientation.z = data_point |
---|
409 | self.detector.orientation_unit = unit |
---|
410 | |
---|
411 | # Collimation and Aperture |
---|
412 | elif tagname == 'length' and self.parent_class == 'SAScollimation': |
---|
413 | self.collimation.length = data_point |
---|
414 | self.collimation.length_unit = unit |
---|
415 | elif tagname == 'name' and self.parent_class == 'SAScollimation': |
---|
416 | self.collimation.name = data_point |
---|
417 | elif tagname == 'distance' and self.parent_class == 'aperture': |
---|
418 | self.aperture.distance = data_point |
---|
419 | self.aperture.distance_unit = unit |
---|
420 | elif tagname == 'x' and self.parent_class == 'size': |
---|
421 | self.aperture.size.x = data_point |
---|
422 | self.collimation.size_unit = unit |
---|
423 | elif tagname == 'y' and self.parent_class == 'size': |
---|
424 | self.aperture.size.y = data_point |
---|
425 | self.collimation.size_unit = unit |
---|
426 | elif tagname == 'z' and self.parent_class == 'size': |
---|
427 | self.aperture.size.z = data_point |
---|
428 | self.collimation.size_unit = unit |
---|
429 | |
---|
430 | # Process Information |
---|
431 | elif tagname == 'name' and self.parent_class == 'SASprocess': |
---|
432 | self.process.name = data_point |
---|
433 | elif tagname == 'description' and self.parent_class == 'SASprocess': |
---|
434 | self.process.description = data_point |
---|
435 | elif tagname == 'date' and self.parent_class == 'SASprocess': |
---|
436 | try: |
---|
437 | self.process.date = datetime.datetime.fromtimestamp(data_point) |
---|
438 | except: |
---|
439 | self.process.date = data_point |
---|
440 | elif tagname == 'SASprocessnote': |
---|
441 | self.process.notes.append(data_point) |
---|
442 | elif tagname == 'term' and self.parent_class == 'SASprocess': |
---|
443 | unit = attr.get("unit", "") |
---|
444 | dic = { "name": name, "value": data_point, "unit": unit } |
---|
445 | self.process.term.append(dic) |
---|
446 | |
---|
447 | # Transmission Spectrum |
---|
448 | elif tagname == 'T' and self.parent_class == 'Tdata': |
---|
449 | self.transspectrum.transmission = np.append(self.transspectrum.transmission, data_point) |
---|
450 | self.transspectrum.transmission_unit = unit |
---|
451 | elif tagname == 'Tdev' and self.parent_class == 'Tdata': |
---|
452 | self.transspectrum.transmission_deviation = np.append(self.transspectrum.transmission_deviation, data_point) |
---|
453 | self.transspectrum.transmission_deviation_unit = unit |
---|
454 | elif tagname == 'Lambda' and self.parent_class == 'Tdata': |
---|
455 | self.transspectrum.wavelength = np.append(self.transspectrum.wavelength, data_point) |
---|
456 | self.transspectrum.wavelength_unit = unit |
---|
457 | |
---|
458 | # Source Information |
---|
459 | elif tagname == 'wavelength' and (self.parent_class == 'SASsource' or self.parent_class == 'SASData'): |
---|
460 | self.current_datainfo.source.wavelength = data_point |
---|
461 | self.current_datainfo.source.wavelength_unit = unit |
---|
462 | elif tagname == 'wavelength_min' and self.parent_class == 'SASsource': |
---|
463 | self.current_datainfo.source.wavelength_min = data_point |
---|
464 | self.current_datainfo.source.wavelength_min_unit = unit |
---|
465 | elif tagname == 'wavelength_max' and self.parent_class == 'SASsource': |
---|
466 | self.current_datainfo.source.wavelength_max = data_point |
---|
467 | self.current_datainfo.source.wavelength_max_unit = unit |
---|
468 | elif tagname == 'wavelength_spread' and self.parent_class == 'SASsource': |
---|
469 | self.current_datainfo.source.wavelength_spread = data_point |
---|
470 | self.current_datainfo.source.wavelength_spread_unit = unit |
---|
471 | elif tagname == 'x' and self.parent_class == 'beam_size': |
---|
472 | self.current_datainfo.source.beam_size.x = data_point |
---|
473 | self.current_datainfo.source.beam_size_unit = unit |
---|
474 | elif tagname == 'y' and self.parent_class == 'beam_size': |
---|
475 | self.current_datainfo.source.beam_size.y = data_point |
---|
476 | self.current_datainfo.source.beam_size_unit = unit |
---|
477 | elif tagname == 'z' and self.parent_class == 'pixel_size': |
---|
478 | self.current_datainfo.source.data_point.z = data_point |
---|
479 | self.current_datainfo.source.beam_size_unit = unit |
---|
480 | elif tagname == 'radiation' and self.parent_class == 'SASsource': |
---|
481 | self.current_datainfo.source.radiation = data_point |
---|
482 | elif tagname == 'beam_shape' and self.parent_class == 'SASsource': |
---|
483 | self.current_datainfo.source.beam_shape = data_point |
---|
484 | |
---|
485 | # Everything else goes in meta_data |
---|
486 | else: |
---|
487 | new_key = self._create_unique_key(self.current_datainfo.meta_data, tagname) |
---|
488 | self.current_datainfo.meta_data[new_key] = data_point |
---|
489 | |
---|
490 | self.names.remove(tagname_original) |
---|
491 | length = 0 |
---|
492 | if len(self.names) > 1: |
---|
493 | length = len(self.names) - 1 |
---|
494 | self.parent_class = self.names[length] |
---|
495 | if not self._is_call_local() and not recurse: |
---|
496 | self.frm = "" |
---|
497 | self.current_datainfo.errors = set() |
---|
498 | for error in self.errors: |
---|
499 | self.current_datainfo.errors.add(error) |
---|
500 | self.data_cleanup() |
---|
501 | self.sort_one_d_data() |
---|
502 | self.sort_two_d_data() |
---|
503 | self.reset_data_list() |
---|
504 | empty = None |
---|
505 | return self.output[0], empty |
---|
506 | |
---|
507 | def data_cleanup(self): |
---|
508 | """ |
---|
509 | Clean up the data sets and refresh everything |
---|
510 | :return: None |
---|
511 | """ |
---|
512 | has_error_dx = self.current_dataset.dx is not None |
---|
513 | has_error_dy = self.current_dataset.dy is not None |
---|
514 | self.remove_empty_q_values(has_error_dx=has_error_dx, |
---|
515 | has_error_dy=has_error_dy) |
---|
516 | self.send_to_output() # Combine datasets with DataInfo |
---|
517 | self.current_datainfo = DataInfo() # Reset DataInfo |
---|
518 | |
---|
519 | def _is_call_local(self): |
---|
520 | if self.frm == "": |
---|
521 | inter = inspect.stack() |
---|
522 | self.frm = inter[2] |
---|
523 | mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "") |
---|
524 | mod_name = mod_name.replace(".py", "") |
---|
525 | mod = mod_name.split("sas/") |
---|
526 | mod_name = mod[1] |
---|
527 | if mod_name != "sascalc/dataloader/readers/cansas_reader": |
---|
528 | return False |
---|
529 | return True |
---|
530 | |
---|
531 | def _add_intermediate(self): |
---|
532 | """ |
---|
533 | This method stores any intermediate objects within the final data set after fully reading the set. |
---|
534 | """ |
---|
535 | if self.parent_class == 'SASprocess': |
---|
536 | self.current_datainfo.process.append(self.process) |
---|
537 | self.process = Process() |
---|
538 | elif self.parent_class == 'SASdetector': |
---|
539 | self.current_datainfo.detector.append(self.detector) |
---|
540 | self.detector = Detector() |
---|
541 | elif self.parent_class == 'SAStransmission_spectrum': |
---|
542 | self.current_datainfo.trans_spectrum.append(self.transspectrum) |
---|
543 | self.transspectrum = TransmissionSpectrum() |
---|
544 | elif self.parent_class == 'SAScollimation': |
---|
545 | self.current_datainfo.collimation.append(self.collimation) |
---|
546 | self.collimation = Collimation() |
---|
547 | elif self.parent_class == 'aperture': |
---|
548 | self.collimation.aperture.append(self.aperture) |
---|
549 | self.aperture = Aperture() |
---|
550 | elif self.parent_class == 'SASdata': |
---|
551 | self._check_for_empty_resolution() |
---|
552 | self.data.append(self.current_dataset) |
---|
553 | |
---|
554 | def _get_node_value(self, node, tagname): |
---|
555 | """ |
---|
556 | Get the value of a node and any applicable units |
---|
557 | |
---|
558 | :param node: The XML node to get the value of |
---|
559 | :param tagname: The tagname of the node |
---|
560 | """ |
---|
561 | #Get the text from the node and convert all whitespace to spaces |
---|
562 | units = '' |
---|
563 | node_value = node.text |
---|
564 | if node_value is not None: |
---|
565 | node_value = ' '.join(node_value.split()) |
---|
566 | else: |
---|
567 | node_value = "" |
---|
568 | |
---|
569 | # If the value is a float, compile with units. |
---|
570 | if self.ns_list.ns_datatype == "float": |
---|
571 | # If an empty value is given, set as zero. |
---|
572 | if node_value is None or node_value.isspace() \ |
---|
573 | or node_value.lower() == "nan": |
---|
574 | node_value = "0.0" |
---|
575 | #Convert the value to the base units |
---|
576 | node_value, units = self._unit_conversion(node, tagname, node_value) |
---|
577 | |
---|
578 | # If the value is a timestamp, convert to a datetime object |
---|
579 | elif self.ns_list.ns_datatype == "timestamp": |
---|
580 | if node_value is None or node_value.isspace(): |
---|
581 | pass |
---|
582 | else: |
---|
583 | try: |
---|
584 | node_value = \ |
---|
585 | datetime.datetime.fromtimestamp(node_value) |
---|
586 | except ValueError: |
---|
587 | node_value = None |
---|
588 | return node_value, units |
---|
589 | |
---|
590 | def _unit_conversion(self, node, tagname, node_value): |
---|
591 | """ |
---|
592 | A unit converter method used to convert the data included in the file |
---|
593 | to the default units listed in data_info |
---|
594 | |
---|
595 | :param node: XML node |
---|
596 | :param tagname: name of the node |
---|
597 | :param node_value: The value of the current dom node |
---|
598 | """ |
---|
599 | attr = node.attrib |
---|
600 | value_unit = '' |
---|
601 | err_msg = None |
---|
602 | default_unit = None |
---|
603 | if not isinstance(node_value, float): |
---|
604 | node_value = float(node_value) |
---|
605 | if 'unit' in attr and attr.get('unit') is not None: |
---|
606 | try: |
---|
607 | local_unit = attr['unit'] |
---|
608 | unitname = self.ns_list.current_level.get("unit", "") |
---|
609 | if "SASdetector" in self.names: |
---|
610 | save_in = "detector" |
---|
611 | elif "aperture" in self.names: |
---|
612 | save_in = "aperture" |
---|
613 | elif "SAScollimation" in self.names: |
---|
614 | save_in = "collimation" |
---|
615 | elif "SAStransmission_spectrum" in self.names: |
---|
616 | save_in = "transspectrum" |
---|
617 | elif "SASdata" in self.names: |
---|
618 | x = np.zeros(1) |
---|
619 | y = np.zeros(1) |
---|
620 | self.current_data1d = Data1D(x, y) |
---|
621 | save_in = "current_data1d" |
---|
622 | elif "SASsource" in self.names: |
---|
623 | save_in = "current_datainfo.source" |
---|
624 | elif "SASsample" in self.names: |
---|
625 | save_in = "current_datainfo.sample" |
---|
626 | elif "SASprocess" in self.names: |
---|
627 | save_in = "process" |
---|
628 | else: |
---|
629 | save_in = "current_datainfo" |
---|
630 | exec "default_unit = self.{0}.{1}".format(save_in, unitname) |
---|
631 | if local_unit and default_unit and local_unit.lower() != default_unit.lower() \ |
---|
632 | and local_unit.lower() != "none": |
---|
633 | if HAS_CONVERTER == True: |
---|
634 | # Check local units - bad units raise KeyError |
---|
635 | data_conv_q = Converter(local_unit) |
---|
636 | value_unit = default_unit |
---|
637 | node_value = data_conv_q(node_value, units=default_unit) |
---|
638 | else: |
---|
639 | value_unit = local_unit |
---|
640 | err_msg = "Unit converter is not available.\n" |
---|
641 | else: |
---|
642 | value_unit = local_unit |
---|
643 | except KeyError: |
---|
644 | # Do not throw an error for loading Sesans data in cansas xml |
---|
645 | # This is a temporary fix. |
---|
646 | if local_unit != "A" and local_unit != 'pol': |
---|
647 | err_msg = "CanSAS reader: unexpected " |
---|
648 | err_msg += "\"{0}\" unit [{1}]; " |
---|
649 | err_msg = err_msg.format(tagname, local_unit) |
---|
650 | err_msg += "expecting [{0}]".format(default_unit) |
---|
651 | value_unit = local_unit |
---|
652 | except: |
---|
653 | err_msg = "CanSAS reader: unknown error converting " |
---|
654 | err_msg += "\"{0}\" unit [{1}]" |
---|
655 | err_msg = err_msg.format(tagname, local_unit) |
---|
656 | value_unit = local_unit |
---|
657 | elif 'unit' in attr: |
---|
658 | value_unit = attr['unit'] |
---|
659 | if err_msg: |
---|
660 | self.errors.add(err_msg) |
---|
661 | return node_value, value_unit |
---|
662 | |
---|
663 | def _check_for_empty_resolution(self): |
---|
664 | """ |
---|
665 | a method to check all resolution data sets are the same size as I and q |
---|
666 | """ |
---|
667 | dql_exists = False |
---|
668 | dqw_exists = False |
---|
669 | dq_exists = False |
---|
670 | di_exists = False |
---|
671 | if self.current_dataset.dxl is not None: |
---|
672 | dql_exists = True |
---|
673 | if self.current_dataset.dxw is not None: |
---|
674 | dqw_exists = True |
---|
675 | if self.current_dataset.dx is not None: |
---|
676 | dq_exists = True |
---|
677 | if self.current_dataset.dy is not None: |
---|
678 | di_exists = True |
---|
679 | if dqw_exists and not dql_exists: |
---|
680 | array_size = self.current_dataset.dxw.size - 1 |
---|
681 | self.current_dataset.dxl = np.append(self.current_dataset.dxl, |
---|
682 | np.zeros([array_size])) |
---|
683 | elif dql_exists and not dqw_exists: |
---|
684 | array_size = self.current_dataset.dxl.size - 1 |
---|
685 | self.current_dataset.dxw = np.append(self.current_dataset.dxw, |
---|
686 | np.zeros([array_size])) |
---|
687 | elif not dql_exists and not dqw_exists and not dq_exists: |
---|
688 | array_size = self.current_dataset.x.size - 1 |
---|
689 | self.current_dataset.dx = np.append(self.current_dataset.dx, |
---|
690 | np.zeros([array_size])) |
---|
691 | if not di_exists: |
---|
692 | array_size = self.current_dataset.y.size - 1 |
---|
693 | self.current_dataset.dy = np.append(self.current_dataset.dy, |
---|
694 | np.zeros([array_size])) |
---|
695 | |
---|
696 | def _initialize_new_data_set(self, node=None): |
---|
697 | if node is not None: |
---|
698 | for child in node: |
---|
699 | if child.tag.replace(self.base_ns, "") == "Idata": |
---|
700 | for i_child in child: |
---|
701 | if i_child.tag.replace(self.base_ns, "") == "Qx": |
---|
702 | self.current_dataset = plottable_2D() |
---|
703 | return |
---|
704 | self.current_dataset = plottable_1D(np.array(0), np.array(0)) |
---|
705 | |
---|
706 | ## Writing Methods |
---|
707 | def write(self, filename, datainfo): |
---|
708 | """ |
---|
709 | Write the content of a Data1D as a CanSAS XML file |
---|
710 | |
---|
711 | :param filename: name of the file to write |
---|
712 | :param datainfo: Data1D object |
---|
713 | """ |
---|
714 | # Create XML document |
---|
715 | doc, _ = self._to_xml_doc(datainfo) |
---|
716 | # Write the file |
---|
717 | file_ref = open(filename, 'w') |
---|
718 | if self.encoding is None: |
---|
719 | self.encoding = "UTF-8" |
---|
720 | doc.write(file_ref, encoding=self.encoding, |
---|
721 | pretty_print=True, xml_declaration=True) |
---|
722 | file_ref.close() |
---|
723 | |
---|
724 | def _to_xml_doc(self, datainfo): |
---|
725 | """ |
---|
726 | Create an XML document to contain the content of a Data1D |
---|
727 | |
---|
728 | :param datainfo: Data1D object |
---|
729 | """ |
---|
730 | is_2d = False |
---|
731 | if issubclass(datainfo.__class__, Data2D): |
---|
732 | is_2d = True |
---|
733 | |
---|
734 | # Get PIs and create root element |
---|
735 | pi_string = self._get_pi_string() |
---|
736 | # Define namespaces and create SASroot object |
---|
737 | main_node = self._create_main_node() |
---|
738 | # Create ElementTree, append SASroot and apply processing instructions |
---|
739 | base_string = pi_string + self.to_string(main_node) |
---|
740 | base_element = self.create_element_from_string(base_string) |
---|
741 | doc = self.create_tree(base_element) |
---|
742 | # Create SASentry Element |
---|
743 | entry_node = self.create_element("SASentry") |
---|
744 | root = doc.getroot() |
---|
745 | root.append(entry_node) |
---|
746 | |
---|
747 | # Add Title to SASentry |
---|
748 | self.write_node(entry_node, "Title", datainfo.title) |
---|
749 | # Add Run to SASentry |
---|
750 | self._write_run_names(datainfo, entry_node) |
---|
751 | # Add Data info to SASEntry |
---|
752 | if is_2d: |
---|
753 | self._write_data_2d(datainfo, entry_node) |
---|
754 | else: |
---|
755 | self._write_data(datainfo, entry_node) |
---|
756 | # Transmission Spectrum Info |
---|
757 | # TODO: fix the writer to linearize all data, including T_spectrum |
---|
758 | # self._write_trans_spectrum(datainfo, entry_node) |
---|
759 | # Sample info |
---|
760 | self._write_sample_info(datainfo, entry_node) |
---|
761 | # Instrument info |
---|
762 | instr = self._write_instrument(datainfo, entry_node) |
---|
763 | # Source |
---|
764 | self._write_source(datainfo, instr) |
---|
765 | # Collimation |
---|
766 | self._write_collimation(datainfo, instr) |
---|
767 | # Detectors |
---|
768 | self._write_detectors(datainfo, instr) |
---|
769 | # Processes info |
---|
770 | self._write_process_notes(datainfo, entry_node) |
---|
771 | # Note info |
---|
772 | self._write_notes(datainfo, entry_node) |
---|
773 | # Return the document, and the SASentry node associated with |
---|
774 | # the data we just wrote |
---|
775 | # If the calling function was not the cansas reader, return a minidom |
---|
776 | # object rather than an lxml object. |
---|
777 | self.frm = inspect.stack()[1] |
---|
778 | doc, entry_node = self._check_origin(entry_node, doc) |
---|
779 | return doc, entry_node |
---|
780 | |
---|
781 | def write_node(self, parent, name, value, attr=None): |
---|
782 | """ |
---|
783 | :param doc: document DOM |
---|
784 | :param parent: parent node |
---|
785 | :param name: tag of the element |
---|
786 | :param value: value of the child text node |
---|
787 | :param attr: attribute dictionary |
---|
788 | |
---|
789 | :return: True if something was appended, otherwise False |
---|
790 | """ |
---|
791 | if value is not None: |
---|
792 | parent = self.ebuilder(parent, name, value, attr) |
---|
793 | return True |
---|
794 | return False |
---|
795 | |
---|
796 | def _get_pi_string(self): |
---|
797 | """ |
---|
798 | Creates the processing instructions header for writing to file |
---|
799 | """ |
---|
800 | pis = self.return_processing_instructions() |
---|
801 | if len(pis) > 0: |
---|
802 | pi_tree = self.create_tree(pis[0]) |
---|
803 | i = 1 |
---|
804 | for i in range(1, len(pis) - 1): |
---|
805 | pi_tree = self.append(pis[i], pi_tree) |
---|
806 | pi_string = self.to_string(pi_tree) |
---|
807 | else: |
---|
808 | pi_string = "" |
---|
809 | return pi_string |
---|
810 | |
---|
811 | def _create_main_node(self): |
---|
812 | """ |
---|
813 | Creates the primary xml header used when writing to file |
---|
814 | """ |
---|
815 | xsi = "http://www.w3.org/2001/XMLSchema-instance" |
---|
816 | version = self.cansas_version |
---|
817 | n_s = CANSAS_NS.get(version).get("ns") |
---|
818 | if version == "1.1": |
---|
819 | url = "http://www.cansas.org/formats/1.1/" |
---|
820 | else: |
---|
821 | url = "http://svn.smallangles.net/svn/canSAS/1dwg/trunk/" |
---|
822 | schema_location = "{0} {1}cansas1d.xsd".format(n_s, url) |
---|
823 | attrib = {"{" + xsi + "}schemaLocation" : schema_location, |
---|
824 | "version" : version} |
---|
825 | nsmap = {'xsi' : xsi, None: n_s} |
---|
826 | |
---|
827 | main_node = self.create_element("{" + n_s + "}SASroot", |
---|
828 | attrib=attrib, nsmap=nsmap) |
---|
829 | return main_node |
---|
830 | |
---|
831 | def _write_run_names(self, datainfo, entry_node): |
---|
832 | """ |
---|
833 | Writes the run names to the XML file |
---|
834 | |
---|
835 | :param datainfo: The Data1D object the information is coming from |
---|
836 | :param entry_node: lxml node ElementTree object to be appended to |
---|
837 | """ |
---|
838 | if datainfo.run is None or datainfo.run == []: |
---|
839 | datainfo.run.append(RUN_NAME_DEFAULT) |
---|
840 | datainfo.run_name[RUN_NAME_DEFAULT] = RUN_NAME_DEFAULT |
---|
841 | for item in datainfo.run: |
---|
842 | runname = {} |
---|
843 | if item in datainfo.run_name and \ |
---|
844 | len(str(datainfo.run_name[item])) > 1: |
---|
845 | runname = {'name': datainfo.run_name[item]} |
---|
846 | self.write_node(entry_node, "Run", item, runname) |
---|
847 | |
---|
848 | def _write_data(self, datainfo, entry_node): |
---|
849 | """ |
---|
850 | Writes 1D I and Q data to the XML file |
---|
851 | |
---|
852 | :param datainfo: The Data1D object the information is coming from |
---|
853 | :param entry_node: lxml node ElementTree object to be appended to |
---|
854 | """ |
---|
855 | node = self.create_element("SASdata") |
---|
856 | self.append(node, entry_node) |
---|
857 | |
---|
858 | for i in range(len(datainfo.x)): |
---|
859 | point = self.create_element("Idata") |
---|
860 | node.append(point) |
---|
861 | self.write_node(point, "Q", datainfo.x[i], |
---|
862 | {'unit': datainfo.x_unit}) |
---|
863 | if len(datainfo.y) >= i: |
---|
864 | self.write_node(point, "I", datainfo.y[i], |
---|
865 | {'unit': datainfo.y_unit}) |
---|
866 | if datainfo.dy is not None and len(datainfo.dy) > i: |
---|
867 | self.write_node(point, "Idev", datainfo.dy[i], |
---|
868 | {'unit': datainfo.y_unit}) |
---|
869 | if datainfo.dx is not None and len(datainfo.dx) > i: |
---|
870 | self.write_node(point, "Qdev", datainfo.dx[i], |
---|
871 | {'unit': datainfo.x_unit}) |
---|
872 | if datainfo.dxw is not None and len(datainfo.dxw) > i: |
---|
873 | self.write_node(point, "dQw", datainfo.dxw[i], |
---|
874 | {'unit': datainfo.x_unit}) |
---|
875 | if datainfo.dxl is not None and len(datainfo.dxl) > i: |
---|
876 | self.write_node(point, "dQl", datainfo.dxl[i], |
---|
877 | {'unit': datainfo.x_unit}) |
---|
878 | if datainfo.isSesans: |
---|
879 | sesans_attrib = {'x_axis': datainfo._xaxis, |
---|
880 | 'y_axis': datainfo._yaxis, |
---|
881 | 'x_unit': datainfo.x_unit, |
---|
882 | 'y_unit': datainfo.y_unit} |
---|
883 | sesans = self.create_element("Sesans", attrib=sesans_attrib) |
---|
884 | sesans.text = str(datainfo.isSesans) |
---|
885 | entry_node.append(sesans) |
---|
886 | self.write_node(entry_node, "yacceptance", datainfo.sample.yacceptance[0], |
---|
887 | {'unit': datainfo.sample.yacceptance[1]}) |
---|
888 | self.write_node(entry_node, "zacceptance", datainfo.sample.zacceptance[0], |
---|
889 | {'unit': datainfo.sample.zacceptance[1]}) |
---|
890 | |
---|
891 | |
---|
892 | def _write_data_2d(self, datainfo, entry_node): |
---|
893 | """ |
---|
894 | Writes 2D data to the XML file |
---|
895 | |
---|
896 | :param datainfo: The Data2D object the information is coming from |
---|
897 | :param entry_node: lxml node ElementTree object to be appended to |
---|
898 | """ |
---|
899 | attr = {} |
---|
900 | if datainfo.data.shape: |
---|
901 | attr["x_bins"] = str(len(datainfo.x_bins)) |
---|
902 | attr["y_bins"] = str(len(datainfo.y_bins)) |
---|
903 | node = self.create_element("SASdata", attr) |
---|
904 | self.append(node, entry_node) |
---|
905 | |
---|
906 | point = self.create_element("Idata") |
---|
907 | node.append(point) |
---|
908 | qx = ','.join([str(datainfo.qx_data[i]) for i in xrange(len(datainfo.qx_data))]) |
---|
909 | qy = ','.join([str(datainfo.qy_data[i]) for i in xrange(len(datainfo.qy_data))]) |
---|
910 | intensity = ','.join([str(datainfo.data[i]) for i in xrange(len(datainfo.data))]) |
---|
911 | |
---|
912 | self.write_node(point, "Qx", qx, |
---|
913 | {'unit': datainfo._xunit}) |
---|
914 | self.write_node(point, "Qy", qy, |
---|
915 | {'unit': datainfo._yunit}) |
---|
916 | self.write_node(point, "I", intensity, |
---|
917 | {'unit': datainfo._zunit}) |
---|
918 | if datainfo.err_data is not None: |
---|
919 | err = ','.join([str(datainfo.err_data[i]) for i in |
---|
920 | xrange(len(datainfo.err_data))]) |
---|
921 | self.write_node(point, "Idev", err, |
---|
922 | {'unit': datainfo._zunit}) |
---|
923 | if datainfo.dqy_data is not None: |
---|
924 | dqy = ','.join([str(datainfo.dqy_data[i]) for i in |
---|
925 | xrange(len(datainfo.dqy_data))]) |
---|
926 | self.write_node(point, "Qydev", dqy, |
---|
927 | {'unit': datainfo._yunit}) |
---|
928 | if datainfo.dqx_data is not None: |
---|
929 | dqx = ','.join([str(datainfo.dqx_data[i]) for i in |
---|
930 | xrange(len(datainfo.dqx_data))]) |
---|
931 | self.write_node(point, "Qxdev", dqx, |
---|
932 | {'unit': datainfo._xunit}) |
---|
933 | if datainfo.mask is not None: |
---|
934 | mask = ','.join( |
---|
935 | ["1" if datainfo.mask[i] else "0" |
---|
936 | for i in xrange(len(datainfo.mask))]) |
---|
937 | self.write_node(point, "Mask", mask) |
---|
938 | |
---|
939 | def _write_trans_spectrum(self, datainfo, entry_node): |
---|
940 | """ |
---|
941 | Writes the transmission spectrum data to the XML file |
---|
942 | |
---|
943 | :param datainfo: The Data1D object the information is coming from |
---|
944 | :param entry_node: lxml node ElementTree object to be appended to |
---|
945 | """ |
---|
946 | for i in range(len(datainfo.trans_spectrum)): |
---|
947 | spectrum = datainfo.trans_spectrum[i] |
---|
948 | node = self.create_element("SAStransmission_spectrum", |
---|
949 | {"name" : spectrum.name}) |
---|
950 | self.append(node, entry_node) |
---|
951 | if isinstance(spectrum.timestamp, datetime.datetime): |
---|
952 | node.setAttribute("timestamp", spectrum.timestamp) |
---|
953 | for i in range(len(spectrum.wavelength)): |
---|
954 | point = self.create_element("Tdata") |
---|
955 | node.append(point) |
---|
956 | self.write_node(point, "Lambda", spectrum.wavelength[i], |
---|
957 | {'unit': spectrum.wavelength_unit}) |
---|
958 | self.write_node(point, "T", spectrum.transmission[i], |
---|
959 | {'unit': spectrum.transmission_unit}) |
---|
960 | if spectrum.transmission_deviation is not None \ |
---|
961 | and len(spectrum.transmission_deviation) >= i: |
---|
962 | self.write_node(point, "Tdev", |
---|
963 | spectrum.transmission_deviation[i], |
---|
964 | {'unit': |
---|
965 | spectrum.transmission_deviation_unit}) |
---|
966 | |
---|
967 | def _write_sample_info(self, datainfo, entry_node): |
---|
968 | """ |
---|
969 | Writes the sample information to the XML file |
---|
970 | |
---|
971 | :param datainfo: The Data1D object the information is coming from |
---|
972 | :param entry_node: lxml node ElementTree object to be appended to |
---|
973 | """ |
---|
974 | sample = self.create_element("SASsample") |
---|
975 | if datainfo.sample.name is not None: |
---|
976 | self.write_attribute(sample, "name", |
---|
977 | str(datainfo.sample.name)) |
---|
978 | self.append(sample, entry_node) |
---|
979 | self.write_node(sample, "ID", str(datainfo.sample.ID)) |
---|
980 | self.write_node(sample, "thickness", datainfo.sample.thickness, |
---|
981 | {"unit": datainfo.sample.thickness_unit}) |
---|
982 | self.write_node(sample, "transmission", datainfo.sample.transmission) |
---|
983 | self.write_node(sample, "temperature", datainfo.sample.temperature, |
---|
984 | {"unit": datainfo.sample.temperature_unit}) |
---|
985 | |
---|
986 | pos = self.create_element("position") |
---|
987 | written = self.write_node(pos, |
---|
988 | "x", |
---|
989 | datainfo.sample.position.x, |
---|
990 | {"unit": datainfo.sample.position_unit}) |
---|
991 | written = written | self.write_node( \ |
---|
992 | pos, "y", datainfo.sample.position.y, |
---|
993 | {"unit": datainfo.sample.position_unit}) |
---|
994 | written = written | self.write_node( \ |
---|
995 | pos, "z", datainfo.sample.position.z, |
---|
996 | {"unit": datainfo.sample.position_unit}) |
---|
997 | if written == True: |
---|
998 | self.append(pos, sample) |
---|
999 | |
---|
1000 | ori = self.create_element("orientation") |
---|
1001 | written = self.write_node(ori, "roll", |
---|
1002 | datainfo.sample.orientation.x, |
---|
1003 | {"unit": datainfo.sample.orientation_unit}) |
---|
1004 | written = written | self.write_node( \ |
---|
1005 | ori, "pitch", datainfo.sample.orientation.y, |
---|
1006 | {"unit": datainfo.sample.orientation_unit}) |
---|
1007 | written = written | self.write_node( \ |
---|
1008 | ori, "yaw", datainfo.sample.orientation.z, |
---|
1009 | {"unit": datainfo.sample.orientation_unit}) |
---|
1010 | if written == True: |
---|
1011 | self.append(ori, sample) |
---|
1012 | |
---|
1013 | for item in datainfo.sample.details: |
---|
1014 | self.write_node(sample, "details", item) |
---|
1015 | |
---|
1016 | def _write_instrument(self, datainfo, entry_node): |
---|
1017 | """ |
---|
1018 | Writes the instrumental information to the XML file |
---|
1019 | |
---|
1020 | :param datainfo: The Data1D object the information is coming from |
---|
1021 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1022 | """ |
---|
1023 | instr = self.create_element("SASinstrument") |
---|
1024 | self.append(instr, entry_node) |
---|
1025 | self.write_node(instr, "name", datainfo.instrument) |
---|
1026 | return instr |
---|
1027 | |
---|
1028 | def _write_source(self, datainfo, instr): |
---|
1029 | """ |
---|
1030 | Writes the source information to the XML file |
---|
1031 | |
---|
1032 | :param datainfo: The Data1D object the information is coming from |
---|
1033 | :param instr: instrument node to be appended to |
---|
1034 | """ |
---|
1035 | source = self.create_element("SASsource") |
---|
1036 | if datainfo.source.name is not None: |
---|
1037 | self.write_attribute(source, "name", |
---|
1038 | str(datainfo.source.name)) |
---|
1039 | self.append(source, instr) |
---|
1040 | if datainfo.source.radiation is None or datainfo.source.radiation == '': |
---|
1041 | datainfo.source.radiation = "neutron" |
---|
1042 | self.write_node(source, "radiation", datainfo.source.radiation) |
---|
1043 | |
---|
1044 | size = self.create_element("beam_size") |
---|
1045 | if datainfo.source.beam_size_name is not None: |
---|
1046 | self.write_attribute(size, "name", |
---|
1047 | str(datainfo.source.beam_size_name)) |
---|
1048 | written = self.write_node( \ |
---|
1049 | size, "x", datainfo.source.beam_size.x, |
---|
1050 | {"unit": datainfo.source.beam_size_unit}) |
---|
1051 | written = written | self.write_node( \ |
---|
1052 | size, "y", datainfo.source.beam_size.y, |
---|
1053 | {"unit": datainfo.source.beam_size_unit}) |
---|
1054 | written = written | self.write_node( \ |
---|
1055 | size, "z", datainfo.source.beam_size.z, |
---|
1056 | {"unit": datainfo.source.beam_size_unit}) |
---|
1057 | if written == True: |
---|
1058 | self.append(size, source) |
---|
1059 | |
---|
1060 | self.write_node(source, "beam_shape", datainfo.source.beam_shape) |
---|
1061 | self.write_node(source, "wavelength", |
---|
1062 | datainfo.source.wavelength, |
---|
1063 | {"unit": datainfo.source.wavelength_unit}) |
---|
1064 | self.write_node(source, "wavelength_min", |
---|
1065 | datainfo.source.wavelength_min, |
---|
1066 | {"unit": datainfo.source.wavelength_min_unit}) |
---|
1067 | self.write_node(source, "wavelength_max", |
---|
1068 | datainfo.source.wavelength_max, |
---|
1069 | {"unit": datainfo.source.wavelength_max_unit}) |
---|
1070 | self.write_node(source, "wavelength_spread", |
---|
1071 | datainfo.source.wavelength_spread, |
---|
1072 | {"unit": datainfo.source.wavelength_spread_unit}) |
---|
1073 | |
---|
1074 | def _write_collimation(self, datainfo, instr): |
---|
1075 | """ |
---|
1076 | Writes the collimation information to the XML file |
---|
1077 | |
---|
1078 | :param datainfo: The Data1D object the information is coming from |
---|
1079 | :param instr: lxml node ElementTree object to be appended to |
---|
1080 | """ |
---|
1081 | if datainfo.collimation == [] or datainfo.collimation is None: |
---|
1082 | coll = Collimation() |
---|
1083 | datainfo.collimation.append(coll) |
---|
1084 | for item in datainfo.collimation: |
---|
1085 | coll = self.create_element("SAScollimation") |
---|
1086 | if item.name is not None: |
---|
1087 | self.write_attribute(coll, "name", str(item.name)) |
---|
1088 | self.append(coll, instr) |
---|
1089 | |
---|
1090 | self.write_node(coll, "length", item.length, |
---|
1091 | {"unit": item.length_unit}) |
---|
1092 | |
---|
1093 | for aperture in item.aperture: |
---|
1094 | apert = self.create_element("aperture") |
---|
1095 | if aperture.name is not None: |
---|
1096 | self.write_attribute(apert, "name", str(aperture.name)) |
---|
1097 | if aperture.type is not None: |
---|
1098 | self.write_attribute(apert, "type", str(aperture.type)) |
---|
1099 | self.append(apert, coll) |
---|
1100 | |
---|
1101 | size = self.create_element("size") |
---|
1102 | if aperture.size_name is not None: |
---|
1103 | self.write_attribute(size, "name", |
---|
1104 | str(aperture.size_name)) |
---|
1105 | written = self.write_node(size, "x", aperture.size.x, |
---|
1106 | {"unit": aperture.size_unit}) |
---|
1107 | written = written | self.write_node( \ |
---|
1108 | size, "y", aperture.size.y, |
---|
1109 | {"unit": aperture.size_unit}) |
---|
1110 | written = written | self.write_node( \ |
---|
1111 | size, "z", aperture.size.z, |
---|
1112 | {"unit": aperture.size_unit}) |
---|
1113 | if written == True: |
---|
1114 | self.append(size, apert) |
---|
1115 | |
---|
1116 | self.write_node(apert, "distance", aperture.distance, |
---|
1117 | {"unit": aperture.distance_unit}) |
---|
1118 | |
---|
1119 | def _write_detectors(self, datainfo, instr): |
---|
1120 | """ |
---|
1121 | Writes the detector information to the XML file |
---|
1122 | |
---|
1123 | :param datainfo: The Data1D object the information is coming from |
---|
1124 | :param inst: lxml instrument node to be appended to |
---|
1125 | """ |
---|
1126 | if datainfo.detector is None or datainfo.detector == []: |
---|
1127 | det = Detector() |
---|
1128 | det.name = "" |
---|
1129 | datainfo.detector.append(det) |
---|
1130 | |
---|
1131 | for item in datainfo.detector: |
---|
1132 | det = self.create_element("SASdetector") |
---|
1133 | written = self.write_node(det, "name", item.name) |
---|
1134 | written = written | self.write_node(det, "SDD", item.distance, |
---|
1135 | {"unit": item.distance_unit}) |
---|
1136 | if written == True: |
---|
1137 | self.append(det, instr) |
---|
1138 | |
---|
1139 | off = self.create_element("offset") |
---|
1140 | written = self.write_node(off, "x", item.offset.x, |
---|
1141 | {"unit": item.offset_unit}) |
---|
1142 | written = written | self.write_node(off, "y", item.offset.y, |
---|
1143 | {"unit": item.offset_unit}) |
---|
1144 | written = written | self.write_node(off, "z", item.offset.z, |
---|
1145 | {"unit": item.offset_unit}) |
---|
1146 | if written == True: |
---|
1147 | self.append(off, det) |
---|
1148 | |
---|
1149 | ori = self.create_element("orientation") |
---|
1150 | written = self.write_node(ori, "roll", item.orientation.x, |
---|
1151 | {"unit": item.orientation_unit}) |
---|
1152 | written = written | self.write_node(ori, "pitch", |
---|
1153 | item.orientation.y, |
---|
1154 | {"unit": item.orientation_unit}) |
---|
1155 | written = written | self.write_node(ori, "yaw", |
---|
1156 | item.orientation.z, |
---|
1157 | {"unit": item.orientation_unit}) |
---|
1158 | if written == True: |
---|
1159 | self.append(ori, det) |
---|
1160 | |
---|
1161 | center = self.create_element("beam_center") |
---|
1162 | written = self.write_node(center, "x", item.beam_center.x, |
---|
1163 | {"unit": item.beam_center_unit}) |
---|
1164 | written = written | self.write_node(center, "y", |
---|
1165 | item.beam_center.y, |
---|
1166 | {"unit": item.beam_center_unit}) |
---|
1167 | written = written | self.write_node(center, "z", |
---|
1168 | item.beam_center.z, |
---|
1169 | {"unit": item.beam_center_unit}) |
---|
1170 | if written == True: |
---|
1171 | self.append(center, det) |
---|
1172 | |
---|
1173 | pix = self.create_element("pixel_size") |
---|
1174 | written = self.write_node(pix, "x", item.pixel_size.x, |
---|
1175 | {"unit": item.pixel_size_unit}) |
---|
1176 | written = written | self.write_node(pix, "y", item.pixel_size.y, |
---|
1177 | {"unit": item.pixel_size_unit}) |
---|
1178 | written = written | self.write_node(pix, "z", item.pixel_size.z, |
---|
1179 | {"unit": item.pixel_size_unit}) |
---|
1180 | if written == True: |
---|
1181 | self.append(pix, det) |
---|
1182 | self.write_node(det, "slit_length", item.slit_length, |
---|
1183 | {"unit": item.slit_length_unit}) |
---|
1184 | |
---|
1185 | |
---|
1186 | def _write_process_notes(self, datainfo, entry_node): |
---|
1187 | """ |
---|
1188 | Writes the process notes to the XML file |
---|
1189 | |
---|
1190 | :param datainfo: The Data1D object the information is coming from |
---|
1191 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1192 | |
---|
1193 | """ |
---|
1194 | for item in datainfo.process: |
---|
1195 | node = self.create_element("SASprocess") |
---|
1196 | self.append(node, entry_node) |
---|
1197 | self.write_node(node, "name", item.name) |
---|
1198 | self.write_node(node, "date", item.date) |
---|
1199 | self.write_node(node, "description", item.description) |
---|
1200 | for term in item.term: |
---|
1201 | if isinstance(term, list): |
---|
1202 | value = term['value'] |
---|
1203 | del term['value'] |
---|
1204 | elif isinstance(term, dict): |
---|
1205 | value = term.get("value") |
---|
1206 | del term['value'] |
---|
1207 | else: |
---|
1208 | value = term |
---|
1209 | self.write_node(node, "term", value, term) |
---|
1210 | for note in item.notes: |
---|
1211 | self.write_node(node, "SASprocessnote", note) |
---|
1212 | if len(item.notes) == 0: |
---|
1213 | self.write_node(node, "SASprocessnote", "") |
---|
1214 | |
---|
1215 | def _write_notes(self, datainfo, entry_node): |
---|
1216 | """ |
---|
1217 | Writes the notes to the XML file and creates an empty note if none |
---|
1218 | exist |
---|
1219 | |
---|
1220 | :param datainfo: The Data1D object the information is coming from |
---|
1221 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1222 | |
---|
1223 | """ |
---|
1224 | if len(datainfo.notes) == 0: |
---|
1225 | node = self.create_element("SASnote") |
---|
1226 | self.append(node, entry_node) |
---|
1227 | else: |
---|
1228 | for item in datainfo.notes: |
---|
1229 | node = self.create_element("SASnote") |
---|
1230 | self.write_text(node, item) |
---|
1231 | self.append(node, entry_node) |
---|
1232 | |
---|
1233 | def _check_origin(self, entry_node, doc): |
---|
1234 | """ |
---|
1235 | Return the document, and the SASentry node associated with |
---|
1236 | the data we just wrote. |
---|
1237 | If the calling function was not the cansas reader, return a minidom |
---|
1238 | object rather than an lxml object. |
---|
1239 | |
---|
1240 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1241 | :param doc: entire xml tree |
---|
1242 | """ |
---|
1243 | if not self.frm: |
---|
1244 | self.frm = inspect.stack()[1] |
---|
1245 | mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "") |
---|
1246 | mod_name = mod_name.replace(".py", "") |
---|
1247 | mod = mod_name.split("sas/") |
---|
1248 | mod_name = mod[1] |
---|
1249 | if mod_name != "sascalc/dataloader/readers/cansas_reader": |
---|
1250 | string = self.to_string(doc, pretty_print=False) |
---|
1251 | doc = parseString(string) |
---|
1252 | node_name = entry_node.tag |
---|
1253 | node_list = doc.getElementsByTagName(node_name) |
---|
1254 | entry_node = node_list.item(0) |
---|
1255 | return doc, entry_node |
---|
1256 | |
---|
1257 | # DO NOT REMOVE - used in saving and loading panel states. |
---|
1258 | def _store_float(self, location, node, variable, storage, optional=True): |
---|
1259 | """ |
---|
1260 | Get the content of a xpath location and store |
---|
1261 | the result. Check that the units are compatible |
---|
1262 | with the destination. The value is expected to |
---|
1263 | be a float. |
---|
1264 | |
---|
1265 | The xpath location might or might not exist. |
---|
1266 | If it does not exist, nothing is done |
---|
1267 | |
---|
1268 | :param location: xpath location to fetch |
---|
1269 | :param node: node to read the data from |
---|
1270 | :param variable: name of the data member to store it in [string] |
---|
1271 | :param storage: data object that has the 'variable' data member |
---|
1272 | :param optional: if True, no exception will be raised |
---|
1273 | if unit conversion can't be done |
---|
1274 | |
---|
1275 | :raise ValueError: raised when the units are not recognized |
---|
1276 | """ |
---|
1277 | entry = get_content(location, node) |
---|
1278 | try: |
---|
1279 | value = float(entry.text) |
---|
1280 | except: |
---|
1281 | value = None |
---|
1282 | |
---|
1283 | if value is not None: |
---|
1284 | # If the entry has units, check to see that they are |
---|
1285 | # compatible with what we currently have in the data object |
---|
1286 | units = entry.get('unit') |
---|
1287 | if units is not None: |
---|
1288 | toks = variable.split('.') |
---|
1289 | local_unit = None |
---|
1290 | exec "local_unit = storage.%s_unit" % toks[0] |
---|
1291 | if local_unit is not None and units.lower() != local_unit.lower(): |
---|
1292 | if HAS_CONVERTER == True: |
---|
1293 | try: |
---|
1294 | conv = Converter(units) |
---|
1295 | exec "storage.%s = %g" % \ |
---|
1296 | (variable, conv(value, units=local_unit)) |
---|
1297 | except: |
---|
1298 | _, exc_value, _ = sys.exc_info() |
---|
1299 | err_mess = "CanSAS reader: could not convert" |
---|
1300 | err_mess += " %s unit [%s]; expecting [%s]\n %s" \ |
---|
1301 | % (variable, units, local_unit, exc_value) |
---|
1302 | self.errors.add(err_mess) |
---|
1303 | if optional: |
---|
1304 | logger.info(err_mess) |
---|
1305 | else: |
---|
1306 | raise ValueError, err_mess |
---|
1307 | else: |
---|
1308 | err_mess = "CanSAS reader: unrecognized %s unit [%s];"\ |
---|
1309 | % (variable, units) |
---|
1310 | err_mess += " expecting [%s]" % local_unit |
---|
1311 | self.errors.add(err_mess) |
---|
1312 | if optional: |
---|
1313 | logger.info(err_mess) |
---|
1314 | else: |
---|
1315 | raise ValueError, err_mess |
---|
1316 | else: |
---|
1317 | exec "storage.%s = value" % variable |
---|
1318 | else: |
---|
1319 | exec "storage.%s = value" % variable |
---|
1320 | |
---|
1321 | # DO NOT REMOVE - used in saving and loading panel states. |
---|
1322 | def _store_content(self, location, node, variable, storage): |
---|
1323 | """ |
---|
1324 | Get the content of a xpath location and store |
---|
1325 | the result. The value is treated as a string. |
---|
1326 | |
---|
1327 | The xpath location might or might not exist. |
---|
1328 | If it does not exist, nothing is done |
---|
1329 | |
---|
1330 | :param location: xpath location to fetch |
---|
1331 | :param node: node to read the data from |
---|
1332 | :param variable: name of the data member to store it in [string] |
---|
1333 | :param storage: data object that has the 'variable' data member |
---|
1334 | |
---|
1335 | :return: return a list of errors |
---|
1336 | """ |
---|
1337 | entry = get_content(location, node) |
---|
1338 | if entry is not None and entry.text is not None: |
---|
1339 | exec "storage.%s = entry.text.strip()" % variable |
---|
1340 | |
---|
1341 | # DO NOT REMOVE Called by outside packages: |
---|
1342 | # sas.sasgui.perspectives.invariant.invariant_state |
---|
1343 | # sas.sasgui.perspectives.fitting.pagestate |
---|
1344 | def get_content(location, node): |
---|
1345 | """ |
---|
1346 | Get the first instance of the content of a xpath location. |
---|
1347 | |
---|
1348 | :param location: xpath location |
---|
1349 | :param node: node to start at |
---|
1350 | |
---|
1351 | :return: Element, or None |
---|
1352 | """ |
---|
1353 | nodes = node.xpath(location, |
---|
1354 | namespaces={'ns': CANSAS_NS.get("1.0").get("ns")}) |
---|
1355 | if len(nodes) > 0: |
---|
1356 | return nodes[0] |
---|
1357 | else: |
---|
1358 | return None |
---|
1359 | |
---|
1360 | # DO NOT REMOVE Called by outside packages: |
---|
1361 | # sas.sasgui.perspectives.fitting.pagestate |
---|
1362 | def write_node(doc, parent, name, value, attr=None): |
---|
1363 | """ |
---|
1364 | :param doc: document DOM |
---|
1365 | :param parent: parent node |
---|
1366 | :param name: tag of the element |
---|
1367 | :param value: value of the child text node |
---|
1368 | :param attr: attribute dictionary |
---|
1369 | |
---|
1370 | :return: True if something was appended, otherwise False |
---|
1371 | """ |
---|
1372 | if attr is None: |
---|
1373 | attr = {} |
---|
1374 | if value is not None: |
---|
1375 | node = doc.createElement(name) |
---|
1376 | node.appendChild(doc.createTextNode(str(value))) |
---|
1377 | for item in attr: |
---|
1378 | node.setAttribute(item, attr[item]) |
---|
1379 | parent.appendChild(node) |
---|
1380 | return True |
---|
1381 | return False |
---|