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

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.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since c221349 was c221349, checked in by krzywon, 7 years ago

Split unit axis and label on "|" and then strip whitespace.

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