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

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

Modify base file reader class and cansas reader to properly load save states.

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