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

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 17e257b5 was 17e257b5, checked in by krzywon, 7 years ago

Fix the broken unit tests associated with the readers.

  • 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: self.current_dataset.dxw = np.empty(0)
302                    self.current_dataset.dxw = np.append(self.current_dataset.dxw, data_point)
303                elif tagname == 'dQl':
304                    if self.current_dataset.dxl is None: self.current_dataset.dxl = np.empty(0)
305                    self.current_dataset.dxl = np.append(self.current_dataset.dxl, data_point)
306                elif tagname == 'Qmean':
307                    pass
308                elif tagname == 'Shadowfactor':
309                    pass
310                elif tagname == 'Sesans':
311                    self.current_datainfo.isSesans = bool(data_point)
312                elif tagname == 'yacceptance':
313                    self.current_datainfo.sample.yacceptance = (data_point, unit)
314                elif tagname == 'zacceptance':
315                    self.current_datainfo.sample.zacceptance = (data_point, unit)
316
317                # I and Qx, Qy - 2D data
318                elif tagname == 'I' and isinstance(self.current_dataset, plottable_2D):
319                    self.current_dataset.yaxis("Intensity", unit)
320                    self.current_dataset.data = np.fromstring(data_point, dtype=float, sep=",")
321                elif tagname == 'Idev' and isinstance(self.current_dataset, plottable_2D):
322                    self.current_dataset.err_data = np.fromstring(data_point, dtype=float, sep=",")
323                elif tagname == 'Qx':
324                    self.current_dataset.xaxis("Qx", unit)
325                    self.current_dataset.qx_data = np.fromstring(data_point, dtype=float, sep=",")
326                elif tagname == 'Qy':
327                    self.current_dataset.yaxis("Qy", unit)
328                    self.current_dataset.qy_data = np.fromstring(data_point, dtype=float, sep=",")
329                elif tagname == 'Qxdev':
330                    self.current_dataset.xaxis("Qxdev", unit)
331                    self.current_dataset.dqx_data = np.fromstring(data_point, dtype=float, sep=",")
332                elif tagname == 'Qydev':
333                    self.current_dataset.yaxis("Qydev", unit)
334                    self.current_dataset.dqy_data = np.fromstring(data_point, dtype=float, sep=",")
335                elif tagname == 'Mask':
336                    inter = [item == "1" for item in data_point.split(",")]
337                    self.current_dataset.mask = np.asarray(inter, dtype=bool)
338
339                # Sample Information
340                elif tagname == 'ID' and self.parent_class == 'SASsample':
341                    self.current_datainfo.sample.ID = data_point
342                elif tagname == 'Title' and self.parent_class == 'SASsample':
343                    self.current_datainfo.sample.name = data_point
344                elif tagname == 'thickness' and self.parent_class == 'SASsample':
345                    self.current_datainfo.sample.thickness = data_point
346                    self.current_datainfo.sample.thickness_unit = unit
347                elif tagname == 'transmission' and self.parent_class == 'SASsample':
348                    self.current_datainfo.sample.transmission = data_point
349                elif tagname == 'temperature' and self.parent_class == 'SASsample':
350                    self.current_datainfo.sample.temperature = data_point
351                    self.current_datainfo.sample.temperature_unit = unit
352                elif tagname == 'details' and self.parent_class == 'SASsample':
353                    self.current_datainfo.sample.details.append(data_point)
354                elif tagname == 'x' and self.parent_class == 'position':
355                    self.current_datainfo.sample.position.x = data_point
356                    self.current_datainfo.sample.position_unit = unit
357                elif tagname == 'y' and self.parent_class == 'position':
358                    self.current_datainfo.sample.position.y = data_point
359                    self.current_datainfo.sample.position_unit = unit
360                elif tagname == 'z' and self.parent_class == 'position':
361                    self.current_datainfo.sample.position.z = data_point
362                    self.current_datainfo.sample.position_unit = unit
363                elif tagname == 'roll' and self.parent_class == 'orientation' and 'SASsample' in self.names:
364                    self.current_datainfo.sample.orientation.x = data_point
365                    self.current_datainfo.sample.orientation_unit = unit
366                elif tagname == 'pitch' and self.parent_class == 'orientation' and 'SASsample' in self.names:
367                    self.current_datainfo.sample.orientation.y = data_point
368                    self.current_datainfo.sample.orientation_unit = unit
369                elif tagname == 'yaw' and self.parent_class == 'orientation' and 'SASsample' in self.names:
370                    self.current_datainfo.sample.orientation.z = data_point
371                    self.current_datainfo.sample.orientation_unit = unit
372
373                # Instrumental Information
374                elif tagname == 'name' and self.parent_class == 'SASinstrument':
375                    self.current_datainfo.instrument = data_point
376
377                # Detector Information
378                elif tagname == 'name' and self.parent_class == 'SASdetector':
379                    self.detector.name = data_point
380                elif tagname == 'SDD' and self.parent_class == 'SASdetector':
381                    self.detector.distance = data_point
382                    self.detector.distance_unit = unit
383                elif tagname == 'slit_length' and self.parent_class == 'SASdetector':
384                    self.detector.slit_length = data_point
385                    self.detector.slit_length_unit = unit
386                elif tagname == 'x' and self.parent_class == 'offset':
387                    self.detector.offset.x = data_point
388                    self.detector.offset_unit = unit
389                elif tagname == 'y' and self.parent_class == 'offset':
390                    self.detector.offset.y = data_point
391                    self.detector.offset_unit = unit
392                elif tagname == 'z' and self.parent_class == 'offset':
393                    self.detector.offset.z = data_point
394                    self.detector.offset_unit = unit
395                elif tagname == 'x' and self.parent_class == 'beam_center':
396                    self.detector.beam_center.x = data_point
397                    self.detector.beam_center_unit = unit
398                elif tagname == 'y' and self.parent_class == 'beam_center':
399                    self.detector.beam_center.y = data_point
400                    self.detector.beam_center_unit = unit
401                elif tagname == 'z' and self.parent_class == 'beam_center':
402                    self.detector.beam_center.z = data_point
403                    self.detector.beam_center_unit = unit
404                elif tagname == 'x' and self.parent_class == 'pixel_size':
405                    self.detector.pixel_size.x = data_point
406                    self.detector.pixel_size_unit = unit
407                elif tagname == 'y' and self.parent_class == 'pixel_size':
408                    self.detector.pixel_size.y = data_point
409                    self.detector.pixel_size_unit = unit
410                elif tagname == 'z' and self.parent_class == 'pixel_size':
411                    self.detector.pixel_size.z = data_point
412                    self.detector.pixel_size_unit = unit
413                elif tagname == 'roll' and self.parent_class == 'orientation' and 'SASdetector' in self.names:
414                    self.detector.orientation.x = data_point
415                    self.detector.orientation_unit = unit
416                elif tagname == 'pitch' and self.parent_class == 'orientation' and 'SASdetector' in self.names:
417                    self.detector.orientation.y = data_point
418                    self.detector.orientation_unit = unit
419                elif tagname == 'yaw' and self.parent_class == 'orientation' and 'SASdetector' in self.names:
420                    self.detector.orientation.z = data_point
421                    self.detector.orientation_unit = unit
422
423                # Collimation and Aperture
424                elif tagname == 'length' and self.parent_class == 'SAScollimation':
425                    self.collimation.length = data_point
426                    self.collimation.length_unit = unit
427                elif tagname == 'name' and self.parent_class == 'SAScollimation':
428                    self.collimation.name = data_point
429                elif tagname == 'distance' and self.parent_class == 'aperture':
430                    self.aperture.distance = data_point
431                    self.aperture.distance_unit = unit
432                elif tagname == 'x' and self.parent_class == 'size':
433                    self.aperture.size.x = data_point
434                    self.collimation.size_unit = unit
435                elif tagname == 'y' and self.parent_class == 'size':
436                    self.aperture.size.y = data_point
437                    self.collimation.size_unit = unit
438                elif tagname == 'z' and self.parent_class == 'size':
439                    self.aperture.size.z = data_point
440                    self.collimation.size_unit = unit
441
442                # Process Information
443                elif tagname == 'name' and self.parent_class == 'SASprocess':
444                    self.process.name = data_point
445                elif tagname == 'description' and self.parent_class == 'SASprocess':
446                    self.process.description = data_point
447                elif tagname == 'date' and self.parent_class == 'SASprocess':
448                    try:
449                        self.process.date = datetime.datetime.fromtimestamp(data_point)
450                    except:
451                        self.process.date = data_point
452                elif tagname == 'SASprocessnote':
453                    self.process.notes.append(data_point)
454                elif tagname == 'term' and self.parent_class == 'SASprocess':
455                    unit = attr.get("unit", "")
456                    dic = { "name": name, "value": data_point, "unit": unit }
457                    self.process.term.append(dic)
458
459                # Transmission Spectrum
460                elif tagname == 'T' and self.parent_class == 'Tdata':
461                    self.transspectrum.transmission = np.append(self.transspectrum.transmission, data_point)
462                    self.transspectrum.transmission_unit = unit
463                elif tagname == 'Tdev' and self.parent_class == 'Tdata':
464                    self.transspectrum.transmission_deviation = np.append(self.transspectrum.transmission_deviation, data_point)
465                    self.transspectrum.transmission_deviation_unit = unit
466                elif tagname == 'Lambda' and self.parent_class == 'Tdata':
467                    self.transspectrum.wavelength = np.append(self.transspectrum.wavelength, data_point)
468                    self.transspectrum.wavelength_unit = unit
469
470                # Source Information
471                elif tagname == 'wavelength' and (self.parent_class == 'SASsource' or self.parent_class == 'SASData'):
472                    self.current_datainfo.source.wavelength = data_point
473                    self.current_datainfo.source.wavelength_unit = unit
474                elif tagname == 'wavelength_min' and self.parent_class == 'SASsource':
475                    self.current_datainfo.source.wavelength_min = data_point
476                    self.current_datainfo.source.wavelength_min_unit = unit
477                elif tagname == 'wavelength_max' and self.parent_class == 'SASsource':
478                    self.current_datainfo.source.wavelength_max = data_point
479                    self.current_datainfo.source.wavelength_max_unit = unit
480                elif tagname == 'wavelength_spread' and self.parent_class == 'SASsource':
481                    self.current_datainfo.source.wavelength_spread = data_point
482                    self.current_datainfo.source.wavelength_spread_unit = unit
483                elif tagname == 'x' and self.parent_class == 'beam_size':
484                    self.current_datainfo.source.beam_size.x = data_point
485                    self.current_datainfo.source.beam_size_unit = unit
486                elif tagname == 'y' and self.parent_class == 'beam_size':
487                    self.current_datainfo.source.beam_size.y = data_point
488                    self.current_datainfo.source.beam_size_unit = unit
489                elif tagname == 'z' and self.parent_class == 'pixel_size':
490                    self.current_datainfo.source.data_point.z = data_point
491                    self.current_datainfo.source.beam_size_unit = unit
492                elif tagname == 'radiation' and self.parent_class == 'SASsource':
493                    self.current_datainfo.source.radiation = data_point
494                elif tagname == 'beam_shape' and self.parent_class == 'SASsource':
495                    self.current_datainfo.source.beam_shape = data_point
496
497                # Everything else goes in meta_data
498                else:
499                    new_key = self._create_unique_key(self.current_datainfo.meta_data, tagname)
500                    self.current_datainfo.meta_data[new_key] = data_point
501
502            self.names.remove(tagname_original)
503            length = 0
504            if len(self.names) > 1:
505                length = len(self.names) - 1
506            self.parent_class = self.names[length]
507        if not self._is_call_local() and not recurse:
508            self.frm = ""
509            self.current_datainfo.errors = set()
510            for error in self.errors:
511                self.current_datainfo.errors.add(error)
512            self.errors.clear()
513            self.send_to_output()
514            empty = None
515            return self.output[0], empty
516
517    def _is_call_local(self):
518        if self.frm == "":
519            inter = inspect.stack()
520            self.frm = inter[2]
521        mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "")
522        mod_name = mod_name.replace(".py", "")
523        mod = mod_name.split("sas/")
524        mod_name = mod[1]
525        if mod_name != "sascalc/dataloader/readers/cansas_reader":
526            return False
527        return True
528
529    def _add_intermediate(self):
530        """
531        This method stores any intermediate objects within the final data set after fully reading the set.
532        """
533        if self.parent_class == 'SASprocess':
534            self.current_datainfo.process.append(self.process)
535            self.process = Process()
536        elif self.parent_class == 'SASdetector':
537            self.current_datainfo.detector.append(self.detector)
538            self.detector = Detector()
539        elif self.parent_class == 'SAStransmission_spectrum':
540            self.current_datainfo.trans_spectrum.append(self.transspectrum)
541            self.transspectrum = TransmissionSpectrum()
542        elif self.parent_class == 'SAScollimation':
543            self.current_datainfo.collimation.append(self.collimation)
544            self.collimation = Collimation()
545        elif self.parent_class == 'aperture':
546            self.collimation.aperture.append(self.aperture)
547            self.aperture = Aperture()
548        elif self.parent_class == 'SASdata':
549            self._check_for_empty_resolution()
550            self.data.append(self.current_dataset)
551
552    def _get_node_value(self, node, tagname):
553        """
554        Get the value of a node and any applicable units
555
556        :param node: The XML node to get the value of
557        :param tagname: The tagname of the node
558        """
559        #Get the text from the node and convert all whitespace to spaces
560        units = ''
561        node_value = node.text
562        if node_value is not None:
563            node_value = ' '.join(node_value.split())
564        else:
565            node_value = ""
566
567        # If the value is a float, compile with units.
568        if self.ns_list.ns_datatype == "float":
569            # If an empty value is given, set as zero.
570            if node_value is None or node_value.isspace() \
571                                    or node_value.lower() == "nan":
572                node_value = "0.0"
573            #Convert the value to the base units
574            node_value, units = self._unit_conversion(node, tagname, node_value)
575
576        # If the value is a timestamp, convert to a datetime object
577        elif self.ns_list.ns_datatype == "timestamp":
578            if node_value is None or node_value.isspace():
579                pass
580            else:
581                try:
582                    node_value = \
583                        datetime.datetime.fromtimestamp(node_value)
584                except ValueError:
585                    node_value = None
586        return node_value, units
587
588    def _unit_conversion(self, node, tagname, node_value):
589        """
590        A unit converter method used to convert the data included in the file
591        to the default units listed in data_info
592
593        :param node: XML node
594        :param tagname: name of the node
595        :param node_value: The value of the current dom node
596        """
597        attr = node.attrib
598        value_unit = ''
599        err_msg = None
600        default_unit = None
601        if not isinstance(node_value, float):
602            node_value = float(node_value)
603        if 'unit' in attr and attr.get('unit') is not None:
604            try:
605                local_unit = attr['unit']
606                unitname = self.ns_list.current_level.get("unit", "")
607                if "SASdetector" in self.names:
608                    save_in = "detector"
609                elif "aperture" in self.names:
610                    save_in = "aperture"
611                elif "SAScollimation" in self.names:
612                    save_in = "collimation"
613                elif "SAStransmission_spectrum" in self.names:
614                    save_in = "transspectrum"
615                elif "SASdata" in self.names:
616                    x = np.zeros(1)
617                    y = np.zeros(1)
618                    self.current_data1d = Data1D(x, y)
619                    save_in = "current_data1d"
620                elif "SASsource" in self.names:
621                    save_in = "current_datainfo.source"
622                elif "SASsample" in self.names:
623                    save_in = "current_datainfo.sample"
624                elif "SASprocess" in self.names:
625                    save_in = "process"
626                else:
627                    save_in = "current_datainfo"
628                exec "default_unit = self.{0}.{1}".format(save_in, unitname)
629                if local_unit and default_unit and local_unit.lower() != default_unit.lower() \
630                        and local_unit.lower() != "none":
631                    if HAS_CONVERTER == True:
632                        # Check local units - bad units raise KeyError
633                        data_conv_q = Converter(local_unit)
634                        value_unit = default_unit
635                        node_value = data_conv_q(node_value, units=default_unit)
636                    else:
637                        value_unit = local_unit
638                        err_msg = "Unit converter is not available.\n"
639                else:
640                    value_unit = local_unit
641            except KeyError:
642                err_msg = "CanSAS reader: unexpected "
643                err_msg += "\"{0}\" unit [{1}]; "
644                err_msg = err_msg.format(tagname, local_unit)
645                err_msg += "expecting [{0}]".format(default_unit)
646                value_unit = local_unit
647            except:
648                err_msg = "CanSAS reader: unknown error converting "
649                err_msg += "\"{0}\" unit [{1}]"
650                err_msg = err_msg.format(tagname, local_unit)
651                value_unit = local_unit
652        elif 'unit' in attr:
653            value_unit = attr['unit']
654        if err_msg:
655            self.errors.add(err_msg)
656        return node_value, value_unit
657
658    def _check_for_empty_resolution(self):
659        """
660        a method to check all resolution data sets are the same size as I and q
661        """
662        dql_exists = False
663        dqw_exists = False
664        dq_exists = False
665        di_exists = False
666        if self.current_dataset.dxl is not None:
667            dql_exists = True
668        if self.current_dataset.dxw is not None:
669            dqw_exists = True
670        if self.current_dataset.dx is not None:
671            dq_exists = True
672        if self.current_dataset.dy is not None:
673            di_exists = True
674        if dqw_exists and not dql_exists:
675            array_size = self.current_dataset.dxw.size - 1
676            self.current_dataset.dxl = np.append(self.current_dataset.dxl,
677                                                 np.zeros([array_size]))
678        elif dql_exists and not dqw_exists:
679            array_size = self.current_dataset.dxl.size - 1
680            self.current_dataset.dxw = np.append(self.current_dataset.dxw,
681                                                 np.zeros([array_size]))
682        elif not dql_exists and not dqw_exists and not dq_exists:
683            array_size = self.current_dataset.x.size - 1
684            self.current_dataset.dx = np.append(self.current_dataset.dx,
685                                                np.zeros([array_size]))
686        if not di_exists:
687            array_size = self.current_dataset.y.size - 1
688            self.current_dataset.dy = np.append(self.current_dataset.dy,
689                                                np.zeros([array_size]))
690
691    def _initialize_new_data_set(self, node=None):
692        if node is not None:
693            for child in node:
694                if child.tag.replace(self.base_ns, "") == "Idata":
695                    for i_child in child:
696                        if i_child.tag.replace(self.base_ns, "") == "Qx":
697                            self.current_dataset = plottable_2D()
698                            return
699        self.current_dataset = plottable_1D(np.array(0), np.array(0))
700
701    ## Writing Methods
702    def write(self, filename, datainfo):
703        """
704        Write the content of a Data1D as a CanSAS XML file
705
706        :param filename: name of the file to write
707        :param datainfo: Data1D object
708        """
709        # Create XML document
710        doc, _ = self._to_xml_doc(datainfo)
711        # Write the file
712        file_ref = open(filename, 'w')
713        if self.encoding is None:
714            self.encoding = "UTF-8"
715        doc.write(file_ref, encoding=self.encoding,
716                  pretty_print=True, xml_declaration=True)
717        file_ref.close()
718
719    def _to_xml_doc(self, datainfo):
720        """
721        Create an XML document to contain the content of a Data1D
722
723        :param datainfo: Data1D object
724        """
725        is_2d = False
726        if issubclass(datainfo.__class__, Data2D):
727            is_2d = True
728
729        # Get PIs and create root element
730        pi_string = self._get_pi_string()
731        # Define namespaces and create SASroot object
732        main_node = self._create_main_node()
733        # Create ElementTree, append SASroot and apply processing instructions
734        base_string = pi_string + self.to_string(main_node)
735        base_element = self.create_element_from_string(base_string)
736        doc = self.create_tree(base_element)
737        # Create SASentry Element
738        entry_node = self.create_element("SASentry")
739        root = doc.getroot()
740        root.append(entry_node)
741
742        # Add Title to SASentry
743        self.write_node(entry_node, "Title", datainfo.title)
744        # Add Run to SASentry
745        self._write_run_names(datainfo, entry_node)
746        # Add Data info to SASEntry
747        if is_2d:
748            self._write_data_2d(datainfo, entry_node)
749        else:
750            self._write_data(datainfo, entry_node)
751        # Transmission Spectrum Info
752        # TODO: fix the writer to linearize all data, including T_spectrum
753        # self._write_trans_spectrum(datainfo, entry_node)
754        # Sample info
755        self._write_sample_info(datainfo, entry_node)
756        # Instrument info
757        instr = self._write_instrument(datainfo, entry_node)
758        #   Source
759        self._write_source(datainfo, instr)
760        #   Collimation
761        self._write_collimation(datainfo, instr)
762        #   Detectors
763        self._write_detectors(datainfo, instr)
764        # Processes info
765        self._write_process_notes(datainfo, entry_node)
766        # Note info
767        self._write_notes(datainfo, entry_node)
768        # Return the document, and the SASentry node associated with
769        #      the data we just wrote
770        # If the calling function was not the cansas reader, return a minidom
771        #      object rather than an lxml object.
772        self.frm = inspect.stack()[1]
773        doc, entry_node = self._check_origin(entry_node, doc)
774        return doc, entry_node
775
776    def write_node(self, parent, name, value, attr=None):
777        """
778        :param doc: document DOM
779        :param parent: parent node
780        :param name: tag of the element
781        :param value: value of the child text node
782        :param attr: attribute dictionary
783
784        :return: True if something was appended, otherwise False
785        """
786        if value is not None:
787            parent = self.ebuilder(parent, name, value, attr)
788            return True
789        return False
790
791    def _get_pi_string(self):
792        """
793        Creates the processing instructions header for writing to file
794        """
795        pis = self.return_processing_instructions()
796        if len(pis) > 0:
797            pi_tree = self.create_tree(pis[0])
798            i = 1
799            for i in range(1, len(pis) - 1):
800                pi_tree = self.append(pis[i], pi_tree)
801            pi_string = self.to_string(pi_tree)
802        else:
803            pi_string = ""
804        return pi_string
805
806    def _create_main_node(self):
807        """
808        Creates the primary xml header used when writing to file
809        """
810        xsi = "http://www.w3.org/2001/XMLSchema-instance"
811        version = self.cansas_version
812        n_s = CANSAS_NS.get(version).get("ns")
813        if version == "1.1":
814            url = "http://www.cansas.org/formats/1.1/"
815        else:
816            url = "http://svn.smallangles.net/svn/canSAS/1dwg/trunk/"
817        schema_location = "{0} {1}cansas1d.xsd".format(n_s, url)
818        attrib = {"{" + xsi + "}schemaLocation" : schema_location,
819                  "version" : version}
820        nsmap = {'xsi' : xsi, None: n_s}
821
822        main_node = self.create_element("{" + n_s + "}SASroot",
823                                        attrib=attrib, nsmap=nsmap)
824        return main_node
825
826    def _write_run_names(self, datainfo, entry_node):
827        """
828        Writes the run names to the XML file
829
830        :param datainfo: The Data1D object the information is coming from
831        :param entry_node: lxml node ElementTree object to be appended to
832        """
833        if datainfo.run is None or datainfo.run == []:
834            datainfo.run.append(RUN_NAME_DEFAULT)
835            datainfo.run_name[RUN_NAME_DEFAULT] = RUN_NAME_DEFAULT
836        for item in datainfo.run:
837            runname = {}
838            if item in datainfo.run_name and \
839            len(str(datainfo.run_name[item])) > 1:
840                runname = {'name': datainfo.run_name[item]}
841            self.write_node(entry_node, "Run", item, runname)
842
843    def _write_data(self, datainfo, entry_node):
844        """
845        Writes 1D I and Q data to the XML file
846
847        :param datainfo: The Data1D object the information is coming from
848        :param entry_node: lxml node ElementTree object to be appended to
849        """
850        node = self.create_element("SASdata")
851        self.append(node, entry_node)
852
853        for i in range(len(datainfo.x)):
854            point = self.create_element("Idata")
855            node.append(point)
856            self.write_node(point, "Q", datainfo.x[i],
857                            {'unit': datainfo._xaxis + " | " + datainfo._xunit})
858            if len(datainfo.y) >= i:
859                self.write_node(point, "I", datainfo.y[i],
860                                {'unit': datainfo._yaxis + " | " + datainfo._yunit})
861            if datainfo.dy is not None and len(datainfo.dy) > i:
862                self.write_node(point, "Idev", datainfo.dy[i],
863                                {'unit': datainfo._yaxis + " | " + datainfo._yunit})
864            if datainfo.dx is not None and len(datainfo.dx) > i:
865                self.write_node(point, "Qdev", datainfo.dx[i],
866                                {'unit': datainfo._xaxis + " | " + datainfo._xunit})
867            if datainfo.dxw is not None and len(datainfo.dxw) > i:
868                self.write_node(point, "dQw", datainfo.dxw[i],
869                                {'unit': datainfo._xaxis + " | " + datainfo._xunit})
870            if datainfo.dxl is not None and len(datainfo.dxl) > i:
871                self.write_node(point, "dQl", datainfo.dxl[i],
872                                {'unit': datainfo._xaxis + " | " + datainfo._xunit})
873        if datainfo.isSesans:
874            sesans = self.create_element("Sesans")
875            sesans.text = str(datainfo.isSesans)
876            node.append(sesans)
877            self.write_node(node, "yacceptance", datainfo.sample.yacceptance[0],
878                             {'unit': datainfo.sample.yacceptance[1]})
879            self.write_node(node, "zacceptance", datainfo.sample.zacceptance[0],
880                             {'unit': datainfo.sample.zacceptance[1]})
881
882
883    def _write_data_2d(self, datainfo, entry_node):
884        """
885        Writes 2D data to the XML file
886
887        :param datainfo: The Data2D object the information is coming from
888        :param entry_node: lxml node ElementTree object to be appended to
889        """
890        attr = {}
891        if datainfo.data.shape:
892            attr["x_bins"] = str(len(datainfo.x_bins))
893            attr["y_bins"] = str(len(datainfo.y_bins))
894        node = self.create_element("SASdata", attr)
895        self.append(node, entry_node)
896
897        point = self.create_element("Idata")
898        node.append(point)
899        qx = ','.join([str(datainfo.qx_data[i]) for i in xrange(len(datainfo.qx_data))])
900        qy = ','.join([str(datainfo.qy_data[i]) for i in xrange(len(datainfo.qy_data))])
901        intensity = ','.join([str(datainfo.data[i]) for i in xrange(len(datainfo.data))])
902
903        self.write_node(point, "Qx", qx,
904                        {'unit': datainfo._xunit})
905        self.write_node(point, "Qy", qy,
906                        {'unit': datainfo._yunit})
907        self.write_node(point, "I", intensity,
908                        {'unit': datainfo._zunit})
909        if datainfo.err_data is not None:
910            err = ','.join([str(datainfo.err_data[i]) for i in
911                            xrange(len(datainfo.err_data))])
912            self.write_node(point, "Idev", err,
913                            {'unit': datainfo._zunit})
914        if datainfo.dqy_data is not None:
915            dqy = ','.join([str(datainfo.dqy_data[i]) for i in
916                            xrange(len(datainfo.dqy_data))])
917            self.write_node(point, "Qydev", dqy,
918                            {'unit': datainfo._yunit})
919        if datainfo.dqx_data is not None:
920            dqx = ','.join([str(datainfo.dqx_data[i]) for i in
921                            xrange(len(datainfo.dqx_data))])
922            self.write_node(point, "Qxdev", dqx,
923                            {'unit': datainfo._xunit})
924        if datainfo.mask is not None:
925            mask = ','.join(
926                ["1" if datainfo.mask[i] else "0"
927                 for i in xrange(len(datainfo.mask))])
928            self.write_node(point, "Mask", mask)
929
930    def _write_trans_spectrum(self, datainfo, entry_node):
931        """
932        Writes the transmission spectrum data to the XML file
933
934        :param datainfo: The Data1D object the information is coming from
935        :param entry_node: lxml node ElementTree object to be appended to
936        """
937        for i in range(len(datainfo.trans_spectrum)):
938            spectrum = datainfo.trans_spectrum[i]
939            node = self.create_element("SAStransmission_spectrum",
940                                       {"name" : spectrum.name})
941            self.append(node, entry_node)
942            if isinstance(spectrum.timestamp, datetime.datetime):
943                node.setAttribute("timestamp", spectrum.timestamp)
944            for i in range(len(spectrum.wavelength)):
945                point = self.create_element("Tdata")
946                node.append(point)
947                self.write_node(point, "Lambda", spectrum.wavelength[i],
948                                {'unit': spectrum.wavelength_unit})
949                self.write_node(point, "T", spectrum.transmission[i],
950                                {'unit': spectrum.transmission_unit})
951                if spectrum.transmission_deviation is not None \
952                and len(spectrum.transmission_deviation) >= i:
953                    self.write_node(point, "Tdev",
954                                    spectrum.transmission_deviation[i],
955                                    {'unit':
956                                     spectrum.transmission_deviation_unit})
957
958    def _write_sample_info(self, datainfo, entry_node):
959        """
960        Writes the sample information to the XML file
961
962        :param datainfo: The Data1D object the information is coming from
963        :param entry_node: lxml node ElementTree object to be appended to
964        """
965        sample = self.create_element("SASsample")
966        if datainfo.sample.name is not None:
967            self.write_attribute(sample, "name",
968                                 str(datainfo.sample.name))
969        self.append(sample, entry_node)
970        self.write_node(sample, "ID", str(datainfo.sample.ID))
971        self.write_node(sample, "thickness", datainfo.sample.thickness,
972                        {"unit": datainfo.sample.thickness_unit})
973        self.write_node(sample, "transmission", datainfo.sample.transmission)
974        self.write_node(sample, "temperature", datainfo.sample.temperature,
975                        {"unit": datainfo.sample.temperature_unit})
976
977        pos = self.create_element("position")
978        written = self.write_node(pos,
979                                  "x",
980                                  datainfo.sample.position.x,
981                                  {"unit": datainfo.sample.position_unit})
982        written = written | self.write_node( \
983            pos, "y", datainfo.sample.position.y,
984            {"unit": datainfo.sample.position_unit})
985        written = written | self.write_node( \
986            pos, "z", datainfo.sample.position.z,
987            {"unit": datainfo.sample.position_unit})
988        if written == True:
989            self.append(pos, sample)
990
991        ori = self.create_element("orientation")
992        written = self.write_node(ori, "roll",
993                                  datainfo.sample.orientation.x,
994                                  {"unit": datainfo.sample.orientation_unit})
995        written = written | self.write_node( \
996            ori, "pitch", datainfo.sample.orientation.y,
997            {"unit": datainfo.sample.orientation_unit})
998        written = written | self.write_node( \
999            ori, "yaw", datainfo.sample.orientation.z,
1000            {"unit": datainfo.sample.orientation_unit})
1001        if written == True:
1002            self.append(ori, sample)
1003
1004        for item in datainfo.sample.details:
1005            self.write_node(sample, "details", item)
1006
1007    def _write_instrument(self, datainfo, entry_node):
1008        """
1009        Writes the instrumental information to the XML file
1010
1011        :param datainfo: The Data1D object the information is coming from
1012        :param entry_node: lxml node ElementTree object to be appended to
1013        """
1014        instr = self.create_element("SASinstrument")
1015        self.append(instr, entry_node)
1016        self.write_node(instr, "name", datainfo.instrument)
1017        return instr
1018
1019    def _write_source(self, datainfo, instr):
1020        """
1021        Writes the source information to the XML file
1022
1023        :param datainfo: The Data1D object the information is coming from
1024        :param instr: instrument node  to be appended to
1025        """
1026        source = self.create_element("SASsource")
1027        if datainfo.source.name is not None:
1028            self.write_attribute(source, "name",
1029                                 str(datainfo.source.name))
1030        self.append(source, instr)
1031        if datainfo.source.radiation is None or datainfo.source.radiation == '':
1032            datainfo.source.radiation = "neutron"
1033        self.write_node(source, "radiation", datainfo.source.radiation)
1034
1035        size = self.create_element("beam_size")
1036        if datainfo.source.beam_size_name is not None:
1037            self.write_attribute(size, "name",
1038                                 str(datainfo.source.beam_size_name))
1039        written = self.write_node( \
1040            size, "x", datainfo.source.beam_size.x,
1041            {"unit": datainfo.source.beam_size_unit})
1042        written = written | self.write_node( \
1043            size, "y", datainfo.source.beam_size.y,
1044            {"unit": datainfo.source.beam_size_unit})
1045        written = written | self.write_node( \
1046            size, "z", datainfo.source.beam_size.z,
1047            {"unit": datainfo.source.beam_size_unit})
1048        if written == True:
1049            self.append(size, source)
1050
1051        self.write_node(source, "beam_shape", datainfo.source.beam_shape)
1052        self.write_node(source, "wavelength",
1053                        datainfo.source.wavelength,
1054                        {"unit": datainfo.source.wavelength_unit})
1055        self.write_node(source, "wavelength_min",
1056                        datainfo.source.wavelength_min,
1057                        {"unit": datainfo.source.wavelength_min_unit})
1058        self.write_node(source, "wavelength_max",
1059                        datainfo.source.wavelength_max,
1060                        {"unit": datainfo.source.wavelength_max_unit})
1061        self.write_node(source, "wavelength_spread",
1062                        datainfo.source.wavelength_spread,
1063                        {"unit": datainfo.source.wavelength_spread_unit})
1064
1065    def _write_collimation(self, datainfo, instr):
1066        """
1067        Writes the collimation information to the XML file
1068
1069        :param datainfo: The Data1D object the information is coming from
1070        :param instr: lxml node ElementTree object to be appended to
1071        """
1072        if datainfo.collimation == [] or datainfo.collimation is None:
1073            coll = Collimation()
1074            datainfo.collimation.append(coll)
1075        for item in datainfo.collimation:
1076            coll = self.create_element("SAScollimation")
1077            if item.name is not None:
1078                self.write_attribute(coll, "name", str(item.name))
1079            self.append(coll, instr)
1080
1081            self.write_node(coll, "length", item.length,
1082                            {"unit": item.length_unit})
1083
1084            for aperture in item.aperture:
1085                apert = self.create_element("aperture")
1086                if aperture.name is not None:
1087                    self.write_attribute(apert, "name", str(aperture.name))
1088                if aperture.type is not None:
1089                    self.write_attribute(apert, "type", str(aperture.type))
1090                self.append(apert, coll)
1091
1092                size = self.create_element("size")
1093                if aperture.size_name is not None:
1094                    self.write_attribute(size, "name",
1095                                         str(aperture.size_name))
1096                written = self.write_node(size, "x", aperture.size.x,
1097                                          {"unit": aperture.size_unit})
1098                written = written | self.write_node( \
1099                    size, "y", aperture.size.y,
1100                    {"unit": aperture.size_unit})
1101                written = written | self.write_node( \
1102                    size, "z", aperture.size.z,
1103                    {"unit": aperture.size_unit})
1104                if written == True:
1105                    self.append(size, apert)
1106
1107                self.write_node(apert, "distance", aperture.distance,
1108                                {"unit": aperture.distance_unit})
1109
1110    def _write_detectors(self, datainfo, instr):
1111        """
1112        Writes the detector information to the XML file
1113
1114        :param datainfo: The Data1D object the information is coming from
1115        :param inst: lxml instrument node to be appended to
1116        """
1117        if datainfo.detector is None or datainfo.detector == []:
1118            det = Detector()
1119            det.name = ""
1120            datainfo.detector.append(det)
1121
1122        for item in datainfo.detector:
1123            det = self.create_element("SASdetector")
1124            written = self.write_node(det, "name", item.name)
1125            written = written | self.write_node(det, "SDD", item.distance,
1126                                                {"unit": item.distance_unit})
1127            if written == True:
1128                self.append(det, instr)
1129
1130            off = self.create_element("offset")
1131            written = self.write_node(off, "x", item.offset.x,
1132                                      {"unit": item.offset_unit})
1133            written = written | self.write_node(off, "y", item.offset.y,
1134                                                {"unit": item.offset_unit})
1135            written = written | self.write_node(off, "z", item.offset.z,
1136                                                {"unit": item.offset_unit})
1137            if written == True:
1138                self.append(off, det)
1139
1140            ori = self.create_element("orientation")
1141            written = self.write_node(ori, "roll", item.orientation.x,
1142                                      {"unit": item.orientation_unit})
1143            written = written | self.write_node(ori, "pitch",
1144                                                item.orientation.y,
1145                                                {"unit": item.orientation_unit})
1146            written = written | self.write_node(ori, "yaw",
1147                                                item.orientation.z,
1148                                                {"unit": item.orientation_unit})
1149            if written == True:
1150                self.append(ori, det)
1151
1152            center = self.create_element("beam_center")
1153            written = self.write_node(center, "x", item.beam_center.x,
1154                                      {"unit": item.beam_center_unit})
1155            written = written | self.write_node(center, "y",
1156                                                item.beam_center.y,
1157                                                {"unit": item.beam_center_unit})
1158            written = written | self.write_node(center, "z",
1159                                                item.beam_center.z,
1160                                                {"unit": item.beam_center_unit})
1161            if written == True:
1162                self.append(center, det)
1163
1164            pix = self.create_element("pixel_size")
1165            written = self.write_node(pix, "x", item.pixel_size.x,
1166                                      {"unit": item.pixel_size_unit})
1167            written = written | self.write_node(pix, "y", item.pixel_size.y,
1168                                                {"unit": item.pixel_size_unit})
1169            written = written | self.write_node(pix, "z", item.pixel_size.z,
1170                                                {"unit": item.pixel_size_unit})
1171            if written == True:
1172                self.append(pix, det)
1173            self.write_node(det, "slit_length", item.slit_length,
1174                {"unit": item.slit_length_unit})
1175
1176
1177    def _write_process_notes(self, datainfo, entry_node):
1178        """
1179        Writes the process notes to the XML file
1180
1181        :param datainfo: The Data1D object the information is coming from
1182        :param entry_node: lxml node ElementTree object to be appended to
1183
1184        """
1185        for item in datainfo.process:
1186            node = self.create_element("SASprocess")
1187            self.append(node, entry_node)
1188            self.write_node(node, "name", item.name)
1189            self.write_node(node, "date", item.date)
1190            self.write_node(node, "description", item.description)
1191            for term in item.term:
1192                if isinstance(term, list):
1193                    value = term['value']
1194                    del term['value']
1195                elif isinstance(term, dict):
1196                    value = term.get("value")
1197                    del term['value']
1198                else:
1199                    value = term
1200                self.write_node(node, "term", value, term)
1201            for note in item.notes:
1202                self.write_node(node, "SASprocessnote", note)
1203            if len(item.notes) == 0:
1204                self.write_node(node, "SASprocessnote", "")
1205
1206    def _write_notes(self, datainfo, entry_node):
1207        """
1208        Writes the notes to the XML file and creates an empty note if none
1209        exist
1210
1211        :param datainfo: The Data1D object the information is coming from
1212        :param entry_node: lxml node ElementTree object to be appended to
1213
1214        """
1215        if len(datainfo.notes) == 0:
1216            node = self.create_element("SASnote")
1217            self.append(node, entry_node)
1218        else:
1219            for item in datainfo.notes:
1220                node = self.create_element("SASnote")
1221                self.write_text(node, item)
1222                self.append(node, entry_node)
1223
1224    def _check_origin(self, entry_node, doc):
1225        """
1226        Return the document, and the SASentry node associated with
1227        the data we just wrote.
1228        If the calling function was not the cansas reader, return a minidom
1229        object rather than an lxml object.
1230
1231        :param entry_node: lxml node ElementTree object to be appended to
1232        :param doc: entire xml tree
1233        """
1234        if not self.frm:
1235            self.frm = inspect.stack()[1]
1236        mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "")
1237        mod_name = mod_name.replace(".py", "")
1238        mod = mod_name.split("sas/")
1239        mod_name = mod[1]
1240        if mod_name != "sascalc/dataloader/readers/cansas_reader":
1241            string = self.to_string(doc, pretty_print=False)
1242            doc = parseString(string)
1243            node_name = entry_node.tag
1244            node_list = doc.getElementsByTagName(node_name)
1245            entry_node = node_list.item(0)
1246        return doc, entry_node
1247
1248    # DO NOT REMOVE - used in saving and loading panel states.
1249    def _store_float(self, location, node, variable, storage, optional=True):
1250        """
1251        Get the content of a xpath location and store
1252        the result. Check that the units are compatible
1253        with the destination. The value is expected to
1254        be a float.
1255
1256        The xpath location might or might not exist.
1257        If it does not exist, nothing is done
1258
1259        :param location: xpath location to fetch
1260        :param node: node to read the data from
1261        :param variable: name of the data member to store it in [string]
1262        :param storage: data object that has the 'variable' data member
1263        :param optional: if True, no exception will be raised
1264            if unit conversion can't be done
1265
1266        :raise ValueError: raised when the units are not recognized
1267        """
1268        entry = get_content(location, node)
1269        try:
1270            value = float(entry.text)
1271        except:
1272            value = None
1273
1274        if value is not None:
1275            # If the entry has units, check to see that they are
1276            # compatible with what we currently have in the data object
1277            units = entry.get('unit')
1278            if units is not None:
1279                toks = variable.split('.')
1280                local_unit = None
1281                exec "local_unit = storage.%s_unit" % toks[0]
1282                if local_unit is not None and units.lower() != local_unit.lower():
1283                    if HAS_CONVERTER == True:
1284                        try:
1285                            conv = Converter(units)
1286                            exec "storage.%s = %g" % \
1287                                (variable, conv(value, units=local_unit))
1288                        except:
1289                            _, exc_value, _ = sys.exc_info()
1290                            err_mess = "CanSAS reader: could not convert"
1291                            err_mess += " %s unit [%s]; expecting [%s]\n  %s" \
1292                                % (variable, units, local_unit, exc_value)
1293                            self.errors.add(err_mess)
1294                            if optional:
1295                                logger.info(err_mess)
1296                            else:
1297                                raise ValueError, err_mess
1298                    else:
1299                        err_mess = "CanSAS reader: unrecognized %s unit [%s];"\
1300                        % (variable, units)
1301                        err_mess += " expecting [%s]" % local_unit
1302                        self.errors.add(err_mess)
1303                        if optional:
1304                            logger.info(err_mess)
1305                        else:
1306                            raise ValueError, err_mess
1307                else:
1308                    exec "storage.%s = value" % variable
1309            else:
1310                exec "storage.%s = value" % variable
1311
1312    # DO NOT REMOVE - used in saving and loading panel states.
1313    def _store_content(self, location, node, variable, storage):
1314        """
1315        Get the content of a xpath location and store
1316        the result. The value is treated as a string.
1317
1318        The xpath location might or might not exist.
1319        If it does not exist, nothing is done
1320
1321        :param location: xpath location to fetch
1322        :param node: node to read the data from
1323        :param variable: name of the data member to store it in [string]
1324        :param storage: data object that has the 'variable' data member
1325
1326        :return: return a list of errors
1327        """
1328        entry = get_content(location, node)
1329        if entry is not None and entry.text is not None:
1330            exec "storage.%s = entry.text.strip()" % variable
1331
1332# DO NOT REMOVE Called by outside packages:
1333#    sas.sasgui.perspectives.invariant.invariant_state
1334#    sas.sasgui.perspectives.fitting.pagestate
1335def get_content(location, node):
1336    """
1337    Get the first instance of the content of a xpath location.
1338
1339    :param location: xpath location
1340    :param node: node to start at
1341
1342    :return: Element, or None
1343    """
1344    nodes = node.xpath(location,
1345                       namespaces={'ns': CANSAS_NS.get("1.0").get("ns")})
1346    if len(nodes) > 0:
1347        return nodes[0]
1348    else:
1349        return None
1350
1351# DO NOT REMOVE Called by outside packages:
1352#    sas.sasgui.perspectives.fitting.pagestate
1353def write_node(doc, parent, name, value, attr=None):
1354    """
1355    :param doc: document DOM
1356    :param parent: parent node
1357    :param name: tag of the element
1358    :param value: value of the child text node
1359    :param attr: attribute dictionary
1360
1361    :return: True if something was appended, otherwise False
1362    """
1363    if attr is None:
1364        attr = {}
1365    if value is not None:
1366        node = doc.createElement(name)
1367        node.appendChild(doc.createTextNode(str(value)))
1368        for item in attr:
1369            node.setAttribute(item, attr[item])
1370        parent.appendChild(node)
1371        return True
1372    return False
Note: See TracBrowser for help on using the repository browser.