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

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.1.1release-4.1.2release-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since af08e55 was af08e55, checked in by krzywon, 7 years ago

Saving and loading of 2D data within projects and fit save states is working. This works alongside saving and loading 1D fits withint the same .svs file. #827

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