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