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