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