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

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

Merge branch 'master' into 4_1_issues

# Conflicts:
# src/sas/sascalc/dataloader/readers/cansas_reader.py

  • Property mode set to 100644
File size: 63.5 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                    if invalid_xml != "":
157                        invalid_xml = INVALID_XML.format(basename + self.extension) + invalid_xml
158                        raise DataReaderException(invalid_xml) # Handled by base class
159                except FileContentsException as fc_exc:
160                    msg = "CanSAS Reader could not load the file {}".format(xml_file)
161                    if fc_exc.message is not None: # Propagate error messages from earlier
162                        msg = fc_exc.message
163                    if not self.extension in self.ext: # If the file has no associated loader
164                        raise DefaultReaderException(msg)
165                    raise FileContentsException(msg)
166                    pass
167            else:
168                raise fc_exc
169        except Exception as e: # Convert all other exceptions to FileContentsExceptions
170            raise FileContentsException(e.message)
171
172
173    def load_file_and_schema(self, xml_file, schema_path=""):
174        base_name = xml_reader.__file__
175        base_name = base_name.replace("\\", "/")
176        base = base_name.split("/sas/")[0]
177
178        # Try and parse the XML file
179        try:
180            self.set_xml_file(xml_file)
181        except etree.XMLSyntaxError: # File isn't valid XML so can't be loaded
182            msg = "SasView cannot load {}.\nInvalid XML syntax".format(xml_file)
183            raise FileContentsException(msg)
184
185        self.cansas_version = self.xmlroot.get("version", "1.0")
186        self.cansas_defaults = CANSAS_NS.get(self.cansas_version, "1.0")
187
188        if schema_path == "":
189            schema_path = "{}/sas/sascalc/dataloader/readers/schema/{}".format(
190                base, self.cansas_defaults.get("schema").replace("\\", "/")
191            )
192        self.set_schema(schema_path)
193
194    def is_cansas(self, ext="xml"):
195        """
196        Checks to see if the XML file is a CanSAS file
197
198        :param ext: The file extension of the data file
199        :raises FileContentsException: Raised if XML file isn't valid CanSAS
200        """
201        if self.validate_xml(): # Check file is valid XML
202            name = "{http://www.w3.org/2001/XMLSchema-instance}schemaLocation"
203            value = self.xmlroot.get(name)
204            # Check schema CanSAS version matches file CanSAS version
205            if CANSAS_NS.get(self.cansas_version).get("ns") == value.rsplit(" ")[0]:
206                return True
207        if ext == "svs":
208            return True # Why is this required?
209        # If we get to this point then file isn't valid CanSAS
210        logger.warning("File doesn't meet CanSAS schema. Trying to load anyway.")
211        raise FileContentsException("The file is not valid CanSAS")
212
213    def _parse_entry(self, dom, recurse=False):
214        if not self._is_call_local() and not recurse:
215            self.reset_state()
216            self.data = []
217            self.current_datainfo = DataInfo()
218            self.names.append("SASentry")
219            self.parent_class = "SASentry"
220        # Create an empty dataset if no data has been passed to the reader
221        if self.current_dataset is None:
222            self.current_dataset = plottable_1D(np.empty(0), np.empty(0),
223                np.empty(0), np.empty(0))
224        self.base_ns = "{" + CANSAS_NS.get(self.cansas_version).get("ns") + "}"
225
226        # Loop through each child in the parent element
227        for node in dom:
228            attr = node.attrib
229            name = attr.get("name", "")
230            type = attr.get("type", "")
231            # Get the element name and set the current names level
232            tagname = node.tag.replace(self.base_ns, "")
233            tagname_original = tagname
234            # Skip this iteration when loading in save state information
235            if tagname == "fitting_plug_in" or tagname == "pr_inversion" or tagname == "invariant":
236                continue
237            # Get where to store content
238            self.names.append(tagname_original)
239            self.ns_list = CONSTANTS.iterate_namespace(self.names)
240            # If the element is a child element, recurse
241            if len(node.getchildren()) > 0:
242                self.parent_class = tagname_original
243                if tagname == 'SASdata':
244                    self._initialize_new_data_set(node)
245                    if isinstance(self.current_dataset, plottable_2D):
246                        x_bins = attr.get("x_bins", "")
247                        y_bins = attr.get("y_bins", "")
248                        if x_bins is not "" and y_bins is not "":
249                            self.current_dataset.shape = (x_bins, y_bins)
250                        else:
251                            self.current_dataset.shape = ()
252                # Recurse to access data within the group
253                self._parse_entry(node, recurse=True)
254                if tagname == "SASsample":
255                    self.current_datainfo.sample.name = name
256                elif tagname == "beam_size":
257                    self.current_datainfo.source.beam_size_name = name
258                elif tagname == "SAScollimation":
259                    self.collimation.name = name
260                elif tagname == "aperture":
261                    self.aperture.name = name
262                    self.aperture.type = type
263                self._add_intermediate()
264            else:
265                if isinstance(self.current_dataset, plottable_2D):
266                    data_point = node.text
267                    unit = attr.get('unit', '')
268                else:
269                    data_point, unit = self._get_node_value(node, tagname)
270
271                # If this is a dataset, store the data appropriately
272                if tagname == 'Run':
273                    self.current_datainfo.run_name[data_point] = name
274                    self.current_datainfo.run.append(data_point)
275                elif tagname == 'Title':
276                    self.current_datainfo.title = data_point
277                elif tagname == 'SASnote':
278                    self.current_datainfo.notes.append(data_point)
279
280                # I and Q points
281                elif tagname == 'I' and isinstance(self.current_dataset, plottable_1D):
282                    self.current_dataset.yaxis("Intensity", unit)
283                    self.current_dataset.y = np.append(self.current_dataset.y, data_point)
284                elif tagname == 'Idev' and isinstance(self.current_dataset, plottable_1D):
285                    self.current_dataset.dy = np.append(self.current_dataset.dy, data_point)
286                elif tagname == 'Q':
287                    self.current_dataset.xaxis("Q", unit)
288                    self.current_dataset.x = np.append(self.current_dataset.x, data_point)
289                elif tagname == 'Qdev':
290                    self.current_dataset.dx = np.append(self.current_dataset.dx, data_point)
291                elif tagname == 'dQw':
292                    if self.current_dataset.dxw is None:
293                        self.current_dataset.dxw = np.empty(0)
294                    self.current_dataset.dxw = np.append(self.current_dataset.dxw, data_point)
295                elif tagname == 'dQl':
296                    if self.current_dataset.dxl is None:
297                        self.current_dataset.dxl = np.empty(0)
298                    self.current_dataset.dxl = np.append(self.current_dataset.dxl, data_point)
299                elif tagname == 'Qmean':
300                    pass
301                elif tagname == 'Shadowfactor':
302                    pass
303                elif tagname == 'Sesans':
304                    self.current_datainfo.isSesans = bool(data_point)
305                    self.current_dataset.xaxis(attr.get('x_axis'),
306                                                attr.get('x_unit'))
307                    self.current_dataset.yaxis(attr.get('y_axis'),
308                                                attr.get('y_unit'))
309                elif tagname == 'yacceptance':
310                    self.current_datainfo.sample.yacceptance = (data_point, unit)
311                elif tagname == 'zacceptance':
312                    self.current_datainfo.sample.zacceptance = (data_point, unit)
313
314                # I and Qx, Qy - 2D data
315                elif tagname == 'I' and isinstance(self.current_dataset, plottable_2D):
316                    self.current_dataset.yaxis("Intensity", unit)
317                    self.current_dataset.data = np.fromstring(data_point, dtype=float, sep=",")
318                elif tagname == 'Idev' and isinstance(self.current_dataset, plottable_2D):
319                    self.current_dataset.err_data = np.fromstring(data_point, dtype=float, sep=",")
320                elif tagname == 'Qx':
321                    self.current_dataset.xaxis("Qx", unit)
322                    self.current_dataset.qx_data = np.fromstring(data_point, dtype=float, sep=",")
323                elif tagname == 'Qy':
324                    self.current_dataset.yaxis("Qy", unit)
325                    self.current_dataset.qy_data = np.fromstring(data_point, dtype=float, sep=",")
326                elif tagname == 'Qxdev':
327                    self.current_dataset.xaxis("Qxdev", unit)
328                    self.current_dataset.dqx_data = np.fromstring(data_point, dtype=float, sep=",")
329                elif tagname == 'Qydev':
330                    self.current_dataset.yaxis("Qydev", unit)
331                    self.current_dataset.dqy_data = np.fromstring(data_point, dtype=float, sep=",")
332                elif tagname == 'Mask':
333                    inter = [item == "1" for item in data_point.split(",")]
334                    self.current_dataset.mask = np.asarray(inter, dtype=bool)
335
336                # Sample Information
337                elif tagname == 'ID' and self.parent_class == 'SASsample':
338                    self.current_datainfo.sample.ID = data_point
339                elif tagname == 'Title' and self.parent_class == 'SASsample':
340                    self.current_datainfo.sample.name = data_point
341                elif tagname == 'thickness' and self.parent_class == 'SASsample':
342                    self.current_datainfo.sample.thickness = data_point
343                    self.current_datainfo.sample.thickness_unit = unit
344                elif tagname == 'transmission' and self.parent_class == 'SASsample':
345                    self.current_datainfo.sample.transmission = data_point
346                elif tagname == 'temperature' and self.parent_class == 'SASsample':
347                    self.current_datainfo.sample.temperature = data_point
348                    self.current_datainfo.sample.temperature_unit = unit
349                elif tagname == 'details' and self.parent_class == 'SASsample':
350                    self.current_datainfo.sample.details.append(data_point)
351                elif tagname == 'x' and self.parent_class == 'position':
352                    self.current_datainfo.sample.position.x = data_point
353                    self.current_datainfo.sample.position_unit = unit
354                elif tagname == 'y' and self.parent_class == 'position':
355                    self.current_datainfo.sample.position.y = data_point
356                    self.current_datainfo.sample.position_unit = unit
357                elif tagname == 'z' and self.parent_class == 'position':
358                    self.current_datainfo.sample.position.z = data_point
359                    self.current_datainfo.sample.position_unit = unit
360                elif tagname == 'roll' and self.parent_class == 'orientation' and 'SASsample' in self.names:
361                    self.current_datainfo.sample.orientation.x = data_point
362                    self.current_datainfo.sample.orientation_unit = unit
363                elif tagname == 'pitch' and self.parent_class == 'orientation' and 'SASsample' in self.names:
364                    self.current_datainfo.sample.orientation.y = data_point
365                    self.current_datainfo.sample.orientation_unit = unit
366                elif tagname == 'yaw' and self.parent_class == 'orientation' and 'SASsample' in self.names:
367                    self.current_datainfo.sample.orientation.z = data_point
368                    self.current_datainfo.sample.orientation_unit = unit
369
370                # Instrumental Information
371                elif tagname == 'name' and self.parent_class == 'SASinstrument':
372                    self.current_datainfo.instrument = data_point
373
374                # Detector Information
375                elif tagname == 'name' and self.parent_class == 'SASdetector':
376                    self.detector.name = data_point
377                elif tagname == 'SDD' and self.parent_class == 'SASdetector':
378                    self.detector.distance = data_point
379                    self.detector.distance_unit = unit
380                elif tagname == 'slit_length' and self.parent_class == 'SASdetector':
381                    self.detector.slit_length = data_point
382                    self.detector.slit_length_unit = unit
383                elif tagname == 'x' and self.parent_class == 'offset':
384                    self.detector.offset.x = data_point
385                    self.detector.offset_unit = unit
386                elif tagname == 'y' and self.parent_class == 'offset':
387                    self.detector.offset.y = data_point
388                    self.detector.offset_unit = unit
389                elif tagname == 'z' and self.parent_class == 'offset':
390                    self.detector.offset.z = data_point
391                    self.detector.offset_unit = unit
392                elif tagname == 'x' and self.parent_class == 'beam_center':
393                    self.detector.beam_center.x = data_point
394                    self.detector.beam_center_unit = unit
395                elif tagname == 'y' and self.parent_class == 'beam_center':
396                    self.detector.beam_center.y = data_point
397                    self.detector.beam_center_unit = unit
398                elif tagname == 'z' and self.parent_class == 'beam_center':
399                    self.detector.beam_center.z = data_point
400                    self.detector.beam_center_unit = unit
401                elif tagname == 'x' and self.parent_class == 'pixel_size':
402                    self.detector.pixel_size.x = data_point
403                    self.detector.pixel_size_unit = unit
404                elif tagname == 'y' and self.parent_class == 'pixel_size':
405                    self.detector.pixel_size.y = data_point
406                    self.detector.pixel_size_unit = unit
407                elif tagname == 'z' and self.parent_class == 'pixel_size':
408                    self.detector.pixel_size.z = data_point
409                    self.detector.pixel_size_unit = unit
410                elif tagname == 'roll' and self.parent_class == 'orientation' and 'SASdetector' in self.names:
411                    self.detector.orientation.x = data_point
412                    self.detector.orientation_unit = unit
413                elif tagname == 'pitch' and self.parent_class == 'orientation' and 'SASdetector' in self.names:
414                    self.detector.orientation.y = data_point
415                    self.detector.orientation_unit = unit
416                elif tagname == 'yaw' and self.parent_class == 'orientation' and 'SASdetector' in self.names:
417                    self.detector.orientation.z = data_point
418                    self.detector.orientation_unit = unit
419
420                # Collimation and Aperture
421                elif tagname == 'length' and self.parent_class == 'SAScollimation':
422                    self.collimation.length = data_point
423                    self.collimation.length_unit = unit
424                elif tagname == 'name' and self.parent_class == 'SAScollimation':
425                    self.collimation.name = data_point
426                elif tagname == 'distance' and self.parent_class == 'aperture':
427                    self.aperture.distance = data_point
428                    self.aperture.distance_unit = unit
429                elif tagname == 'x' and self.parent_class == 'size':
430                    self.aperture.size.x = data_point
431                    self.collimation.size_unit = unit
432                elif tagname == 'y' and self.parent_class == 'size':
433                    self.aperture.size.y = data_point
434                    self.collimation.size_unit = unit
435                elif tagname == 'z' and self.parent_class == 'size':
436                    self.aperture.size.z = data_point
437                    self.collimation.size_unit = unit
438
439                # Process Information
440                elif tagname == 'name' and self.parent_class == 'SASprocess':
441                    self.process.name = data_point
442                elif tagname == 'description' and self.parent_class == 'SASprocess':
443                    self.process.description = data_point
444                elif tagname == 'date' and self.parent_class == 'SASprocess':
445                    try:
446                        self.process.date = datetime.datetime.fromtimestamp(data_point)
447                    except:
448                        self.process.date = data_point
449                elif tagname == 'SASprocessnote':
450                    self.process.notes.append(data_point)
451                elif tagname == 'term' and self.parent_class == 'SASprocess':
452                    unit = attr.get("unit", "")
453                    dic = { "name": name, "value": data_point, "unit": unit }
454                    self.process.term.append(dic)
455
456                # Transmission Spectrum
457                elif tagname == 'T' and self.parent_class == 'Tdata':
458                    self.transspectrum.transmission = np.append(self.transspectrum.transmission, data_point)
459                    self.transspectrum.transmission_unit = unit
460                elif tagname == 'Tdev' and self.parent_class == 'Tdata':
461                    self.transspectrum.transmission_deviation = np.append(self.transspectrum.transmission_deviation, data_point)
462                    self.transspectrum.transmission_deviation_unit = unit
463                elif tagname == 'Lambda' and self.parent_class == 'Tdata':
464                    self.transspectrum.wavelength = np.append(self.transspectrum.wavelength, data_point)
465                    self.transspectrum.wavelength_unit = unit
466
467                # Source Information
468                elif tagname == 'wavelength' and (self.parent_class == 'SASsource' or self.parent_class == 'SASData'):
469                    self.current_datainfo.source.wavelength = data_point
470                    self.current_datainfo.source.wavelength_unit = unit
471                elif tagname == 'wavelength_min' and self.parent_class == 'SASsource':
472                    self.current_datainfo.source.wavelength_min = data_point
473                    self.current_datainfo.source.wavelength_min_unit = unit
474                elif tagname == 'wavelength_max' and self.parent_class == 'SASsource':
475                    self.current_datainfo.source.wavelength_max = data_point
476                    self.current_datainfo.source.wavelength_max_unit = unit
477                elif tagname == 'wavelength_spread' and self.parent_class == 'SASsource':
478                    self.current_datainfo.source.wavelength_spread = data_point
479                    self.current_datainfo.source.wavelength_spread_unit = unit
480                elif tagname == 'x' and self.parent_class == 'beam_size':
481                    self.current_datainfo.source.beam_size.x = data_point
482                    self.current_datainfo.source.beam_size_unit = unit
483                elif tagname == 'y' and self.parent_class == 'beam_size':
484                    self.current_datainfo.source.beam_size.y = data_point
485                    self.current_datainfo.source.beam_size_unit = unit
486                elif tagname == 'z' and self.parent_class == 'pixel_size':
487                    self.current_datainfo.source.data_point.z = data_point
488                    self.current_datainfo.source.beam_size_unit = unit
489                elif tagname == 'radiation' and self.parent_class == 'SASsource':
490                    self.current_datainfo.source.radiation = data_point
491                elif tagname == 'beam_shape' and self.parent_class == 'SASsource':
492                    self.current_datainfo.source.beam_shape = data_point
493
494                # Everything else goes in meta_data
495                else:
496                    new_key = self._create_unique_key(self.current_datainfo.meta_data, tagname)
497                    self.current_datainfo.meta_data[new_key] = data_point
498
499            self.names.remove(tagname_original)
500            length = 0
501            if len(self.names) > 1:
502                length = len(self.names) - 1
503            self.parent_class = self.names[length]
504        if not self._is_call_local() and not recurse:
505            self.frm = ""
506            self.current_datainfo.errors = set()
507            for error in self.errors:
508                self.current_datainfo.errors.add(error)
509            self.errors.clear()
510            self.send_to_output()
511            empty = None
512            return self.output[0], empty
513
514    def _is_call_local(self):
515        if self.frm == "":
516            inter = inspect.stack()
517            self.frm = inter[2]
518        mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "")
519        mod_name = mod_name.replace(".py", "")
520        mod = mod_name.split("sas/")
521        mod_name = mod[1]
522        if mod_name != "sascalc/dataloader/readers/cansas_reader":
523            return False
524        return True
525
526    def _add_intermediate(self):
527        """
528        This method stores any intermediate objects within the final data set after fully reading the set.
529        """
530        if self.parent_class == 'SASprocess':
531            self.current_datainfo.process.append(self.process)
532            self.process = Process()
533        elif self.parent_class == 'SASdetector':
534            self.current_datainfo.detector.append(self.detector)
535            self.detector = Detector()
536        elif self.parent_class == 'SAStransmission_spectrum':
537            self.current_datainfo.trans_spectrum.append(self.transspectrum)
538            self.transspectrum = TransmissionSpectrum()
539        elif self.parent_class == 'SAScollimation':
540            self.current_datainfo.collimation.append(self.collimation)
541            self.collimation = Collimation()
542        elif self.parent_class == 'aperture':
543            self.collimation.aperture.append(self.aperture)
544            self.aperture = Aperture()
545        elif self.parent_class == 'SASdata':
546            self._check_for_empty_resolution()
547            self.data.append(self.current_dataset)
548
549    def _get_node_value(self, node, tagname):
550        """
551        Get the value of a node and any applicable units
552
553        :param node: The XML node to get the value of
554        :param tagname: The tagname of the node
555        """
556        #Get the text from the node and convert all whitespace to spaces
557        units = ''
558        node_value = node.text
559        if node_value is not None:
560            node_value = ' '.join(node_value.split())
561        else:
562            node_value = ""
563
564        # If the value is a float, compile with units.
565        if self.ns_list.ns_datatype == "float":
566            # If an empty value is given, set as zero.
567            if node_value is None or node_value.isspace() \
568                                    or node_value.lower() == "nan":
569                node_value = "0.0"
570            #Convert the value to the base units
571            node_value, units = self._unit_conversion(node, tagname, node_value)
572
573        # If the value is a timestamp, convert to a datetime object
574        elif self.ns_list.ns_datatype == "timestamp":
575            if node_value is None or node_value.isspace():
576                pass
577            else:
578                try:
579                    node_value = \
580                        datetime.datetime.fromtimestamp(node_value)
581                except ValueError:
582                    node_value = None
583        return node_value, units
584
585    def _unit_conversion(self, node, tagname, node_value):
586        """
587        A unit converter method used to convert the data included in the file
588        to the default units listed in data_info
589
590        :param node: XML node
591        :param tagname: name of the node
592        :param node_value: The value of the current dom node
593        """
594        attr = node.attrib
595        value_unit = ''
596        err_msg = None
597        default_unit = None
598        if not isinstance(node_value, float):
599            node_value = float(node_value)
600        if 'unit' in attr and attr.get('unit') is not None:
601            try:
602                local_unit = attr['unit']
603                unitname = self.ns_list.current_level.get("unit", "")
604                if "SASdetector" in self.names:
605                    save_in = "detector"
606                elif "aperture" in self.names:
607                    save_in = "aperture"
608                elif "SAScollimation" in self.names:
609                    save_in = "collimation"
610                elif "SAStransmission_spectrum" in self.names:
611                    save_in = "transspectrum"
612                elif "SASdata" in self.names:
613                    x = np.zeros(1)
614                    y = np.zeros(1)
615                    self.current_data1d = Data1D(x, y)
616                    save_in = "current_data1d"
617                elif "SASsource" in self.names:
618                    save_in = "current_datainfo.source"
619                elif "SASsample" in self.names:
620                    save_in = "current_datainfo.sample"
621                elif "SASprocess" in self.names:
622                    save_in = "process"
623                else:
624                    save_in = "current_datainfo"
625                exec "default_unit = self.{0}.{1}".format(save_in, unitname)
626                if local_unit and default_unit and local_unit.lower() != default_unit.lower() \
627                        and local_unit.lower() != "none":
628                    if HAS_CONVERTER == True:
629                        # Check local units - bad units raise KeyError
630                        data_conv_q = Converter(local_unit)
631                        value_unit = default_unit
632                        node_value = data_conv_q(node_value, units=default_unit)
633                    else:
634                        value_unit = local_unit
635                        err_msg = "Unit converter is not available.\n"
636                else:
637                    value_unit = local_unit
638            except KeyError:
639                # Do not throw an error for loading Sesans data in cansas xml
640                # This is a temporary fix.
641                if local_unit != "A" and local_unit != 'pol':
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.x_unit})
858            if len(datainfo.y) >= i:
859                self.write_node(point, "I", datainfo.y[i],
860                                {'unit': datainfo.y_unit})
861            if datainfo.dy is not None and len(datainfo.dy) > i:
862                self.write_node(point, "Idev", datainfo.dy[i],
863                                {'unit': datainfo.y_unit})
864            if datainfo.dx is not None and len(datainfo.dx) > i:
865                self.write_node(point, "Qdev", datainfo.dx[i],
866                                {'unit': datainfo.x_unit})
867            if datainfo.dxw is not None and len(datainfo.dxw) > i:
868                self.write_node(point, "dQw", datainfo.dxw[i],
869                                {'unit': datainfo.x_unit})
870            if datainfo.dxl is not None and len(datainfo.dxl) > i:
871                self.write_node(point, "dQl", datainfo.dxl[i],
872                                {'unit': datainfo.x_unit})
873        if datainfo.isSesans:
874            sesans_attrib = {'x_axis': datainfo._xaxis,
875                             'y_axis': datainfo._yaxis,
876                             'x_unit': datainfo.x_unit,
877                             'y_unit': datainfo.y_unit}
878            sesans = self.create_element("Sesans", attrib=sesans_attrib)
879            sesans.text = str(datainfo.isSesans)
880            entry_node.append(sesans)
881            self.write_node(entry_node, "yacceptance", datainfo.sample.yacceptance[0],
882                             {'unit': datainfo.sample.yacceptance[1]})
883            self.write_node(entry_node, "zacceptance", datainfo.sample.zacceptance[0],
884                             {'unit': datainfo.sample.zacceptance[1]})
885
886
887    def _write_data_2d(self, datainfo, entry_node):
888        """
889        Writes 2D data to the XML file
890
891        :param datainfo: The Data2D object the information is coming from
892        :param entry_node: lxml node ElementTree object to be appended to
893        """
894        attr = {}
895        if datainfo.data.shape:
896            attr["x_bins"] = str(len(datainfo.x_bins))
897            attr["y_bins"] = str(len(datainfo.y_bins))
898        node = self.create_element("SASdata", attr)
899        self.append(node, entry_node)
900
901        point = self.create_element("Idata")
902        node.append(point)
903        qx = ','.join([str(datainfo.qx_data[i]) for i in xrange(len(datainfo.qx_data))])
904        qy = ','.join([str(datainfo.qy_data[i]) for i in xrange(len(datainfo.qy_data))])
905        intensity = ','.join([str(datainfo.data[i]) for i in xrange(len(datainfo.data))])
906
907        self.write_node(point, "Qx", qx,
908                        {'unit': datainfo._xunit})
909        self.write_node(point, "Qy", qy,
910                        {'unit': datainfo._yunit})
911        self.write_node(point, "I", intensity,
912                        {'unit': datainfo._zunit})
913        if datainfo.err_data is not None:
914            err = ','.join([str(datainfo.err_data[i]) for i in
915                            xrange(len(datainfo.err_data))])
916            self.write_node(point, "Idev", err,
917                            {'unit': datainfo._zunit})
918        if datainfo.dqy_data is not None:
919            dqy = ','.join([str(datainfo.dqy_data[i]) for i in
920                            xrange(len(datainfo.dqy_data))])
921            self.write_node(point, "Qydev", dqy,
922                            {'unit': datainfo._yunit})
923        if datainfo.dqx_data is not None:
924            dqx = ','.join([str(datainfo.dqx_data[i]) for i in
925                            xrange(len(datainfo.dqx_data))])
926            self.write_node(point, "Qxdev", dqx,
927                            {'unit': datainfo._xunit})
928        if datainfo.mask is not None:
929            mask = ','.join(
930                ["1" if datainfo.mask[i] else "0"
931                 for i in xrange(len(datainfo.mask))])
932            self.write_node(point, "Mask", mask)
933
934    def _write_trans_spectrum(self, datainfo, entry_node):
935        """
936        Writes the transmission spectrum data to the XML file
937
938        :param datainfo: The Data1D object the information is coming from
939        :param entry_node: lxml node ElementTree object to be appended to
940        """
941        for i in range(len(datainfo.trans_spectrum)):
942            spectrum = datainfo.trans_spectrum[i]
943            node = self.create_element("SAStransmission_spectrum",
944                                       {"name" : spectrum.name})
945            self.append(node, entry_node)
946            if isinstance(spectrum.timestamp, datetime.datetime):
947                node.setAttribute("timestamp", spectrum.timestamp)
948            for i in range(len(spectrum.wavelength)):
949                point = self.create_element("Tdata")
950                node.append(point)
951                self.write_node(point, "Lambda", spectrum.wavelength[i],
952                                {'unit': spectrum.wavelength_unit})
953                self.write_node(point, "T", spectrum.transmission[i],
954                                {'unit': spectrum.transmission_unit})
955                if spectrum.transmission_deviation is not None \
956                and len(spectrum.transmission_deviation) >= i:
957                    self.write_node(point, "Tdev",
958                                    spectrum.transmission_deviation[i],
959                                    {'unit':
960                                     spectrum.transmission_deviation_unit})
961
962    def _write_sample_info(self, datainfo, entry_node):
963        """
964        Writes the sample information to the XML file
965
966        :param datainfo: The Data1D object the information is coming from
967        :param entry_node: lxml node ElementTree object to be appended to
968        """
969        sample = self.create_element("SASsample")
970        if datainfo.sample.name is not None:
971            self.write_attribute(sample, "name",
972                                 str(datainfo.sample.name))
973        self.append(sample, entry_node)
974        self.write_node(sample, "ID", str(datainfo.sample.ID))
975        self.write_node(sample, "thickness", datainfo.sample.thickness,
976                        {"unit": datainfo.sample.thickness_unit})
977        self.write_node(sample, "transmission", datainfo.sample.transmission)
978        self.write_node(sample, "temperature", datainfo.sample.temperature,
979                        {"unit": datainfo.sample.temperature_unit})
980
981        pos = self.create_element("position")
982        written = self.write_node(pos,
983                                  "x",
984                                  datainfo.sample.position.x,
985                                  {"unit": datainfo.sample.position_unit})
986        written = written | self.write_node( \
987            pos, "y", datainfo.sample.position.y,
988            {"unit": datainfo.sample.position_unit})
989        written = written | self.write_node( \
990            pos, "z", datainfo.sample.position.z,
991            {"unit": datainfo.sample.position_unit})
992        if written == True:
993            self.append(pos, sample)
994
995        ori = self.create_element("orientation")
996        written = self.write_node(ori, "roll",
997                                  datainfo.sample.orientation.x,
998                                  {"unit": datainfo.sample.orientation_unit})
999        written = written | self.write_node( \
1000            ori, "pitch", datainfo.sample.orientation.y,
1001            {"unit": datainfo.sample.orientation_unit})
1002        written = written | self.write_node( \
1003            ori, "yaw", datainfo.sample.orientation.z,
1004            {"unit": datainfo.sample.orientation_unit})
1005        if written == True:
1006            self.append(ori, sample)
1007
1008        for item in datainfo.sample.details:
1009            self.write_node(sample, "details", item)
1010
1011    def _write_instrument(self, datainfo, entry_node):
1012        """
1013        Writes the instrumental information to the XML file
1014
1015        :param datainfo: The Data1D object the information is coming from
1016        :param entry_node: lxml node ElementTree object to be appended to
1017        """
1018        instr = self.create_element("SASinstrument")
1019        self.append(instr, entry_node)
1020        self.write_node(instr, "name", datainfo.instrument)
1021        return instr
1022
1023    def _write_source(self, datainfo, instr):
1024        """
1025        Writes the source information to the XML file
1026
1027        :param datainfo: The Data1D object the information is coming from
1028        :param instr: instrument node  to be appended to
1029        """
1030        source = self.create_element("SASsource")
1031        if datainfo.source.name is not None:
1032            self.write_attribute(source, "name",
1033                                 str(datainfo.source.name))
1034        self.append(source, instr)
1035        if datainfo.source.radiation is None or datainfo.source.radiation == '':
1036            datainfo.source.radiation = "neutron"
1037        self.write_node(source, "radiation", datainfo.source.radiation)
1038
1039        size = self.create_element("beam_size")
1040        if datainfo.source.beam_size_name is not None:
1041            self.write_attribute(size, "name",
1042                                 str(datainfo.source.beam_size_name))
1043        written = self.write_node( \
1044            size, "x", datainfo.source.beam_size.x,
1045            {"unit": datainfo.source.beam_size_unit})
1046        written = written | self.write_node( \
1047            size, "y", datainfo.source.beam_size.y,
1048            {"unit": datainfo.source.beam_size_unit})
1049        written = written | self.write_node( \
1050            size, "z", datainfo.source.beam_size.z,
1051            {"unit": datainfo.source.beam_size_unit})
1052        if written == True:
1053            self.append(size, source)
1054
1055        self.write_node(source, "beam_shape", datainfo.source.beam_shape)
1056        self.write_node(source, "wavelength",
1057                        datainfo.source.wavelength,
1058                        {"unit": datainfo.source.wavelength_unit})
1059        self.write_node(source, "wavelength_min",
1060                        datainfo.source.wavelength_min,
1061                        {"unit": datainfo.source.wavelength_min_unit})
1062        self.write_node(source, "wavelength_max",
1063                        datainfo.source.wavelength_max,
1064                        {"unit": datainfo.source.wavelength_max_unit})
1065        self.write_node(source, "wavelength_spread",
1066                        datainfo.source.wavelength_spread,
1067                        {"unit": datainfo.source.wavelength_spread_unit})
1068
1069    def _write_collimation(self, datainfo, instr):
1070        """
1071        Writes the collimation information to the XML file
1072
1073        :param datainfo: The Data1D object the information is coming from
1074        :param instr: lxml node ElementTree object to be appended to
1075        """
1076        if datainfo.collimation == [] or datainfo.collimation is None:
1077            coll = Collimation()
1078            datainfo.collimation.append(coll)
1079        for item in datainfo.collimation:
1080            coll = self.create_element("SAScollimation")
1081            if item.name is not None:
1082                self.write_attribute(coll, "name", str(item.name))
1083            self.append(coll, instr)
1084
1085            self.write_node(coll, "length", item.length,
1086                            {"unit": item.length_unit})
1087
1088            for aperture in item.aperture:
1089                apert = self.create_element("aperture")
1090                if aperture.name is not None:
1091                    self.write_attribute(apert, "name", str(aperture.name))
1092                if aperture.type is not None:
1093                    self.write_attribute(apert, "type", str(aperture.type))
1094                self.append(apert, coll)
1095
1096                size = self.create_element("size")
1097                if aperture.size_name is not None:
1098                    self.write_attribute(size, "name",
1099                                         str(aperture.size_name))
1100                written = self.write_node(size, "x", aperture.size.x,
1101                                          {"unit": aperture.size_unit})
1102                written = written | self.write_node( \
1103                    size, "y", aperture.size.y,
1104                    {"unit": aperture.size_unit})
1105                written = written | self.write_node( \
1106                    size, "z", aperture.size.z,
1107                    {"unit": aperture.size_unit})
1108                if written == True:
1109                    self.append(size, apert)
1110
1111                self.write_node(apert, "distance", aperture.distance,
1112                                {"unit": aperture.distance_unit})
1113
1114    def _write_detectors(self, datainfo, instr):
1115        """
1116        Writes the detector information to the XML file
1117
1118        :param datainfo: The Data1D object the information is coming from
1119        :param inst: lxml instrument node to be appended to
1120        """
1121        if datainfo.detector is None or datainfo.detector == []:
1122            det = Detector()
1123            det.name = ""
1124            datainfo.detector.append(det)
1125
1126        for item in datainfo.detector:
1127            det = self.create_element("SASdetector")
1128            written = self.write_node(det, "name", item.name)
1129            written = written | self.write_node(det, "SDD", item.distance,
1130                                                {"unit": item.distance_unit})
1131            if written == True:
1132                self.append(det, instr)
1133
1134            off = self.create_element("offset")
1135            written = self.write_node(off, "x", item.offset.x,
1136                                      {"unit": item.offset_unit})
1137            written = written | self.write_node(off, "y", item.offset.y,
1138                                                {"unit": item.offset_unit})
1139            written = written | self.write_node(off, "z", item.offset.z,
1140                                                {"unit": item.offset_unit})
1141            if written == True:
1142                self.append(off, det)
1143
1144            ori = self.create_element("orientation")
1145            written = self.write_node(ori, "roll", item.orientation.x,
1146                                      {"unit": item.orientation_unit})
1147            written = written | self.write_node(ori, "pitch",
1148                                                item.orientation.y,
1149                                                {"unit": item.orientation_unit})
1150            written = written | self.write_node(ori, "yaw",
1151                                                item.orientation.z,
1152                                                {"unit": item.orientation_unit})
1153            if written == True:
1154                self.append(ori, det)
1155
1156            center = self.create_element("beam_center")
1157            written = self.write_node(center, "x", item.beam_center.x,
1158                                      {"unit": item.beam_center_unit})
1159            written = written | self.write_node(center, "y",
1160                                                item.beam_center.y,
1161                                                {"unit": item.beam_center_unit})
1162            written = written | self.write_node(center, "z",
1163                                                item.beam_center.z,
1164                                                {"unit": item.beam_center_unit})
1165            if written == True:
1166                self.append(center, det)
1167
1168            pix = self.create_element("pixel_size")
1169            written = self.write_node(pix, "x", item.pixel_size.x,
1170                                      {"unit": item.pixel_size_unit})
1171            written = written | self.write_node(pix, "y", item.pixel_size.y,
1172                                                {"unit": item.pixel_size_unit})
1173            written = written | self.write_node(pix, "z", item.pixel_size.z,
1174                                                {"unit": item.pixel_size_unit})
1175            if written == True:
1176                self.append(pix, det)
1177            self.write_node(det, "slit_length", item.slit_length,
1178                {"unit": item.slit_length_unit})
1179
1180
1181    def _write_process_notes(self, datainfo, entry_node):
1182        """
1183        Writes the process notes to the XML file
1184
1185        :param datainfo: The Data1D object the information is coming from
1186        :param entry_node: lxml node ElementTree object to be appended to
1187
1188        """
1189        for item in datainfo.process:
1190            node = self.create_element("SASprocess")
1191            self.append(node, entry_node)
1192            self.write_node(node, "name", item.name)
1193            self.write_node(node, "date", item.date)
1194            self.write_node(node, "description", item.description)
1195            for term in item.term:
1196                if isinstance(term, list):
1197                    value = term['value']
1198                    del term['value']
1199                elif isinstance(term, dict):
1200                    value = term.get("value")
1201                    del term['value']
1202                else:
1203                    value = term
1204                self.write_node(node, "term", value, term)
1205            for note in item.notes:
1206                self.write_node(node, "SASprocessnote", note)
1207            if len(item.notes) == 0:
1208                self.write_node(node, "SASprocessnote", "")
1209
1210    def _write_notes(self, datainfo, entry_node):
1211        """
1212        Writes the notes to the XML file and creates an empty note if none
1213        exist
1214
1215        :param datainfo: The Data1D object the information is coming from
1216        :param entry_node: lxml node ElementTree object to be appended to
1217
1218        """
1219        if len(datainfo.notes) == 0:
1220            node = self.create_element("SASnote")
1221            self.append(node, entry_node)
1222        else:
1223            for item in datainfo.notes:
1224                node = self.create_element("SASnote")
1225                self.write_text(node, item)
1226                self.append(node, entry_node)
1227
1228    def _check_origin(self, entry_node, doc):
1229        """
1230        Return the document, and the SASentry node associated with
1231        the data we just wrote.
1232        If the calling function was not the cansas reader, return a minidom
1233        object rather than an lxml object.
1234
1235        :param entry_node: lxml node ElementTree object to be appended to
1236        :param doc: entire xml tree
1237        """
1238        if not self.frm:
1239            self.frm = inspect.stack()[1]
1240        mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "")
1241        mod_name = mod_name.replace(".py", "")
1242        mod = mod_name.split("sas/")
1243        mod_name = mod[1]
1244        if mod_name != "sascalc/dataloader/readers/cansas_reader":
1245            string = self.to_string(doc, pretty_print=False)
1246            doc = parseString(string)
1247            node_name = entry_node.tag
1248            node_list = doc.getElementsByTagName(node_name)
1249            entry_node = node_list.item(0)
1250        return doc, entry_node
1251
1252    # DO NOT REMOVE - used in saving and loading panel states.
1253    def _store_float(self, location, node, variable, storage, optional=True):
1254        """
1255        Get the content of a xpath location and store
1256        the result. Check that the units are compatible
1257        with the destination. The value is expected to
1258        be a float.
1259
1260        The xpath location might or might not exist.
1261        If it does not exist, nothing is done
1262
1263        :param location: xpath location to fetch
1264        :param node: node to read the data from
1265        :param variable: name of the data member to store it in [string]
1266        :param storage: data object that has the 'variable' data member
1267        :param optional: if True, no exception will be raised
1268            if unit conversion can't be done
1269
1270        :raise ValueError: raised when the units are not recognized
1271        """
1272        entry = get_content(location, node)
1273        try:
1274            value = float(entry.text)
1275        except:
1276            value = None
1277
1278        if value is not None:
1279            # If the entry has units, check to see that they are
1280            # compatible with what we currently have in the data object
1281            units = entry.get('unit')
1282            if units is not None:
1283                toks = variable.split('.')
1284                local_unit = None
1285                exec "local_unit = storage.%s_unit" % toks[0]
1286                if local_unit is not None and units.lower() != local_unit.lower():
1287                    if HAS_CONVERTER == True:
1288                        try:
1289                            conv = Converter(units)
1290                            exec "storage.%s = %g" % \
1291                                (variable, conv(value, units=local_unit))
1292                        except:
1293                            _, exc_value, _ = sys.exc_info()
1294                            err_mess = "CanSAS reader: could not convert"
1295                            err_mess += " %s unit [%s]; expecting [%s]\n  %s" \
1296                                % (variable, units, local_unit, exc_value)
1297                            self.errors.add(err_mess)
1298                            if optional:
1299                                logger.info(err_mess)
1300                            else:
1301                                raise ValueError, err_mess
1302                    else:
1303                        err_mess = "CanSAS reader: unrecognized %s unit [%s];"\
1304                        % (variable, units)
1305                        err_mess += " expecting [%s]" % local_unit
1306                        self.errors.add(err_mess)
1307                        if optional:
1308                            logger.info(err_mess)
1309                        else:
1310                            raise ValueError, err_mess
1311                else:
1312                    exec "storage.%s = value" % variable
1313            else:
1314                exec "storage.%s = value" % variable
1315
1316    # DO NOT REMOVE - used in saving and loading panel states.
1317    def _store_content(self, location, node, variable, storage):
1318        """
1319        Get the content of a xpath location and store
1320        the result. The value is treated as a string.
1321
1322        The xpath location might or might not exist.
1323        If it does not exist, nothing is done
1324
1325        :param location: xpath location to fetch
1326        :param node: node to read the data from
1327        :param variable: name of the data member to store it in [string]
1328        :param storage: data object that has the 'variable' data member
1329
1330        :return: return a list of errors
1331        """
1332        entry = get_content(location, node)
1333        if entry is not None and entry.text is not None:
1334            exec "storage.%s = entry.text.strip()" % variable
1335
1336# DO NOT REMOVE Called by outside packages:
1337#    sas.sasgui.perspectives.invariant.invariant_state
1338#    sas.sasgui.perspectives.fitting.pagestate
1339def get_content(location, node):
1340    """
1341    Get the first instance of the content of a xpath location.
1342
1343    :param location: xpath location
1344    :param node: node to start at
1345
1346    :return: Element, or None
1347    """
1348    nodes = node.xpath(location,
1349                       namespaces={'ns': CANSAS_NS.get("1.0").get("ns")})
1350    if len(nodes) > 0:
1351        return nodes[0]
1352    else:
1353        return None
1354
1355# DO NOT REMOVE Called by outside packages:
1356#    sas.sasgui.perspectives.fitting.pagestate
1357def write_node(doc, parent, name, value, attr=None):
1358    """
1359    :param doc: document DOM
1360    :param parent: parent node
1361    :param name: tag of the element
1362    :param value: value of the child text node
1363    :param attr: attribute dictionary
1364
1365    :return: True if something was appended, otherwise False
1366    """
1367    if attr is None:
1368        attr = {}
1369    if value is not None:
1370        node = doc.createElement(name)
1371        node.appendChild(doc.createTextNode(str(value)))
1372        for item in attr:
1373            node.setAttribute(item, attr[item])
1374        parent.appendChild(node)
1375        return True
1376    return False
Note: See TracBrowser for help on using the repository browser.