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

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalcmagnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 24d9e84 was 62160509, checked in by krzywon, 7 years ago

Check for units saved in v4.1.0 and convert to current.

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