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

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 9efdb29 was 9efdb29, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

further python3 conversion cleanup for cansas

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