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

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

Make suggested changes for unit test fixes.

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