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 |
---|
17 | import os |
---|
18 | import sys |
---|
19 | import datetime |
---|
20 | import inspect |
---|
21 | # For saving individual sections of data |
---|
22 | from sans.dataloader.data_info import Data1D |
---|
23 | from sans.dataloader.data_info import Collimation |
---|
24 | from sans.dataloader.data_info import TransmissionSpectrum |
---|
25 | from sans.dataloader.data_info import Detector |
---|
26 | from sans.dataloader.data_info import Process |
---|
27 | from sans.dataloader.data_info import Aperture |
---|
28 | # Both imports used. Do not remove either. |
---|
29 | from xml.dom.minidom import parseString |
---|
30 | import sans.dataloader.readers.xml_reader as xml_reader |
---|
31 | from sans.dataloader.readers.xml_reader import XMLreader |
---|
32 | from sans.dataloader.readers.cansas_constants import CansasConstants |
---|
33 | |
---|
34 | _ZERO = 1e-16 |
---|
35 | PREPROCESS = "xmlpreprocess" |
---|
36 | ENCODING = "encoding" |
---|
37 | HAS_CONVERTER = True |
---|
38 | try: |
---|
39 | from sans.data_util.nxsunit import Converter |
---|
40 | except: |
---|
41 | HAS_CONVERTER = False |
---|
42 | |
---|
43 | CONSTANTS = CansasConstants() |
---|
44 | CANSAS_FORMAT = CONSTANTS.format |
---|
45 | CANSAS_NS = CONSTANTS.names |
---|
46 | ALLOW_ALL = True |
---|
47 | |
---|
48 | |
---|
49 | # minidom used in functions called by outside classes |
---|
50 | import xml.dom.minidom |
---|
51 | # DO NOT REMOVE |
---|
52 | # Called by outside packages: |
---|
53 | # sans.perspectives.invariant.invariant_state |
---|
54 | # sans.perspectives.fitting.pagestate |
---|
55 | def get_content(location, node): |
---|
56 | """ |
---|
57 | Get the first instance of the content of a xpath location. |
---|
58 | |
---|
59 | :param location: xpath location |
---|
60 | :param node: node to start at |
---|
61 | |
---|
62 | :return: Element, or None |
---|
63 | """ |
---|
64 | nodes = node.xpath(location, |
---|
65 | namespaces={'ns': CANSAS_NS.get("1.0").get("ns")}) |
---|
66 | |
---|
67 | if len(nodes) > 0: |
---|
68 | return nodes[0] |
---|
69 | else: |
---|
70 | return None |
---|
71 | |
---|
72 | |
---|
73 | # DO NOT REMOVE |
---|
74 | # Called by outside packages: |
---|
75 | # sans.perspectives.fitting.pagestate |
---|
76 | def write_node(doc, parent, name, value, attr={}): |
---|
77 | """ |
---|
78 | :param doc: document DOM |
---|
79 | :param parent: parent node |
---|
80 | :param name: tag of the element |
---|
81 | :param value: value of the child text node |
---|
82 | :param attr: attribute dictionary |
---|
83 | |
---|
84 | :return: True if something was appended, otherwise False |
---|
85 | """ |
---|
86 | if value is not None: |
---|
87 | node = doc.createElement(name) |
---|
88 | node.appendChild(doc.createTextNode(str(value))) |
---|
89 | for item in attr: |
---|
90 | node.setAttribute(item, attr[item]) |
---|
91 | parent.appendChild(node) |
---|
92 | return True |
---|
93 | return False |
---|
94 | |
---|
95 | |
---|
96 | class Reader(XMLreader): |
---|
97 | """ |
---|
98 | Class to load cansas 1D XML files |
---|
99 | |
---|
100 | :Dependencies: |
---|
101 | The CanSAS reader requires PyXML 0.8.4 or later. |
---|
102 | """ |
---|
103 | ##CanSAS version - defaults to version 1.0 |
---|
104 | cansas_version = "1.0" |
---|
105 | |
---|
106 | logging = [] |
---|
107 | errors = [] |
---|
108 | |
---|
109 | type_name = "canSAS" |
---|
110 | ## Wildcards |
---|
111 | type = ["XML files (*.xml)|*.xml", "SasView Save Files (*.svs)|*.svs"] |
---|
112 | ## List of allowed extensions |
---|
113 | ext = ['.xml', '.XML', '.svs', '.SVS'] |
---|
114 | |
---|
115 | ## Flag to bypass extension check |
---|
116 | allow_all = True |
---|
117 | |
---|
118 | def __init__(self): |
---|
119 | ## List of errors |
---|
120 | self.errors = [] |
---|
121 | |
---|
122 | def is_cansas(self, ext="xml"): |
---|
123 | """ |
---|
124 | Checks to see if the xml file is a CanSAS file |
---|
125 | """ |
---|
126 | if self.validate_xml(): |
---|
127 | name = "{http://www.w3.org/2001/XMLSchema-instance}schemaLocation" |
---|
128 | value = self.xmlroot.get(name) |
---|
129 | if CANSAS_NS.get(self.cansas_version).get("ns") == \ |
---|
130 | value.rsplit(" ")[0]: |
---|
131 | return True |
---|
132 | if ext == "svs": |
---|
133 | return True |
---|
134 | return False |
---|
135 | |
---|
136 | def read(self, xml): |
---|
137 | """ |
---|
138 | Validate and read in an xml file in the canSAS format. |
---|
139 | |
---|
140 | :param xml: A canSAS file path in proper XML format |
---|
141 | """ |
---|
142 | # X - Q value; Y - Intensity (Abs) |
---|
143 | x_vals = numpy.empty(0) |
---|
144 | y_vals = numpy.empty(0) |
---|
145 | dx_vals = numpy.empty(0) |
---|
146 | dy_vals = numpy.empty(0) |
---|
147 | dxl = numpy.empty(0) |
---|
148 | dxw = numpy.empty(0) |
---|
149 | |
---|
150 | # output - Final list of Data1D objects |
---|
151 | output = [] |
---|
152 | # ns - Namespace hierarchy for current xml object |
---|
153 | ns_list = [] |
---|
154 | |
---|
155 | # Check that the file exists |
---|
156 | if os.path.isfile(xml): |
---|
157 | basename = os.path.basename(xml) |
---|
158 | _, extension = os.path.splitext(basename) |
---|
159 | # If the file type is not allowed, return nothing |
---|
160 | if extension in self.ext or self.allow_all: |
---|
161 | # Get the file location of |
---|
162 | base_name = xml_reader.__file__ |
---|
163 | base_name = base_name.replace("\\","/") |
---|
164 | base = base_name.split("/sans/")[0] |
---|
165 | |
---|
166 | # Load in xml file and get the cansas version from the header |
---|
167 | self.set_xml_file(xml) |
---|
168 | root = self.xmlroot |
---|
169 | if root is None: |
---|
170 | root = {} |
---|
171 | self.cansas_version = root.get("version", "1.0") |
---|
172 | |
---|
173 | # Generic values for the cansas file based on the version |
---|
174 | cansas_defaults = CANSAS_NS.get(self.cansas_version, "1.0") |
---|
175 | schema_path = "{0}/sans/dataloader/readers/schema/{1}".format\ |
---|
176 | (base, cansas_defaults.get("schema")).replace("\\", "/") |
---|
177 | |
---|
178 | # Link a schema to the XML file. |
---|
179 | self.set_schema(schema_path) |
---|
180 | |
---|
181 | # Try to load the file, but raise an error if unable to. |
---|
182 | # Check the file matches the XML schema |
---|
183 | try: |
---|
184 | if self.is_cansas(extension): |
---|
185 | # Get each SASentry from XML file and add it to a list. |
---|
186 | entry_list = root.xpath('/ns:SASroot/ns:SASentry', |
---|
187 | namespaces={'ns': cansas_defaults.get("ns")}) |
---|
188 | ns_list.append("SASentry") |
---|
189 | |
---|
190 | # If multiple files, modify the name for each is unique |
---|
191 | multiple_files = len(entry_list) - 1 |
---|
192 | increment = 0 |
---|
193 | name = basename |
---|
194 | # Parse each SASentry item |
---|
195 | for entry in entry_list: |
---|
196 | # Define a new Data1D object with zeroes for |
---|
197 | # x_vals and y_vals |
---|
198 | data1d = Data1D(x_vals, y_vals, dx_vals, dy_vals) |
---|
199 | data1d.dxl = dxl |
---|
200 | data1d.dxw = dxw |
---|
201 | |
---|
202 | # If more than one SASentry, increment each in order |
---|
203 | if multiple_files: |
---|
204 | name += "_{0}".format(increment) |
---|
205 | increment += 1 |
---|
206 | |
---|
207 | # Set the Data1D name and then parse the entry. |
---|
208 | # The entry is appended to a list of entry values |
---|
209 | data1d.filename = name |
---|
210 | data1d.meta_data["loader"] = "CanSAS 1D" |
---|
211 | |
---|
212 | # Get all preprocessing events and encoding |
---|
213 | self.set_processing_instructions() |
---|
214 | data1d.meta_data[PREPROCESS] = \ |
---|
215 | self.processing_instructions |
---|
216 | |
---|
217 | # Parse the XML file |
---|
218 | return_value, extras = \ |
---|
219 | self._parse_entry(entry, ns_list, data1d) |
---|
220 | del extras[:] |
---|
221 | |
---|
222 | # Final cleanup |
---|
223 | # Remove empty nodes, verify array sizes are correct |
---|
224 | for error in self.errors: |
---|
225 | return_value.errors.append(error) |
---|
226 | del self.errors[:] |
---|
227 | numpy.trim_zeros(return_value.x) |
---|
228 | numpy.trim_zeros(return_value.y) |
---|
229 | numpy.trim_zeros(return_value.dy) |
---|
230 | size_dx = return_value.dx.size |
---|
231 | size_dxl = return_value.dxl.size |
---|
232 | size_dxw = return_value.dxw.size |
---|
233 | if size_dxl == 0 and size_dxw == 0: |
---|
234 | return_value.dxl = None |
---|
235 | return_value.dxw = None |
---|
236 | numpy.trim_zeros(return_value.dx) |
---|
237 | elif size_dx == 0: |
---|
238 | return_value.dx = None |
---|
239 | size_dx = size_dxl |
---|
240 | numpy.trim_zeros(return_value.dxl) |
---|
241 | numpy.trim_zeros(return_value.dxw) |
---|
242 | output.append(return_value) |
---|
243 | else: |
---|
244 | value = self.find_invalid_xml() |
---|
245 | output.append("Invalid XML at: {0}".format(value)) |
---|
246 | except: |
---|
247 | # If the file does not match the schema, raise this error |
---|
248 | raise RuntimeError, "%s cannot be read" % xml |
---|
249 | return output |
---|
250 | # Return a list of parsed entries that dataloader can manage |
---|
251 | return None |
---|
252 | |
---|
253 | def _create_unique_key(self, dictionary, name, numb = 0): |
---|
254 | """ |
---|
255 | Create a unique key value for any dictionary to prevent overwriting |
---|
256 | Recurses until a unique key value is found. |
---|
257 | |
---|
258 | :param dictionary: A dictionary with any number of entries |
---|
259 | :param name: The index of the item to be added to dictionary |
---|
260 | :param numb: The number to be appended to the name, starts at 0 |
---|
261 | """ |
---|
262 | if dictionary.get(name) is not None: |
---|
263 | numb += 1 |
---|
264 | name = name.split("_")[0] |
---|
265 | name += "_{0}".format(numb) |
---|
266 | name = self._create_unique_key(dictionary, name, numb) |
---|
267 | return name |
---|
268 | |
---|
269 | |
---|
270 | def _unit_conversion(self, new_current_level, attr, data1d, \ |
---|
271 | tagname, node_value, optional = True): |
---|
272 | """ |
---|
273 | A unit converter method used to convert the data included in the file |
---|
274 | to the default units listed in data_info |
---|
275 | |
---|
276 | :param new_current_level: cansas_constants level as returned by |
---|
277 | iterate_namespace |
---|
278 | :param attr: The attributes of the node |
---|
279 | :param data1d: Where the values will be saved |
---|
280 | :param node_value: The value of the current dom node |
---|
281 | :param optional: Boolean that says if the units are required |
---|
282 | """ |
---|
283 | value_unit = '' |
---|
284 | if 'unit' in attr and new_current_level.get('unit') is not None: |
---|
285 | try: |
---|
286 | if isinstance(node_value, float) is False: |
---|
287 | exec("node_value = float({0})".format(node_value)) |
---|
288 | default_unit = None |
---|
289 | unitname = new_current_level.get("unit") |
---|
290 | exec "default_unit = data1d.{0}".format(unitname) |
---|
291 | local_unit = attr['unit'] |
---|
292 | if local_unit.lower() != default_unit.lower() and \ |
---|
293 | local_unit is not None and local_unit.lower() != "none" and\ |
---|
294 | default_unit is not None: |
---|
295 | if HAS_CONVERTER == True: |
---|
296 | try: |
---|
297 | ## Check local units - bad units raise KeyError |
---|
298 | Converter(local_unit) |
---|
299 | data_conv_q = Converter(attr['unit']) |
---|
300 | value_unit = default_unit |
---|
301 | exec "node_value = data_conv_q(node_value, units=data1d.{0})".format(unitname) |
---|
302 | except KeyError as e: |
---|
303 | err_msg = "CanSAS reader: could not convert " |
---|
304 | err_msg += "{0} unit {1}; ".format(tagname, local_unit) |
---|
305 | intermediate = "err_msg += \"expecting [{1}] {2}\".format(data1d.{0}, sys.exc_info()[1])".format(unitname, "{0}", "{1}") |
---|
306 | exec intermediate |
---|
307 | self.errors.append(err_msg) |
---|
308 | raise ValueError(err_msg) |
---|
309 | return |
---|
310 | except: |
---|
311 | err_msg = \ |
---|
312 | "CanSAS reader: could not convert the units" |
---|
313 | self.errors.append(err_msg) |
---|
314 | return |
---|
315 | else: |
---|
316 | value_unit = local_unit |
---|
317 | err_msg = "CanSAS reader: unrecognized %s unit [%s];"\ |
---|
318 | % (node_value, default_unit) |
---|
319 | err_msg += " expecting [%s]" % local_unit |
---|
320 | self.errors.append(err_msg) |
---|
321 | raise ValueError, err_msg |
---|
322 | return |
---|
323 | else: |
---|
324 | value_unit = local_unit |
---|
325 | except: |
---|
326 | err_msg = "CanSAS reader: could not convert " |
---|
327 | err_msg += "Q unit [%s]; " % attr['unit'], |
---|
328 | exec "err_msg += \"expecting [%s]\n %s\" % (data1d.{0}, sys.exc_info()[1])".format(unitname) |
---|
329 | self.errors.append(err_msg) |
---|
330 | raise ValueError, err_msg |
---|
331 | return |
---|
332 | elif 'unit' in attr: |
---|
333 | value_unit = attr['unit'] |
---|
334 | node_value = "float({0})".format(node_value) |
---|
335 | return node_value, value_unit |
---|
336 | |
---|
337 | def _parse_entry(self, dom, names=["SASentry"], data1d=None, extras=[]): |
---|
338 | """ |
---|
339 | Parse a SASEntry - new recursive method for parsing the dom of |
---|
340 | the CanSAS data format. This will allow multiple data files |
---|
341 | and extra nodes to be read in simultaneously. |
---|
342 | |
---|
343 | :param dom: dom object with a namespace base of names |
---|
344 | :param names: A list of element names that lead up to the dom object |
---|
345 | :param data1d: The data1d object that will be modified |
---|
346 | :param extras: Any values that should go into meta_data when data1d |
---|
347 | is not a Data1D object |
---|
348 | """ |
---|
349 | |
---|
350 | # A portion of every namespace entry |
---|
351 | if data1d == None: |
---|
352 | x_vals = numpy.empty(0) |
---|
353 | y_vals = numpy.empty(0) |
---|
354 | dx_vals = numpy.empty(0) |
---|
355 | dy_vals = numpy.empty(0) |
---|
356 | dxl = numpy.empty(0) |
---|
357 | dxw = numpy.empty(0) |
---|
358 | data1d = Data1D(x_vals, y_vals, dx_vals, dy_vals) |
---|
359 | data1d.dxl = dxl |
---|
360 | data1d.dxw = dxw |
---|
361 | |
---|
362 | base_ns = "{0}{1}{2}".format("{", \ |
---|
363 | CANSAS_NS.get(self.cansas_version).get("ns"), "}") |
---|
364 | unit = '' |
---|
365 | tagname = '' |
---|
366 | tagname_original = '' |
---|
367 | |
---|
368 | # Go through each child in the parent element |
---|
369 | for node in dom: |
---|
370 | try: |
---|
371 | # Get the element name and set the current names level |
---|
372 | tagname = node.tag.replace(base_ns, "") |
---|
373 | tagname_original = tagname |
---|
374 | if tagname == "fitting_plug_in" or tagname == "pr_inversion" or\ |
---|
375 | tagname == "invariant": |
---|
376 | continue |
---|
377 | names.append(tagname) |
---|
378 | attr = node.attrib |
---|
379 | children = node.getchildren() |
---|
380 | if len(children) == 0: |
---|
381 | children = None |
---|
382 | save_data1d = data1d |
---|
383 | |
---|
384 | # Look for special cases |
---|
385 | if tagname == "SASdetector": |
---|
386 | data1d = Detector() |
---|
387 | elif tagname == "SAScollimation": |
---|
388 | data1d = Collimation() |
---|
389 | elif tagname == "SAStransmission_spectrum": |
---|
390 | data1d = TransmissionSpectrum() |
---|
391 | elif tagname == "SASprocess": |
---|
392 | data1d = Process() |
---|
393 | for child in node: |
---|
394 | if child.tag.replace(base_ns, "") == "term": |
---|
395 | term_attr = {} |
---|
396 | for attr in child.keys(): |
---|
397 | term_attr[attr] = \ |
---|
398 | ' '.join(child.get(attr).split()) |
---|
399 | if child.text is not None: |
---|
400 | term_attr['value'] = \ |
---|
401 | ' '.join(child.text.split()) |
---|
402 | data1d.term.append(term_attr) |
---|
403 | elif tagname == "aperture": |
---|
404 | data1d = Aperture() |
---|
405 | if tagname == "Idata" and children is not None: |
---|
406 | dql = 0 |
---|
407 | dqw = 0 |
---|
408 | for child in children: |
---|
409 | tag = child.tag.replace(base_ns, "") |
---|
410 | if tag == "dQl": |
---|
411 | dql = 1 |
---|
412 | if tag == "dQw": |
---|
413 | dqw = 1 |
---|
414 | if dqw == 1 and dql == 0: |
---|
415 | data1d.dxl = numpy.append(data1d.dxl, 0.0) |
---|
416 | elif dql == 1 and dqw == 0: |
---|
417 | data1d.dxw = numpy.append(data1d.dxw, 0.0) |
---|
418 | |
---|
419 | # Get where to store content |
---|
420 | cs_values = CONSTANTS.iterate_namespace(names) |
---|
421 | # If the element is a child element, recurse |
---|
422 | if children is not None: |
---|
423 | # Returned value is new Data1D object with all previous and |
---|
424 | # new values in it. |
---|
425 | data1d, extras = self._parse_entry(node, |
---|
426 | names, data1d, extras) |
---|
427 | |
---|
428 | #Get the information from the node |
---|
429 | node_value = node.text |
---|
430 | if node_value == "": |
---|
431 | node_value = None |
---|
432 | if node_value is not None: |
---|
433 | node_value = ' '.join(node_value.split()) |
---|
434 | |
---|
435 | # If the value is a float, compile with units. |
---|
436 | if cs_values.ns_datatype == "float": |
---|
437 | # If an empty value is given, store as zero. |
---|
438 | if node_value is None or node_value.isspace() \ |
---|
439 | or node_value.lower() == "nan": |
---|
440 | node_value = "0.0" |
---|
441 | node_value, unit = self._unit_conversion(\ |
---|
442 | cs_values.current_level, attr, data1d, \ |
---|
443 | tagname, node_value, cs_values.ns_optional) |
---|
444 | # If the value is a timestamp, convert to a datetime object |
---|
445 | elif cs_values.ns_datatype == "timestamp": |
---|
446 | if node_value is None or node_value.isspace(): |
---|
447 | pass |
---|
448 | else: |
---|
449 | try: |
---|
450 | node_value = \ |
---|
451 | datetime.datetime.fromtimestamp(node_value) |
---|
452 | except ValueError: |
---|
453 | node_value = None |
---|
454 | # If appending to a dictionary (meta_data | run_name) |
---|
455 | # make sure the key is unique |
---|
456 | if cs_values.ns_variable == "{0}.meta_data[\"{2}\"] = \"{1}\"": |
---|
457 | # If we are within a Process, Detector, Collimation or |
---|
458 | # Aperture instance, pull out old data1d |
---|
459 | tagname = self._create_unique_key(data1d.meta_data, \ |
---|
460 | tagname, 0) |
---|
461 | if isinstance(data1d, Data1D) == False: |
---|
462 | store_me = cs_values.ns_variable.format("data1d", \ |
---|
463 | node_value, tagname) |
---|
464 | extras.append(store_me) |
---|
465 | cs_values.ns_variable = None |
---|
466 | if cs_values.ns_variable == "{0}.run_name[\"{2}\"] = \"{1}\"": |
---|
467 | tagname = self._create_unique_key(data1d.run_name, \ |
---|
468 | tagname, 0) |
---|
469 | |
---|
470 | # Check for Data1D object and any extra commands to save |
---|
471 | if isinstance(data1d, Data1D): |
---|
472 | for item in extras: |
---|
473 | exec item |
---|
474 | # Don't bother saving empty information unless it is a float |
---|
475 | if cs_values.ns_variable is not None and \ |
---|
476 | node_value is not None and \ |
---|
477 | node_value.isspace() == False: |
---|
478 | # Format a string and then execute it. |
---|
479 | store_me = cs_values.ns_variable.format("data1d", \ |
---|
480 | node_value, tagname) |
---|
481 | exec store_me |
---|
482 | # Get attributes and process them |
---|
483 | if attr is not None: |
---|
484 | for key in node.keys(): |
---|
485 | try: |
---|
486 | cansas_attrib = \ |
---|
487 | cs_values.current_level.get("attributes").get(key) |
---|
488 | attrib_variable = cansas_attrib.get("variable") |
---|
489 | if key == 'unit' and unit != '': |
---|
490 | attrib_value = unit |
---|
491 | else: |
---|
492 | attrib_value = node.attrib[key] |
---|
493 | store_attr = attrib_variable.format("data1d", \ |
---|
494 | attrib_value, key) |
---|
495 | exec store_attr |
---|
496 | except AttributeError as e: |
---|
497 | pass |
---|
498 | |
---|
499 | except TypeError as e: |
---|
500 | pass |
---|
501 | except Exception as e: |
---|
502 | exc_type, exc_obj, exc_tb = sys.exc_info() |
---|
503 | fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] |
---|
504 | print(e, exc_type, fname, exc_tb.tb_lineno, tagname, exc_obj) |
---|
505 | finally: |
---|
506 | # Save special cases in original data1d object |
---|
507 | # then restore the data1d |
---|
508 | if tagname_original == "SASdetector": |
---|
509 | save_data1d.detector.append(data1d) |
---|
510 | elif tagname_original == "SAScollimation": |
---|
511 | save_data1d.collimation.append(data1d) |
---|
512 | elif tagname == "SAStransmission_spectrum": |
---|
513 | save_data1d.trans_spectrum.append(data1d) |
---|
514 | elif tagname_original == "SASprocess": |
---|
515 | save_data1d.process.append(data1d) |
---|
516 | elif tagname_original == "aperture": |
---|
517 | save_data1d.aperture.append(data1d) |
---|
518 | else: |
---|
519 | save_data1d = data1d |
---|
520 | if tagname_original == "fitting_plug_in" or \ |
---|
521 | tagname_original == "invariant" or \ |
---|
522 | tagname_original == "pr_inversion": |
---|
523 | pass |
---|
524 | else: |
---|
525 | data1d = save_data1d |
---|
526 | # Remove tagname from names to restore original base |
---|
527 | names.remove(tagname_original) |
---|
528 | return data1d, extras |
---|
529 | |
---|
530 | |
---|
531 | def _to_xml_doc(self, datainfo): |
---|
532 | """ |
---|
533 | Create an XML document to contain the content of a Data1D |
---|
534 | |
---|
535 | :param datainfo: Data1D object |
---|
536 | """ |
---|
537 | |
---|
538 | if not issubclass(datainfo.__class__, Data1D): |
---|
539 | raise RuntimeError, "The cansas writer expects a Data1D instance" |
---|
540 | |
---|
541 | # Get PIs and create root element |
---|
542 | pis = self.return_processing_instructions() |
---|
543 | if len(pis) > 0: |
---|
544 | pi_tree = self.create_tree(pis[0]) |
---|
545 | i = 1 |
---|
546 | for i in range(1,len(pis) - 1): |
---|
547 | pi_tree = self.append(pis[i], pi_tree) |
---|
548 | pi_string = self.to_string(pi_tree) |
---|
549 | else: |
---|
550 | pi_string = "" |
---|
551 | |
---|
552 | # Define namespaces and create SASroot object |
---|
553 | xsi = "http://www.w3.org/2001/XMLSchema-instance" |
---|
554 | version = self.cansas_version |
---|
555 | ns = CANSAS_NS.get(version).get("ns") |
---|
556 | if version == "1.1": |
---|
557 | url = "http://www.cansas.org/formats/1.1/" |
---|
558 | else: |
---|
559 | url = "http://svn.smallangles.net/svn/canSAS/1dwg/trunk/" |
---|
560 | schema_location = "{0} {1}cansas1d.xsd".format(ns, url) |
---|
561 | attrib = {"{" + xsi + "}schemaLocation" : schema_location, |
---|
562 | "version" : version} |
---|
563 | nsmap = {'xsi' : xsi, None: ns} |
---|
564 | |
---|
565 | main_node = self.create_element("{" + ns + "}SASroot", \ |
---|
566 | attrib = attrib, \ |
---|
567 | nsmap = nsmap) |
---|
568 | |
---|
569 | # Create ElementTree, append SASroot and apply processing instructions |
---|
570 | base_string = pi_string + self.to_string(main_node) |
---|
571 | base_element = self.create_element_from_string(base_string) |
---|
572 | doc = self.create_tree(base_element) |
---|
573 | |
---|
574 | # Create SASentry Element |
---|
575 | entry_node = self.create_element("SASentry") |
---|
576 | root = doc.getroot() |
---|
577 | root.append(entry_node) |
---|
578 | |
---|
579 | # Add Title to SASentry |
---|
580 | self.write_node(entry_node, "Title", datainfo.title) |
---|
581 | |
---|
582 | # Add Run to SASentry |
---|
583 | if datainfo.run == None or datainfo.run == []: |
---|
584 | RUN_NAME_DEFAULT = "None" |
---|
585 | datainfo.run.append(RUN_NAME_DEFAULT) |
---|
586 | datainfo.run_name[RUN_NAME_DEFAULT] = RUN_NAME_DEFAULT |
---|
587 | for item in datainfo.run: |
---|
588 | runname = {} |
---|
589 | if item in datainfo.run_name and \ |
---|
590 | len(str(datainfo.run_name[item])) > 1: |
---|
591 | runname = {'name': datainfo.run_name[item]} |
---|
592 | self.write_node(entry_node, "Run", item, runname) |
---|
593 | |
---|
594 | # Data info |
---|
595 | node = self.create_element("SASdata") |
---|
596 | self.append(node, entry_node) |
---|
597 | |
---|
598 | for i in range(len(datainfo.x)): |
---|
599 | pt = self.create_element("Idata") |
---|
600 | node.append(pt) |
---|
601 | self.write_node(pt, "Q", datainfo.x[i], {'unit': datainfo.x_unit}) |
---|
602 | if len(datainfo.y) >= i: |
---|
603 | self.write_node(pt, "I", datainfo.y[i], |
---|
604 | {'unit': datainfo.y_unit}) |
---|
605 | if datainfo.dy != None and len(datainfo.dy) > i: |
---|
606 | self.write_node(pt, "Idev", datainfo.dy[i], |
---|
607 | {'unit': datainfo.y_unit}) |
---|
608 | if datainfo.dx != None and len(datainfo.dx) > i: |
---|
609 | self.write_node(pt, "Qdev", datainfo.dx[i], |
---|
610 | {'unit': datainfo.x_unit}) |
---|
611 | if datainfo.dxw != None and len(datainfo.dxw) > i: |
---|
612 | self.write_node(pt, "dQw", datainfo.dxw[i], |
---|
613 | {'unit': datainfo.x_unit}) |
---|
614 | if datainfo.dxl != None and len(datainfo.dxl) > i: |
---|
615 | self.write_node(pt, "dQl", datainfo.dxl[i], |
---|
616 | {'unit': datainfo.x_unit}) |
---|
617 | |
---|
618 | # Transmission Spectrum Info |
---|
619 | for i in range(len(datainfo.trans_spectrum)): |
---|
620 | spectrum = datainfo.trans_spectrum[i] |
---|
621 | node = self.create_element("SAStransmission_spectrum", |
---|
622 | {"name" : spectrum.name}) |
---|
623 | self.append(node, entry_node) |
---|
624 | if isinstance(spectrum.timestamp, datetime.datetime): |
---|
625 | node.setAttribute("timestamp", spectrum.timestamp) |
---|
626 | for i in range(len(spectrum.wavelength)): |
---|
627 | pt = self.create_element("Tdata") |
---|
628 | node.append(pt) |
---|
629 | self.write_node(pt, "Lambda", spectrum.wavelength[i], |
---|
630 | {'unit': spectrum.wavelength_unit}) |
---|
631 | self.write_node(pt, "T", spectrum.transmission[i], |
---|
632 | {'unit': spectrum.transmission_unit}) |
---|
633 | if spectrum.transmission_deviation != None \ |
---|
634 | and len(spectrum.transmission_deviation) >= i: |
---|
635 | self.write_node(pt, "Tdev", \ |
---|
636 | spectrum.transmission_deviation[i], \ |
---|
637 | {'unit': spectrum.transmission_deviation_unit}) |
---|
638 | |
---|
639 | # Sample info |
---|
640 | sample = self.create_element("SASsample") |
---|
641 | if datainfo.sample.name is not None: |
---|
642 | self.write_attribute(sample, |
---|
643 | "name", |
---|
644 | str(datainfo.sample.name)) |
---|
645 | self.append(sample, entry_node) |
---|
646 | self.write_node(sample, "ID", str(datainfo.sample.ID)) |
---|
647 | self.write_node(sample, "thickness", datainfo.sample.thickness, |
---|
648 | {"unit": datainfo.sample.thickness_unit}) |
---|
649 | self.write_node(sample, "transmission", datainfo.sample.transmission) |
---|
650 | self.write_node(sample, "temperature", datainfo.sample.temperature, |
---|
651 | {"unit": datainfo.sample.temperature_unit}) |
---|
652 | |
---|
653 | pos = self.create_element("position") |
---|
654 | written = self.write_node(pos, |
---|
655 | "x", |
---|
656 | datainfo.sample.position.x, |
---|
657 | {"unit": datainfo.sample.position_unit}) |
---|
658 | written = written | self.write_node(pos, |
---|
659 | "y", |
---|
660 | datainfo.sample.position.y, |
---|
661 | {"unit": datainfo.sample.position_unit}) |
---|
662 | written = written | self.write_node(pos, |
---|
663 | "z", |
---|
664 | datainfo.sample.position.z, |
---|
665 | {"unit": datainfo.sample.position_unit}) |
---|
666 | if written == True: |
---|
667 | self.append(pos, sample) |
---|
668 | |
---|
669 | ori = self.create_element("orientation") |
---|
670 | written = self.write_node(ori, "roll", |
---|
671 | datainfo.sample.orientation.x, |
---|
672 | {"unit": datainfo.sample.orientation_unit}) |
---|
673 | written = written | self.write_node(ori, "pitch", |
---|
674 | datainfo.sample.orientation.y, |
---|
675 | {"unit": datainfo.sample.orientation_unit}) |
---|
676 | written = written | self.write_node(ori, "yaw", |
---|
677 | datainfo.sample.orientation.z, |
---|
678 | {"unit": datainfo.sample.orientation_unit}) |
---|
679 | if written == True: |
---|
680 | self.append(ori, sample) |
---|
681 | |
---|
682 | for item in datainfo.sample.details: |
---|
683 | self.write_node(sample, "details", item) |
---|
684 | |
---|
685 | # Instrument info |
---|
686 | instr = self.create_element("SASinstrument") |
---|
687 | self.append(instr, entry_node) |
---|
688 | |
---|
689 | self.write_node(instr, "name", datainfo.instrument) |
---|
690 | |
---|
691 | # Source |
---|
692 | source = self.create_element("SASsource") |
---|
693 | if datainfo.source.name is not None: |
---|
694 | self.write_attribute(source, |
---|
695 | "name", |
---|
696 | str(datainfo.source.name)) |
---|
697 | self.append(source, instr) |
---|
698 | if datainfo.source.radiation == None or datainfo.source.radiation == '': |
---|
699 | datainfo.source.radiation = "neutron" |
---|
700 | self.write_node(source, "radiation", datainfo.source.radiation) |
---|
701 | |
---|
702 | size = self.create_element("beam_size") |
---|
703 | if datainfo.source.beam_size_name is not None: |
---|
704 | self.write_attribute(size, |
---|
705 | "name", |
---|
706 | str(datainfo.source.beam_size_name)) |
---|
707 | written = self.write_node(size, "x", datainfo.source.beam_size.x, |
---|
708 | {"unit": datainfo.source.beam_size_unit}) |
---|
709 | written = written | self.write_node(size, "y", |
---|
710 | datainfo.source.beam_size.y, |
---|
711 | {"unit": datainfo.source.beam_size_unit}) |
---|
712 | written = written | self.write_node(size, "z", |
---|
713 | datainfo.source.beam_size.z, |
---|
714 | {"unit": datainfo.source.beam_size_unit}) |
---|
715 | if written == True: |
---|
716 | self.append(size, source) |
---|
717 | |
---|
718 | self.write_node(source, "beam_shape", datainfo.source.beam_shape) |
---|
719 | self.write_node(source, "wavelength", |
---|
720 | datainfo.source.wavelength, |
---|
721 | {"unit": datainfo.source.wavelength_unit}) |
---|
722 | self.write_node(source, "wavelength_min", |
---|
723 | datainfo.source.wavelength_min, |
---|
724 | {"unit": datainfo.source.wavelength_min_unit}) |
---|
725 | self.write_node(source, "wavelength_max", |
---|
726 | datainfo.source.wavelength_max, |
---|
727 | {"unit": datainfo.source.wavelength_max_unit}) |
---|
728 | self.write_node(source, "wavelength_spread", |
---|
729 | datainfo.source.wavelength_spread, |
---|
730 | {"unit": datainfo.source.wavelength_spread_unit}) |
---|
731 | |
---|
732 | # Collimation |
---|
733 | if datainfo.collimation == [] or datainfo.collimation == None: |
---|
734 | coll = Collimation() |
---|
735 | datainfo.collimation.append(coll) |
---|
736 | for item in datainfo.collimation: |
---|
737 | coll = self.create_element("SAScollimation") |
---|
738 | if item.name is not None: |
---|
739 | self.write_attribute(coll, "name", str(item.name)) |
---|
740 | self.append(coll, instr) |
---|
741 | |
---|
742 | self.write_node(coll, "length", item.length, |
---|
743 | {"unit": item.length_unit}) |
---|
744 | |
---|
745 | for apert in item.aperture: |
---|
746 | ap = self.create_element("aperture") |
---|
747 | if apert.name is not None: |
---|
748 | self.write_attribute(ap, "name", str(apert.name)) |
---|
749 | if apert.type is not None: |
---|
750 | self.write_attribute(ap, "type", str(apert.type)) |
---|
751 | self.append(ap, coll) |
---|
752 | |
---|
753 | size = self.create_element("size") |
---|
754 | if apert.size_name is not None: |
---|
755 | self.write_attribute(size, |
---|
756 | "name", |
---|
757 | str(apert.size_name)) |
---|
758 | written = self.write_node(size, "x", apert.size.x, |
---|
759 | {"unit": apert.size_unit}) |
---|
760 | written = written | self.write_node(size, "y", apert.size.y, |
---|
761 | {"unit": apert.size_unit}) |
---|
762 | written = written | self.write_node(size, "z", apert.size.z, |
---|
763 | {"unit": apert.size_unit}) |
---|
764 | if written == True: |
---|
765 | self.append(size, ap) |
---|
766 | |
---|
767 | self.write_node(ap, "distance", apert.distance, |
---|
768 | {"unit": apert.distance_unit}) |
---|
769 | |
---|
770 | # Detectors |
---|
771 | if datainfo.detector == None or datainfo.detector == []: |
---|
772 | det = Detector() |
---|
773 | det.name = "" |
---|
774 | datainfo.detector.append(det) |
---|
775 | |
---|
776 | for item in datainfo.detector: |
---|
777 | det = self.create_element("SASdetector") |
---|
778 | written = self.write_node(det, "name", item.name) |
---|
779 | written = written | self.write_node(det, "SDD", item.distance, |
---|
780 | {"unit": item.distance_unit}) |
---|
781 | if written == True: |
---|
782 | self.append(det, instr) |
---|
783 | |
---|
784 | off = self.create_element("offset") |
---|
785 | written = self.write_node(off, "x", item.offset.x, |
---|
786 | {"unit": item.offset_unit}) |
---|
787 | written = written | self.write_node(off, "y", item.offset.y, |
---|
788 | {"unit": item.offset_unit}) |
---|
789 | written = written | self.write_node(off, "z", item.offset.z, |
---|
790 | {"unit": item.offset_unit}) |
---|
791 | if written == True: |
---|
792 | self.append(off, det) |
---|
793 | |
---|
794 | ori = self.create_element("orientation") |
---|
795 | written = self.write_node(ori, "roll", item.orientation.x, |
---|
796 | {"unit": item.orientation_unit}) |
---|
797 | written = written | self.write_node(ori, "pitch", |
---|
798 | item.orientation.y, |
---|
799 | {"unit": item.orientation_unit}) |
---|
800 | written = written | self.write_node(ori, "yaw", |
---|
801 | item.orientation.z, |
---|
802 | {"unit": item.orientation_unit}) |
---|
803 | if written == True: |
---|
804 | self.append(ori, det) |
---|
805 | |
---|
806 | center = self.create_element("beam_center") |
---|
807 | written = self.write_node(center, "x", item.beam_center.x, |
---|
808 | {"unit": item.beam_center_unit}) |
---|
809 | written = written | self.write_node(center, "y", |
---|
810 | item.beam_center.y, |
---|
811 | {"unit": item.beam_center_unit}) |
---|
812 | written = written | self.write_node(center, "z", |
---|
813 | item.beam_center.z, |
---|
814 | {"unit": item.beam_center_unit}) |
---|
815 | if written == True: |
---|
816 | self.append(center, det) |
---|
817 | |
---|
818 | pix = self.create_element("pixel_size") |
---|
819 | written = self.write_node(pix, "x", item.pixel_size.x, |
---|
820 | {"unit": item.pixel_size_unit}) |
---|
821 | written = written | self.write_node(pix, "y", item.pixel_size.y, |
---|
822 | {"unit": item.pixel_size_unit}) |
---|
823 | written = written | self.write_node(pix, "z", item.pixel_size.z, |
---|
824 | {"unit": item.pixel_size_unit}) |
---|
825 | written = written | self.write_node(det, "slit_length", |
---|
826 | item.slit_length, |
---|
827 | {"unit": item.slit_length_unit}) |
---|
828 | if written == True: |
---|
829 | self.append(pix, det) |
---|
830 | |
---|
831 | # Processes info |
---|
832 | for item in datainfo.process: |
---|
833 | node = self.create_element("SASprocess") |
---|
834 | self.append(node, entry_node) |
---|
835 | |
---|
836 | self.write_node(node, "name", item.name) |
---|
837 | self.write_node(node, "date", item.date) |
---|
838 | self.write_node(node, "description", item.description) |
---|
839 | for term in item.term: |
---|
840 | value = term['value'] |
---|
841 | del term['value'] |
---|
842 | self.write_node(node, "term", value, term) |
---|
843 | for note in item.notes: |
---|
844 | self.write_node(node, "SASprocessnote", note) |
---|
845 | if len(item.notes) == 0: |
---|
846 | self.write_node(node, "SASprocessnote", "") |
---|
847 | |
---|
848 | # Note info |
---|
849 | if len(datainfo.notes) == 0: |
---|
850 | node = self.create_element("SASnote") |
---|
851 | self.append(node, entry_node) |
---|
852 | else: |
---|
853 | for item in datainfo.notes: |
---|
854 | node = self.create_element("SASnote") |
---|
855 | self.write_text(node, item) |
---|
856 | self.append(node, entry_node) |
---|
857 | |
---|
858 | |
---|
859 | # Return the document, and the SASentry node associated with |
---|
860 | # the data we just wrote |
---|
861 | |
---|
862 | frm = inspect.stack()[1] |
---|
863 | mod = inspect.getmodule(frm[0]) |
---|
864 | mod_name = mod.__name__ |
---|
865 | if mod_name != "sans.dataloader.readers.cansas_reader": |
---|
866 | string = self.to_string(doc, pp=True) |
---|
867 | doc = parseString(string) |
---|
868 | node_name = entry_node.tag |
---|
869 | node_list = doc.getElementsByTagName(node_name) |
---|
870 | entry_node = node_list.item(0) |
---|
871 | |
---|
872 | return doc, entry_node |
---|
873 | |
---|
874 | |
---|
875 | def write_node(self, parent, name, value, attr=None): |
---|
876 | """ |
---|
877 | :param doc: document DOM |
---|
878 | :param parent: parent node |
---|
879 | :param name: tag of the element |
---|
880 | :param value: value of the child text node |
---|
881 | :param attr: attribute dictionary |
---|
882 | |
---|
883 | :return: True if something was appended, otherwise False |
---|
884 | """ |
---|
885 | if value is not None: |
---|
886 | parent = self.ebuilder(parent, name, value, attr) |
---|
887 | return True |
---|
888 | return False |
---|
889 | |
---|
890 | |
---|
891 | def write(self, filename, datainfo): |
---|
892 | """ |
---|
893 | Write the content of a Data1D as a CanSAS XML file |
---|
894 | |
---|
895 | :param filename: name of the file to write |
---|
896 | :param datainfo: Data1D object |
---|
897 | """ |
---|
898 | # Create XML document |
---|
899 | doc, _ = self._to_xml_doc(datainfo) |
---|
900 | # Write the file |
---|
901 | fd = open(filename, 'w') |
---|
902 | if self.encoding == None: |
---|
903 | self.encoding = "UTF-8" |
---|
904 | doc.write(fd, encoding=self.encoding, |
---|
905 | pretty_print=True, xml_declaration=True) |
---|
906 | fd.close() |
---|
907 | |
---|
908 | |
---|
909 | # DO NOT REMOVE - used in saving and loading panel states. |
---|
910 | def _store_float(self, location, node, variable, storage, optional=True): |
---|
911 | """ |
---|
912 | Get the content of a xpath location and store |
---|
913 | the result. Check that the units are compatible |
---|
914 | with the destination. The value is expected to |
---|
915 | be a float. |
---|
916 | |
---|
917 | The xpath location might or might not exist. |
---|
918 | If it does not exist, nothing is done |
---|
919 | |
---|
920 | :param location: xpath location to fetch |
---|
921 | :param node: node to read the data from |
---|
922 | :param variable: name of the data member to store it in [string] |
---|
923 | :param storage: data object that has the 'variable' data member |
---|
924 | :param optional: if True, no exception will be raised |
---|
925 | if unit conversion can't be done |
---|
926 | |
---|
927 | :raise ValueError: raised when the units are not recognized |
---|
928 | """ |
---|
929 | entry = get_content(location, node) |
---|
930 | try: |
---|
931 | value = float(entry.text) |
---|
932 | except: |
---|
933 | value = None |
---|
934 | |
---|
935 | if value is not None: |
---|
936 | # If the entry has units, check to see that they are |
---|
937 | # compatible with what we currently have in the data object |
---|
938 | units = entry.get('unit') |
---|
939 | if units is not None: |
---|
940 | toks = variable.split('.') |
---|
941 | local_unit = None |
---|
942 | exec "local_unit = storage.%s_unit" % toks[0] |
---|
943 | if local_unit != None and units.lower() != local_unit.lower(): |
---|
944 | if HAS_CONVERTER == True: |
---|
945 | try: |
---|
946 | conv = Converter(units) |
---|
947 | exec "storage.%s = %g" % (variable, |
---|
948 | conv(value, units=local_unit)) |
---|
949 | except: |
---|
950 | err_mess = "CanSAS reader: could not convert" |
---|
951 | err_mess += " %s unit [%s]; expecting [%s]\n %s" \ |
---|
952 | % (variable, units, local_unit, sys.exc_value) |
---|
953 | self.errors.append(err_mess) |
---|
954 | if optional: |
---|
955 | logging.info(err_mess) |
---|
956 | else: |
---|
957 | raise ValueError, err_mess |
---|
958 | else: |
---|
959 | err_mess = "CanSAS reader: unrecognized %s unit [%s];"\ |
---|
960 | % (variable, units) |
---|
961 | err_mess += " expecting [%s]" % local_unit |
---|
962 | self.errors.append(err_mess) |
---|
963 | if optional: |
---|
964 | logging.info(err_mess) |
---|
965 | else: |
---|
966 | raise ValueError, err_mess |
---|
967 | else: |
---|
968 | exec "storage.%s = value" % variable |
---|
969 | else: |
---|
970 | exec "storage.%s = value" % variable |
---|
971 | |
---|
972 | |
---|
973 | # DO NOT REMOVE - used in saving and loading panel states. |
---|
974 | def _store_content(self, location, node, variable, storage): |
---|
975 | """ |
---|
976 | Get the content of a xpath location and store |
---|
977 | the result. The value is treated as a string. |
---|
978 | |
---|
979 | The xpath location might or might not exist. |
---|
980 | If it does not exist, nothing is done |
---|
981 | |
---|
982 | :param location: xpath location to fetch |
---|
983 | :param node: node to read the data from |
---|
984 | :param variable: name of the data member to store it in [string] |
---|
985 | :param storage: data object that has the 'variable' data member |
---|
986 | |
---|
987 | :return: return a list of errors |
---|
988 | """ |
---|
989 | entry = get_content(location, node) |
---|
990 | if entry is not None and entry.text is not None: |
---|
991 | exec "storage.%s = entry.text.strip()" % variable |
---|