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

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

exec magic for dereferencing default units didn't work in python 3

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