source: sasview/src/sans/dataloader/readers/cansas_reader.py @ 51af54b

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

Fixing project save/load and changed up an poorly worded error message.

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