source: sasview/src/sas/sascalc/dataloader/readers/cansas_reader.py @ d398285

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 d398285 was d398285, checked in by krzywon, 8 years ago

#237: Modified the CanSAS HDF5 reader to read the latest version output from Mantid. Fixed the CanSAS XML reader so the axis titles and units are displayed properly.

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