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