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