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

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 9706d88 was ae69c690, checked in by krzywon, 7 years ago

Ensure dxl and dxw and the same length as each other and as x.

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