source: sasview/src/sans/dataloader/readers/cansas_reader.py @ 3241dd2

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 3241dd2 was 3241dd2, checked in by Jeff Krzywon <jeffery.krzywon@…>, 10 years ago

Fixed the issue as described in ticket 269: "Failure to assign model when using attached data file" and made the change for ticket 264: "Remove .TIF extension from Load Data file extension filter."

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