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

ESS_GUIESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_opencl
Last change on this file since 12dfce6 was 1078936c, checked in by Piotr Rozyczko <piotr.rozyczko@…>, 5 years ago

Cherry picking from ticket-1243 branch in master

  • Property mode set to 100644
File size: 61.1 KB
Line 
1import logging
2import os
3import sys
4import datetime
5import inspect
6
7import numpy as np
8
9# The following 2 imports *ARE* used. Do not remove either.
10import xml.dom.minidom
11from xml.dom.minidom import parseString
12
13from lxml import etree
14
15from sas.sascalc.data_util.nxsunit import Converter
16
17# For saving individual sections of data
18from ..data_info import Data1D, Data2D, DataInfo, plottable_1D, plottable_2D, \
19    Collimation, TransmissionSpectrum, Detector, Process, Aperture, \
20    combine_data_info_with_plottable as combine_data
21from ..loader_exceptions import FileContentsException, DefaultReaderException, \
22    DataReaderException
23from . import xml_reader
24from .xml_reader import XMLreader
25from .cansas_constants import CansasConstants, CurrentLevel
26
27logger = logging.getLogger(__name__)
28
29PREPROCESS = "xmlpreprocess"
30ENCODING = "encoding"
31RUN_NAME_DEFAULT = "None"
32INVALID_SCHEMA_PATH_1_1 = "{0}/sas/sascalc/dataloader/readers/schema/cansas1d_invalid_v1_1.xsd"
33INVALID_SCHEMA_PATH_1_0 = "{0}/sas/sascalc/dataloader/readers/schema/cansas1d_invalid_v1_0.xsd"
34INVALID_XML = "\n\nThe loaded xml file, {0} does not fully meet the CanSAS v1.x specification. SasView loaded " + \
35              "as much of the data as possible.\n\n"
36
37CONSTANTS = CansasConstants()
38CANSAS_FORMAT = CONSTANTS.format
39CANSAS_NS = CONSTANTS.names
40ALLOW_ALL = True
41
42class Reader(XMLreader):
43    cansas_version = "1.0"
44    base_ns = "{cansas1d/1.0}"
45    cansas_defaults = None
46    type_name = "canSAS"
47    invalid = True
48    frm = ""
49    # Log messages and errors
50    logging = None
51    errors = set()
52    # Namespace hierarchy for current xml_file object
53    names = None
54    ns_list = None
55    # Temporary storage location for loading multiple data sets in a single file
56    current_data1d = None
57    data = None
58    # Wildcards
59    type = ["XML files (*.xml)|*.xml", "SasView Save Files (*.svs)|*.svs"]
60    # List of allowed extensions
61    ext = ['.xml', '.XML', '.svs', '.SVS']
62    # Flag to bypass extension check
63    allow_all = True
64
65    def reset_state(self):
66        """
67        Resets the class state to a base case when loading a new data file so previous
68        data files do not appear a second time
69        """
70        super(Reader, self).reset_state()
71        self.data = []
72        self.process = Process()
73        self.transspectrum = TransmissionSpectrum()
74        self.aperture = Aperture()
75        self.collimation = Collimation()
76        self.detector = Detector()
77        self.names = []
78        self.cansas_defaults = {}
79        self.ns_list = None
80        self.logging = []
81        self.encoding = None
82
83    def read(self, xml_file, schema_path="", invalid=True):
84        if schema_path != "" or not invalid:
85            # read has been called from self.get_file_contents because xml file doens't conform to schema
86            _, self.extension = os.path.splitext(os.path.basename(xml_file))
87            return self.get_file_contents(xml_file=xml_file, schema_path=schema_path, invalid=invalid)
88
89        # Otherwise, read has been called by the data loader - file_reader_base_class handles this
90        return super(XMLreader, self).read(xml_file)
91
92    def get_file_contents(self, xml_file=None, schema_path="", invalid=True):
93        # Reset everything since we're loading a new file
94        self.reset_state()
95        self.invalid = invalid
96        if xml_file is None:
97            xml_file = self.f_open.name
98        # We don't sure f_open since lxml handles opnening/closing files
99        try:
100            # Raises FileContentsException
101            self.load_file_and_schema(xml_file, schema_path)
102            # Parse each SASentry
103            entry_list = self.xmlroot.xpath('/ns:SASroot/ns:SASentry',
104                                            namespaces={
105                                                'ns': self.cansas_defaults.get(
106                                                    "ns")
107                                            })
108            self.is_cansas(self.extension)
109            self.set_processing_instructions()
110            for entry in entry_list:
111                self._parse_entry(entry)
112                self.data_cleanup()
113        except FileContentsException as fc_exc:
114            # File doesn't meet schema - try loading with a less strict schema
115            base_name = xml_reader.__file__
116            base_name = base_name.replace("\\", "/")
117            base = base_name.split("/sas/")[0]
118            if self.cansas_version == "1.1":
119                invalid_schema = INVALID_SCHEMA_PATH_1_1.format(base, self.cansas_defaults.get("schema"))
120            else:
121                invalid_schema = INVALID_SCHEMA_PATH_1_0.format(base, self.cansas_defaults.get("schema"))
122            self.set_schema(invalid_schema)
123            if self.invalid:
124                try:
125                    # Load data with less strict schema
126                    self.read(xml_file, invalid_schema, False)
127
128                    # File can still be read but doesn't match schema, so raise exception
129                    self.load_file_and_schema(xml_file) # Reload strict schema so we can find where error are in file
130                    invalid_xml = self.find_invalid_xml()
131                    if invalid_xml != "":
132                        basename, _ = os.path.splitext(
133                            os.path.basename(self.f_open.name))
134                        invalid_xml = INVALID_XML.format(basename + self.extension) + invalid_xml
135                        raise DataReaderException(invalid_xml) # Handled by base class
136                except FileContentsException as fc_exc:
137                    msg = "CanSAS Reader could not load the file {}".format(xml_file)
138                    if fc_exc.message is not None: # Propagate error messages from earlier
139                        msg = fc_exc.message
140                    if not self.extension in self.ext: # If the file has no associated loader
141                        raise DefaultReaderException(msg)
142                    raise FileContentsException(msg)
143                    pass
144            else:
145                raise fc_exc
146        except Exception as e: # Convert all other exceptions to FileContentsExceptions
147            raise FileContentsException(str(e))
148        finally:
149            if not self.f_open.closed:
150                self.f_open.close()
151
152    def load_file_and_schema(self, xml_file, schema_path=""):
153        base_name = xml_reader.__file__
154        base_name = base_name.replace("\\", "/")
155        base = base_name.split("/sas/")[0]
156
157        # Try and parse the XML file
158        try:
159            self.set_xml_file(xml_file)
160        except etree.XMLSyntaxError: # File isn't valid XML so can't be loaded
161            msg = "SasView cannot load {}.\nInvalid XML syntax".format(xml_file)
162            raise FileContentsException(msg)
163
164        self.cansas_version = self.xmlroot.get("version", "1.0")
165        self.cansas_defaults = CANSAS_NS.get(self.cansas_version, "1.0")
166
167        if schema_path == "":
168            schema_path = "{}/sas/sascalc/dataloader/readers/schema/{}".format(
169                base, self.cansas_defaults.get("schema").replace("\\", "/")
170            )
171        self.set_schema(schema_path)
172
173    def is_cansas(self, ext="xml"):
174        """
175        Checks to see if the XML file is a CanSAS file
176
177        :param ext: The file extension of the data file
178        :raises FileContentsException: Raised if XML file isn't valid CanSAS
179        """
180        if self.validate_xml(): # Check file is valid XML
181            name = "{http://www.w3.org/2001/XMLSchema-instance}schemaLocation"
182            value = self.xmlroot.get(name)
183            # Check schema CanSAS version matches file CanSAS version
184            if CANSAS_NS.get(self.cansas_version).get("ns") == value.rsplit(" ")[0]:
185                return True
186        if ext == ".svs":
187            return True # Why is this required?
188        # If we get to this point then file isn't valid CanSAS
189        logger.warning("File doesn't meet CanSAS schema. Trying to load anyway.")
190        raise FileContentsException("The file is not valid CanSAS")
191
192    def _parse_entry(self, dom, recurse=False):
193        if not self._is_call_local() and not recurse:
194            self.reset_state()
195        if not recurse:
196            self.current_datainfo = DataInfo()
197            # Raises FileContentsException if file doesn't meet CanSAS schema
198            self.invalid = False
199            # Look for a SASentry
200            self.data = []
201            self.parent_class = "SASentry"
202            self.names.append("SASentry")
203            self.current_datainfo.meta_data["loader"] = "CanSAS XML 1D"
204            self.current_datainfo.meta_data[
205                PREPROCESS] = self.processing_instructions
206        if self._is_call_local() and not recurse:
207            basename, _ = os.path.splitext(os.path.basename(self.f_open.name))
208            self.current_datainfo.filename = basename + self.extension
209        # Create an empty dataset if no data has been passed to the reader
210        if self.current_dataset is None:
211            self._initialize_new_data_set(dom)
212        self.base_ns = "{" + CANSAS_NS.get(self.cansas_version).get("ns") + "}"
213
214        # Loop through each child in the parent element
215        for node in dom:
216            attr = node.attrib
217            name = attr.get("name", "")
218            type = attr.get("type", "")
219            # Get the element name and set the current names level
220            tagname = node.tag.replace(self.base_ns, "")
221            tagname_original = tagname
222            # Skip this iteration when loading in save state information
223            if tagname in ["fitting_plug_in", "pr_inversion", "invariant", "corfunc"]:
224                continue
225            # Get where to store content
226            self.names.append(tagname_original)
227            self.ns_list = CONSTANTS.iterate_namespace(self.names)
228            # If the element is a child element, recurse
229            if len(node.getchildren()) > 0:
230                self.parent_class = tagname_original
231                if tagname == 'SASdata':
232                    self._initialize_new_data_set(node)
233                    if isinstance(self.current_dataset, plottable_2D):
234                        x_bins = attr.get("x_bins", "")
235                        y_bins = attr.get("y_bins", "")
236                        if x_bins is not "" and y_bins is not "":
237                            self.current_dataset.shape = (x_bins, y_bins)
238                        else:
239                            self.current_dataset.shape = ()
240                # Recurse to access data within the group
241                self._parse_entry(node, recurse=True)
242                if tagname == "SASsample":
243                    self.current_datainfo.sample.name = name
244                elif tagname == "beam_size":
245                    self.current_datainfo.source.beam_size_name = name
246                elif tagname == "SAScollimation":
247                    self.collimation.name = name
248                elif tagname == "aperture":
249                    self.aperture.name = name
250                    self.aperture.type = type
251                self._add_intermediate()
252            else:
253                # TODO: Clean this up to make it faster (fewer if/elifs)
254                if isinstance(self.current_dataset, plottable_2D):
255                    data_point = node.text
256                    unit = attr.get('unit', '')
257                else:
258                    data_point, unit = self._get_node_value(node, tagname)
259
260                # If this is a dataset, store the data appropriately
261                if tagname == 'Run':
262                    self.current_datainfo.run_name[data_point] = name
263                    self.current_datainfo.run.append(data_point)
264                elif tagname == 'Title':
265                    self.current_datainfo.title = data_point
266                elif tagname == 'SASnote':
267                    self.current_datainfo.notes.append(data_point)
268
269                # I and Q points
270                elif tagname == 'I' and isinstance(self.current_dataset, plottable_1D):
271                    self.current_dataset.yaxis("Intensity", unit)
272                    self.current_dataset.y = np.append(self.current_dataset.y, data_point)
273                elif tagname == 'Idev' and isinstance(self.current_dataset, plottable_1D):
274                    self.current_dataset.dy = np.append(self.current_dataset.dy, data_point)
275                elif tagname == 'Q':
276                    self.current_dataset.xaxis("Q", unit)
277                    self.current_dataset.x = np.append(self.current_dataset.x, data_point)
278                elif tagname == 'Qdev':
279                    self.current_dataset.dx = np.append(self.current_dataset.dx, data_point)
280                elif tagname == 'dQw':
281                   self.current_dataset.dxw = np.append(self.current_dataset.dxw, data_point)
282                elif tagname == 'dQl':
283                    self.current_dataset.dxl = np.append(self.current_dataset.dxl, data_point)
284                elif tagname == 'Qmean':
285                    pass
286                elif tagname == 'Shadowfactor':
287                    pass
288                elif tagname == 'Sesans':
289                    self.current_datainfo.isSesans = bool(data_point)
290                    self.current_dataset.xaxis(attr.get('x_axis'),
291                                                attr.get('x_unit'))
292                    self.current_dataset.yaxis(attr.get('y_axis'),
293                                                attr.get('y_unit'))
294                elif tagname == 'yacceptance':
295                    self.current_datainfo.sample.yacceptance = (data_point, unit)
296                elif tagname == 'zacceptance':
297                    self.current_datainfo.sample.zacceptance = (data_point, unit)
298
299                # I and Qx, Qy - 2D data
300                elif tagname == 'I' and isinstance(self.current_dataset, plottable_2D):
301                    self.current_dataset.yaxis("Intensity", unit)
302                    self.current_dataset.data = np.fromstring(data_point, dtype=float, sep=",")
303                elif tagname == 'Idev' and isinstance(self.current_dataset, plottable_2D):
304                    self.current_dataset.err_data = np.fromstring(data_point, dtype=float, sep=",")
305                elif tagname == 'Qx':
306                    self.current_dataset.xaxis("Qx", unit)
307                    self.current_dataset.qx_data = np.fromstring(data_point, dtype=float, sep=",")
308                elif tagname == 'Qy':
309                    self.current_dataset.yaxis("Qy", unit)
310                    self.current_dataset.qy_data = np.fromstring(data_point, dtype=float, sep=",")
311                elif tagname == 'Qxdev':
312                    self.current_dataset.xaxis("Qxdev", unit)
313                    self.current_dataset.dqx_data = np.fromstring(data_point, dtype=float, sep=",")
314                elif tagname == 'Qydev':
315                    self.current_dataset.yaxis("Qydev", unit)
316                    self.current_dataset.dqy_data = np.fromstring(data_point, dtype=float, sep=",")
317                elif tagname == 'Mask':
318                    inter = [item == "1" for item in data_point.split(",")]
319                    self.current_dataset.mask = np.asarray(inter, dtype=bool)
320
321                # Sample Information
322                elif tagname == 'ID' and self.parent_class == 'SASsample':
323                    self.current_datainfo.sample.ID = data_point
324                elif tagname == 'Title' and self.parent_class == 'SASsample':
325                    self.current_datainfo.sample.name = data_point
326                elif tagname == 'thickness' and self.parent_class == 'SASsample':
327                    self.current_datainfo.sample.thickness = data_point
328                    self.current_datainfo.sample.thickness_unit = unit
329                elif tagname == 'transmission' and self.parent_class == 'SASsample':
330                    self.current_datainfo.sample.transmission = data_point
331                elif tagname == 'temperature' and self.parent_class == 'SASsample':
332                    self.current_datainfo.sample.temperature = data_point
333                    self.current_datainfo.sample.temperature_unit = unit
334                elif tagname == 'details' and self.parent_class == 'SASsample':
335                    self.current_datainfo.sample.details.append(data_point)
336                elif tagname == 'x' and self.parent_class == 'position':
337                    self.current_datainfo.sample.position.x = data_point
338                    self.current_datainfo.sample.position_unit = unit
339                elif tagname == 'y' and self.parent_class == 'position':
340                    self.current_datainfo.sample.position.y = data_point
341                    self.current_datainfo.sample.position_unit = unit
342                elif tagname == 'z' and self.parent_class == 'position':
343                    self.current_datainfo.sample.position.z = data_point
344                    self.current_datainfo.sample.position_unit = unit
345                elif tagname == 'roll' and self.parent_class == 'orientation' and 'SASsample' in self.names:
346                    self.current_datainfo.sample.orientation.x = data_point
347                    self.current_datainfo.sample.orientation_unit = unit
348                elif tagname == 'pitch' and self.parent_class == 'orientation' and 'SASsample' in self.names:
349                    self.current_datainfo.sample.orientation.y = data_point
350                    self.current_datainfo.sample.orientation_unit = unit
351                elif tagname == 'yaw' and self.parent_class == 'orientation' and 'SASsample' in self.names:
352                    self.current_datainfo.sample.orientation.z = data_point
353                    self.current_datainfo.sample.orientation_unit = unit
354
355                # Instrumental Information
356                elif tagname == 'name' and self.parent_class == 'SASinstrument':
357                    self.current_datainfo.instrument = data_point
358
359                # Detector Information
360                elif tagname == 'name' and self.parent_class == 'SASdetector':
361                    self.detector.name = data_point
362                elif tagname == 'SDD' and self.parent_class == 'SASdetector':
363                    self.detector.distance = data_point
364                    self.detector.distance_unit = unit
365                elif tagname == 'slit_length' and self.parent_class == 'SASdetector':
366                    self.detector.slit_length = data_point
367                    self.detector.slit_length_unit = unit
368                elif tagname == 'x' and self.parent_class == 'offset':
369                    self.detector.offset.x = data_point
370                    self.detector.offset_unit = unit
371                elif tagname == 'y' and self.parent_class == 'offset':
372                    self.detector.offset.y = data_point
373                    self.detector.offset_unit = unit
374                elif tagname == 'z' and self.parent_class == 'offset':
375                    self.detector.offset.z = data_point
376                    self.detector.offset_unit = unit
377                elif tagname == 'x' and self.parent_class == 'beam_center':
378                    self.detector.beam_center.x = data_point
379                    self.detector.beam_center_unit = unit
380                elif tagname == 'y' and self.parent_class == 'beam_center':
381                    self.detector.beam_center.y = data_point
382                    self.detector.beam_center_unit = unit
383                elif tagname == 'z' and self.parent_class == 'beam_center':
384                    self.detector.beam_center.z = data_point
385                    self.detector.beam_center_unit = unit
386                elif tagname == 'x' and self.parent_class == 'pixel_size':
387                    self.detector.pixel_size.x = data_point
388                    self.detector.pixel_size_unit = unit
389                elif tagname == 'y' and self.parent_class == 'pixel_size':
390                    self.detector.pixel_size.y = data_point
391                    self.detector.pixel_size_unit = unit
392                elif tagname == 'z' and self.parent_class == 'pixel_size':
393                    self.detector.pixel_size.z = data_point
394                    self.detector.pixel_size_unit = unit
395                elif tagname == 'roll' and self.parent_class == 'orientation' and 'SASdetector' in self.names:
396                    self.detector.orientation.x = data_point
397                    self.detector.orientation_unit = unit
398                elif tagname == 'pitch' and self.parent_class == 'orientation' and 'SASdetector' in self.names:
399                    self.detector.orientation.y = data_point
400                    self.detector.orientation_unit = unit
401                elif tagname == 'yaw' and self.parent_class == 'orientation' and 'SASdetector' in self.names:
402                    self.detector.orientation.z = data_point
403                    self.detector.orientation_unit = unit
404
405                # Collimation and Aperture
406                elif tagname == 'length' and self.parent_class == 'SAScollimation':
407                    self.collimation.length = data_point
408                    self.collimation.length_unit = unit
409                elif tagname == 'name' and self.parent_class == 'SAScollimation':
410                    self.collimation.name = data_point
411                elif tagname == 'distance' and self.parent_class == 'aperture':
412                    self.aperture.distance = data_point
413                    self.aperture.distance_unit = unit
414                elif tagname == 'x' and self.parent_class == 'size':
415                    self.aperture.size.x = data_point
416                    self.collimation.size_unit = unit
417                elif tagname == 'y' and self.parent_class == 'size':
418                    self.aperture.size.y = data_point
419                    self.collimation.size_unit = unit
420                elif tagname == 'z' and self.parent_class == 'size':
421                    self.aperture.size.z = data_point
422                    self.collimation.size_unit = unit
423
424                # Process Information
425                elif tagname == 'name' and self.parent_class == 'SASprocess':
426                    self.process.name = data_point
427                elif tagname == 'description' and self.parent_class == 'SASprocess':
428                    self.process.description = data_point
429                elif tagname == 'date' and self.parent_class == 'SASprocess':
430                    try:
431                        self.process.date = datetime.datetime.fromtimestamp(data_point)
432                    except:
433                        self.process.date = data_point
434                elif tagname == 'SASprocessnote':
435                    self.process.notes.append(data_point)
436                elif tagname == 'term' and self.parent_class == 'SASprocess':
437                    unit = attr.get("unit", "")
438                    dic = { "name": name, "value": data_point, "unit": unit }
439                    self.process.term.append(dic)
440
441                # Transmission Spectrum
442                elif tagname == 'T' and self.parent_class == 'Tdata':
443                    self.transspectrum.transmission = np.append(self.transspectrum.transmission, data_point)
444                    self.transspectrum.transmission_unit = unit
445                elif tagname == 'Tdev' and self.parent_class == 'Tdata':
446                    self.transspectrum.transmission_deviation = np.append(self.transspectrum.transmission_deviation, data_point)
447                    self.transspectrum.transmission_deviation_unit = unit
448                elif tagname == 'Lambda' and self.parent_class == 'Tdata':
449                    self.transspectrum.wavelength = np.append(self.transspectrum.wavelength, data_point)
450                    self.transspectrum.wavelength_unit = unit
451
452                # Source Information
453                elif tagname == 'wavelength' and (self.parent_class == 'SASsource' or self.parent_class == 'SASData'):
454                    self.current_datainfo.source.wavelength = data_point
455                    self.current_datainfo.source.wavelength_unit = unit
456                elif tagname == 'wavelength_min' and self.parent_class == 'SASsource':
457                    self.current_datainfo.source.wavelength_min = data_point
458                    self.current_datainfo.source.wavelength_min_unit = unit
459                elif tagname == 'wavelength_max' and self.parent_class == 'SASsource':
460                    self.current_datainfo.source.wavelength_max = data_point
461                    self.current_datainfo.source.wavelength_max_unit = unit
462                elif tagname == 'wavelength_spread' and self.parent_class == 'SASsource':
463                    self.current_datainfo.source.wavelength_spread = data_point
464                    self.current_datainfo.source.wavelength_spread_unit = unit
465                elif tagname == 'x' and self.parent_class == 'beam_size':
466                    self.current_datainfo.source.beam_size.x = data_point
467                    self.current_datainfo.source.beam_size_unit = unit
468                elif tagname == 'y' and self.parent_class == 'beam_size':
469                    self.current_datainfo.source.beam_size.y = data_point
470                    self.current_datainfo.source.beam_size_unit = unit
471                elif tagname == 'z' and self.parent_class == 'pixel_size':
472                    self.current_datainfo.source.data_point.z = data_point
473                    self.current_datainfo.source.beam_size_unit = unit
474                elif tagname == 'radiation' and self.parent_class == 'SASsource':
475                    self.current_datainfo.source.radiation = data_point
476                elif tagname == 'beam_shape' and self.parent_class == 'SASsource':
477                    self.current_datainfo.source.beam_shape = data_point
478
479                # Everything else goes in meta_data
480                else:
481                    new_key = self._create_unique_key(self.current_datainfo.meta_data, tagname)
482                    self.current_datainfo.meta_data[new_key] = data_point
483
484            self.names.remove(tagname_original)
485            length = 0
486            if len(self.names) > 1:
487                length = len(self.names) - 1
488            self.parent_class = self.names[length]
489        if not self._is_call_local() and not recurse:
490            self.frm = ""
491            self.current_datainfo.errors = set()
492            for error in self.errors:
493                self.current_datainfo.errors.add(error)
494            self.data_cleanup()
495            self.sort_data()
496            self.reset_data_list()
497            return self.output[0], None
498
499    def _is_call_local(self):
500        if self.frm == "":
501            inter = inspect.stack()
502            self.frm = inter[2]
503        mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "")
504        mod_name = mod_name.replace(".py", "")
505        mod = mod_name.split("sas/")
506        mod_name = mod[1]
507        if mod_name != "sascalc/dataloader/readers/cansas_reader":
508            return False
509        return True
510
511    def _add_intermediate(self):
512        """
513        This method stores any intermediate objects within the final data set after fully reading the set.
514        """
515        if self.parent_class == 'SASprocess':
516            self.current_datainfo.process.append(self.process)
517            self.process = Process()
518        elif self.parent_class == 'SASdetector':
519            self.current_datainfo.detector.append(self.detector)
520            self.detector = Detector()
521        elif self.parent_class == 'SAStransmission_spectrum':
522            self.current_datainfo.trans_spectrum.append(self.transspectrum)
523            self.transspectrum = TransmissionSpectrum()
524        elif self.parent_class == 'SAScollimation':
525            self.current_datainfo.collimation.append(self.collimation)
526            self.collimation = Collimation()
527        elif self.parent_class == 'aperture':
528            self.collimation.aperture.append(self.aperture)
529            self.aperture = Aperture()
530        elif self.parent_class == 'SASdata':
531            self.data.append(self.current_dataset)
532
533    def _get_node_value(self, node, tagname):
534        """
535        Get the value of a node and any applicable units
536
537        :param node: The XML node to get the value of
538        :param tagname: The tagname of the node
539        """
540        #Get the text from the node and convert all whitespace to spaces
541        units = ''
542        node_value = node.text
543        if node_value is not None:
544            node_value = ' '.join(node_value.split())
545        else:
546            node_value = ""
547
548        # If the value is a float, compile with units.
549        if self.ns_list.ns_datatype == "float":
550            # If an empty value is given, set as zero.
551            if node_value is None or node_value.isspace() \
552                                    or node_value.lower() == "nan":
553                node_value = "0.0"
554            #Convert the value to the base units
555            node_value, units = self._unit_conversion(node, tagname, node_value)
556
557        # If the value is a timestamp, convert to a datetime object
558        elif self.ns_list.ns_datatype == "timestamp":
559            if node_value is None or node_value.isspace():
560                pass
561            else:
562                try:
563                    node_value = \
564                        datetime.datetime.fromtimestamp(node_value)
565                except ValueError:
566                    node_value = None
567        return node_value, units
568
569    def _unit_conversion(self, node, tagname, node_value):
570        """
571        A unit converter method used to convert the data included in the file
572        to the default units listed in data_info
573
574        :param node: XML node
575        :param tagname: name of the node
576        :param node_value: The value of the current dom node
577        """
578        attr = node.attrib
579        value_unit = ''
580        err_msg = None
581        default_unit = None
582        if not isinstance(node_value, float):
583            node_value = float(node_value)
584        if 'unit' in attr and attr.get('unit') is not None:
585            try:
586                unit = attr['unit']
587                # Split the units to retain backwards compatibility with
588                # projects, analyses, and saved data from v4.1.0
589                unit_list = unit.split("|")
590                if len(unit_list) > 1:
591                    local_unit = unit_list[1]
592                else:
593                    local_unit = unit
594                unitname = self.ns_list.current_level.get("unit", "")
595                if "SASdetector" in self.names:
596                    save_in = "detector"
597                elif "aperture" in self.names:
598                    save_in = "aperture"
599                elif "SAScollimation" in self.names:
600                    save_in = "collimation"
601                elif "SAStransmission_spectrum" in self.names:
602                    save_in = "transspectrum"
603                elif "SASdata" in self.names:
604                    x = np.zeros(1)
605                    y = np.zeros(1)
606                    self.current_data1d = Data1D(x, y)
607                    save_in = "current_data1d"
608                elif "SASsource" in self.names:
609                    save_in = "current_datainfo.source"
610                elif "SASsample" in self.names:
611                    save_in = "current_datainfo.sample"
612                elif "SASprocess" in self.names:
613                    save_in = "process"
614                else:
615                    save_in = "current_datainfo"
616                default_unit = getattrchain(self, '.'.join((save_in, unitname)))
617                if (local_unit and default_unit
618                        and local_unit.lower() != default_unit.lower()
619                        and local_unit.lower() != "none"):
620                    # Check local units - bad units raise KeyError
621                    #print("loading", tagname, node_value, local_unit, default_unit)
622                    data_conv_q = Converter(local_unit)
623                    value_unit = default_unit
624                    node_value = data_conv_q(node_value, units=default_unit)
625                else:
626                    value_unit = local_unit
627            except KeyError:
628                # Do not throw an error for loading Sesans data in cansas xml
629                # This is a temporary fix.
630                if local_unit != "A" and local_unit != 'pol':
631                    err_msg = "CanSAS reader: unexpected "
632                    err_msg += "\"{0}\" unit [{1}]; "
633                    err_msg = err_msg.format(tagname, local_unit)
634                    err_msg += "expecting [{0}]".format(default_unit)
635                value_unit = local_unit
636            except Exception:
637                err_msg = "CanSAS reader: unknown error converting "
638                err_msg += "\"{0}\" unit [{1}]"
639                err_msg = err_msg.format(tagname, local_unit)
640                value_unit = local_unit
641        elif 'unit' in attr:
642            value_unit = attr['unit']
643        if err_msg:
644            self.errors.add(err_msg)
645        return node_value, value_unit
646
647    def _initialize_new_data_set(self, node=None):
648        if node is not None:
649            for child in node:
650                if child.tag.replace(self.base_ns, "") == "Idata":
651                    for i_child in child:
652                        if i_child.tag.replace(self.base_ns, "") == "Qx":
653                            self.current_dataset = plottable_2D()
654                            return
655        self.current_dataset = plottable_1D(np.array(0), np.array(0))
656
657    ## Writing Methods
658    def write(self, filename, datainfo):
659        """
660        Write the content of a Data1D as a CanSAS XML file
661
662        :param filename: name of the file to write
663        :param datainfo: Data1D object
664        """
665        # Create XML document
666        doc, _ = self._to_xml_doc(datainfo)
667        # Write the file
668        file_ref = open(filename, 'wb')
669        if self.encoding is None:
670            self.encoding = "UTF-8"
671        doc.write(file_ref, encoding=self.encoding,
672                  pretty_print=True, xml_declaration=True)
673        file_ref.close()
674
675    def _to_xml_doc(self, datainfo):
676        """
677        Create an XML document to contain the content of a Data1D
678
679        :param datainfo: Data1D object
680        """
681        is_2d = False
682        if issubclass(datainfo.__class__, Data2D):
683            is_2d = True
684
685        # Get PIs and create root element
686        pi_string = self._get_pi_string()
687        # Define namespaces and create SASroot object
688        main_node = self._create_main_node()
689        # Create ElementTree, append SASroot and apply processing instructions
690        base_string = pi_string + self.to_string(main_node)
691        base_element = self.create_element_from_string(base_string)
692        doc = self.create_tree(base_element)
693        # Create SASentry Element
694        entry_node = self.create_element("SASentry")
695        root = doc.getroot()
696        root.append(entry_node)
697
698        # Add Title to SASentry
699        self.write_node(entry_node, "Title", datainfo.title)
700        # Add Run to SASentry
701        self._write_run_names(datainfo, entry_node)
702        # Add Data info to SASEntry
703        if is_2d:
704            self._write_data_2d(datainfo, entry_node)
705        else:
706            self._write_data(datainfo, entry_node)
707        # Transmission Spectrum Info
708        # TODO: fix the writer to linearize all data, including T_spectrum
709        # self._write_trans_spectrum(datainfo, entry_node)
710        # Sample info
711        self._write_sample_info(datainfo, entry_node)
712        # Instrument info
713        instr = self._write_instrument(datainfo, entry_node)
714        #   Source
715        self._write_source(datainfo, instr)
716        #   Collimation
717        self._write_collimation(datainfo, instr)
718        #   Detectors
719        self._write_detectors(datainfo, instr)
720        # Processes info
721        self._write_process_notes(datainfo, entry_node)
722        # Note info
723        self._write_notes(datainfo, entry_node)
724        # Return the document, and the SASentry node associated with
725        #      the data we just wrote
726        # If the calling function was not the cansas reader, return a minidom
727        #      object rather than an lxml object.
728        self.frm = inspect.stack()[1]
729        doc, entry_node = self._check_origin(entry_node, doc)
730        return doc, entry_node
731
732    def write_node(self, parent, name, value, attr=None):
733        """
734        :param doc: document DOM
735        :param parent: parent node
736        :param name: tag of the element
737        :param value: value of the child text node
738        :param attr: attribute dictionary
739
740        :return: True if something was appended, otherwise False
741        """
742        if value is not None:
743            parent = self.ebuilder(parent, name, value, attr)
744            return True
745        return False
746
747    def _get_pi_string(self):
748        """
749        Creates the processing instructions header for writing to file
750        """
751        pis = self.return_processing_instructions()
752        if len(pis) > 0:
753            pi_tree = self.create_tree(pis[0])
754            i = 1
755            for i in range(1, len(pis) - 1):
756                pi_tree = self.append(pis[i], pi_tree)
757            pi_string = self.to_string(pi_tree)
758        else:
759            pi_string = ""
760        return pi_string
761
762    def _create_main_node(self):
763        """
764        Creates the primary xml header used when writing to file
765        """
766        xsi = "http://www.w3.org/2001/XMLSchema-instance"
767        version = self.cansas_version
768        n_s = CANSAS_NS.get(version).get("ns")
769        if version == "1.1":
770            url = "http://www.cansas.org/formats/1.1/"
771        else:
772            url = "http://svn.smallangles.net/svn/canSAS/1dwg/trunk/"
773        schema_location = "{0} {1}cansas1d.xsd".format(n_s, url)
774        attrib = {"{" + xsi + "}schemaLocation" : schema_location,
775                  "version" : version}
776        nsmap = {'xsi' : xsi, None: n_s}
777
778        main_node = self.create_element("{" + n_s + "}SASroot",
779                                        attrib=attrib, nsmap=nsmap)
780        return main_node
781
782    def _write_run_names(self, datainfo, entry_node):
783        """
784        Writes the run names to the XML file
785
786        :param datainfo: The Data1D object the information is coming from
787        :param entry_node: lxml node ElementTree object to be appended to
788        """
789        if datainfo.run is None or datainfo.run == []:
790            datainfo.run.append(RUN_NAME_DEFAULT)
791            datainfo.run_name[RUN_NAME_DEFAULT] = RUN_NAME_DEFAULT
792        for item in datainfo.run:
793            runname = {}
794            if item in datainfo.run_name and \
795            len(str(datainfo.run_name[item])) > 1:
796                runname = {'name': datainfo.run_name[item]}
797            self.write_node(entry_node, "Run", item, runname)
798
799    def _write_data(self, datainfo, entry_node):
800        """
801        Writes 1D I and Q data to the XML file
802
803        :param datainfo: The Data1D object the information is coming from
804        :param entry_node: lxml node ElementTree object to be appended to
805        """
806        node = self.create_element("SASdata")
807        self.append(node, entry_node)
808
809        for i in range(len(datainfo.x)):
810            point = self.create_element("Idata")
811            node.append(point)
812            self.write_node(point, "Q", datainfo.x[i],
813                            {'unit': datainfo._xunit})
814            if len(datainfo.y) >= i:
815                self.write_node(point, "I", datainfo.y[i],
816                                {'unit': datainfo._yunit})
817            if datainfo.dy is not None and len(datainfo.dy) > i:
818                self.write_node(point, "Idev", datainfo.dy[i],
819                                {'unit': datainfo._yunit})
820            if datainfo.dx is not None and len(datainfo.dx) > i:
821                self.write_node(point, "Qdev", datainfo.dx[i],
822                                {'unit': datainfo._xunit})
823            if datainfo.dxw is not None and len(datainfo.dxw) > i:
824                self.write_node(point, "dQw", datainfo.dxw[i],
825                                {'unit': datainfo._xunit})
826            if datainfo.dxl is not None and len(datainfo.dxl) > i:
827                self.write_node(point, "dQl", datainfo.dxl[i],
828                                {'unit': datainfo._xunit})
829        if datainfo.isSesans:
830            sesans_attrib = {'x_axis': datainfo._xaxis,
831                             'y_axis': datainfo._yaxis,
832                             'x_unit': datainfo.x_unit,
833                             'y_unit': datainfo.y_unit}
834            sesans = self.create_element("Sesans", attrib=sesans_attrib)
835            sesans.text = str(datainfo.isSesans)
836            entry_node.append(sesans)
837            self.write_node(entry_node, "yacceptance", datainfo.sample.yacceptance[0],
838                             {'unit': datainfo.sample.yacceptance[1]})
839            self.write_node(entry_node, "zacceptance", datainfo.sample.zacceptance[0],
840                             {'unit': datainfo.sample.zacceptance[1]})
841
842
843    def _write_data_2d(self, datainfo, entry_node):
844        """
845        Writes 2D data to the XML file
846
847        :param datainfo: The Data2D object the information is coming from
848        :param entry_node: lxml node ElementTree object to be appended to
849        """
850        attr = {}
851        if datainfo.data.shape:
852            attr["x_bins"] = str(len(datainfo.x_bins))
853            attr["y_bins"] = str(len(datainfo.y_bins))
854        node = self.create_element("SASdata", attr)
855        self.append(node, entry_node)
856
857        point = self.create_element("Idata")
858        node.append(point)
859        qx = ','.join(str(v) for v in datainfo.qx_data)
860        qy = ','.join(str(v) for v in datainfo.qy_data)
861        intensity = ','.join(str(v) for v in datainfo.data)
862
863        self.write_node(point, "Qx", qx,
864                        {'unit': datainfo._xunit})
865        self.write_node(point, "Qy", qy,
866                        {'unit': datainfo._yunit})
867        self.write_node(point, "I", intensity,
868                        {'unit': datainfo._zunit})
869        if datainfo.err_data is not None:
870            err = ','.join(str(v) for v in datainfo.err_data)
871            self.write_node(point, "Idev", err,
872                            {'unit': datainfo._zunit})
873        if datainfo.dqy_data is not None:
874            dqy = ','.join(str(v) for v in datainfo.dqy_data)
875            self.write_node(point, "Qydev", dqy,
876                            {'unit': datainfo._yunit})
877        if datainfo.dqx_data is not None:
878            dqx = ','.join(str(v) for v in datainfo.dqx_data)
879            self.write_node(point, "Qxdev", dqx,
880                            {'unit': datainfo._xunit})
881        if datainfo.mask is not None:
882            mask = ','.join("1" if v else "0" for v in datainfo.mask)
883            self.write_node(point, "Mask", mask)
884
885    def _write_trans_spectrum(self, datainfo, entry_node):
886        """
887        Writes the transmission spectrum data to the XML file
888
889        :param datainfo: The Data1D object the information is coming from
890        :param entry_node: lxml node ElementTree object to be appended to
891        """
892        for i in range(len(datainfo.trans_spectrum)):
893            spectrum = datainfo.trans_spectrum[i]
894            node = self.create_element("SAStransmission_spectrum",
895                                       {"name" : spectrum.name})
896            self.append(node, entry_node)
897            if isinstance(spectrum.timestamp, datetime.datetime):
898                node.setAttribute("timestamp", spectrum.timestamp)
899            for i in range(len(spectrum.wavelength)):
900                point = self.create_element("Tdata")
901                node.append(point)
902                self.write_node(point, "Lambda", spectrum.wavelength[i],
903                                {'unit': spectrum.wavelength_unit})
904                self.write_node(point, "T", spectrum.transmission[i],
905                                {'unit': spectrum.transmission_unit})
906                if spectrum.transmission_deviation is not None \
907                and len(spectrum.transmission_deviation) >= i:
908                    self.write_node(point, "Tdev",
909                                    spectrum.transmission_deviation[i],
910                                    {'unit':
911                                     spectrum.transmission_deviation_unit})
912
913    def _write_sample_info(self, datainfo, entry_node):
914        """
915        Writes the sample information to the XML file
916
917        :param datainfo: The Data1D object the information is coming from
918        :param entry_node: lxml node ElementTree object to be appended to
919        """
920        sample = self.create_element("SASsample")
921        if datainfo.sample.name is not None:
922            self.write_attribute(sample, "name",
923                                 str(datainfo.sample.name))
924        self.append(sample, entry_node)
925        self.write_node(sample, "ID", str(datainfo.sample.ID))
926        self.write_node(sample, "thickness", datainfo.sample.thickness,
927                        {"unit": datainfo.sample.thickness_unit})
928        self.write_node(sample, "transmission", datainfo.sample.transmission)
929        self.write_node(sample, "temperature", datainfo.sample.temperature,
930                        {"unit": datainfo.sample.temperature_unit})
931
932        pos = self.create_element("position")
933        written = self.write_node(pos,
934                                  "x",
935                                  datainfo.sample.position.x,
936                                  {"unit": datainfo.sample.position_unit})
937        written = written | self.write_node( \
938            pos, "y", datainfo.sample.position.y,
939            {"unit": datainfo.sample.position_unit})
940        written = written | self.write_node( \
941            pos, "z", datainfo.sample.position.z,
942            {"unit": datainfo.sample.position_unit})
943        if written:
944            self.append(pos, sample)
945
946        ori = self.create_element("orientation")
947        written = self.write_node(ori, "roll",
948                                  datainfo.sample.orientation.x,
949                                  {"unit": datainfo.sample.orientation_unit})
950        written = written | self.write_node( \
951            ori, "pitch", datainfo.sample.orientation.y,
952            {"unit": datainfo.sample.orientation_unit})
953        written = written | self.write_node( \
954            ori, "yaw", datainfo.sample.orientation.z,
955            {"unit": datainfo.sample.orientation_unit})
956        if written:
957            self.append(ori, sample)
958
959        for item in datainfo.sample.details:
960            self.write_node(sample, "details", item)
961
962    def _write_instrument(self, datainfo, entry_node):
963        """
964        Writes the instrumental information to the XML file
965
966        :param datainfo: The Data1D object the information is coming from
967        :param entry_node: lxml node ElementTree object to be appended to
968        """
969        instr = self.create_element("SASinstrument")
970        self.append(instr, entry_node)
971        self.write_node(instr, "name", datainfo.instrument)
972        return instr
973
974    def _write_source(self, datainfo, instr):
975        """
976        Writes the source information to the XML file
977
978        :param datainfo: The Data1D object the information is coming from
979        :param instr: instrument node  to be appended to
980        """
981        source = self.create_element("SASsource")
982        if datainfo.source.name is not None:
983            self.write_attribute(source, "name",
984                                 str(datainfo.source.name))
985        self.append(source, instr)
986        if datainfo.source.radiation is None or datainfo.source.radiation == '':
987            datainfo.source.radiation = "neutron"
988        self.write_node(source, "radiation", datainfo.source.radiation)
989
990        size = self.create_element("beam_size")
991        if datainfo.source.beam_size_name is not None:
992            self.write_attribute(size, "name",
993                                 str(datainfo.source.beam_size_name))
994        written = self.write_node( \
995            size, "x", datainfo.source.beam_size.x,
996            {"unit": datainfo.source.beam_size_unit})
997        written = written | self.write_node( \
998            size, "y", datainfo.source.beam_size.y,
999            {"unit": datainfo.source.beam_size_unit})
1000        written = written | self.write_node( \
1001            size, "z", datainfo.source.beam_size.z,
1002            {"unit": datainfo.source.beam_size_unit})
1003        if written:
1004            self.append(size, source)
1005
1006        self.write_node(source, "beam_shape", datainfo.source.beam_shape)
1007        self.write_node(source, "wavelength",
1008                        datainfo.source.wavelength,
1009                        {"unit": datainfo.source.wavelength_unit})
1010        self.write_node(source, "wavelength_min",
1011                        datainfo.source.wavelength_min,
1012                        {"unit": datainfo.source.wavelength_min_unit})
1013        self.write_node(source, "wavelength_max",
1014                        datainfo.source.wavelength_max,
1015                        {"unit": datainfo.source.wavelength_max_unit})
1016        self.write_node(source, "wavelength_spread",
1017                        datainfo.source.wavelength_spread,
1018                        {"unit": datainfo.source.wavelength_spread_unit})
1019
1020    def _write_collimation(self, datainfo, instr):
1021        """
1022        Writes the collimation information to the XML file
1023
1024        :param datainfo: The Data1D object the information is coming from
1025        :param instr: lxml node ElementTree object to be appended to
1026        """
1027        if datainfo.collimation == [] or datainfo.collimation is None:
1028            coll = Collimation()
1029            datainfo.collimation.append(coll)
1030        for item in datainfo.collimation:
1031            coll = self.create_element("SAScollimation")
1032            if item.name is not None:
1033                self.write_attribute(coll, "name", str(item.name))
1034            self.append(coll, instr)
1035
1036            self.write_node(coll, "length", item.length,
1037                            {"unit": item.length_unit})
1038
1039            for aperture in item.aperture:
1040                apert = self.create_element("aperture")
1041                if aperture.name is not None:
1042                    self.write_attribute(apert, "name", str(aperture.name))
1043                if aperture.type is not None:
1044                    self.write_attribute(apert, "type", str(aperture.type))
1045                self.append(apert, coll)
1046
1047                size = self.create_element("size")
1048                if aperture.size_name is not None:
1049                    self.write_attribute(size, "name",
1050                                         str(aperture.size_name))
1051                written = self.write_node(size, "x", aperture.size.x,
1052                                          {"unit": aperture.size_unit})
1053                written = written | self.write_node( \
1054                    size, "y", aperture.size.y,
1055                    {"unit": aperture.size_unit})
1056                written = written | self.write_node( \
1057                    size, "z", aperture.size.z,
1058                    {"unit": aperture.size_unit})
1059                if written:
1060                    self.append(size, apert)
1061
1062                self.write_node(apert, "distance", aperture.distance,
1063                                {"unit": aperture.distance_unit})
1064
1065    def _write_detectors(self, datainfo, instr):
1066        """
1067        Writes the detector information to the XML file
1068
1069        :param datainfo: The Data1D object the information is coming from
1070        :param inst: lxml instrument node to be appended to
1071        """
1072        if datainfo.detector is None or datainfo.detector == []:
1073            det = Detector()
1074            det.name = ""
1075            datainfo.detector.append(det)
1076
1077        for item in datainfo.detector:
1078            det = self.create_element("SASdetector")
1079            written = self.write_node(det, "name", item.name)
1080            written = written | self.write_node(det, "SDD", item.distance,
1081                                                {"unit": item.distance_unit})
1082            if written:
1083                self.append(det, instr)
1084
1085            off = self.create_element("offset")
1086            written = self.write_node(off, "x", item.offset.x,
1087                                      {"unit": item.offset_unit})
1088            written = written | self.write_node(off, "y", item.offset.y,
1089                                                {"unit": item.offset_unit})
1090            written = written | self.write_node(off, "z", item.offset.z,
1091                                                {"unit": item.offset_unit})
1092            if written:
1093                self.append(off, det)
1094
1095            ori = self.create_element("orientation")
1096            written = self.write_node(ori, "roll", item.orientation.x,
1097                                      {"unit": item.orientation_unit})
1098            written = written | self.write_node(ori, "pitch",
1099                                                item.orientation.y,
1100                                                {"unit": item.orientation_unit})
1101            written = written | self.write_node(ori, "yaw",
1102                                                item.orientation.z,
1103                                                {"unit": item.orientation_unit})
1104            if written:
1105                self.append(ori, det)
1106
1107            center = self.create_element("beam_center")
1108            written = self.write_node(center, "x", item.beam_center.x,
1109                                      {"unit": item.beam_center_unit})
1110            written = written | self.write_node(center, "y",
1111                                                item.beam_center.y,
1112                                                {"unit": item.beam_center_unit})
1113            written = written | self.write_node(center, "z",
1114                                                item.beam_center.z,
1115                                                {"unit": item.beam_center_unit})
1116            if written:
1117                self.append(center, det)
1118
1119            pix = self.create_element("pixel_size")
1120            written = self.write_node(pix, "x", item.pixel_size.x,
1121                                      {"unit": item.pixel_size_unit})
1122            written = written | self.write_node(pix, "y", item.pixel_size.y,
1123                                                {"unit": item.pixel_size_unit})
1124            written = written | self.write_node(pix, "z", item.pixel_size.z,
1125                                                {"unit": item.pixel_size_unit})
1126            if written:
1127                self.append(pix, det)
1128            self.write_node(det, "slit_length", item.slit_length,
1129                {"unit": item.slit_length_unit})
1130
1131
1132    def _write_process_notes(self, datainfo, entry_node):
1133        """
1134        Writes the process notes to the XML file
1135
1136        :param datainfo: The Data1D object the information is coming from
1137        :param entry_node: lxml node ElementTree object to be appended to
1138
1139        """
1140        for item in datainfo.process:
1141            node = self.create_element("SASprocess")
1142            self.append(node, entry_node)
1143            self.write_node(node, "name", item.name)
1144            self.write_node(node, "date", item.date)
1145            self.write_node(node, "description", item.description)
1146            for term in item.term:
1147                if isinstance(term, list):
1148                    value = term['value']
1149                    del term['value']
1150                elif isinstance(term, dict):
1151                    value = term.get("value")
1152                    del term['value']
1153                else:
1154                    value = term
1155                self.write_node(node, "term", value, term)
1156            for note in item.notes:
1157                self.write_node(node, "SASprocessnote", note)
1158            if len(item.notes) == 0:
1159                self.write_node(node, "SASprocessnote", "")
1160
1161    def _write_notes(self, datainfo, entry_node):
1162        """
1163        Writes the notes to the XML file and creates an empty note if none
1164        exist
1165
1166        :param datainfo: The Data1D object the information is coming from
1167        :param entry_node: lxml node ElementTree object to be appended to
1168
1169        """
1170        if len(datainfo.notes) == 0:
1171            node = self.create_element("SASnote")
1172            self.append(node, entry_node)
1173        else:
1174            for item in datainfo.notes:
1175                node = self.create_element("SASnote")
1176                self.write_text(node, item)
1177                self.append(node, entry_node)
1178
1179    def _check_origin(self, entry_node, doc):
1180        """
1181        Return the document, and the SASentry node associated with
1182        the data we just wrote.
1183        If the calling function was not the cansas reader, return a minidom
1184        object rather than an lxml object.
1185
1186        :param entry_node: lxml node ElementTree object to be appended to
1187        :param doc: entire xml tree
1188        """
1189        if not self.frm:
1190            self.frm = inspect.stack()[1]
1191        mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "")
1192        mod_name = mod_name.replace(".py", "")
1193        mod = mod_name.split("sas/")
1194        mod_name = mod[1]
1195        if mod_name != "sascalc/dataloader/readers/cansas_reader":
1196            string = self.to_string(doc, pretty_print=False)
1197            doc = parseString(string)
1198            node_name = entry_node.tag
1199            node_list = doc.getElementsByTagName(node_name)
1200            entry_node = node_list.item(0)
1201        return doc, entry_node
1202
1203    # DO NOT REMOVE - used in saving and loading panel states.
1204    def _store_float(self, location, node, variable, storage, optional=True):
1205        """
1206        Get the content of a xpath location and store
1207        the result. Check that the units are compatible
1208        with the destination. The value is expected to
1209        be a float.
1210
1211        The xpath location might or might not exist.
1212        If it does not exist, nothing is done
1213
1214        :param location: xpath location to fetch
1215        :param node: node to read the data from
1216        :param variable: name of the data member to store it in [string]
1217        :param storage: data object that has the 'variable' data member
1218        :param optional: if True, no exception will be raised
1219            if unit conversion can't be done
1220
1221        :raise ValueError: raised when the units are not recognized
1222        """
1223        entry = get_content(location, node)
1224        try:
1225            value = float(entry.text)
1226        except ValueError:
1227            value = None
1228
1229        if value is not None:
1230            # If the entry has units, check to see that they are
1231            # compatible with what we currently have in the data object
1232            units = entry.get('unit')
1233            if units is not None:
1234                toks = variable.split('.')
1235                local_unit = getattr(storage, toks[0]+"_unit")
1236                if local_unit is not None and units.lower() != local_unit.lower():
1237                    try:
1238                        conv = Converter(units)
1239                        setattrchain(storage, variable, conv(value, units=local_unit))
1240                    except Exception:
1241                        _, exc_value, _ = sys.exc_info()
1242                        err_mess = "CanSAS reader: could not convert"
1243                        err_mess += " %s unit [%s]; expecting [%s]\n  %s" \
1244                            % (variable, units, local_unit, exc_value)
1245                        self.errors.add(err_mess)
1246                        if optional:
1247                            logger.info(err_mess)
1248                        else:
1249                            raise ValueError(err_mess)
1250                else:
1251                    setattrchain(storage, variable, value)
1252            else:
1253                setattrchain(storage, variable, value)
1254
1255    # DO NOT REMOVE - used in saving and loading panel states.
1256    def _store_content(self, location, node, variable, storage):
1257        """
1258        Get the content of a xpath location and store
1259        the result. The value is treated as a string.
1260
1261        The xpath location might or might not exist.
1262        If it does not exist, nothing is done
1263
1264        :param location: xpath location to fetch
1265        :param node: node to read the data from
1266        :param variable: name of the data member to store it in [string]
1267        :param storage: data object that has the 'variable' data member
1268
1269        :return: return a list of errors
1270        """
1271        entry = get_content(location, node)
1272        if entry is not None and entry.text is not None:
1273            setattrchain(storage, variable, entry.text.strip())
1274
1275# DO NOT REMOVE Called by outside packages:
1276#    sas.sasgui.perspectives.invariant.invariant_state
1277#    sas.sasgui.perspectives.fitting.pagestate
1278def get_content(location, node):
1279    """
1280    Get the first instance of the content of a xpath location.
1281
1282    :param location: xpath location
1283    :param node: node to start at
1284
1285    :return: Element, or None
1286    """
1287    nodes = node.xpath(location,
1288                       namespaces={'ns': CANSAS_NS.get("1.0").get("ns")})
1289    if len(nodes) > 0:
1290        return nodes[0]
1291    else:
1292        return None
1293
1294# DO NOT REMOVE Called by outside packages:
1295#    sas.sasgui.perspectives.fitting.pagestate
1296def write_node(doc, parent, name, value, attr=None):
1297    """
1298    :param doc: document DOM
1299    :param parent: parent node
1300    :param name: tag of the element
1301    :param value: value of the child text node
1302    :param attr: attribute dictionary
1303
1304    :return: True if something was appended, otherwise False
1305    """
1306    if attr is None:
1307        attr = {}
1308    if value is not None:
1309        node = doc.createElement(name)
1310        node.appendChild(doc.createTextNode(str(value)))
1311        for item in attr:
1312            node.setAttribute(item, attr[item])
1313        parent.appendChild(node)
1314        return True
1315    return False
1316
1317def getattrchain(obj, chain, default=None):
1318    """Like getattr, but the attr may contain multiple parts separated by '.'"""
1319    for part in chain.split('.'):
1320        if hasattr(obj, part):
1321            obj = getattr(obj, part, None)
1322        else:
1323            return default
1324    return obj
1325
1326def setattrchain(obj, chain, value):
1327    """Like setattr, but the attr may contain multiple parts separated by '.'"""
1328    parts = list(chain.split('.'))
1329    for part in parts[-1]:
1330        obj = getattr(obj, part, None)
1331        if obj is None:
1332            raise ValueError("missing parent object "+part)
1333    setattr(obj, value)
Note: See TracBrowser for help on using the repository browser.