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

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 747334d was 747334d, checked in by Adam Washington <adam.washington@…>, 7 years ago

Add yacceptance

Needed to correspond to zacceptance for 2D sesans

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