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

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

Move generic loading functions from cansas_reader into file_reader_base_class. Cascade changes to other readers. refs #985

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