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

Last change on this file since 3d6c010 was 3d6c010, checked in by Tim Snow <tim.snow@…>, 7 years ago

Merge master into branch

  • Property mode set to 100644
File size: 71.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
15import logging
16import numpy as np
17import os
18import sys
19import datetime
20import inspect
21# For saving individual sections of data
22from sas.sascalc.dataloader.data_info import Data1D, Data2D, DataInfo, \
23    plottable_1D, plottable_2D
24from sas.sascalc.dataloader.data_info import Collimation, TransmissionSpectrum, \
25    Detector, Process, Aperture
26from sas.sascalc.dataloader.data_info import \
27    combine_data_info_with_plottable as combine_data
28import sas.sascalc.dataloader.readers.xml_reader as xml_reader
29from sas.sascalc.dataloader.readers.xml_reader import XMLreader
30from sas.sascalc.dataloader.readers.cansas_constants import CansasConstants, CurrentLevel
31
32# The following 2 imports *ARE* used. Do not remove either.
33import xml.dom.minidom
34from xml.dom.minidom import parseString
35
36PREPROCESS = "xmlpreprocess"
37ENCODING = "encoding"
38RUN_NAME_DEFAULT = "None"
39INVALID_SCHEMA_PATH_1_1 = "{0}/sas/sascalc/dataloader/readers/schema/cansas1d_invalid_v1_1.xsd"
40INVALID_SCHEMA_PATH_1_0 = "{0}/sas/sascalc/dataloader/readers/schema/cansas1d_invalid_v1_0.xsd"
41INVALID_XML = "\n\nThe loaded xml file, {0} does not fully meet the CanSAS v1.x specification. SasView loaded " + \
42              "as much of the data as possible.\n\n"
43HAS_CONVERTER = True
44try:
45    from sas.sascalc.data_util.nxsunit import Converter
46except ImportError:
47    HAS_CONVERTER = False
48
49CONSTANTS = CansasConstants()
50CANSAS_FORMAT = CONSTANTS.format
51CANSAS_NS = CONSTANTS.names
52ALLOW_ALL = True
53
54class Reader(XMLreader):
55    """
56    Class to load cansas 1D XML files
57
58    :Dependencies:
59        The CanSAS reader requires PyXML 0.8.4 or later.
60    """
61    # CanSAS version - defaults to version 1.0
62    cansas_version = "1.0"
63    base_ns = "{cansas1d/1.0}"
64    cansas_defaults = None
65    type_name = "canSAS"
66    invalid = True
67    frm = ""
68    # Log messages and errors
69    logging = None
70    errors = set()
71    # Namespace hierarchy for current xml_file object
72    names = None
73    ns_list = None
74    # Temporary storage location for loading multiple data sets in a single file
75    current_datainfo = None
76    current_dataset = None
77    current_data1d = None
78    data = None
79    # List of data1D objects to be sent back to SasView
80    output = None
81    # Wildcards
82    type = ["XML files (*.xml)|*.xml", "SasView Save Files (*.svs)|*.svs"]
83    # List of allowed extensions
84    ext = ['.xml', '.XML', '.svs', '.SVS']
85    # Flag to bypass extension check
86    allow_all = True
87
88    def reset_state(self):
89        """
90        Resets the class state to a base case when loading a new data file so previous
91        data files do not appear a second time
92        """
93        self.current_datainfo = None
94        self.current_dataset = None
95        self.current_data1d = None
96        self.data = []
97        self.process = Process()
98        self.transspectrum = TransmissionSpectrum()
99        self.aperture = Aperture()
100        self.collimation = Collimation()
101        self.detector = Detector()
102        self.names = []
103        self.cansas_defaults = {}
104        self.output = []
105        self.ns_list = None
106        self.logging = []
107        self.encoding = None
108
109    def read(self, xml_file, schema_path="", invalid=True):
110        """
111        Validate and read in an xml_file file in the canSAS format.
112
113        :param xml_file: A canSAS file path in proper XML format
114        :param schema_path: A file path to an XML schema to validate the xml_file against
115        """
116        # For every file loaded, reset everything to a base state
117        self.reset_state()
118        self.invalid = invalid
119        # Check that the file exists
120        if os.path.isfile(xml_file):
121            basename, extension = os.path.splitext(os.path.basename(xml_file))
122            # If the file type is not allowed, return nothing
123            if extension in self.ext or self.allow_all:
124                # Get the file location of
125                self.load_file_and_schema(xml_file, schema_path)
126                self.add_data_set()
127                # Try to load the file, but raise an error if unable to.
128                # Check the file matches the XML schema
129                try:
130                    self.is_cansas(extension)
131                    self.invalid = False
132                    # Get each SASentry from XML file and add it to a list.
133                    entry_list = self.xmlroot.xpath(
134                            '/ns:SASroot/ns:SASentry',
135                            namespaces={'ns': self.cansas_defaults.get("ns")})
136                    self.names.append("SASentry")
137
138                    # Get all preprocessing events and encoding
139                    self.set_processing_instructions()
140
141                    # Parse each <SASentry> item
142                    for entry in entry_list:
143                        # Create a new DataInfo object for every <SASentry>
144
145                        # Set the file name and then parse the entry.
146                        self.current_datainfo.filename = basename + extension
147                        self.current_datainfo.meta_data["loader"] = "CanSAS XML 1D"
148                        self.current_datainfo.meta_data[PREPROCESS] = \
149                            self.processing_instructions
150
151                        # Parse the XML SASentry
152                        self._parse_entry(entry)
153                        # Combine datasets with datainfo
154                        self.add_data_set()
155                except RuntimeError:
156                    # If the file does not match the schema, raise this error
157                    invalid_xml = self.find_invalid_xml()
158                    invalid_xml = INVALID_XML.format(basename + extension) + invalid_xml
159                    self.errors.add(invalid_xml)
160                    # Try again with an invalid CanSAS schema, that requires only a data set in each
161                    base_name = xml_reader.__file__
162                    base_name = base_name.replace("\\", "/")
163                    base = base_name.split("/sas/")[0]
164                    if self.cansas_version == "1.1":
165                        invalid_schema = INVALID_SCHEMA_PATH_1_1.format(base, self.cansas_defaults.get("schema"))
166                    else:
167                        invalid_schema = INVALID_SCHEMA_PATH_1_0.format(base, self.cansas_defaults.get("schema"))
168                    self.set_schema(invalid_schema)
169                    try:
170                        if self.invalid:
171                            if self.is_cansas():
172                                self.output = self.read(xml_file, invalid_schema, False)
173                            else:
174                                raise RuntimeError
175                        else:
176                            raise RuntimeError
177                    except RuntimeError:
178                        x = np.zeros(1)
179                        y = np.zeros(1)
180                        self.current_data1d = Data1D(x,y)
181                        self.current_data1d.errors = self.errors
182                        return [self.current_data1d]
183        else:
184            self.output.append("Not a valid file path.")
185        # Return a list of parsed entries that dataloader can manage
186        return self.output
187
188    def _parse_entry(self, dom, recurse=False):
189        """
190        Parse a SASEntry - new recursive method for parsing the dom of
191            the CanSAS data format. This will allow multiple data files
192            and extra nodes to be read in simultaneously.
193
194        :param dom: dom object with a namespace base of names
195        """
196
197        if not self._is_call_local() and not recurse:
198            self.reset_state()
199            self.add_data_set()
200            self.names.append("SASentry")
201            self.parent_class = "SASentry"
202        self._check_for_empty_data()
203        self.base_ns = "{0}{1}{2}".format("{", \
204                            CANSAS_NS.get(self.cansas_version).get("ns"), "}")
205
206        # Go through each child in the parent element
207        for node in dom:
208            attr = node.attrib
209            name = attr.get("name", "")
210            type = attr.get("type", "")
211            unit = attr.get("unit", "")
212            # Get the element name and set the current names level
213            tagname = node.tag.replace(self.base_ns, "")
214            tagname_original = tagname
215            # Skip this iteration when loading in save state information
216            if tagname == "fitting_plug_in" or tagname == "pr_inversion" or tagname == "invariant":
217                continue
218
219            # Get where to store content
220            self.names.append(tagname_original)
221            self.ns_list = CONSTANTS.iterate_namespace(self.names)
222            # If the element is a child element, recurse
223            if len(node.getchildren()) > 0:
224                self.parent_class = tagname_original
225                if tagname == 'SASdata':
226                    self._initialize_new_data_set(node)
227                    if isinstance(self.current_dataset, plottable_2D):
228                        x_bins = attr.get("x_bins", "")
229                        y_bins = attr.get("y_bins", "")
230                        if x_bins is not "" and y_bins is not "":
231                            self.current_dataset.shape = (x_bins, y_bins)
232                        else:
233                            self.current_dataset.shape = ()
234                # Recursion step to access data within the group
235                self._parse_entry(node, True)
236                if tagname == "SASsample":
237                    self.current_datainfo.sample.name = name
238                elif tagname == "beam_size":
239                    self.current_datainfo.source.beam_size_name = name
240                elif tagname == "SAScollimation":
241                    self.collimation.name = name
242                elif tagname == "aperture":
243                    self.aperture.name = name
244                    self.aperture.type = type
245                self.add_intermediate()
246            else:
247                if isinstance(self.current_dataset, plottable_2D):
248                    data_point = node.text
249                    unit = attr.get('unit', '')
250                else:
251                    data_point, unit = self._get_node_value(node)
252
253                # If this is a dataset, store the data appropriately
254                if tagname == 'Run':
255                    self.current_datainfo.run_name[data_point] = name
256                    self.current_datainfo.run.append(data_point)
257                elif tagname == 'Title':
258                    self.current_datainfo.title = data_point
259                elif tagname == 'SASnote':
260                    self.current_datainfo.notes.append(data_point)
261
262                # I and Q - 1D data
263                elif tagname == 'I' and isinstance(self.current_dataset, plottable_1D):
264                    unit_list = unit.split("|")
265                    if len(unit_list) > 1:
266                        self.current_dataset.yaxis(unit_list[0].strip(),
267                                                   unit_list[1].strip())
268                    else:
269                        self.current_dataset.yaxis("Intensity", unit)
270                    self.current_dataset.y = np.append(self.current_dataset.y, data_point)
271                elif tagname == 'Idev' and isinstance(self.current_dataset, plottable_1D):
272                    self.current_dataset.dy = np.append(self.current_dataset.dy, data_point)
273                elif tagname == 'Q':
274                    unit_list = unit.split("|")
275                    if len(unit_list) > 1:
276                        self.current_dataset.xaxis(unit_list[0].strip(),
277                                                   unit_list[1].strip())
278                    else:
279                        self.current_dataset.xaxis("Q", unit)
280                    self.current_dataset.x = np.append(self.current_dataset.x, data_point)
281                elif tagname == 'Qdev':
282                    self.current_dataset.dx = np.append(self.current_dataset.dx, data_point)
283                elif tagname == 'dQw':
284                    self.current_dataset.dxw = np.append(self.current_dataset.dxw, data_point)
285                elif tagname == 'dQl':
286                    self.current_dataset.dxl = np.append(self.current_dataset.dxl, data_point)
287                elif tagname == 'Qmean':
288                    pass
289                elif tagname == 'Shadowfactor':
290                    pass
291                elif tagname == 'Sesans':
292                    self.current_datainfo.isSesans = bool(data_point)
293                elif tagname == 'zacceptance':
294                    self.current_datainfo.sample.zacceptance = (data_point, unit)
295
296                # I and Qx, Qy - 2D data
297                elif tagname == 'I' and isinstance(self.current_dataset, plottable_2D):
298                    self.current_dataset.yaxis("Intensity", unit)
299                    self.current_dataset.data = np.fromstring(data_point, dtype=float, sep=",")
300                elif tagname == 'Idev' and isinstance(self.current_dataset, plottable_2D):
301                    self.current_dataset.err_data = np.fromstring(data_point, dtype=float, sep=",")
302                elif tagname == 'Qx':
303                    self.current_dataset.xaxis("Qx", unit)
304                    self.current_dataset.qx_data = np.fromstring(data_point, dtype=float, sep=",")
305                elif tagname == 'Qy':
306                    self.current_dataset.yaxis("Qy", unit)
307                    self.current_dataset.qy_data = np.fromstring(data_point, dtype=float, sep=",")
308                elif tagname == 'Qxdev':
309                    self.current_dataset.xaxis("Qxdev", unit)
310                    self.current_dataset.dqx_data = np.fromstring(data_point, dtype=float, sep=",")
311                elif tagname == 'Qydev':
312                    self.current_dataset.yaxis("Qydev", unit)
313                    self.current_dataset.dqy_data = np.fromstring(data_point, dtype=float, sep=",")
314                elif tagname == 'Mask':
315                    inter = [item == "1" for item in data_point.split(",")]
316                    self.current_dataset.mask = np.asarray(inter, dtype=bool)
317
318                # Sample Information
319                elif tagname == 'ID' and self.parent_class == 'SASsample':
320                    self.current_datainfo.sample.ID = data_point
321                elif tagname == 'Title' and self.parent_class == 'SASsample':
322                    self.current_datainfo.sample.name = data_point
323                elif tagname == 'thickness' and self.parent_class == 'SASsample':
324                    self.current_datainfo.sample.thickness = data_point
325                    self.current_datainfo.sample.thickness_unit = unit
326                elif tagname == 'transmission' and self.parent_class == 'SASsample':
327                    self.current_datainfo.sample.transmission = data_point
328                elif tagname == 'temperature' and self.parent_class == 'SASsample':
329                    self.current_datainfo.sample.temperature = data_point
330                    self.current_datainfo.sample.temperature_unit = unit
331                elif tagname == 'details' and self.parent_class == 'SASsample':
332                    self.current_datainfo.sample.details.append(data_point)
333                elif tagname == 'x' and self.parent_class == 'position':
334                    self.current_datainfo.sample.position.x = data_point
335                    self.current_datainfo.sample.position_unit = unit
336                elif tagname == 'y' and self.parent_class == 'position':
337                    self.current_datainfo.sample.position.y = data_point
338                    self.current_datainfo.sample.position_unit = unit
339                elif tagname == 'z' and self.parent_class == 'position':
340                    self.current_datainfo.sample.position.z = data_point
341                    self.current_datainfo.sample.position_unit = unit
342                elif tagname == 'roll' and self.parent_class == 'orientation' and 'SASsample' in self.names:
343                    self.current_datainfo.sample.orientation.x = data_point
344                    self.current_datainfo.sample.orientation_unit = unit
345                elif tagname == 'pitch' and self.parent_class == 'orientation' and 'SASsample' in self.names:
346                    self.current_datainfo.sample.orientation.y = data_point
347                    self.current_datainfo.sample.orientation_unit = unit
348                elif tagname == 'yaw' and self.parent_class == 'orientation' and 'SASsample' in self.names:
349                    self.current_datainfo.sample.orientation.z = data_point
350                    self.current_datainfo.sample.orientation_unit = unit
351
352                # Instrumental Information
353                elif tagname == 'name' and self.parent_class == 'SASinstrument':
354                    self.current_datainfo.instrument = data_point
355                # Detector Information
356                elif tagname == 'name' and self.parent_class == 'SASdetector':
357                    self.detector.name = data_point
358                elif tagname == 'SDD' and self.parent_class == 'SASdetector':
359                    self.detector.distance = data_point
360                    self.detector.distance_unit = unit
361                elif tagname == 'slit_length' and self.parent_class == 'SASdetector':
362                    self.detector.slit_length = data_point
363                    self.detector.slit_length_unit = unit
364                elif tagname == 'x' and self.parent_class == 'offset':
365                    self.detector.offset.x = data_point
366                    self.detector.offset_unit = unit
367                elif tagname == 'y' and self.parent_class == 'offset':
368                    self.detector.offset.y = data_point
369                    self.detector.offset_unit = unit
370                elif tagname == 'z' and self.parent_class == 'offset':
371                    self.detector.offset.z = data_point
372                    self.detector.offset_unit = unit
373                elif tagname == 'x' and self.parent_class == 'beam_center':
374                    self.detector.beam_center.x = data_point
375                    self.detector.beam_center_unit = unit
376                elif tagname == 'y' and self.parent_class == 'beam_center':
377                    self.detector.beam_center.y = data_point
378                    self.detector.beam_center_unit = unit
379                elif tagname == 'z' and self.parent_class == 'beam_center':
380                    self.detector.beam_center.z = data_point
381                    self.detector.beam_center_unit = unit
382                elif tagname == 'x' and self.parent_class == 'pixel_size':
383                    self.detector.pixel_size.x = data_point
384                    self.detector.pixel_size_unit = unit
385                elif tagname == 'y' and self.parent_class == 'pixel_size':
386                    self.detector.pixel_size.y = data_point
387                    self.detector.pixel_size_unit = unit
388                elif tagname == 'z' and self.parent_class == 'pixel_size':
389                    self.detector.pixel_size.z = data_point
390                    self.detector.pixel_size_unit = unit
391                elif tagname == 'roll' and self.parent_class == 'orientation' and 'SASdetector' in self.names:
392                    self.detector.orientation.x = data_point
393                    self.detector.orientation_unit = unit
394                elif tagname == 'pitch' and self.parent_class == 'orientation' and 'SASdetector' in self.names:
395                    self.detector.orientation.y = data_point
396                    self.detector.orientation_unit = unit
397                elif tagname == 'yaw' and self.parent_class == 'orientation' and 'SASdetector' in self.names:
398                    self.detector.orientation.z = data_point
399                    self.detector.orientation_unit = unit
400                # Collimation and Aperture
401                elif tagname == 'length' and self.parent_class == 'SAScollimation':
402                    self.collimation.length = data_point
403                    self.collimation.length_unit = unit
404                elif tagname == 'name' and self.parent_class == 'SAScollimation':
405                    self.collimation.name = data_point
406                elif tagname == 'distance' and self.parent_class == 'aperture':
407                    self.aperture.distance = data_point
408                    self.aperture.distance_unit = unit
409                elif tagname == 'x' and self.parent_class == 'size':
410                    self.aperture.size.x = data_point
411                    self.collimation.size_unit = unit
412                elif tagname == 'y' and self.parent_class == 'size':
413                    self.aperture.size.y = data_point
414                    self.collimation.size_unit = unit
415                elif tagname == 'z' and self.parent_class == 'size':
416                    self.aperture.size.z = data_point
417                    self.collimation.size_unit = unit
418
419                # Process Information
420                elif tagname == 'name' and self.parent_class == 'SASprocess':
421                    self.process.name = data_point
422                elif tagname == 'description' and self.parent_class == 'SASprocess':
423                    self.process.description = data_point
424                elif tagname == 'date' and self.parent_class == 'SASprocess':
425                    try:
426                        self.process.date = datetime.datetime.fromtimestamp(data_point)
427                    except:
428                        self.process.date = data_point
429                elif tagname == 'SASprocessnote':
430                    self.process.notes.append(data_point)
431                elif tagname == 'term' and self.parent_class == 'SASprocess':
432                    unit = attr.get("unit", "")
433                    dic = {}
434                    dic["name"] = name
435                    dic["value"] = data_point
436                    dic["unit"] = unit
437                    self.process.term.append(dic)
438
439                # Transmission Spectrum
440                elif tagname == 'T' and self.parent_class == 'Tdata':
441                    self.transspectrum.transmission = np.append(self.transspectrum.transmission, data_point)
442                    self.transspectrum.transmission_unit = unit
443                elif tagname == 'Tdev' and self.parent_class == 'Tdata':
444                    self.transspectrum.transmission_deviation = np.append(self.transspectrum.transmission_deviation, data_point)
445                    self.transspectrum.transmission_deviation_unit = unit
446                elif tagname == 'Lambda' and self.parent_class == 'Tdata':
447                    self.transspectrum.wavelength = np.append(self.transspectrum.wavelength, data_point)
448                    self.transspectrum.wavelength_unit = unit
449
450                # Source Information
451                elif tagname == 'wavelength' and (self.parent_class == 'SASsource' or self.parent_class == 'SASData'):
452                    self.current_datainfo.source.wavelength = data_point
453                    self.current_datainfo.source.wavelength_unit = unit
454                elif tagname == 'wavelength_min' and self.parent_class == 'SASsource':
455                    self.current_datainfo.source.wavelength_min = data_point
456                    self.current_datainfo.source.wavelength_min_unit = unit
457                elif tagname == 'wavelength_max' and self.parent_class == 'SASsource':
458                    self.current_datainfo.source.wavelength_max = data_point
459                    self.current_datainfo.source.wavelength_max_unit = unit
460                elif tagname == 'wavelength_spread' and self.parent_class == 'SASsource':
461                    self.current_datainfo.source.wavelength_spread = data_point
462                    self.current_datainfo.source.wavelength_spread_unit = unit
463                elif tagname == 'x' and self.parent_class == 'beam_size':
464                    self.current_datainfo.source.beam_size.x = data_point
465                    self.current_datainfo.source.beam_size_unit = unit
466                elif tagname == 'y' and self.parent_class == 'beam_size':
467                    self.current_datainfo.source.beam_size.y = data_point
468                    self.current_datainfo.source.beam_size_unit = unit
469                elif tagname == 'z' and self.parent_class == 'pixel_size':
470                    self.current_datainfo.source.data_point.z = data_point
471                    self.current_datainfo.source.beam_size_unit = unit
472                elif tagname == 'radiation' and self.parent_class == 'SASsource':
473                    self.current_datainfo.source.radiation = data_point
474                elif tagname == 'beam_shape' and self.parent_class == 'SASsource':
475                    self.current_datainfo.source.beam_shape = data_point
476
477                # Everything else goes in meta_data
478                else:
479                    new_key = self._create_unique_key(self.current_datainfo.meta_data, tagname)
480                    self.current_datainfo.meta_data[new_key] = data_point
481
482            self.names.remove(tagname_original)
483            length = 0
484            if len(self.names) > 1:
485                length = len(self.names) - 1
486            self.parent_class = self.names[length]
487        if not self._is_call_local() and not recurse:
488            self.frm = ""
489            self.add_data_set()
490            empty = None
491            return self.output[0], empty
492
493
494    def _is_call_local(self):
495        """
496
497        """
498        if self.frm == "":
499            inter = inspect.stack()
500            self.frm = inter[2]
501        mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "")
502        mod_name = mod_name.replace(".py", "")
503        mod = mod_name.split("sas/")
504        mod_name = mod[1]
505        if mod_name != "sascalc/dataloader/readers/cansas_reader":
506            return False
507        return True
508
509    def is_cansas(self, ext="xml"):
510        """
511        Checks to see if the xml file is a CanSAS file
512
513        :param ext: The file extension of the data file
514        """
515        if self.validate_xml():
516            name = "{http://www.w3.org/2001/XMLSchema-instance}schemaLocation"
517            value = self.xmlroot.get(name)
518            if CANSAS_NS.get(self.cansas_version).get("ns") == \
519                    value.rsplit(" ")[0]:
520                return True
521        if ext == "svs":
522            return True
523        raise RuntimeError
524
525    def load_file_and_schema(self, xml_file, schema_path=""):
526        """
527        Loads the file and associates a schema, if a schema is passed in or if one already exists
528
529        :param xml_file: The xml file path sent to Reader.read
530        :param schema_path: The path to a schema associated with the xml_file, or find one based on the file
531        """
532        base_name = xml_reader.__file__
533        base_name = base_name.replace("\\", "/")
534        base = base_name.split("/sas/")[0]
535
536        # Load in xml file and get the cansas version from the header
537        self.set_xml_file(xml_file)
538        self.cansas_version = self.xmlroot.get("version", "1.0")
539
540        # Generic values for the cansas file based on the version
541        self.cansas_defaults = CANSAS_NS.get(self.cansas_version, "1.0")
542        if schema_path == "":
543            schema_path = "{0}/sas/sascalc/dataloader/readers/schema/{1}".format \
544                (base, self.cansas_defaults.get("schema")).replace("\\", "/")
545
546        # Link a schema to the XML file.
547        self.set_schema(schema_path)
548
549    def add_data_set(self):
550        """
551        Adds the current_dataset to the list of outputs after preforming final processing on the data and then calls a
552        private method to generate a new data set.
553
554        :param key: NeXus group name for current tree level
555        """
556
557        if self.current_datainfo and self.current_dataset:
558            self._final_cleanup()
559        self.data = []
560        self.current_datainfo = DataInfo()
561
562    def _initialize_new_data_set(self, node=None):
563        """
564        A private class method to generate a new 1D data object.
565        Outside methods should call add_data_set() to be sure any existing data is stored properly.
566
567        :param node: XML node to determine if 1D or 2D data
568        """
569        x = np.array(0)
570        y = np.array(0)
571        for child in node:
572            if child.tag.replace(self.base_ns, "") == "Idata":
573                for i_child in child:
574                    if i_child.tag.replace(self.base_ns, "") == "Qx":
575                        self.current_dataset = plottable_2D()
576                        return
577        self.current_dataset = plottable_1D(x, y)
578
579    def add_intermediate(self):
580        """
581        This method stores any intermediate objects within the final data set after fully reading the set.
582
583        :param parent: The NXclass name for the h5py Group object that just finished being processed
584        """
585
586        if self.parent_class == 'SASprocess':
587            self.current_datainfo.process.append(self.process)
588            self.process = Process()
589        elif self.parent_class == 'SASdetector':
590            self.current_datainfo.detector.append(self.detector)
591            self.detector = Detector()
592        elif self.parent_class == 'SAStransmission_spectrum':
593            self.current_datainfo.trans_spectrum.append(self.transspectrum)
594            self.transspectrum = TransmissionSpectrum()
595        elif self.parent_class == 'SAScollimation':
596            self.current_datainfo.collimation.append(self.collimation)
597            self.collimation = Collimation()
598        elif self.parent_class == 'aperture':
599            self.collimation.aperture.append(self.aperture)
600            self.aperture = Aperture()
601        elif self.parent_class == 'SASdata':
602            self._check_for_empty_resolution()
603            self.data.append(self.current_dataset)
604
605    def _final_cleanup(self):
606        """
607        Final cleanup of the Data1D object to be sure it has all the
608        appropriate information needed for perspectives
609        """
610
611        # Append errors to dataset and reset class errors
612        self.current_datainfo.errors = set()
613        for error in self.errors:
614            self.current_datainfo.errors.add(error)
615        self.errors.clear()
616
617        # Combine all plottables with datainfo and append each to output
618        # Type cast data arrays to float64 and find min/max as appropriate
619        for dataset in self.data:
620            if isinstance(dataset, plottable_1D):
621                if dataset.x is not None:
622                    dataset.x = np.delete(dataset.x, [0])
623                    dataset.x = dataset.x.astype(np.float64)
624                    dataset.xmin = np.min(dataset.x)
625                    dataset.xmax = np.max(dataset.x)
626                if dataset.y is not None:
627                    dataset.y = np.delete(dataset.y, [0])
628                    dataset.y = dataset.y.astype(np.float64)
629                    dataset.ymin = np.min(dataset.y)
630                    dataset.ymax = np.max(dataset.y)
631                if dataset.dx is not None:
632                    dataset.dx = np.delete(dataset.dx, [0])
633                    dataset.dx = dataset.dx.astype(np.float64)
634                if dataset.dxl is not None:
635                    dataset.dxl = np.delete(dataset.dxl, [0])
636                    dataset.dxl = dataset.dxl.astype(np.float64)
637                if dataset.dxw is not None:
638                    dataset.dxw = np.delete(dataset.dxw, [0])
639                    dataset.dxw = dataset.dxw.astype(np.float64)
640                if dataset.dy is not None:
641                    dataset.dy = np.delete(dataset.dy, [0])
642                    dataset.dy = dataset.dy.astype(np.float64)
643                np.trim_zeros(dataset.x)
644                np.trim_zeros(dataset.y)
645                np.trim_zeros(dataset.dy)
646            elif isinstance(dataset, plottable_2D):
647                dataset.data = dataset.data.astype(np.float64)
648                dataset.qx_data = dataset.qx_data.astype(np.float64)
649                dataset.xmin = np.min(dataset.qx_data)
650                dataset.xmax = np.max(dataset.qx_data)
651                dataset.qy_data = dataset.qy_data.astype(np.float64)
652                dataset.ymin = np.min(dataset.qy_data)
653                dataset.ymax = np.max(dataset.qy_data)
654                dataset.q_data = np.sqrt(dataset.qx_data * dataset.qx_data
655                                         + dataset.qy_data * dataset.qy_data)
656                if dataset.err_data is not None:
657                    dataset.err_data = dataset.err_data.astype(np.float64)
658                if dataset.dqx_data is not None:
659                    dataset.dqx_data = dataset.dqx_data.astype(np.float64)
660                if dataset.dqy_data is not None:
661                    dataset.dqy_data = dataset.dqy_data.astype(np.float64)
662                if dataset.mask is not None:
663                    dataset.mask = dataset.mask.astype(dtype=bool)
664
665                if len(dataset.shape) == 2:
666                    n_rows, n_cols = dataset.shape
667                    dataset.y_bins = dataset.qy_data[0::int(n_cols)]
668                    dataset.x_bins = dataset.qx_data[:int(n_cols)]
669                    dataset.data = dataset.data.flatten()
670                else:
671                    dataset.y_bins = []
672                    dataset.x_bins = []
673                    dataset.data = dataset.data.flatten()
674
675            final_dataset = combine_data(dataset, self.current_datainfo)
676            self.output.append(final_dataset)
677
678    def _create_unique_key(self, dictionary, name, numb=0):
679        """
680        Create a unique key value for any dictionary to prevent overwriting
681        Recurse until a unique key value is found.
682
683        :param dictionary: A dictionary with any number of entries
684        :param name: The index of the item to be added to dictionary
685        :param numb: The number to be appended to the name, starts at 0
686        """
687        if dictionary.get(name) is not None:
688            numb += 1
689            name = name.split("_")[0]
690            name += "_{0}".format(numb)
691            name = self._create_unique_key(dictionary, name, numb)
692        return name
693
694    def _get_node_value_from_text(self, node, node_text):
695        """
696        Get the value of a node and any applicable units
697
698        :param node: The XML node to get the value of
699        :param tagname: The tagname of the node
700        """
701        units = ""
702        # If the value is a float, compile with units.
703        if self.ns_list.ns_datatype == "float":
704            # If an empty value is given, set as zero.
705            if node_text is None or node_text.isspace() \
706                    or node_text.lower() == "nan":
707                node_text = "0.0"
708            # Convert the value to the base units
709            tag = node.tag.replace(self.base_ns, "")
710            node_text, units = self._unit_conversion(node, tag, node_text)
711
712        # If the value is a timestamp, convert to a datetime object
713        elif self.ns_list.ns_datatype == "timestamp":
714            if node_text is None or node_text.isspace():
715                pass
716            else:
717                try:
718                    node_text = \
719                        datetime.datetime.fromtimestamp(node_text)
720                except ValueError:
721                    node_text = None
722        return node_text, units
723
724    def _get_node_value(self, node):
725        """
726        Get the value of a node and any applicable units
727
728        :param node: The XML node to get the value of
729        :param tagname: The tagname of the node
730        """
731        #Get the text from the node and convert all whitespace to spaces
732        units = ''
733        node_value = node.text
734        if node_value is not None:
735            node_value = ' '.join(node_value.split())
736        else:
737            node_value = ""
738        node_value, units = self._get_node_value_from_text(node, node_value)
739        return node_value, units
740
741    def _unit_conversion(self, node, tagname, node_value):
742        """
743        A unit converter method used to convert the data included in the file
744        to the default units listed in data_info
745
746        :param node: XML node
747        :param tagname: name of the node
748        :param node_value: The value of the current dom node
749        """
750        attr = node.attrib
751        value_unit = ''
752        err_msg = None
753        default_unit = None
754        if not isinstance(node_value, float):
755            node_value = float(node_value)
756        if 'unit' in attr and attr.get('unit') is not None:
757            try:
758                local_unit = attr['unit']
759                unitname = self.ns_list.current_level.get("unit", "")
760                if "SASdetector" in self.names:
761                    save_in = "detector"
762                elif "aperture" in self.names:
763                    save_in = "aperture"
764                elif "SAScollimation" in self.names:
765                    save_in = "collimation"
766                elif "SAStransmission_spectrum" in self.names:
767                    save_in = "transspectrum"
768                elif "SASdata" in self.names:
769                    x = np.zeros(1)
770                    y = np.zeros(1)
771                    self.current_data1d = Data1D(x, y)
772                    save_in = "current_data1d"
773                elif "SASsource" in self.names:
774                    save_in = "current_datainfo.source"
775                elif "SASsample" in self.names:
776                    save_in = "current_datainfo.sample"
777                elif "SASprocess" in self.names:
778                    save_in = "process"
779                else:
780                    save_in = "current_datainfo"
781                exec "default_unit = self.{0}.{1}".format(save_in, unitname)
782                if local_unit and default_unit and local_unit.lower() != default_unit.lower() \
783                        and local_unit.lower() != "none":
784                    if HAS_CONVERTER == True:
785                        # Check local units - bad units raise KeyError
786                        data_conv_q = Converter(local_unit)
787                        value_unit = default_unit
788                        node_value = data_conv_q(node_value, units=default_unit)
789                    else:
790                        value_unit = local_unit
791                        err_msg = "Unit converter is not available.\n"
792                else:
793                    value_unit = local_unit
794            except KeyError:
795                err_msg = "CanSAS reader: unexpected "
796                err_msg += "\"{0}\" unit [{1}]; "
797                err_msg = err_msg.format(tagname, local_unit)
798                err_msg += "expecting [{0}]".format(default_unit)
799                value_unit = local_unit
800            except:
801                err_msg = "CanSAS reader: unknown error converting "
802                err_msg += "\"{0}\" unit [{1}]"
803                err_msg = err_msg.format(tagname, local_unit)
804                value_unit = local_unit
805        elif 'unit' in attr:
806            value_unit = attr['unit']
807        if err_msg:
808            self.errors.add(err_msg)
809        return node_value, value_unit
810
811    def _check_for_empty_data(self):
812        """
813        Creates an empty data set if no data is passed to the reader
814
815        :param data1d: presumably a Data1D object
816        """
817        if self.current_dataset == None:
818            x_vals = np.empty(0)
819            y_vals = np.empty(0)
820            dx_vals = np.empty(0)
821            dy_vals = np.empty(0)
822            dxl = np.empty(0)
823            dxw = np.empty(0)
824            self.current_dataset = plottable_1D(x_vals, y_vals, dx_vals, dy_vals)
825            self.current_dataset.dxl = dxl
826            self.current_dataset.dxw = dxw
827
828    def _check_for_empty_resolution(self):
829        """
830        A method to check all resolution data sets are the same size as I and Q
831        """
832        if isinstance(self.current_dataset, plottable_1D):
833            dql_exists = False
834            dqw_exists = False
835            dq_exists = False
836            di_exists = False
837            if self.current_dataset.dxl is not None:
838                dql_exists = True
839            if self.current_dataset.dxw is not None:
840                dqw_exists = True
841            if self.current_dataset.dx is not None:
842                dq_exists = True
843            if self.current_dataset.dy is not None:
844                di_exists = True
845            if dqw_exists and not dql_exists:
846                array_size = self.current_dataset.dxw.size - 1
847                self.current_dataset.dxl = np.append(self.current_dataset.dxl,
848                                                     np.zeros([array_size]))
849            elif dql_exists and not dqw_exists:
850                array_size = self.current_dataset.dxl.size - 1
851                self.current_dataset.dxw = np.append(self.current_dataset.dxw,
852                                                     np.zeros([array_size]))
853            elif not dql_exists and not dqw_exists and not dq_exists:
854                array_size = self.current_dataset.x.size - 1
855                self.current_dataset.dx = np.append(self.current_dataset.dx,
856                                                    np.zeros([array_size]))
857            if not di_exists:
858                array_size = self.current_dataset.y.size - 1
859                self.current_dataset.dy = np.append(self.current_dataset.dy,
860                                                    np.zeros([array_size]))
861        elif isinstance(self.current_dataset, plottable_2D):
862            dqx_exists = False
863            dqy_exists = False
864            di_exists = False
865            mask_exists = False
866            if self.current_dataset.dqx_data is not None:
867                dqx_exists = True
868            if self.current_dataset.dqy_data is not None:
869                dqy_exists = True
870            if self.current_dataset.err_data is not None:
871                di_exists = True
872            if self.current_dataset.mask is not None:
873                mask_exists = True
874            if not dqy_exists:
875                array_size = self.current_dataset.qy_data.size - 1
876                self.current_dataset.dqy_data = np.append(
877                    self.current_dataset.dqy_data, np.zeros([array_size]))
878            if not dqx_exists:
879                array_size = self.current_dataset.qx_data.size - 1
880                self.current_dataset.dqx_data = np.append(
881                    self.current_dataset.dqx_data, np.zeros([array_size]))
882            if not di_exists:
883                array_size = self.current_dataset.data.size - 1
884                self.current_dataset.err_data = np.append(
885                    self.current_dataset.err_data, np.zeros([array_size]))
886            if not mask_exists:
887                array_size = self.current_dataset.data.size - 1
888                self.current_dataset.mask = np.append(
889                    self.current_dataset.mask,
890                    np.ones([array_size] ,dtype=bool))
891
892    ####### All methods below are for writing CanSAS XML files #######
893
894    def write(self, filename, datainfo):
895        """
896        Write the content of a Data1D as a CanSAS XML file
897
898        :param filename: name of the file to write
899        :param datainfo: Data1D object
900        """
901        # Create XML document
902        doc, _ = self._to_xml_doc(datainfo)
903        # Write the file
904        file_ref = open(filename, 'w')
905        if self.encoding == None:
906            self.encoding = "UTF-8"
907        doc.write(file_ref, encoding=self.encoding,
908                  pretty_print=True, xml_declaration=True)
909        file_ref.close()
910
911    def _to_xml_doc(self, datainfo):
912        """
913        Create an XML document to contain the content of a Data1D
914
915        :param datainfo: Data1D object
916        """
917        is_2d = False
918        if issubclass(datainfo.__class__, Data2D):
919            is_2d = True
920
921        # Get PIs and create root element
922        pi_string = self._get_pi_string()
923        # Define namespaces and create SASroot object
924        main_node = self._create_main_node()
925        # Create ElementTree, append SASroot and apply processing instructions
926        base_string = pi_string + self.to_string(main_node)
927        base_element = self.create_element_from_string(base_string)
928        doc = self.create_tree(base_element)
929        # Create SASentry Element
930        entry_node = self.create_element("SASentry")
931        root = doc.getroot()
932        root.append(entry_node)
933
934        # Add Title to SASentry
935        self.write_node(entry_node, "Title", datainfo.title)
936        # Add Run to SASentry
937        self._write_run_names(datainfo, entry_node)
938        # Add Data info to SASEntry
939        if is_2d:
940            self._write_data_2d(datainfo, entry_node)
941        else:
942            if self._check_root():
943                self._write_data(datainfo, entry_node)
944            else:
945                self._write_data_linearized(datainfo, entry_node)
946        # Transmission Spectrum Info
947        # TODO: fix the writer to linearize all data, including T_spectrum
948        # self._write_trans_spectrum(datainfo, entry_node)
949        # Sample info
950        self._write_sample_info(datainfo, entry_node)
951        # Instrument info
952        instr = self._write_instrument(datainfo, entry_node)
953        #   Source
954        self._write_source(datainfo, instr)
955        #   Collimation
956        self._write_collimation(datainfo, instr)
957        #   Detectors
958        self._write_detectors(datainfo, instr)
959        # Processes info
960        self._write_process_notes(datainfo, entry_node)
961        # Note info
962        self._write_notes(datainfo, entry_node)
963        # Return the document, and the SASentry node associated with
964        #      the data we just wrote
965        # If the calling function was not the cansas reader, return a minidom
966        #      object rather than an lxml object.
967        self.frm = inspect.stack()[1]
968        doc, entry_node = self._check_origin(entry_node, doc)
969        return doc, entry_node
970
971    def write_node(self, parent, name, value, attr=None):
972        """
973        :param doc: document DOM
974        :param parent: parent node
975        :param name: tag of the element
976        :param value: value of the child text node
977        :param attr: attribute dictionary
978
979        :return: True if something was appended, otherwise False
980        """
981        if value is not None:
982            parent = self.ebuilder(parent, name, value, attr)
983            return True
984        return False
985
986    def _get_pi_string(self):
987        """
988        Creates the processing instructions header for writing to file
989        """
990        pis = self.return_processing_instructions()
991        if len(pis) > 0:
992            pi_tree = self.create_tree(pis[0])
993            i = 1
994            for i in range(1, len(pis) - 1):
995                pi_tree = self.append(pis[i], pi_tree)
996            pi_string = self.to_string(pi_tree)
997        else:
998            pi_string = ""
999        return pi_string
1000
1001    def _create_main_node(self):
1002        """
1003        Creates the primary xml header used when writing to file
1004        """
1005        xsi = "http://www.w3.org/2001/XMLSchema-instance"
1006        version = self.cansas_version
1007        n_s = CANSAS_NS.get(version).get("ns")
1008        if version == "1.1":
1009            url = "http://www.cansas.org/formats/1.1/"
1010        else:
1011            url = "http://www.cansas.org/formats/1.0/"
1012        schema_location = "{0} {1}cansas1d.xsd".format(n_s, url)
1013        attrib = {"{" + xsi + "}schemaLocation" : schema_location,
1014                  "version" : version}
1015        nsmap = {'xsi' : xsi, None: n_s}
1016
1017        main_node = self.create_element("{" + n_s + "}SASroot",
1018                                        attrib=attrib, nsmap=nsmap)
1019        return main_node
1020
1021    def _write_run_names(self, datainfo, entry_node):
1022        """
1023        Writes the run names to the XML file
1024
1025        :param datainfo: The Data1D object the information is coming from
1026        :param entry_node: lxml node ElementTree object to be appended to
1027        """
1028        if datainfo.run == None or datainfo.run == []:
1029            datainfo.run.append(RUN_NAME_DEFAULT)
1030            datainfo.run_name[RUN_NAME_DEFAULT] = RUN_NAME_DEFAULT
1031        for item in datainfo.run:
1032            runname = {}
1033            if item in datainfo.run_name and \
1034            len(str(datainfo.run_name[item])) > 1:
1035                runname = {'name': datainfo.run_name[item]}
1036            self.write_node(entry_node, "Run", item, runname)
1037
1038    def _write_data(self, datainfo, entry_node):
1039        """
1040        Writes 1D I and Q data to the XML file
1041
1042        :param datainfo: The Data1D object the information is coming from
1043        :param entry_node: lxml node ElementTree object to be appended to
1044        """
1045        node = self.create_element("SASdata")
1046        self.append(node, entry_node)
1047
1048        for i in range(len(datainfo.x)):
1049            point = self.create_element("Idata")
1050            node.append(point)
1051            self.write_node(point, "Q", datainfo.x[i],
1052                            {'unit': datainfo._xaxis + " | " + datainfo._xunit})
1053            if len(datainfo.y) >= i:
1054                self.write_node(point, "I", datainfo.y[i],
1055                                {'unit': datainfo._yaxis + " | " + datainfo._yunit})
1056            if datainfo.dy is not None and len(datainfo.dy) > i:
1057                self.write_node(point, "Idev", datainfo.dy[i],
1058                                {'unit': datainfo._yaxis + " | " + datainfo._yunit})
1059            if datainfo.dx is not None and len(datainfo.dx) > i:
1060                self.write_node(point, "Qdev", datainfo.dx[i],
1061                                {'unit': datainfo._xaxis + " | " + datainfo._xunit})
1062            if datainfo.dxw is not None and len(datainfo.dxw) > i:
1063                self.write_node(point, "dQw", datainfo.dxw[i],
1064                                {'unit': datainfo._xaxis + " | " + datainfo._xunit})
1065            if datainfo.dxl is not None and len(datainfo.dxl) > i:
1066                self.write_node(point, "dQl", datainfo.dxl[i],
1067                                {'unit': datainfo._xaxis + " | " + datainfo._xunit})
1068        if datainfo.isSesans:
1069            sesans = self.create_element("Sesans")
1070            sesans.text = str(datainfo.isSesans)
1071            node.append(sesans)
1072            self.write_node(node, "zacceptance", datainfo.sample.zacceptance[0],
1073                             {'unit': datainfo.sample.zacceptance[1]})
1074
1075
1076    def _write_data_2d(self, datainfo, entry_node):
1077        """
1078        Writes 2D data to the XML file
1079
1080        :param datainfo: The Data2D object the information is coming from
1081        :param entry_node: lxml node ElementTree object to be appended to
1082        """
1083        attr = {}
1084        if datainfo.data.shape:
1085            attr["x_bins"] = str(len(datainfo.x_bins))
1086            attr["y_bins"] = str(len(datainfo.y_bins))
1087        node = self.create_element("SASdata", attr)
1088        self.append(node, entry_node)
1089
1090        point = self.create_element("Idata")
1091        node.append(point)
1092        qx = ','.join([str(datainfo.qx_data[i]) for i in xrange(len(datainfo.qx_data))])
1093        qy = ','.join([str(datainfo.qy_data[i]) for i in xrange(len(datainfo.qy_data))])
1094        intensity = ','.join([str(datainfo.data[i]) for i in xrange(len(datainfo.data))])
1095
1096        self.write_node(point, "Qx", qx,
1097                        {'unit': datainfo._xunit})
1098        self.write_node(point, "Qy", qy,
1099                        {'unit': datainfo._yunit})
1100        self.write_node(point, "I", intensity,
1101                        {'unit': datainfo._zunit})
1102        if datainfo.err_data is not None:
1103            err = ','.join([str(datainfo.err_data[i]) for i in
1104                            xrange(len(datainfo.err_data))])
1105            self.write_node(point, "Idev", err,
1106                            {'unit': datainfo._zunit})
1107        if datainfo.dqy_data is not None:
1108            dqy = ','.join([str(datainfo.dqy_data[i]) for i in
1109                            xrange(len(datainfo.dqy_data))])
1110            self.write_node(point, "Qydev", dqy,
1111                            {'unit': datainfo._yunit})
1112        if datainfo.dqx_data is not None:
1113            dqx = ','.join([str(datainfo.dqx_data[i]) for i in
1114                            xrange(len(datainfo.dqx_data))])
1115            self.write_node(point, "Qxdev", dqx,
1116                            {'unit': datainfo._xunit})
1117        if datainfo.mask is not None:
1118            mask = ','.join(
1119                ["1" if datainfo.mask[i] else "0"
1120                 for i in xrange(len(datainfo.mask))])
1121            self.write_node(point, "Mask", mask)
1122
1123    def _write_trans_spectrum(self, datainfo, entry_node):
1124        """
1125        Writes the transmission spectrum data to the XML file
1126
1127        :param datainfo: The Data1D object the information is coming from
1128        :param entry_node: lxml node ElementTree object to be appended to
1129        """
1130        for i in range(len(datainfo.trans_spectrum)):
1131            spectrum = datainfo.trans_spectrum[i]
1132            node = self.create_element("SAStransmission_spectrum",
1133                                       {"name" : spectrum.name})
1134            self.append(node, entry_node)
1135            if isinstance(spectrum.timestamp, datetime.datetime):
1136                node.setAttribute("timestamp", spectrum.timestamp)
1137            for i in range(len(spectrum.wavelength)):
1138                point = self.create_element("Tdata")
1139                node.append(point)
1140                self.write_node(point, "Lambda", spectrum.wavelength[i],
1141                                {'unit': spectrum.wavelength_unit})
1142                self.write_node(point, "T", spectrum.transmission[i],
1143                                {'unit': spectrum.transmission_unit})
1144                if spectrum.transmission_deviation != None \
1145                and len(spectrum.transmission_deviation) >= i:
1146                    self.write_node(point, "Tdev",
1147                                    spectrum.transmission_deviation[i],
1148                                    {'unit':
1149                                     spectrum.transmission_deviation_unit})
1150
1151    def _write_sample_info(self, datainfo, entry_node):
1152        """
1153        Writes the sample information to the XML file
1154
1155        :param datainfo: The Data1D object the information is coming from
1156        :param entry_node: lxml node ElementTree object to be appended to
1157        """
1158        sample = self.create_element("SASsample")
1159        if datainfo.sample.name is not None:
1160            self.write_attribute(sample, "name",
1161                                 str(datainfo.sample.name))
1162        self.append(sample, entry_node)
1163        self.write_node(sample, "ID", str(datainfo.sample.ID))
1164        self.write_node(sample, "thickness", datainfo.sample.thickness,
1165                        {"unit": datainfo.sample.thickness_unit})
1166        self.write_node(sample, "transmission", datainfo.sample.transmission)
1167        self.write_node(sample, "temperature", datainfo.sample.temperature,
1168                        {"unit": datainfo.sample.temperature_unit})
1169
1170        pos = self.create_element("position")
1171        written = self.write_node(pos,
1172                                  "x",
1173                                  datainfo.sample.position.x,
1174                                  {"unit": datainfo.sample.position_unit})
1175        written = written | self.write_node( \
1176            pos, "y", datainfo.sample.position.y,
1177            {"unit": datainfo.sample.position_unit})
1178        written = written | self.write_node( \
1179            pos, "z", datainfo.sample.position.z,
1180            {"unit": datainfo.sample.position_unit})
1181        if written == True:
1182            self.append(pos, sample)
1183
1184        ori = self.create_element("orientation")
1185        written = self.write_node(ori, "roll",
1186                                  datainfo.sample.orientation.x,
1187                                  {"unit": datainfo.sample.orientation_unit})
1188        written = written | self.write_node( \
1189            ori, "pitch", datainfo.sample.orientation.y,
1190            {"unit": datainfo.sample.orientation_unit})
1191        written = written | self.write_node( \
1192            ori, "yaw", datainfo.sample.orientation.z,
1193            {"unit": datainfo.sample.orientation_unit})
1194        if written == True:
1195            self.append(ori, sample)
1196
1197        for item in datainfo.sample.details:
1198            self.write_node(sample, "details", item)
1199
1200    def _write_instrument(self, datainfo, entry_node):
1201        """
1202        Writes the instrumental information to the XML file
1203
1204        :param datainfo: The Data1D object the information is coming from
1205        :param entry_node: lxml node ElementTree object to be appended to
1206        """
1207        instr = self.create_element("SASinstrument")
1208        self.append(instr, entry_node)
1209        self.write_node(instr, "name", datainfo.instrument)
1210        return instr
1211
1212    def _write_source(self, datainfo, instr):
1213        """
1214        Writes the source information to the XML file
1215
1216        :param datainfo: The Data1D object the information is coming from
1217        :param instr: instrument node  to be appended to
1218        """
1219        source = self.create_element("SASsource")
1220        if datainfo.source.name is not None:
1221            self.write_attribute(source, "name",
1222                                 str(datainfo.source.name))
1223        self.append(source, instr)
1224        if datainfo.source.radiation == None or datainfo.source.radiation == '':
1225            datainfo.source.radiation = "neutron"
1226        self.write_node(source, "radiation", datainfo.source.radiation)
1227
1228        size = self.create_element("beam_size")
1229        if datainfo.source.beam_size_name is not None:
1230            self.write_attribute(size, "name",
1231                                 str(datainfo.source.beam_size_name))
1232        written = self.write_node( \
1233            size, "x", datainfo.source.beam_size.x,
1234            {"unit": datainfo.source.beam_size_unit})
1235        written = written | self.write_node( \
1236            size, "y", datainfo.source.beam_size.y,
1237            {"unit": datainfo.source.beam_size_unit})
1238        written = written | self.write_node( \
1239            size, "z", datainfo.source.beam_size.z,
1240            {"unit": datainfo.source.beam_size_unit})
1241        if written == True:
1242            self.append(size, source)
1243
1244        self.write_node(source, "beam_shape", datainfo.source.beam_shape)
1245        self.write_node(source, "wavelength",
1246                        datainfo.source.wavelength,
1247                        {"unit": datainfo.source.wavelength_unit})
1248        self.write_node(source, "wavelength_min",
1249                        datainfo.source.wavelength_min,
1250                        {"unit": datainfo.source.wavelength_min_unit})
1251        self.write_node(source, "wavelength_max",
1252                        datainfo.source.wavelength_max,
1253                        {"unit": datainfo.source.wavelength_max_unit})
1254        self.write_node(source, "wavelength_spread",
1255                        datainfo.source.wavelength_spread,
1256                        {"unit": datainfo.source.wavelength_spread_unit})
1257
1258    def _write_collimation(self, datainfo, instr):
1259        """
1260        Writes the collimation information to the XML file
1261
1262        :param datainfo: The Data1D object the information is coming from
1263        :param instr: lxml node ElementTree object to be appended to
1264        """
1265        if datainfo.collimation == [] or datainfo.collimation == None:
1266            coll = Collimation()
1267            datainfo.collimation.append(coll)
1268        for item in datainfo.collimation:
1269            coll = self.create_element("SAScollimation")
1270            if item.name is not None:
1271                self.write_attribute(coll, "name", str(item.name))
1272            self.append(coll, instr)
1273
1274            self.write_node(coll, "length", item.length,
1275                            {"unit": item.length_unit})
1276
1277            for aperture in item.aperture:
1278                apert = self.create_element("aperture")
1279                if aperture.name is not None:
1280                    self.write_attribute(apert, "name", str(aperture.name))
1281                if aperture.type is not None:
1282                    self.write_attribute(apert, "type", str(aperture.type))
1283                self.append(apert, coll)
1284
1285                size = self.create_element("size")
1286                if aperture.size_name is not None:
1287                    self.write_attribute(size, "name",
1288                                         str(aperture.size_name))
1289                written = self.write_node(size, "x", aperture.size.x,
1290                                          {"unit": aperture.size_unit})
1291                written = written | self.write_node( \
1292                    size, "y", aperture.size.y,
1293                    {"unit": aperture.size_unit})
1294                written = written | self.write_node( \
1295                    size, "z", aperture.size.z,
1296                    {"unit": aperture.size_unit})
1297                if written == True:
1298                    self.append(size, apert)
1299
1300                self.write_node(apert, "distance", aperture.distance,
1301                                {"unit": aperture.distance_unit})
1302
1303    def _write_detectors(self, datainfo, instr):
1304        """
1305        Writes the detector information to the XML file
1306
1307        :param datainfo: The Data1D object the information is coming from
1308        :param inst: lxml instrument node to be appended to
1309        """
1310        if datainfo.detector == None or datainfo.detector == []:
1311            det = Detector()
1312            det.name = ""
1313            datainfo.detector.append(det)
1314
1315        for item in datainfo.detector:
1316            det = self.create_element("SASdetector")
1317            written = self.write_node(det, "name", item.name)
1318            written = written | self.write_node(det, "SDD", item.distance,
1319                                                {"unit": item.distance_unit})
1320            if written == True:
1321                self.append(det, instr)
1322
1323            off = self.create_element("offset")
1324            written = self.write_node(off, "x", item.offset.x,
1325                                      {"unit": item.offset_unit})
1326            written = written | self.write_node(off, "y", item.offset.y,
1327                                                {"unit": item.offset_unit})
1328            written = written | self.write_node(off, "z", item.offset.z,
1329                                                {"unit": item.offset_unit})
1330            if written == True:
1331                self.append(off, det)
1332
1333            ori = self.create_element("orientation")
1334            written = self.write_node(ori, "roll", item.orientation.x,
1335                                      {"unit": item.orientation_unit})
1336            written = written | self.write_node(ori, "pitch",
1337                                                item.orientation.y,
1338                                                {"unit": item.orientation_unit})
1339            written = written | self.write_node(ori, "yaw",
1340                                                item.orientation.z,
1341                                                {"unit": item.orientation_unit})
1342            if written == True:
1343                self.append(ori, det)
1344
1345            center = self.create_element("beam_center")
1346            written = self.write_node(center, "x", item.beam_center.x,
1347                                      {"unit": item.beam_center_unit})
1348            written = written | self.write_node(center, "y",
1349                                                item.beam_center.y,
1350                                                {"unit": item.beam_center_unit})
1351            written = written | self.write_node(center, "z",
1352                                                item.beam_center.z,
1353                                                {"unit": item.beam_center_unit})
1354            if written == True:
1355                self.append(center, det)
1356
1357            pix = self.create_element("pixel_size")
1358            written = self.write_node(pix, "x", item.pixel_size.x,
1359                                      {"unit": item.pixel_size_unit})
1360            written = written | self.write_node(pix, "y", item.pixel_size.y,
1361                                                {"unit": item.pixel_size_unit})
1362            written = written | self.write_node(pix, "z", item.pixel_size.z,
1363                                                {"unit": item.pixel_size_unit})
1364            if written == True:
1365                self.append(pix, det)
1366            self.write_node(det, "slit_length", item.slit_length,
1367                {"unit": item.slit_length_unit})
1368
1369    def _write_process_notes(self, datainfo, entry_node):
1370        """
1371        Writes the process notes to the XML file
1372
1373        :param datainfo: The Data1D object the information is coming from
1374        :param entry_node: lxml node ElementTree object to be appended to
1375
1376        """
1377        for item in datainfo.process:
1378            node = self.create_element("SASprocess")
1379            self.append(node, entry_node)
1380            self.write_node(node, "name", item.name)
1381            self.write_node(node, "date", item.date)
1382            self.write_node(node, "description", item.description)
1383            for term in item.term:
1384                if isinstance(term, list):
1385                    value = term['value']
1386                    del term['value']
1387                elif isinstance(term, dict):
1388                    value = term.get("value")
1389                    del term['value']
1390                else:
1391                    value = term
1392                self.write_node(node, "term", value, term)
1393            for note in item.notes:
1394                self.write_node(node, "SASprocessnote", note)
1395            if len(item.notes) == 0:
1396                self.write_node(node, "SASprocessnote", "")
1397
1398    def _write_notes(self, datainfo, entry_node):
1399        """
1400        Writes the notes to the XML file and creates an empty note if none
1401        exist
1402
1403        :param datainfo: The Data1D object the information is coming from
1404        :param entry_node: lxml node ElementTree object to be appended to
1405
1406        """
1407        if len(datainfo.notes) == 0:
1408            node = self.create_element("SASnote")
1409            self.append(node, entry_node)
1410        else:
1411            for item in datainfo.notes:
1412                node = self.create_element("SASnote")
1413                self.write_text(node, item)
1414                self.append(node, entry_node)
1415
1416    def _check_root(self):
1417        """
1418        Return the document, and the SASentry node associated with
1419        the data we just wrote.
1420        If the calling function was not the cansas reader, return a minidom
1421        object rather than an lxml object.
1422
1423        :param entry_node: lxml node ElementTree object to be appended to
1424        :param doc: entire xml tree
1425        """
1426        if not self.frm:
1427            self.frm = inspect.stack()[2]
1428        mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "")
1429        mod_name = mod_name.replace(".py", "")
1430        mod = mod_name.split("sas/")
1431        mod_name = mod[1]
1432        return mod_name == "sascalc/dataloader/readers/cansas_reader"
1433
1434    def _check_origin(self, entry_node, doc):
1435        """
1436        Return the document, and the SASentry node associated with
1437        the data we just wrote.
1438        If the calling function was not the cansas reader, return a minidom
1439        object rather than an lxml object.
1440
1441        :param entry_node: lxml node ElementTree object to be appended to
1442        :param doc: entire xml tree
1443        """
1444        if not self._check_root():
1445            string = self.to_string(doc, pretty_print=False)
1446            doc = parseString(string)
1447            node_name = entry_node.tag
1448            node_list = doc.getElementsByTagName(node_name)
1449            entry_node = node_list.item(0)
1450        return doc, entry_node
1451
1452    # DO NOT REMOVE - used in saving and loading panel states.
1453    def _store_float(self, location, node, variable, storage, optional=True):
1454        """
1455        Get the content of a xpath location and store
1456        the result. Check that the units are compatible
1457        with the destination. The value is expected to
1458        be a float.
1459
1460        The xpath location might or might not exist.
1461        If it does not exist, nothing is done
1462
1463        :param location: xpath location to fetch
1464        :param node: node to read the data from
1465        :param variable: name of the data member to store it in [string]
1466        :param storage: data object that has the 'variable' data member
1467        :param optional: if True, no exception will be raised
1468            if unit conversion can't be done
1469
1470        :raise ValueError: raised when the units are not recognized
1471        """
1472        entry = get_content(location, node)
1473        try:
1474            value = float(entry.text)
1475        except:
1476            value = None
1477
1478        if value is not None:
1479            # If the entry has units, check to see that they are
1480            # compatible with what we currently have in the data object
1481            units = entry.get('unit')
1482            if units is not None:
1483                toks = variable.split('.')
1484                local_unit = None
1485                exec "local_unit = storage.%s_unit" % toks[0]
1486                if local_unit != None and units.lower() != local_unit.lower():
1487                    if HAS_CONVERTER == True:
1488                        try:
1489                            conv = Converter(units)
1490                            exec "storage.%s = %g" % \
1491                                (variable, conv(value, units=local_unit))
1492                        except:
1493                            _, exc_value, _ = sys.exc_info()
1494                            err_mess = "CanSAS reader: could not convert"
1495                            err_mess += " %s unit [%s]; expecting [%s]\n  %s" \
1496                                % (variable, units, local_unit, exc_value)
1497                            self.errors.add(err_mess)
1498                            if optional:
1499                                logging.info(err_mess)
1500                            else:
1501                                raise ValueError, err_mess
1502                    else:
1503                        err_mess = "CanSAS reader: unrecognized %s unit [%s];"\
1504                        % (variable, units)
1505                        err_mess += " expecting [%s]" % local_unit
1506                        self.errors.add(err_mess)
1507                        if optional:
1508                            logging.info(err_mess)
1509                        else:
1510                            raise ValueError, err_mess
1511                else:
1512                    exec "storage.%s = value" % variable
1513            else:
1514                exec "storage.%s = value" % variable
1515
1516    # DO NOT REMOVE - used in saving and loading panel states.
1517    def _store_content(self, location, node, variable, storage):
1518        """
1519        Get the content of a xpath location and store
1520        the result. The value is treated as a string.
1521
1522        The xpath location might or might not exist.
1523        If it does not exist, nothing is done
1524
1525        :param location: xpath location to fetch
1526        :param node: node to read the data from
1527        :param variable: name of the data member to store it in [string]
1528        :param storage: data object that has the 'variable' data member
1529
1530        :return: return a list of errors
1531        """
1532        entry = get_content(location, node)
1533        if entry is not None and entry.text is not None:
1534            exec "storage.%s = entry.text.strip()" % variable
1535
1536
1537# DO NOT REMOVE Called by outside packages:
1538#    sas.sasgui.perspectives.invariant.invariant_state
1539#    sas.sasgui.perspectives.fitting.pagestate
1540def get_content(location, node):
1541    """
1542    Get the first instance of the content of a xpath location.
1543
1544    :param location: xpath location
1545    :param node: node to start at
1546
1547    :return: Element, or None
1548    """
1549    nodes = node.xpath(location,
1550                       namespaces={'ns': CANSAS_NS.get("1.0").get("ns")})
1551    if len(nodes) > 0:
1552        return nodes[0]
1553    else:
1554        return None
1555
1556# DO NOT REMOVE Called by outside packages:
1557#    sas.sasgui.perspectives.fitting.pagestate
1558def write_node(doc, parent, name, value, attr=None):
1559    """
1560    :param doc: document DOM
1561    :param parent: parent node
1562    :param name: tag of the element
1563    :param value: value of the child text node
1564    :param attr: attribute dictionary
1565
1566    :return: True if something was appended, otherwise False
1567    """
1568    if attr is None:
1569        attr = {}
1570    if value is not None:
1571        node = doc.createElement(name)
1572        node.appendChild(doc.createTextNode(str(value)))
1573        for item in attr:
1574            node.setAttribute(item, attr[item])
1575        parent.appendChild(node)
1576        return True
1577    return False
Note: See TracBrowser for help on using the repository browser.