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

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

Fit states and projects are now able to save 2D data. Loading is still not working. #827

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