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