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

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

More explicit error messages when file loading fails. see #889

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