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