source: sasview/src/sas/dataloader/readers/cansas_reader.py @ 9dedf40

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 9dedf40 was 9dedf40, checked in by Doucet, Mathieu <doucetm@…>, 9 years ago

Fix issue do to misleading use of exec

  • Property mode set to 100644
File size: 50.2 KB
RevLine 
[7d6351e]1"""
[76cd1ae]2    CanSAS data reader - new recursive cansas_version.
[7d6351e]3"""
[0997158f]4############################################################################
5#This software was developed by the University of Tennessee as part of the
6#Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
[aa720c4]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
[0997158f]10#following sentence:
[aa720c4]11#This work benefited from DANSE software developed under NSF award DMR-0520547.
[0997158f]12#copyright 2008,2009 University of Tennessee
13#############################################################################
14
[8780e9a]15import logging
16import numpy
[a7a5886]17import os
18import sys
[9e2bc6c]19import datetime
[ac5b69d]20import inspect
21# For saving individual sections of data
[79492222]22from sas.dataloader.data_info import Data1D
23from sas.dataloader.data_info import Collimation
24from sas.dataloader.data_info import TransmissionSpectrum
25from sas.dataloader.data_info import Detector
26from sas.dataloader.data_info import Process
27from sas.dataloader.data_info import Aperture
[ac5b69d]28# Both imports used. Do not remove either.
29from xml.dom.minidom import parseString
[79492222]30import sas.dataloader.readers.xml_reader as xml_reader
31from sas.dataloader.readers.xml_reader import XMLreader
32from sas.dataloader.readers.cansas_constants import CansasConstants
[19b628f]33
[da96629]34_ZERO = 1e-16
[ea67541]35PREPROCESS = "xmlpreprocess"
[2e3b055]36ENCODING = "encoding"
[3241dd2]37RUN_NAME_DEFAULT = "None"
[5a0dac1f]38HAS_CONVERTER = True
[b39c817]39try:
[79492222]40    from sas.data_util.nxsunit import Converter
[3241dd2]41except ImportError:
[5a0dac1f]42    HAS_CONVERTER = False
[76cd1ae]43
[aa720c4]44CONSTANTS = CansasConstants()
[ac5b69d]45CANSAS_FORMAT = CONSTANTS.format
46CANSAS_NS = CONSTANTS.names
[5a0dac1f]47ALLOW_ALL = True
[b0d0723]48
[ac5b69d]49# DO NOT REMOVE
50# Called by outside packages:
[79492222]51#    sas.perspectives.invariant.invariant_state
52#    sas.perspectives.fitting.pagestate
[8780e9a]53def get_content(location, node):
54    """
[0997158f]55    Get the first instance of the content of a xpath location.
[aa720c4]56
[0997158f]57    :param location: xpath location
58    :param node: node to start at
[aa720c4]59
[0997158f]60    :return: Element, or None
[8780e9a]61    """
[aa720c4]62    nodes = node.xpath(location,
[ac5b69d]63                       namespaces={'ns': CANSAS_NS.get("1.0").get("ns")})
[aa720c4]64
[7d6351e]65    if len(nodes) > 0:
[b0d0723]66        return nodes[0]
67    else:
68        return None
[8780e9a]69
[7d6351e]70
[ac5b69d]71# DO NOT REMOVE
72# Called by outside packages:
[79492222]73#    sas.perspectives.fitting.pagestate
[3241dd2]74def write_node(doc, parent, name, value, attr=None):
[e090c624]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
[aa720c4]81
[e090c624]82    :return: True if something was appended, otherwise False
83    """
[3241dd2]84    if attr is None:
85        attr = {}
[e090c624]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
[aa720c4]94
[19b628f]95
[ac5b69d]96class Reader(XMLreader):
[8780e9a]97    """
[0997158f]98    Class to load cansas 1D XML files
[aa720c4]99
[0997158f]100    :Dependencies:
[19b628f]101        The CanSAS reader requires PyXML 0.8.4 or later.
[8780e9a]102    """
[19b628f]103    ##CanSAS version - defaults to version 1.0
[76cd1ae]104    cansas_version = "1.0"
[3241dd2]105    base_ns = "{cansas1d/1.0}"
[aa720c4]106
[ac5b69d]107    logging = []
[19b628f]108    errors = []
[aa720c4]109
[19b628f]110    type_name = "canSAS"
[28caa03]111    ## Wildcards
[ac5b69d]112    type = ["XML files (*.xml)|*.xml", "SasView Save Files (*.svs)|*.svs"]
[8780e9a]113    ## List of allowed extensions
[ac5b69d]114    ext = ['.xml', '.XML', '.svs', '.SVS']
[aa720c4]115
[19b628f]116    ## Flag to bypass extension check
117    allow_all = True
[aa720c4]118
119
[fe78c7b]120    def __init__(self):
121        ## List of errors
122        self.errors = []
[3241dd2]123        self.encoding = None
[aa720c4]124
125
[ac5b69d]126    def is_cansas(self, ext="xml"):
[19b628f]127        """
128        Checks to see if the xml file is a CanSAS file
[aa720c4]129
[3241dd2]130        :param ext: The file extension of the data file
[19b628f]131        """
[ac5b69d]132        if self.validate_xml():
[2e3b055]133            name = "{http://www.w3.org/2001/XMLSchema-instance}schemaLocation"
[ac5b69d]134            value = self.xmlroot.get(name)
135            if CANSAS_NS.get(self.cansas_version).get("ns") == \
136                    value.rsplit(" ")[0]:
[19b628f]137                return True
[ac5b69d]138        if ext == "svs":
139            return True
[19b628f]140        return False
[aa720c4]141
142
[3241dd2]143    def load_file_and_schema(self, xml_file):
[7d6351e]144        """
[3241dd2]145        Loads the file and associates a schema, if a known schema exists
[aa720c4]146
[3241dd2]147        :param xml_file: The xml file path sent to Reader.read
148        """
149        base_name = xml_reader.__file__
[aa720c4]150        base_name = base_name.replace("\\", "/")
[79492222]151        base = base_name.split("/sas/")[0]
[aa720c4]152
[3241dd2]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")
[aa720c4]156
[3241dd2]157        # Generic values for the cansas file based on the version
158        cansas_defaults = CANSAS_NS.get(self.cansas_version, "1.0")
[79492222]159        schema_path = "{0}/sas/dataloader/readers/schema/{1}".format\
[3241dd2]160                (base, cansas_defaults.get("schema")).replace("\\", "/")
[aa720c4]161
[3241dd2]162        # Link a schema to the XML file.
163        self.set_schema(schema_path)
164        return cansas_defaults
[aa720c4]165
166
[3241dd2]167    def read(self, xml_file):
168        """
169        Validate and read in an xml_file file in the canSAS format.
[aa720c4]170
[3241dd2]171        :param xml_file: A canSAS file path in proper XML format
[8780e9a]172        """
[aa720c4]173
[19b628f]174        # output - Final list of Data1D objects
[8780e9a]175        output = []
[3241dd2]176        # ns - Namespace hierarchy for current xml_file object
[ac5b69d]177        ns_list = []
[aa720c4]178
[19b628f]179        # Check that the file exists
[3241dd2]180        if os.path.isfile(xml_file):
181            basename = os.path.basename(xml_file)
[19b628f]182            _, extension = os.path.splitext(basename)
[ac5b69d]183            # If the file type is not allowed, return nothing
[19b628f]184            if extension in self.ext or self.allow_all:
[aa720c4]185                # Get the file location of
[3241dd2]186                cansas_defaults = self.load_file_and_schema(xml_file)
[aa720c4]187
[19b628f]188                # Try to load the file, but raise an error if unable to.
189                # Check the file matches the XML schema
[0a5c8f5]190                try:
[ac5b69d]191                    if self.is_cansas(extension):
[76cd1ae]192                        # Get each SASentry from XML file and add it to a list.
[3241dd2]193                        entry_list = self.xmlroot.xpath(
[aa720c4]194                                '/ns:SASroot/ns:SASentry',
195                                namespaces={'ns': cansas_defaults.get("ns")})
[ac5b69d]196                        ns_list.append("SASentry")
[aa720c4]197
[76cd1ae]198                        # If multiple files, modify the name for each is unique
199                        increment = 0
[19b628f]200                        # Parse each SASentry item
201                        for entry in entry_list:
[aa720c4]202                            # Define a new Data1D object with zeroes for
[ac5b69d]203                            # x_vals and y_vals
[aa720c4]204                            data1d = Data1D(numpy.empty(0), numpy.empty(0),
[3241dd2]205                                            numpy.empty(0), numpy.empty(0))
206                            data1d.dxl = numpy.empty(0)
207                            data1d.dxw = numpy.empty(0)
[aa720c4]208
[76cd1ae]209                            # If more than one SASentry, increment each in order
[3241dd2]210                            name = basename
211                            if len(entry_list) - 1 > 0:
[76cd1ae]212                                name += "_{0}".format(increment)
213                                increment += 1
[aa720c4]214
215                            # Set the Data1D name and then parse the entry.
[76cd1ae]216                            # The entry is appended to a list of entry values
217                            data1d.filename = name
218                            data1d.meta_data["loader"] = "CanSAS 1D"
[aa720c4]219
[2e3b055]220                            # Get all preprocessing events and encoding
[ac5b69d]221                            self.set_processing_instructions()
[ea67541]222                            data1d.meta_data[PREPROCESS] = \
[ac5b69d]223                                    self.processing_instructions
[aa720c4]224
[ea67541]225                            # Parse the XML file
[76cd1ae]226                            return_value, extras = \
[ac5b69d]227                                self._parse_entry(entry, ns_list, data1d)
[19b628f]228                            del extras[:]
[aa720c4]229
[3241dd2]230                            return_value = self._final_cleanup(return_value)
[19b628f]231                            output.append(return_value)
232                    else:
[3241dd2]233                        output.append("Invalid XML at: {0}".format(\
234                                                    self.find_invalid_xml()))
[0a5c8f5]235                except:
[19b628f]236                    # If the file does not match the schema, raise this error
[3241dd2]237                    raise RuntimeError, "%s cannot be read" % xml_file
[19b628f]238                return output
239        # Return a list of parsed entries that dataloader can manage
240        return None
[aa720c4]241
242
[3241dd2]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
[aa720c4]247
[3241dd2]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
[aa720c4]271
272    def _create_unique_key(self, dictionary, name, numb=0):
[76cd1ae]273        """
274        Create a unique key value for any dictionary to prevent overwriting
[ea67541]275        Recurses until a unique key value is found.
[aa720c4]276
[76cd1ae]277        :param dictionary: A dictionary with any number of entries
278        :param name: The index of the item to be added to dictionary
[ac5b69d]279        :param numb: The number to be appended to the name, starts at 0
[76cd1ae]280        """
[19b628f]281        if dictionary.get(name) is not None:
[ac5b69d]282            numb += 1
[19b628f]283            name = name.split("_")[0]
[ac5b69d]284            name += "_{0}".format(numb)
285            name = self._create_unique_key(dictionary, name, numb)
[19b628f]286        return name
[aa720c4]287
288
[3241dd2]289    def _unit_conversion(self, node, new_current_level, data1d, \
290                                                tagname, node_value):
[76cd1ae]291        """
292        A unit converter method used to convert the data included in the file
293        to the default units listed in data_info
[aa720c4]294
295        :param new_current_level: cansas_constants level as returned by
[ac5b69d]296            iterate_namespace
[76cd1ae]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        """
[3241dd2]301        attr = node.attrib
[19b628f]302        value_unit = ''
303        if 'unit' in attr and new_current_level.get('unit') is not None:
[8780e9a]304            try:
[b3efb7d]305                local_unit = attr['unit']
[19b628f]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")
[76cd1ae]310                exec "default_unit = data1d.{0}".format(unitname)
[b3efb7d]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":
[19b628f]314                    if HAS_CONVERTER == True:
[b3efb7d]315                        ## Check local units - bad units raise KeyError
[226ce0b]316                        data_conv_q = Converter(local_unit)
[b3efb7d]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)
[19b628f]321                    else:
322                        value_unit = local_unit
[b3efb7d]323                        err_msg = "Unit converter is not available.\n"
[19b628f]324                        self.errors.append(err_msg)
325                else:
326                    value_unit = local_unit
[b3efb7d]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
[8780e9a]337            except:
[b3efb7d]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)
[19b628f]342                self.errors.append(err_msg)
[b3efb7d]343                value_unit = local_unit
[19b628f]344        elif 'unit' in attr:
345            value_unit = attr['unit']
346        node_value = "float({0})".format(node_value)
347        return node_value, value_unit
[aa720c4]348
349
[3241dd2]350    def _check_for_empty_data(self, data1d):
[19b628f]351        """
[3241dd2]352        Creates an empty data set if no data is passed to the reader
[aa720c4]353
[3241dd2]354        :param data1d: presumably a Data1D object
[19b628f]355        """
[ac5b69d]356        if data1d == None:
[3241dd2]357            self.errors = []
[ac5b69d]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
[3241dd2]367        return data1d
[aa720c4]368
[3241dd2]369    def _handle_special_cases(self, tagname, data1d, children):
370        """
371        Handle cases where the data type in Data1D is a dictionary or list
[aa720c4]372
[3241dd2]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
[aa720c4]401
[3241dd2]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
[aa720c4]430
431    def _restore_original_case(self,
432                               tagname_original,
433                               tagname,
434                               save_data1d,
[3241dd2]435                               data1d):
436        """
437        Save the special case data to the appropriate location and restore
438        the original Data1D object
[aa720c4]439
[3241dd2]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
[aa720c4]458
[3241dd2]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:
[9dedf40]467                    node_value, unit = self._get_node_value(node, cs_values, \
[aa720c4]468                                                   data1d, tagname)
[3241dd2]469                    cansas_attrib = \
[b3efb7d]470                        cs_values.current_level.get("attributes").get(key)
[3241dd2]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:
[aa720c4]480                    pass
[3241dd2]481        return data1d
[aa720c4]482
[3241dd2]483    def _get_node_value(self, node, cs_values, data1d, tagname):
484        """
485        Get the value of a node and any applicable units
[aa720c4]486
[3241dd2]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())
[aa720c4]500
[3241dd2]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)
[aa720c4]510
[3241dd2]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
[aa720c4]522
[3241dd2]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.
[aa720c4]528
[3241dd2]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        """
[aa720c4]535
[3241dd2]536        if extras is None:
537            extras = []
538        if names is None or names == []:
539            names = ["SASentry"]
[aa720c4]540
[3241dd2]541        data1d = self._check_for_empty_data(data1d)
[aa720c4]542
[3241dd2]543        self.base_ns = "{0}{1}{2}".format("{", \
[76cd1ae]544                            CANSAS_NS.get(self.cansas_version).get("ns"), "}")
[ea67541]545        tagname = ''
546        tagname_original = ''
[aa720c4]547
[19b628f]548        # Go through each child in the parent element
549        for node in dom:
[8780e9a]550            try:
[ac5b69d]551                # Get the element name and set the current names level
[3241dd2]552                tagname = node.tag.replace(self.base_ns, "")
[19b628f]553                tagname_original = tagname
[92a2ecd]554                if tagname == "fitting_plug_in" or tagname == "pr_inversion" or\
555                    tagname == "invariant":
[ac5b69d]556                    continue
557                names.append(tagname)
[e090c624]558                children = node.getchildren()
[ac5b69d]559                if len(children) == 0:
560                    children = None
[e090c624]561                save_data1d = data1d
[aa720c4]562
[19b628f]563                # Look for special cases
[3241dd2]564                data1d = self._handle_special_cases(tagname, data1d, children)
[aa720c4]565
[19b628f]566                # Get where to store content
[ac5b69d]567                cs_values = CONSTANTS.iterate_namespace(names)
[19b628f]568                # If the element is a child element, recurse
[e090c624]569                if children is not None:
[aa720c4]570                    # Returned value is new Data1D object with all previous and
[e090c624]571                    # new values in it.
[aa720c4]572                    data1d, extras = self._parse_entry(node,
[ac5b69d]573                                                       names, data1d, extras)
[aa720c4]574
[19b628f]575                #Get the information from the node
[3241dd2]576                node_value, _ = self._get_node_value(node, cs_values, \
577                                                            data1d, tagname)
[aa720c4]578
[e090c624]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}\"":
[aa720c4]582                    # If we are within a Process, Detector, Collimation or
[e090c624]583                    # Aperture instance, pull out old data1d
584                    tagname = self._create_unique_key(data1d.meta_data, \
585                                                      tagname, 0)
[76cd1ae]586                    if isinstance(data1d, Data1D) == False:
[e090c624]587                        store_me = cs_values.ns_variable.format("data1d", \
588                                                            node_value, tagname)
[19b628f]589                        extras.append(store_me)
[e090c624]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)
[aa720c4]594
[19b628f]595                # Check for Data1D object and any extra commands to save
[76cd1ae]596                if isinstance(data1d, Data1D):
[19b628f]597                    for item in extras:
598                        exec item
599                # Don't bother saving empty information unless it is a float
[ea67541]600                if cs_values.ns_variable is not None and \
601                            node_value is not None and \
[76cd1ae]602                            node_value.isspace() == False:
[19b628f]603                    # Format a string and then execute it.
[ea67541]604                    store_me = cs_values.ns_variable.format("data1d", \
605                                                            node_value, tagname)
[19b628f]606                    exec store_me
607                # Get attributes and process them
[3241dd2]608                data1d = self._handle_attributes(node, data1d, cs_values, \
609                                                 tagname)
[aa720c4]610
[3241dd2]611            except TypeError:
[b65ae90]612                pass
[3241dd2]613            except Exception as excep:
[19b628f]614                exc_type, exc_obj, exc_tb = sys.exc_info()
615                fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
[3241dd2]616                print(excep, exc_type, fname, exc_tb.tb_lineno, \
617                      tagname, exc_obj)
[19b628f]618            finally:
[76cd1ae]619                # Save special cases in original data1d object
620                # then restore the data1d
[3241dd2]621                save_data1d = self._restore_original_case(tagname_original, \
622                                                tagname, save_data1d, data1d)
[92a2ecd]623                if tagname_original == "fitting_plug_in" or \
624                    tagname_original == "invariant" or \
625                    tagname_original == "pr_inversion":
626                    pass
627                else:
[ac5b69d]628                    data1d = save_data1d
629                    # Remove tagname from names to restore original base
630                    names.remove(tagname_original)
[76cd1ae]631        return data1d, extras
[aa720c4]632
[3241dd2]633    def _get_pi_string(self):
[4c00964]634        """
[3241dd2]635        Creates the processing instructions header for writing to file
[4c00964]636        """
[ac5b69d]637        pis = self.return_processing_instructions()
638        if len(pis) > 0:
639            pi_tree = self.create_tree(pis[0])
640            i = 1
[3241dd2]641            for i in range(1, len(pis) - 1):
[ac5b69d]642                pi_tree = self.append(pis[i], pi_tree)
643            pi_string = self.to_string(pi_tree)
644        else:
645            pi_string = ""
[3241dd2]646        return pi_string
[aa720c4]647
[3241dd2]648    def _create_main_node(self):
649        """
650        Creates the primary xml header used when writing to file
651        """
[2e3b055]652        xsi = "http://www.w3.org/2001/XMLSchema-instance"
653        version = self.cansas_version
[3241dd2]654        n_s = CANSAS_NS.get(version).get("ns")
[2e3b055]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/"
[3241dd2]659        schema_location = "{0} {1}cansas1d.xsd".format(n_s, url)
[ac5b69d]660        attrib = {"{" + xsi + "}schemaLocation" : schema_location,
[2e3b055]661                  "version" : version}
[3241dd2]662        nsmap = {'xsi' : xsi, None: n_s}
[aa720c4]663
664        main_node = self.create_element("{" + n_s + "}SASroot",
665                                        attrib=attrib, nsmap=nsmap)
[3241dd2]666        return main_node
[aa720c4]667
[3241dd2]668    def _write_run_names(self, datainfo, entry_node):
669        """
670        Writes the run names to the XML file
[aa720c4]671
[3241dd2]672        :param datainfo: The Data1D object the information is coming from
673        :param entry_node: lxml node ElementTree object to be appended to
674        """
[9e2bc6c]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
[579ba85]678        for item in datainfo.run:
679            runname = {}
[7d6351e]680            if item in datainfo.run_name and \
681            len(str(datainfo.run_name[item])) > 1:
682                runname = {'name': datainfo.run_name[item]}
[2e3b055]683            self.write_node(entry_node, "Run", item, runname)
[aa720c4]684
[3241dd2]685    def _write_data(self, datainfo, entry_node):
686        """
687        Writes the I and Q data to the XML file
[aa720c4]688
[3241dd2]689        :param datainfo: The Data1D object the information is coming from
690        :param entry_node: lxml node ElementTree object to be appended to
691        """
[ac5b69d]692        node = self.create_element("SASdata")
693        self.append(node, entry_node)
[aa720c4]694
[579ba85]695        for i in range(len(datainfo.x)):
[3241dd2]696            point = self.create_element("Idata")
697            node.append(point)
[aa720c4]698            self.write_node(point, "Q", datainfo.x[i],
699                            {'unit': datainfo.x_unit})
[7d6351e]700            if len(datainfo.y) >= i:
[3241dd2]701                self.write_node(point, "I", datainfo.y[i],
[aa720c4]702                                {'unit': datainfo.y_unit})
[76cd1ae]703            if datainfo.dy != None and len(datainfo.dy) > i:
[3241dd2]704                self.write_node(point, "Idev", datainfo.dy[i],
[aa720c4]705                                {'unit': datainfo.y_unit})
[76cd1ae]706            if datainfo.dx != None and len(datainfo.dx) > i:
[3241dd2]707                self.write_node(point, "Qdev", datainfo.dx[i],
[aa720c4]708                                {'unit': datainfo.x_unit})
[76cd1ae]709            if datainfo.dxw != None and len(datainfo.dxw) > i:
[3241dd2]710                self.write_node(point, "dQw", datainfo.dxw[i],
[aa720c4]711                                {'unit': datainfo.x_unit})
[76cd1ae]712            if datainfo.dxl != None and len(datainfo.dxl) > i:
[3241dd2]713                self.write_node(point, "dQl", datainfo.dxl[i],
[aa720c4]714                                {'unit': datainfo.x_unit})
715
[3241dd2]716    def _write_trans_spectrum(self, datainfo, entry_node):
717        """
718        Writes the transmission spectrum data to the XML file
[aa720c4]719
[3241dd2]720        :param datainfo: The Data1D object the information is coming from
721        :param entry_node: lxml node ElementTree object to be appended to
722        """
[76cd1ae]723        for i in range(len(datainfo.trans_spectrum)):
724            spectrum = datainfo.trans_spectrum[i]
[ac5b69d]725            node = self.create_element("SAStransmission_spectrum",
[aa720c4]726                                       {"name" : spectrum.name})
[ac5b69d]727            self.append(node, entry_node)
[9e2bc6c]728            if isinstance(spectrum.timestamp, datetime.datetime):
729                node.setAttribute("timestamp", spectrum.timestamp)
[76cd1ae]730            for i in range(len(spectrum.wavelength)):
[3241dd2]731                point = self.create_element("Tdata")
732                node.append(point)
[aa720c4]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})
[76cd1ae]737                if spectrum.transmission_deviation != None \
738                and len(spectrum.transmission_deviation) >= i:
[aa720c4]739                    self.write_node(point, "Tdev",
740                                    spectrum.transmission_deviation[i],
741                                    {'unit':
742                                     spectrum.transmission_deviation_unit})
743
[3241dd2]744    def _write_sample_info(self, datainfo, entry_node):
745        """
746        Writes the sample information to the XML file
[aa720c4]747
[3241dd2]748        :param datainfo: The Data1D object the information is coming from
749        :param entry_node: lxml node ElementTree object to be appended to
750        """
[ac5b69d]751        sample = self.create_element("SASsample")
[579ba85]752        if datainfo.sample.name is not None:
[aa720c4]753            self.write_attribute(sample, "name",
754                                 str(datainfo.sample.name))
[ac5b69d]755        self.append(sample, entry_node)
[2e3b055]756        self.write_node(sample, "ID", str(datainfo.sample.ID))
757        self.write_node(sample, "thickness", datainfo.sample.thickness,
[aa720c4]758                        {"unit": datainfo.sample.thickness_unit})
[2e3b055]759        self.write_node(sample, "transmission", datainfo.sample.transmission)
760        self.write_node(sample, "temperature", datainfo.sample.temperature,
[aa720c4]761                        {"unit": datainfo.sample.temperature_unit})
762
[ac5b69d]763        pos = self.create_element("position")
[aa720c4]764        written = self.write_node(pos,
765                                  "x",
[2e3b055]766                                  datainfo.sample.position.x,
767                                  {"unit": datainfo.sample.position_unit})
[aa720c4]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})
[4c00964]774        if written == True:
[ac5b69d]775            self.append(pos, sample)
[aa720c4]776
[ac5b69d]777        ori = self.create_element("orientation")
[2e3b055]778        written = self.write_node(ori, "roll",
779                                  datainfo.sample.orientation.x,
780                                  {"unit": datainfo.sample.orientation_unit})
[aa720c4]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})
[4c00964]787        if written == True:
[ac5b69d]788            self.append(ori, sample)
[aa720c4]789
[19b628f]790        for item in datainfo.sample.details:
[2e3b055]791            self.write_node(sample, "details", item)
[aa720c4]792
[3241dd2]793    def _write_instrument(self, datainfo, entry_node):
794        """
795        Writes the instrumental information to the XML file
[aa720c4]796
[3241dd2]797        :param datainfo: The Data1D object the information is coming from
798        :param entry_node: lxml node ElementTree object to be appended to
799        """
[ac5b69d]800        instr = self.create_element("SASinstrument")
801        self.append(instr, entry_node)
[2e3b055]802        self.write_node(instr, "name", datainfo.instrument)
[3241dd2]803        return instr
[aa720c4]804
[3241dd2]805    def _write_source(self, datainfo, instr):
806        """
807        Writes the source information to the XML file
[aa720c4]808
[3241dd2]809        :param datainfo: The Data1D object the information is coming from
810        :param instr: instrument node  to be appended to
811        """
[ac5b69d]812        source = self.create_element("SASsource")
[579ba85]813        if datainfo.source.name is not None:
[aa720c4]814            self.write_attribute(source, "name",
815                                 str(datainfo.source.name))
[ac5b69d]816        self.append(source, instr)
[9e2bc6c]817        if datainfo.source.radiation == None or datainfo.source.radiation == '':
818            datainfo.source.radiation = "neutron"
[2e3b055]819        self.write_node(source, "radiation", datainfo.source.radiation)
[aa720c4]820
[ac5b69d]821        size = self.create_element("beam_size")
[579ba85]822        if datainfo.source.beam_size_name is not None:
[aa720c4]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})
[579ba85]834        if written == True:
[ac5b69d]835            self.append(size, source)
[aa720c4]836
[2e3b055]837        self.write_node(source, "beam_shape", datainfo.source.beam_shape)
838        self.write_node(source, "wavelength",
[aa720c4]839                        datainfo.source.wavelength,
840                        {"unit": datainfo.source.wavelength_unit})
[2e3b055]841        self.write_node(source, "wavelength_min",
[aa720c4]842                        datainfo.source.wavelength_min,
843                        {"unit": datainfo.source.wavelength_min_unit})
[2e3b055]844        self.write_node(source, "wavelength_max",
[aa720c4]845                        datainfo.source.wavelength_max,
846                        {"unit": datainfo.source.wavelength_max_unit})
[2e3b055]847        self.write_node(source, "wavelength_spread",
[aa720c4]848                        datainfo.source.wavelength_spread,
849                        {"unit": datainfo.source.wavelength_spread_unit})
850
851    def _write_collimation(self, datainfo, instr):
[3241dd2]852        """
853        Writes the collimation information to the XML file
[aa720c4]854
[3241dd2]855        :param datainfo: The Data1D object the information is coming from
856        :param instr: lxml node ElementTree object to be appended to
857        """
[9e2bc6c]858        if datainfo.collimation == [] or datainfo.collimation == None:
859            coll = Collimation()
860            datainfo.collimation.append(coll)
[4c00964]861        for item in datainfo.collimation:
[ac5b69d]862            coll = self.create_element("SAScollimation")
[579ba85]863            if item.name is not None:
[ac5b69d]864                self.write_attribute(coll, "name", str(item.name))
865            self.append(coll, instr)
[aa720c4]866
[2e3b055]867            self.write_node(coll, "length", item.length,
[aa720c4]868                            {"unit": item.length_unit})
869
[3241dd2]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)
[aa720c4]877
[ac5b69d]878                size = self.create_element("size")
[3241dd2]879                if aperture.size_name is not None:
[aa720c4]880                    self.write_attribute(size, "name",
881                                         str(aperture.size_name))
[3241dd2]882                written = self.write_node(size, "x", aperture.size.x,
[aa720c4]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})
[579ba85]890                if written == True:
[3241dd2]891                    self.append(size, apert)
[aa720c4]892
[3241dd2]893                self.write_node(apert, "distance", aperture.distance,
[aa720c4]894                                {"unit": aperture.distance_unit})
895
896
[3241dd2]897    def _write_detectors(self, datainfo, instr):
898        """
899        Writes the detector information to the XML file
[aa720c4]900
[3241dd2]901        :param datainfo: The Data1D object the information is coming from
902        :param inst: lxml instrument node to be appended to
903        """
[9e2bc6c]904        if datainfo.detector == None or datainfo.detector == []:
905            det = Detector()
906            det.name = ""
907            datainfo.detector.append(det)
[aa720c4]908
[4c00964]909        for item in datainfo.detector:
[ac5b69d]910            det = self.create_element("SASdetector")
[2e3b055]911            written = self.write_node(det, "name", item.name)
912            written = written | self.write_node(det, "SDD", item.distance,
[aa720c4]913                                                {"unit": item.distance_unit})
[579ba85]914            if written == True:
[ac5b69d]915                self.append(det, instr)
[aa720c4]916
[ac5b69d]917            off = self.create_element("offset")
[2e3b055]918            written = self.write_node(off, "x", item.offset.x,
[aa720c4]919                                      {"unit": item.offset_unit})
[2e3b055]920            written = written | self.write_node(off, "y", item.offset.y,
[aa720c4]921                                                {"unit": item.offset_unit})
[2e3b055]922            written = written | self.write_node(off, "z", item.offset.z,
[aa720c4]923                                                {"unit": item.offset_unit})
[579ba85]924            if written == True:
[ac5b69d]925                self.append(off, det)
[aa720c4]926
[ac5b69d]927            ori = self.create_element("orientation")
[2e3b055]928            written = self.write_node(ori, "roll", item.orientation.x,
[aa720c4]929                                      {"unit": item.orientation_unit})
[2e3b055]930            written = written | self.write_node(ori, "pitch",
[aa720c4]931                                                item.orientation.y,
932                                                {"unit": item.orientation_unit})
[2e3b055]933            written = written | self.write_node(ori, "yaw",
[aa720c4]934                                                item.orientation.z,
935                                                {"unit": item.orientation_unit})
[19b628f]936            if written == True:
[ac5b69d]937                self.append(ori, det)
[aa720c4]938
[ac5b69d]939            center = self.create_element("beam_center")
[2e3b055]940            written = self.write_node(center, "x", item.beam_center.x,
[aa720c4]941                                      {"unit": item.beam_center_unit})
[2e3b055]942            written = written | self.write_node(center, "y",
[aa720c4]943                                                item.beam_center.y,
944                                                {"unit": item.beam_center_unit})
[2e3b055]945            written = written | self.write_node(center, "z",
[aa720c4]946                                                item.beam_center.z,
947                                                {"unit": item.beam_center_unit})
[579ba85]948            if written == True:
[ac5b69d]949                self.append(center, det)
[aa720c4]950
[ac5b69d]951            pix = self.create_element("pixel_size")
[2e3b055]952            written = self.write_node(pix, "x", item.pixel_size.x,
[aa720c4]953                                      {"unit": item.pixel_size_unit})
[2e3b055]954            written = written | self.write_node(pix, "y", item.pixel_size.y,
[aa720c4]955                                                {"unit": item.pixel_size_unit})
[2e3b055]956            written = written | self.write_node(pix, "z", item.pixel_size.z,
[aa720c4]957                                                {"unit": item.pixel_size_unit})
[2e3b055]958            written = written | self.write_node(det, "slit_length",
[aa720c4]959                                                item.slit_length,
960                                                {"unit": item.slit_length_unit})
[2e3b055]961            if written == True:
[ac5b69d]962                self.append(pix, det)
[aa720c4]963
[3241dd2]964    def _write_process_notes(self, datainfo, entry_node):
965        """
966        Writes the process notes to the XML file
[aa720c4]967
[3241dd2]968        :param datainfo: The Data1D object the information is coming from
969        :param entry_node: lxml node ElementTree object to be appended to
[aa720c4]970
[3241dd2]971        """
[4c00964]972        for item in datainfo.process:
[ac5b69d]973            node = self.create_element("SASprocess")
974            self.append(node, entry_node)
[2e3b055]975            self.write_node(node, "name", item.name)
976            self.write_node(node, "date", item.date)
977            self.write_node(node, "description", item.description)
[579ba85]978            for term in item.term:
979                value = term['value']
980                del term['value']
[2e3b055]981                self.write_node(node, "term", value, term)
[579ba85]982            for note in item.notes:
[2e3b055]983                self.write_node(node, "SASprocessnote", note)
[19b628f]984            if len(item.notes) == 0:
[2e3b055]985                self.write_node(node, "SASprocessnote", "")
[aa720c4]986
[3241dd2]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
[aa720c4]991
[3241dd2]992        :param datainfo: The Data1D object the information is coming from
993        :param entry_node: lxml node ElementTree object to be appended to
[aa720c4]994
[3241dd2]995        """
[19b628f]996        if len(datainfo.notes) == 0:
[ac5b69d]997            node = self.create_element("SASnote")
998            self.append(node, entry_node)
[19b628f]999        else:
1000            for item in datainfo.notes:
[ac5b69d]1001                node = self.create_element("SASnote")
1002                self.write_text(node, item)
1003                self.append(node, entry_node)
[aa720c4]1004
[3241dd2]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.
[aa720c4]1011
[3241dd2]1012        :param entry_node: lxml node ElementTree object to be appended to
1013        :param doc: entire xml tree
1014        """
[ac5b69d]1015        frm = inspect.stack()[1]
[bb1b892]1016        mod_name = frm[1].replace("\\", "/").replace(".pyc", "")
[a3b635b]1017        mod_name = mod_name.replace(".py", "")
[79492222]1018        mod = mod_name.split("sas/")
[bb1b892]1019        mod_name = mod[1]
[51af54b]1020        if mod_name != "dataloader/readers/cansas_reader":
[3241dd2]1021            string = self.to_string(doc, pretty_print=False)
[ac5b69d]1022            doc = parseString(string)
1023            node_name = entry_node.tag
1024            node_list = doc.getElementsByTagName(node_name)
1025            entry_node = node_list.item(0)
[3241dd2]1026        return entry_node
[aa720c4]1027
[3241dd2]1028    def _to_xml_doc(self, datainfo):
1029        """
1030        Create an XML document to contain the content of a Data1D
[aa720c4]1031
[3241dd2]1032        :param datainfo: Data1D object
1033        """
1034        if not issubclass(datainfo.__class__, Data1D):
1035            raise RuntimeError, "The cansas writer expects a Data1D instance"
[aa720c4]1036
[3241dd2]1037        # Get PIs and create root element
1038        pi_string = self._get_pi_string()
[aa720c4]1039
[3241dd2]1040        # Define namespaces and create SASroot object
1041        main_node = self._create_main_node()
[aa720c4]1042
[3241dd2]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)
[aa720c4]1047
[3241dd2]1048        # Create SASentry Element
1049        entry_node = self.create_element("SASentry")
1050        root = doc.getroot()
1051        root.append(entry_node)
[aa720c4]1052
[3241dd2]1053        # Add Title to SASentry
1054        self.write_node(entry_node, "Title", datainfo.title)
[aa720c4]1055
[3241dd2]1056        # Add Run to SASentry
1057        self._write_run_names(datainfo, entry_node)
[aa720c4]1058
[3241dd2]1059        # Add Data info to SASEntry
1060        self._write_data(datainfo, entry_node)
[aa720c4]1061
[3241dd2]1062        # Transmission Spectrum Info
1063        self._write_trans_spectrum(datainfo, entry_node)
[aa720c4]1064
[3241dd2]1065        # Sample info
1066        self._write_sample_info(datainfo, entry_node)
[aa720c4]1067
[3241dd2]1068        # Instrument info
1069        instr = self._write_instrument(datainfo, entry_node)
[aa720c4]1070
[3241dd2]1071        #   Source
1072        self._write_source(datainfo, instr)
[aa720c4]1073
[3241dd2]1074        #   Collimation
1075        self._write_collimation(datainfo, instr)
1076
1077        #   Detectors
1078        self._write_detectors(datainfo, instr)
[aa720c4]1079
[3241dd2]1080        # Processes info
1081        self._write_process_notes(datainfo, entry_node)
[aa720c4]1082
[3241dd2]1083        # Note info
[aa720c4]1084        self._write_notes(datainfo, entry_node)
1085
[3241dd2]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
[aa720c4]1089        #      object rather than an lxml object.
[3241dd2]1090        entry_node = self._check_origin(entry_node, doc)
[aa720c4]1091
[b3de3a45]1092        return doc, entry_node
[aa720c4]1093
[ac5b69d]1094    def write_node(self, parent, name, value, attr=None):
[2e3b055]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
[aa720c4]1101
[2e3b055]1102        :return: True if something was appended, otherwise False
1103        """
1104        if value is not None:
[ac5b69d]1105            parent = self.ebuilder(parent, name, value, attr)
[2e3b055]1106            return True
1107        return False
[aa720c4]1108
[b3de3a45]1109    def write(self, filename, datainfo):
1110        """
[0997158f]1111        Write the content of a Data1D as a CanSAS XML file
[aa720c4]1112
[0997158f]1113        :param filename: name of the file to write
1114        :param datainfo: Data1D object
[b3de3a45]1115        """
1116        # Create XML document
[7d6351e]1117        doc, _ = self._to_xml_doc(datainfo)
[4c00964]1118        # Write the file
[3241dd2]1119        file_ref = open(filename, 'w')
[ac5b69d]1120        if self.encoding == None:
1121            self.encoding = "UTF-8"
[3241dd2]1122        doc.write(file_ref, encoding=self.encoding,
[2e3b055]1123                  pretty_print=True, xml_declaration=True)
[3241dd2]1124        file_ref.close()
[aa720c4]1125
[ac5b69d]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.
[aa720c4]1133
[ac5b69d]1134        The xpath location might or might not exist.
1135        If it does not exist, nothing is done
[aa720c4]1136
[ac5b69d]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
[aa720c4]1151
[ac5b69d]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)
[aa720c4]1164                            exec "storage.%s = %g" % \
1165                                (variable, conv(value, units=local_unit))
[ac5b69d]1166                        except:
[3241dd2]1167                            _, exc_value, _ = sys.exc_info()
[ac5b69d]1168                            err_mess = "CanSAS reader: could not convert"
1169                            err_mess += " %s unit [%s]; expecting [%s]\n  %s" \
[a3b635b]1170                                % (variable, units, local_unit, exc_value)
[ac5b69d]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
[aa720c4]1189
[ac5b69d]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.
[aa720c4]1195
[ac5b69d]1196        The xpath location might or might not exist.
1197        If it does not exist, nothing is done
[aa720c4]1198
[ac5b69d]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
[aa720c4]1203
[ac5b69d]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:
[aa720c4]1208            exec "storage.%s = entry.text.strip()" % variable
Note: See TracBrowser for help on using the repository browser.