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

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

Ensure unit tests pass

utest_averaging still fails as it relies on loading in an Igor 2D file,
which is no longer possible

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