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

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 bc570f4 was bc570f4, checked in by lewis, 7 years ago

Refactor CanSASReader/XMLReader to use FileReader? class

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