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

Last change on this file since cbb9551 was cbb9551, checked in by Tim Snow <tim.snow@…>, 7 years ago

Merge branch 'master' into load_speed_increase

Merged and sorted conflict

  • Property mode set to 100644
File size: 93.8 KB
Line 
1"""
2    CanSAS data reader - new recursive cansas_version.
3"""
4############################################################################
5#This software was developed by the University of Tennessee as part of the
6#Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
7#project funded by the US National Science Foundation.
8#If you use DANSE applications to do scientific research that leads to
9#publication, we ask that you acknowledge the use of the software with the
10#following sentence:
11#This work benefited from DANSE software developed under NSF award DMR-0520547.
12#copyright 2008,2009 University of Tennessee
13#############################################################################
14
15import logging
16import numpy as np
17import os
18import sys
19import datetime
20import inspect
21# For saving individual sections of data
22from sas.sascalc.dataloader.data_info import Data1D, Data2D, DataInfo, \
23    plottable_1D, plottable_2D
24from sas.sascalc.dataloader.data_info import Collimation, TransmissionSpectrum, \
25    Detector, Process, Aperture
26from sas.sascalc.dataloader.data_info import \
27    combine_data_info_with_plottable as combine_data
28import sas.sascalc.dataloader.readers.xml_reader as xml_reader
29from sas.sascalc.dataloader.readers.xml_reader import XMLreader
30from sas.sascalc.dataloader.readers.cansas_constants import CansasConstants, CurrentLevel
31
32# The following 2 imports *ARE* used. Do not remove either.
33import xml.dom.minidom
34from xml.dom.minidom import parseString
35
36logger = logging.getLogger(__name__)
37
38PREPROCESS = "xmlpreprocess"
39ENCODING = "encoding"
40RUN_NAME_DEFAULT = "None"
41INVALID_SCHEMA_PATH_1_1 = "{0}/sas/sascalc/dataloader/readers/schema/cansas1d_invalid_v1_1.xsd"
42INVALID_SCHEMA_PATH_1_0 = "{0}/sas/sascalc/dataloader/readers/schema/cansas1d_invalid_v1_0.xsd"
43INVALID_XML = "\n\nThe loaded xml file, {0} does not fully meet the CanSAS v1.x specification. SasView loaded " + \
44              "as much of the data as possible.\n\n"
45HAS_CONVERTER = True
46try:
47    from sas.sascalc.data_util.nxsunit import Converter
48except ImportError:
49    HAS_CONVERTER = False
50
51CONSTANTS = CansasConstants()
52CANSAS_FORMAT = CONSTANTS.format
53CANSAS_NS = CONSTANTS.names
54ALLOW_ALL = True
55
56class Reader(XMLreader):
57    """
58    Class to load cansas 1D XML files
59
60    :Dependencies:
61        The CanSAS reader requires PyXML 0.8.4 or later.
62    """
63    # CanSAS version - defaults to version 1.0
64    cansas_version = "1.0"
65    base_ns = "{cansas1d/1.0}"
66    cansas_defaults = None
67    type_name = "canSAS"
68    invalid = True
69    frm = ""
70    # Log messages and errors
71    logging = None
72    errors = set()
73    # Namespace hierarchy for current xml_file object
74    names = None
75    ns_list = None
76    # Temporary storage location for loading multiple data sets in a single file
77    current_datainfo = None
78    current_dataset = None
79    current_data1d = None
80    data = None
81    # List of data1D objects to be sent back to SasView
82    output = None
83    # Wildcards
84    type = ["XML files (*.xml)|*.xml", "SasView Save Files (*.svs)|*.svs"]
85    # List of allowed extensions
86    ext = ['.xml', '.XML', '.svs', '.SVS']
87    # Flag to bypass extension check
88    allow_all = True
89
90    def reset_state(self):
91        """
92        Resets the class state to a base case when loading a new data file so previous
93        data files do not appear a second time
94        """
95        self.current_datainfo = None
96        self.current_dataset = None
97        self.current_data1d = None
98        self.data = []
99        self.process = Process()
100        self.transspectrum = TransmissionSpectrum()
101        self.aperture = Aperture()
102        self.collimation = Collimation()
103        self.detector = Detector()
104        self.names = []
105        self.cansas_defaults = {}
106        self.output = []
107        self.ns_list = None
108        self.logging = []
109        self.encoding = None
110
111    def read(self, xml_file, schema_path="", invalid=True):
112        """
113        Validate and read in an xml_file file in the canSAS format.
114
115        :param xml_file: A canSAS file path in proper XML format
116        :param schema_path: A file path to an XML schema to validate the xml_file against
117        """
118        # For every file loaded, reset everything to a base state
119        self.reset_state()
120        self.invalid = invalid
121        # Check that the file exists
122        if os.path.isfile(xml_file):
123            basename, extension = os.path.splitext(os.path.basename(xml_file))
124            # If the file type is not allowed, return nothing
125            if extension in self.ext or self.allow_all:
126                # Get the file location of
127                self.load_file_and_schema(xml_file, schema_path)
128                self.add_data_set()
129                # Try to load the file, but raise an error if unable to.
130                # Check the file matches the XML schema
131                try:
132                    self.is_cansas(extension)
133                    self.invalid = False
134                    # Get each SASentry from XML file and add it to a list.
135                    entry_list = self.xmlroot.xpath(
136                            '/ns:SASroot/ns:SASentry',
137                            namespaces={'ns': self.cansas_defaults.get("ns")})
138                    self.names.append("SASentry")
139
140                    # Get all preprocessing events and encoding
141                    self.set_processing_instructions()
142
143                    # Parse each <SASentry> item
144                    for entry in entry_list:
145                        # Create a new DataInfo object for every <SASentry>
146
147                        # Set the file name and then parse the entry.
148                        self.current_datainfo.filename = basename + extension
149                        self.current_datainfo.meta_data["loader"] = "CanSAS XML 1D"
150                        self.current_datainfo.meta_data[PREPROCESS] = \
151                            self.processing_instructions
152
153                        # Parse the XML SASentry
154                        self._parse_entry(entry)
155                        # Combine datasets with datainfo
156                        self.add_data_set()
157                except RuntimeError:
158                    # If the file does not match the schema, raise this error
159                    invalid_xml = self.find_invalid_xml()
160                    invalid_xml = INVALID_XML.format(basename + extension) + invalid_xml
161                    self.errors.add(invalid_xml)
162                    # Try again with an invalid CanSAS schema, that requires only a data set in each
163                    base_name = xml_reader.__file__
164                    base_name = base_name.replace("\\", "/")
165                    base = base_name.split("/sas/")[0]
166                    if self.cansas_version == "1.1":
167                        invalid_schema = INVALID_SCHEMA_PATH_1_1.format(base, self.cansas_defaults.get("schema"))
168                    else:
169                        invalid_schema = INVALID_SCHEMA_PATH_1_0.format(base, self.cansas_defaults.get("schema"))
170                    self.set_schema(invalid_schema)
171                    try:
172                        if self.invalid:
173                            if self.is_cansas():
174                                self.output = self.read(xml_file, invalid_schema, False)
175                            else:
176                                raise RuntimeError
177                        else:
178                            raise RuntimeError
179                    except RuntimeError:
180                        x = np.zeros(1)
181                        y = np.zeros(1)
182                        self.current_data1d = Data1D(x,y)
183                        self.current_data1d.errors = self.errors
184                        return [self.current_data1d]
185        else:
186            self.output.append("Not a valid file path.")
187        # Return a list of parsed entries that dataloader can manage
188        return self.output
189
190    def _parse_entry(self, dom, recurse=False):
191        """
192        Parse a SASEntry - new recursive method for parsing the dom of
193            the CanSAS data format. This will allow multiple data files
194            and extra nodes to be read in simultaneously.
195
196        :param dom: dom object with a namespace base of names
197        """
198
199        self._check_for_empty_data()
200        self._initialize_new_data_set(dom)
201
202        self.names.append("SASentry")
203        self.parent_class = "SASentry"
204
205        self.base_ns = "{0}{1}{2}".format("{", \
206                            CANSAS_NS.get(self.cansas_version).get("ns"), "}")
207
208        self.ns_list = CONSTANTS.iterate_namespace(self.names)
209       
210        # Go through each child in the parent element
211        for sasNode in dom:
212            # Get the element name and set the current name's level
213            currentTagName = sasNode.tag.replace(self.base_ns, "")
214            # As this is the most likely tag to examine, lets put it first!
215            if currentTagName == "SASdata":
216                # Are there multiple entries here?
217                if len(sasNode) <= 1:
218                    multipleEntries = False
219                else:
220                    multipleEntries = True
221
222                for setupNode in sasNode[0]:
223                    # Iterating through the tags in the unit node, getting their tag name and respective unit
224                    setupTagName = setupNode.tag.replace(self.base_ns, "")
225                    units = setupNode.attrib.get("unit", "")
226
227                    # Creating our data array first, if there's only one dataNode we will handle this...
228                    startArray = np.fromstring(setupNode.text, dtype=float, sep=",")
229                   
230                    if multipleEntries == True:
231                        setupArray = np.zeros((len(sasNode), len(startArray)))
232                        setupArray[0] = startArray
233                    else:
234                        setupArray = startArray
235
236                    # Now put this into the relevant location
237                    if setupTagName == "I":
238                        self.current_dataset.yaxis("Intensity", units)
239                        self.current_dataset.y = setupArray
240                    elif setupTagName == "Q":
241                        self.current_dataset.xaxis("Q", units)
242                        self.current_dataset.x = setupArray
243
244                    elif setupTagName == "Idev":
245                        self.current_dataset.dy = setupArray 
246                    elif setupTagName == "Qdev":
247                        self.current_dataset.dx = setupArray
248
249                    elif setupTagName == "Qx":
250                        self.current_dataset.xaxis("Qx", units)
251                        self.current_dataset.qx_data = setupArray
252                    elif setupTagName == "Qy":
253                        self.current_dataset.yaxis("Qy", units)
254                        self.current_dataset.qy_data = setupArray
255                    elif setupTagName == "Qxdev":
256                        self.current_dataset.xaxis("Qxdev", units)
257                        self.current_dataset.dqx_data = setupArray
258                    elif setupTagName == "Qydev":
259                        self.current_dataset.yaxis("Qydev", units)
260                        self.current_dataset.dqy_data = setupArray
261                    elif setupTagName == "dQw":
262                        self.current_dataset.dxw = setupArray
263                    elif setupTagName == "dQl":
264                        self.current_dataset.dxl = setupArray
265
266                    elif setupTagName == "Mask":
267                        self.current_dataset.mask = np.ndarray.astype(setupArray, dtype=bool)
268                    elif setupTagName == "Sesans":
269                        self.current_datainfo.isSesans = bool(setupNode.text)
270
271                    elif setupTagName == "zacceptance":
272                        self.current_datainfo.sample.zacceptance = (setupNode.text, units)
273                    elif setupTagName == "Qmean":
274                        pass
275                    elif setupTagName == "Shadowfactor":
276                        pass
277
278                # If there's more data present, let's deal with that too
279                for loopIter in range(1, len(sasNode)):
280                    for dataNode in sasNode[loopIter]:
281                        # Iterating through the tags in the unit node, getting their tag name and respective unit
282                        dataTagName = dataNode.tag.replace(self.base_ns, "")
283                        # Creating our data array first
284                        dataArray = np.fromstring(dataNode.text, dtype=float, sep=",")
285
286                        if dataTagName == "I":
287                            self.current_dataset.y[loopIter] = dataArray
288                        elif dataTagName == "Q":
289                            self.current_dataset.x[loopIter] = dataArray
290                        elif dataTagName == "Idev":
291                            self.current_dataset.dy[loopIter] = dataArray
292                        elif dataTagName == "Qdev":
293                            self.current_dataset.dx[loopIter] = dataArray
294                        elif dataTagName == "Qx":
295                            self.current_dataset.qx_data[loopIter] = dataArray
296                        elif dataTagName == "Qy":
297                            self.current_dataset.qy_data[loopIter] = dataArray
298                        elif dataTagName == "Qxdev":
299                            self.current_dataset.dqx_data[loopIter] = dataArray
300                        elif dataTagName == "Qydev":
301                            self.current_dataset.dqy_data[loopIter] = dataArray
302                        elif dataTagName == "dQw":
303                            self.current_dataset.dxw[loopIter] = dataArray
304                        elif dataTagName == "dQl":
305                            self.current_dataset.dxl[loopIter] = dataArray
306
307                self._check_for_empty_resolution()
308                self.data.append(self.current_dataset)
309
310            # If it's not data, let's check for other tags starting with skippable ones...
311            elif currentTagName == "fitting_plug_in" or currentTagName == "pr_inversion" or currentTagName == "invariant":
312                continue
313
314            # If we'e dealing with a title node then extract the text of the node and put it in the right place
315            elif currentTagName == "Title":
316                self.current_datainfo.title = sasNode.text
317
318
319            # If we'e dealing with a run node then extract the name and text of the node and put it in the right place
320            elif currentTagName == "Run":
321                    self.current_datainfo.run_name[sasNode.text] = sasNode.attrib.get("name", "")
322                    self.current_datainfo.run.append(sasNode.text)
323
324            # If we'e dealing with a sample node
325            elif currentTagName == "SASsample":
326                for sampleNode in sasNode:
327                    # Get the variables
328                    sampleTagName = sampleNode.tag.replace(self.base_ns, "")
329                    sampleUnits = sampleNode.attrib.get("unit", "")
330                    sampleData = sampleNode.text
331
332                    # Populate it via if switching
333                    if sampleTagName == "ID":
334                        self.current_datainfo.sample.ID = sampleData
335                    elif sampleTagName == "Title":
336                        self.current_datainfo.sample.name = sampleData
337                    elif sampleTagName == "thickness":
338                        self.current_datainfo.sample.thickness = sampleData
339                        self.current_datainfo.sample.thickness_unit = sampleUnits
340                    elif sampleTagName == "transmission":
341                        self.current_datainfo.sample.transmission = sampleData
342                    elif sampleTagName == "temperature":
343                        self.current_datainfo.sample.temperature = sampleData
344                        self.current_datainfo.sample.temperature_unit = sampleUnits
345                    elif sampleTagName == "details":
346                        self.current_datainfo.sample.details.append(sampleData)
347
348                    # Extract the positional data
349                    elif sampleTagName == "position":
350                        for positionNode in sampleNode:
351                            positionTagName = positionNode.tag.replace(self.base_ns, "")
352                            positionUnits = positionNode.attrib.get("unit", "")
353                            positionData = positionNode.text
354
355                            # Extract specific tags
356                            if positionTagName == "x":
357                                self.current_datainfo.sample.position.x = positionData
358                                self.current_datainfo.sample.position_unit = positionUnits
359                            elif positionTagName == "y":
360                                self.current_datainfo.sample.position.y = positionData
361                                self.current_datainfo.sample.position_unit = positionUnits
362                            elif positionTagName == "z":
363                                self.current_datainfo.sample.position.z = positionData
364                                self.current_datainfo.sample.position_unit = positionUnits
365
366                    # Extract the orientation data
367                    elif sampleTagName == "orientation":
368                        for orientationNode in sampleNode:
369                            orientationTagName = orientationNode.tag.replace(self.base_ns, "")
370                            orientationUnits = orientationNode.attrib.get("unit", "")
371                            orientationData = orientationNode.text
372
373                            # Extract specific tags
374                            if orientationTagName == "roll":
375                                self.current_datainfo.sample.orientation.x = orientationData
376                                self.current_datainfo.sample.orientation_unit = orientationUnits
377                            elif orientationTagName == "pitch":
378                                self.current_datainfo.sample.orientation.y = orientationData
379                                self.current_datainfo.sample.orientation_unit = orientationUnits
380                            elif orientationTagName == "yaw":
381                                self.current_datainfo.sample.orientation.z = orientationData
382                                self.current_datainfo.sample.orientation_unit = orientationUnits
383
384            # If we're dealing with an instrument node
385            elif currentTagName == "SASinstrument":
386                for instrumentNode in sasNode:
387                    instrumentTagName = instrumentNode.tag.replace(self.base_ns, "")
388                    instrumentUnits = instrumentNode.attrib.get("unit", "")
389                    instrumentData = instrumentNode.text
390
391                    # Extract the source name
392                    if instrumentTagName == "SASsource":
393                        self.name = instrumentNode.attrib.get("name", "")
394
395                        for sourceNode in instrumentNode:
396                            sourceTagName = sourceNode.tag.replace(self.base_ns, "")
397                            sourceUnits = sourceNode.attrib.get("unit", "")
398                            sourceData = sourceNode.text
399
400                            ## Source Information
401                            if sourceTagName == "wavelength":
402                                self.current_datainfo.source.wavelength = sourceData
403                                self.current_datainfo.source.wavelength_unit = sourceUnits
404                            elif sourceTagName == "wavelength_min":
405                                self.current_datainfo.source.wavelength_min = sourceData
406                                self.current_datainfo.source.wavelength_min_unit = sourceUnits
407                            elif sourceTagName == "wavelength_max":
408                                self.current_datainfo.source.wavelength_max = sourceData
409                                self.current_datainfo.source.wavelength_max_unit = sourceUnits
410                            elif sourceTagName == "wavelength_spread":
411                                self.current_datainfo.source.wavelength_spread = sourceData
412                                self.current_datainfo.source.wavelength_spread_unit = sourceUnits
413                            elif sourceTagName == "radiation":
414                                self.current_datainfo.source.radiation = sourceData
415                            elif sourceTagName == "beam_shape":
416                                self.current_datainfo.source.beam_shape = sourceData
417
418                            elif sourceTagName == "beam_size":
419                                for beamNode in sourceNode:
420                                    beamTagName = beamNode.tag.replace(self.base_ns, "")
421                                    beamUnits = beamNode.attrib.get("unit", "")
422                                    beamData = beamNode.text
423
424                                    if beamTagName == "x" and self.parent_class == "beam_size":
425                                       self.current_datainfo.source.beam_size.x = beamData
426                                       self.current_datainfo.source.beam_size_unit = beamUnits
427                                    elif beamTagName == "y" and self.parent_class == "beam_size":
428                                        self.current_datainfo.source.beam_size.y = beamData
429                                        self.current_datainfo.source.beam_size_unit = beamUnits
430
431                            elif sourceTagName == "pixel_size":
432                                for pixelNode in sourceNode:
433                                    pixelTagName = pixelNode.tag.replace(self.base_ns, "")
434                                    pixelUnits = pixelNode.attrib.get("unit", "")
435                                    pixelData = pixelNode.text
436                                       
437                                    if pixelTagName == "z":
438                                        self.current_datainfo.source.data_point.z = pixelData
439                                        self.current_datainfo.source.beam_size_unit = pixelUnits
440
441                    # Extract the collimation
442                    elif instrumentTagName == "SAScollimation":
443                        self.collimation.name = instrumentNode.attrib.get("name", "")
444
445                        for collimationNode in instrumentNode:
446                            collimationTagName = pixelNode.tag.replace(self.base_ns, "")
447                            collimationUnits = pixelNode.attrib.get("unit", "")
448                            collimationData = pixelNode.text
449
450                            if collimationTagName == "length":
451                                self.collimation.length = collimationData
452                                self.collimation.length_unit = collimationUnits
453                            elif collimationTagName == "name":
454                                self.collimation.name = collimationData
455
456                            if collimationTagName == "aperture":
457                                for apertureNode in collimationNode:
458                                    apertureTagName = apertureNode.tag.replace(self.base_ns, "")
459                                    apertureUnits = apertureNode.attrib.get("unit", "")
460                                    apertureData = apertureNode.text
461
462                                if tagname == "distance":
463                                    self.aperture.distance = apertureData
464                                    self.aperture.distance_unit = apertureUnits
465
466                            if collimationTagName == "size":
467                                for sizeNode in collimationNode:
468                                    sizeTagName = sizeNode.tag.replace(self.base_ns, "")
469                                    sizeUnits = sizeNode.attrib.get("unit", "")
470                                    sizeData = sizeNode.text
471
472                                if tagname == "x":
473                                    self.aperture.size.x = sizeData
474                                    self.collimation.size_unit = sizeUnits
475                                elif tagname == "y":
476                                    self.aperture.size.y = sizeData
477                                    self.collimation.size_unit = sizeUnits
478                                elif tagname == "z":
479                                    self.aperture.size.z = sizeData
480                                    self.collimation.size_unit = sizeUnits
481
482                        self.current_datainfo.collimation.append(self.collimation)
483                        self.collimation = Collimation()
484
485                    # Extract the detector
486                    elif instrumentTagName == "SASdetector":
487                        self.name = instrumentNode.attrib.get("name", "")
488
489                        for detectorNode in instrumentNode:
490                            detectorTagName = detectorNode.tag.replace(self.base_ns, "")
491                            detectorUnits = detectorNode.attrib.get("unit", "")
492                            detectorData = detectorNode.text
493
494                            if detectorTagName == "name":
495                                self.detector.name = detectorData
496                            elif detectorTagName == "SDD":
497                                self.detector.distance = detectorData
498                                self.detector.distance_unit = detectorUnits
499                            elif detectorTagName == "slit_length":
500                                self.detector.slit_length = detectorData
501                                self.detector.slit_length_unit = detectorUnits
502
503                            elif detectorTagName == "offset":
504                                for offsetNode in detectorNode:
505                                    offsetTagName = offsetNode.tag.replace(self.base_ns, "")
506                                    offsetUnits = offsetNode.attrib.get("unit", "")
507                                    offsetData = offsetNode.text
508
509                                    if offsetTagName == "x":
510                                        self.detector.offset.x = offsetData
511                                        self.detector.offset_unit = offsetUnits
512                                    elif offsetTagName == "y":
513                                        self.detector.offset.y = offsetData
514                                        self.detector.offset_unit = offsetUnits
515                                    elif offsetTagName == "z":
516                                        self.detector.offset.z = offsetData
517                                        self.detector.offset_unit = offsetUnits
518
519                            elif detectorTagName == "beam_center":
520                                for beamCenterNode in detectorNode:
521                                    beamCenterTagName = beamCenterNode.tag.replace(self.base_ns, "")
522                                    beamCenterUnits = beamCenterNode.attrib.get("unit", "")
523                                    beamCenterData = beamCenterNode.text     
524
525                                    if beamCenterTagName == "x":
526                                        self.detector.beam_center.x = beamCenterData
527                                        self.detector.beam_center_unit = beamCenterUnits
528                                    elif beamCenterTagName == "y":
529                                        self.detector.beam_center.y = beamCenterData
530                                        self.detector.beam_center_unit = beamCenterUnits
531                                    elif beamCenterTagName == "z":
532                                        self.detector.beam_center.z = beamCenterData
533                                        self.detector.beam_center_unit = beamCenterUnits
534
535                            elif detectorTagName == "pixel_size":
536                                for pixelSizeNode in detectorNode:
537                                    pixelSizeTagName = pixelSizeNode.tag.replace(self.base_ns, "")
538                                    pixelSizeUnits = pixelSizeNode.attrib.get("unit", "")
539                                    pixelSizeData = pixelSizeNode.text
540
541                                    if pixelSizeTagName == "x":
542                                        self.detector.pixel_size.x = pixelSizeData
543                                        self.detector.pixel_size_unit = pixelSizeUnits
544                                    elif pixelSizeTagName == "y":
545                                        self.detector.pixel_size.y = pixelSizeData
546                                        self.detector.pixel_size_unit = pixelSizeUnits
547                                    elif pixelSizeTagName == "z":
548                                        self.detector.pixel_size.z = pixelSizeData
549                                        self.detector.pixel_size_unit = pixelSizeUnits
550
551                            elif detectorTagName == "orientation":
552                                for orientationNode in detectorNode:
553                                    orientationTagName = orientationNode.tag.replace(self.base_ns, "")
554                                    orientationUnits = orientationNode.attrib.get("unit", "")
555                                    orientationData = orientationNode.text
556
557                                    if orientationTagName == "roll":
558                                        self.detector.orientation.x = orientationData
559                                        self.detector.orientation_unit = orientationUnits
560                                    elif orientationTagName == "pitch":
561                                        self.detector.orientation.y = orientationData
562                                        self.detector.orientation_unit = orientationUnits
563                                    elif orientationTagName == "yaw":
564                                        self.detector.orientation.z = orientationData
565                                        self.detector.orientation_unit = orientationUnits
566
567                        self.current_datainfo.detector.append(self.detector)
568                        self.detector = Detector()
569
570            ## If we'e dealing with a process node
571            elif currentTagName == "SASprocess":
572                for processNode in sasNode:
573                    setupTagName = setupNode.tag.replace(self.base_ns, "")
574                    units = setupNode.attrib.get("unit", "")
575
576                    if processTagName == "name":
577                        self.process.name = processNode.text
578                    elif processTagName == "description":
579                        self.process.description = processNode.text
580                    elif processTagName == "date":
581                        try:
582                            self.process.date = datetime.datetime.fromtimestamp(processNode.text)
583                        except:
584                            self.process.date = processNode.text
585                    elif processTagName == "term":
586                        unit = attr.get("unit", "")
587                        dic = {}
588                        dic["name"] = processNode.attrib.get("name", "")
589                        dic["value"] = processNode.text
590                        dic["unit"] = processNode.attrib.get("unit", "")
591                        self.process.term.append(dic)
592
593                self.current_datainfo.process.append(self.process)
594                self.process = Process()
595               
596            # If we're dealing with a process note node
597            elif currentTagName == "SASprocessnote":
598                for processNoteNode in sasNode:
599                    self.process.notes.append(processNoteNode.text)
600
601            # If we're dealing with a sas note node
602            elif currentTagName == "SASnote":
603                for noteNode in sasNode:
604                    self.current_datainfo.notes.append(noteNode.text)
605
606            # If we're dealing with a transmission data node
607            elif currentTagName == "Tdata":
608                for transmissionDataNode in sasNode:
609                    transmissionDataTagName = transmissionDataNode.tag.replace(self.base_ns, "")
610                    transmissionDataUnits = transmissionDataNode.attrib.get("unit", "")
611                    transmissionDataData = transmissionDataNode.text
612
613                # Are there multiple entries here?
614                if len(sasNode) <= 1:
615                    multipleEntries == False
616                else:
617                    multipleEntries == True
618
619                for setupNode in sasNode[0]:
620                    # Iterating through the tags in the unit node, getting their tag name and respective unit
621                    setupTagName = setupNode.tag.replace(self.base_ns, "")
622                    transmissionDataUnits = setupNode.attrib.get("unit", "")
623
624                    # Creating our data array first, if there's only one dataNode we will handle this...
625                    startArray = np.fromstring(setupNode.text, dtype=float, sep=",")
626
627                    if multipleEntries == True:
628                        setupArray = np.zeros((len(sasNode), len(startArray)))
629                        setupArray[0] = startArray
630                    else:
631<<<<<<< HEAD
632                        setupArray = startArray
633
634                    ## Transmission Spectrum
635                    if setupTagName == "T":
636                        self.transspectrum.transmission = setupArray
637                        self.transspectrum.transmission_unit = transmissionDataUnits
638                    elif setupTagName == "Tdev":
639                        self.transspectrum.transmission_deviation = setupArray
640                        self.transspectrum.transmission_deviation_unit = transmissionDataUnits
641                    elif setupTagName == "Lambda":
642                        self.transspectrum.wavelength = setupArray
643                        self.transspectrum.wavelength_unit = transmissionDataUnits
644
645                # If there's more data present, let's deal with that too
646                for loopIter in range(1, len(sasNode)):
647                    for dataNode in sasNode[loopIter]:
648                        dataTagName = dataNode.tag.replace(self.base_ns, "")
649                        dataArray = np.fromstring(dataNode.text, dtype=float, sep=",")
650
651                    if dataTagName == "T":
652                        self.transspectrum.transmission[loopIter] = setupArray
653                    elif dataTagName == "Tdev":
654                        self.transspectrum.transmission_deviation[loopIter] = setupArray
655                    elif dataTagName == "Lambda":
656                        self.transspectrum.wavelength[loopIter] = setupArray
657
658                self.current_datainfo.trans_spectrum.append(self.transspectrum)
659                self.transspectrum = TransmissionSpectrum()
660
661
662            ## Everything else goes in meta_data
663            else:
664                new_key = self._create_unique_key(self.current_datainfo.meta_data, currentTagName)
665                self.current_datainfo.meta_data[new_key] = sasNode.text
666=======
667                        self.current_dataset.xaxis("Q", unit)
668                    self.current_dataset.x = np.append(self.current_dataset.x, data_point)
669                elif tagname == 'Qdev':
670                    self.current_dataset.dx = np.append(self.current_dataset.dx, data_point)
671                elif tagname == 'dQw':
672                    self.current_dataset.dxw = np.append(self.current_dataset.dxw, data_point)
673                elif tagname == 'dQl':
674                    self.current_dataset.dxl = np.append(self.current_dataset.dxl, data_point)
675                elif tagname == 'Qmean':
676                    pass
677                elif tagname == 'Shadowfactor':
678                    pass
679                elif tagname == 'Sesans':
680                    self.current_datainfo.isSesans = bool(data_point)
681                elif tagname == 'yacceptance':
682                    self.current_datainfo.sample.yacceptance = (data_point, unit)
683                elif tagname == 'zacceptance':
684                    self.current_datainfo.sample.zacceptance = (data_point, unit)
685
686                # I and Qx, Qy - 2D data
687                elif tagname == 'I' and isinstance(self.current_dataset, plottable_2D):
688                    self.current_dataset.yaxis("Intensity", unit)
689                    self.current_dataset.data = np.fromstring(data_point, dtype=float, sep=",")
690                elif tagname == 'Idev' and isinstance(self.current_dataset, plottable_2D):
691                    self.current_dataset.err_data = np.fromstring(data_point, dtype=float, sep=",")
692                elif tagname == 'Qx':
693                    self.current_dataset.xaxis("Qx", unit)
694                    self.current_dataset.qx_data = np.fromstring(data_point, dtype=float, sep=",")
695                elif tagname == 'Qy':
696                    self.current_dataset.yaxis("Qy", unit)
697                    self.current_dataset.qy_data = np.fromstring(data_point, dtype=float, sep=",")
698                elif tagname == 'Qxdev':
699                    self.current_dataset.xaxis("Qxdev", unit)
700                    self.current_dataset.dqx_data = np.fromstring(data_point, dtype=float, sep=",")
701                elif tagname == 'Qydev':
702                    self.current_dataset.yaxis("Qydev", unit)
703                    self.current_dataset.dqy_data = np.fromstring(data_point, dtype=float, sep=",")
704                elif tagname == 'Mask':
705                    inter = [item == "1" for item in data_point.split(",")]
706                    self.current_dataset.mask = np.asarray(inter, dtype=bool)
707
708                # Sample Information
709                elif tagname == 'ID' and self.parent_class == 'SASsample':
710                    self.current_datainfo.sample.ID = data_point
711                elif tagname == 'Title' and self.parent_class == 'SASsample':
712                    self.current_datainfo.sample.name = data_point
713                elif tagname == 'thickness' and self.parent_class == 'SASsample':
714                    self.current_datainfo.sample.thickness = data_point
715                    self.current_datainfo.sample.thickness_unit = unit
716                elif tagname == 'transmission' and self.parent_class == 'SASsample':
717                    self.current_datainfo.sample.transmission = data_point
718                elif tagname == 'temperature' and self.parent_class == 'SASsample':
719                    self.current_datainfo.sample.temperature = data_point
720                    self.current_datainfo.sample.temperature_unit = unit
721                elif tagname == 'details' and self.parent_class == 'SASsample':
722                    self.current_datainfo.sample.details.append(data_point)
723                elif tagname == 'x' and self.parent_class == 'position':
724                    self.current_datainfo.sample.position.x = data_point
725                    self.current_datainfo.sample.position_unit = unit
726                elif tagname == 'y' and self.parent_class == 'position':
727                    self.current_datainfo.sample.position.y = data_point
728                    self.current_datainfo.sample.position_unit = unit
729                elif tagname == 'z' and self.parent_class == 'position':
730                    self.current_datainfo.sample.position.z = data_point
731                    self.current_datainfo.sample.position_unit = unit
732                elif tagname == 'roll' and self.parent_class == 'orientation' and 'SASsample' in self.names:
733                    self.current_datainfo.sample.orientation.x = data_point
734                    self.current_datainfo.sample.orientation_unit = unit
735                elif tagname == 'pitch' and self.parent_class == 'orientation' and 'SASsample' in self.names:
736                    self.current_datainfo.sample.orientation.y = data_point
737                    self.current_datainfo.sample.orientation_unit = unit
738                elif tagname == 'yaw' and self.parent_class == 'orientation' and 'SASsample' in self.names:
739                    self.current_datainfo.sample.orientation.z = data_point
740                    self.current_datainfo.sample.orientation_unit = unit
741
742                # Instrumental Information
743                elif tagname == 'name' and self.parent_class == 'SASinstrument':
744                    self.current_datainfo.instrument = data_point
745                # Detector Information
746                elif tagname == 'name' and self.parent_class == 'SASdetector':
747                    self.detector.name = data_point
748                elif tagname == 'SDD' and self.parent_class == 'SASdetector':
749                    self.detector.distance = data_point
750                    self.detector.distance_unit = unit
751                elif tagname == 'slit_length' and self.parent_class == 'SASdetector':
752                    self.detector.slit_length = data_point
753                    self.detector.slit_length_unit = unit
754                elif tagname == 'x' and self.parent_class == 'offset':
755                    self.detector.offset.x = data_point
756                    self.detector.offset_unit = unit
757                elif tagname == 'y' and self.parent_class == 'offset':
758                    self.detector.offset.y = data_point
759                    self.detector.offset_unit = unit
760                elif tagname == 'z' and self.parent_class == 'offset':
761                    self.detector.offset.z = data_point
762                    self.detector.offset_unit = unit
763                elif tagname == 'x' and self.parent_class == 'beam_center':
764                    self.detector.beam_center.x = data_point
765                    self.detector.beam_center_unit = unit
766                elif tagname == 'y' and self.parent_class == 'beam_center':
767                    self.detector.beam_center.y = data_point
768                    self.detector.beam_center_unit = unit
769                elif tagname == 'z' and self.parent_class == 'beam_center':
770                    self.detector.beam_center.z = data_point
771                    self.detector.beam_center_unit = unit
772                elif tagname == 'x' and self.parent_class == 'pixel_size':
773                    self.detector.pixel_size.x = data_point
774                    self.detector.pixel_size_unit = unit
775                elif tagname == 'y' and self.parent_class == 'pixel_size':
776                    self.detector.pixel_size.y = data_point
777                    self.detector.pixel_size_unit = unit
778                elif tagname == 'z' and self.parent_class == 'pixel_size':
779                    self.detector.pixel_size.z = data_point
780                    self.detector.pixel_size_unit = unit
781                elif tagname == 'roll' and self.parent_class == 'orientation' and 'SASdetector' in self.names:
782                    self.detector.orientation.x = data_point
783                    self.detector.orientation_unit = unit
784                elif tagname == 'pitch' and self.parent_class == 'orientation' and 'SASdetector' in self.names:
785                    self.detector.orientation.y = data_point
786                    self.detector.orientation_unit = unit
787                elif tagname == 'yaw' and self.parent_class == 'orientation' and 'SASdetector' in self.names:
788                    self.detector.orientation.z = data_point
789                    self.detector.orientation_unit = unit
790                # Collimation and Aperture
791                elif tagname == 'length' and self.parent_class == 'SAScollimation':
792                    self.collimation.length = data_point
793                    self.collimation.length_unit = unit
794                elif tagname == 'name' and self.parent_class == 'SAScollimation':
795                    self.collimation.name = data_point
796                elif tagname == 'distance' and self.parent_class == 'aperture':
797                    self.aperture.distance = data_point
798                    self.aperture.distance_unit = unit
799                elif tagname == 'x' and self.parent_class == 'size':
800                    self.aperture.size.x = data_point
801                    self.collimation.size_unit = unit
802                elif tagname == 'y' and self.parent_class == 'size':
803                    self.aperture.size.y = data_point
804                    self.collimation.size_unit = unit
805                elif tagname == 'z' and self.parent_class == 'size':
806                    self.aperture.size.z = data_point
807                    self.collimation.size_unit = unit
808
809                # Process Information
810                elif tagname == 'name' and self.parent_class == 'SASprocess':
811                    self.process.name = data_point
812                elif tagname == 'description' and self.parent_class == 'SASprocess':
813                    self.process.description = data_point
814                elif tagname == 'date' and self.parent_class == 'SASprocess':
815                    try:
816                        self.process.date = datetime.datetime.fromtimestamp(data_point)
817                    except:
818                        self.process.date = data_point
819                elif tagname == 'SASprocessnote':
820                    self.process.notes.append(data_point)
821                elif tagname == 'term' and self.parent_class == 'SASprocess':
822                    unit = attr.get("unit", "")
823                    dic = {}
824                    dic["name"] = name
825                    dic["value"] = data_point
826                    dic["unit"] = unit
827                    self.process.term.append(dic)
828
829                # Transmission Spectrum
830                elif tagname == 'T' and self.parent_class == 'Tdata':
831                    self.transspectrum.transmission = np.append(self.transspectrum.transmission, data_point)
832                    self.transspectrum.transmission_unit = unit
833                elif tagname == 'Tdev' and self.parent_class == 'Tdata':
834                    self.transspectrum.transmission_deviation = np.append(self.transspectrum.transmission_deviation, data_point)
835                    self.transspectrum.transmission_deviation_unit = unit
836                elif tagname == 'Lambda' and self.parent_class == 'Tdata':
837                    self.transspectrum.wavelength = np.append(self.transspectrum.wavelength, data_point)
838                    self.transspectrum.wavelength_unit = unit
839
840                # Source Information
841                elif tagname == 'wavelength' and (self.parent_class == 'SASsource' or self.parent_class == 'SASData'):
842                    self.current_datainfo.source.wavelength = data_point
843                    self.current_datainfo.source.wavelength_unit = unit
844                elif tagname == 'wavelength_min' and self.parent_class == 'SASsource':
845                    self.current_datainfo.source.wavelength_min = data_point
846                    self.current_datainfo.source.wavelength_min_unit = unit
847                elif tagname == 'wavelength_max' and self.parent_class == 'SASsource':
848                    self.current_datainfo.source.wavelength_max = data_point
849                    self.current_datainfo.source.wavelength_max_unit = unit
850                elif tagname == 'wavelength_spread' and self.parent_class == 'SASsource':
851                    self.current_datainfo.source.wavelength_spread = data_point
852                    self.current_datainfo.source.wavelength_spread_unit = unit
853                elif tagname == 'x' and self.parent_class == 'beam_size':
854                    self.current_datainfo.source.beam_size.x = data_point
855                    self.current_datainfo.source.beam_size_unit = unit
856                elif tagname == 'y' and self.parent_class == 'beam_size':
857                    self.current_datainfo.source.beam_size.y = data_point
858                    self.current_datainfo.source.beam_size_unit = unit
859                elif tagname == 'z' and self.parent_class == 'pixel_size':
860                    self.current_datainfo.source.data_point.z = data_point
861                    self.current_datainfo.source.beam_size_unit = unit
862                elif tagname == 'radiation' and self.parent_class == 'SASsource':
863                    self.current_datainfo.source.radiation = data_point
864                elif tagname == 'beam_shape' and self.parent_class == 'SASsource':
865                    self.current_datainfo.source.beam_shape = data_point
866
867                # Everything else goes in meta_data
868                else:
869                    new_key = self._create_unique_key(self.current_datainfo.meta_data, tagname)
870                    self.current_datainfo.meta_data[new_key] = data_point
871>>>>>>> master
872
873        self.add_intermediate()
874
875        # As before in the code, I guess in case we have to return a tuple for some reason...
876        return self.output, None
877
878    def _is_call_local(self):
879        """
880
881        """
882        if self.frm == "":
883            inter = inspect.stack()
884            self.frm = inter[2]
885        mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "")
886        mod_name = mod_name.replace(".py", "")
887        mod = mod_name.split("sas/")
888        mod_name = mod[1]
889        if mod_name != "sascalc/dataloader/readers/cansas_reader":
890            return False
891        return True
892
893    def is_cansas(self, ext="xml"):
894        """
895        Checks to see if the xml file is a CanSAS file
896
897        :param ext: The file extension of the data file
898        """
899        if self.validate_xml():
900            name = "{http://www.w3.org/2001/XMLSchema-instance}schemaLocation"
901            value = self.xmlroot.get(name)
902            if CANSAS_NS.get(self.cansas_version).get("ns") == \
903                    value.rsplit(" ")[0]:
904                return True
905        if ext == "svs":
906            return True
907        raise RuntimeError
908
909    def load_file_and_schema(self, xml_file, schema_path=""):
910        """
911        Loads the file and associates a schema, if a schema is passed in or if one already exists
912
913        :param xml_file: The xml file path sent to Reader.read
914        :param schema_path: The path to a schema associated with the xml_file, or find one based on the file
915        """
916        base_name = xml_reader.__file__
917        base_name = base_name.replace("\\", "/")
918        base = base_name.split("/sas/")[0]
919
920        # Load in xml file and get the cansas version from the header
921        self.set_xml_file(xml_file)
922        self.cansas_version = self.xmlroot.get("version", "1.0")
923
924        # Generic values for the cansas file based on the version
925        self.cansas_defaults = CANSAS_NS.get(self.cansas_version, "1.0")
926        if schema_path == "":
927            schema_path = "{0}/sas/sascalc/dataloader/readers/schema/{1}".format \
928                (base, self.cansas_defaults.get("schema")).replace("\\", "/")
929
930        # Link a schema to the XML file.
931        self.set_schema(schema_path)
932
933    def add_data_set(self):
934        """
935        Adds the current_dataset to the list of outputs after preforming final processing on the data and then calls a
936        private method to generate a new data set.
937
938        :param key: NeXus group name for current tree level
939        """
940
941        if self.current_datainfo and self.current_dataset:
942            self._final_cleanup()
943        self.data = []
944        self.current_datainfo = DataInfo()
945
946    def _initialize_new_data_set(self, node=None):
947        """
948        A private class method to generate a new 1D data object.
949        Outside methods should call add_data_set() to be sure any existing data is stored properly.
950
951        :param node: XML node to determine if 1D or 2D data
952        """
953        x = np.array(0)
954        y = np.array(0)
955        for child in node:
956            if child.tag.replace(self.base_ns, "") == "Idata":
957                for i_child in child:
958                    if i_child.tag.replace(self.base_ns, "") == "Qx":
959                        self.current_dataset = plottable_2D()
960                        return
961        self.current_dataset = plottable_1D(x, y)
962
963    def add_intermediate(self):
964        """
965        This method stores any intermediate objects within the final data set after fully reading the set.
966
967        :param parent: The NXclass name for the h5py Group object that just finished being processed
968        """
969
970        if self.parent_class == 'SASprocess':
971            self.current_datainfo.process.append(self.process)
972            self.process = Process()
973        elif self.parent_class == 'SASdetector':
974            self.current_datainfo.detector.append(self.detector)
975            self.detector = Detector()
976        elif self.parent_class == 'SAStransmission_spectrum':
977            self.current_datainfo.trans_spectrum.append(self.transspectrum)
978            self.transspectrum = TransmissionSpectrum()
979        elif self.parent_class == 'SAScollimation':
980            self.current_datainfo.collimation.append(self.collimation)
981            self.collimation = Collimation()
982        elif self.parent_class == 'aperture':
983            self.collimation.aperture.append(self.aperture)
984            self.aperture = Aperture()
985        elif self.parent_class == 'SASdata':
986            self._check_for_empty_resolution()
987            self.data.append(self.current_dataset)
988
989    def _final_cleanup(self):
990        """
991        Final cleanup of the Data1D object to be sure it has all the
992        appropriate information needed for perspectives
993        """
994
995        # Append errors to dataset and reset class errors
996        self.current_datainfo.errors = set()
997        for error in self.errors:
998            self.current_datainfo.errors.add(error)
999        self.errors.clear()
1000
1001        # Combine all plottables with datainfo and append each to output
1002        # Type cast data arrays to float64 and find min/max as appropriate
1003        for dataset in self.data:
1004            if isinstance(dataset, plottable_1D):
1005                if dataset.x is not None:
1006                    dataset.x = np.delete(dataset.x, [0])
1007                    dataset.x = dataset.x.astype(np.float64)
1008                    dataset.xmin = np.min(dataset.x)
1009                    dataset.xmax = np.max(dataset.x)
1010                if dataset.y is not None:
1011                    dataset.y = np.delete(dataset.y, [0])
1012                    dataset.y = dataset.y.astype(np.float64)
1013                    dataset.ymin = np.min(dataset.y)
1014                    dataset.ymax = np.max(dataset.y)
1015                if dataset.dx is not None:
1016                    dataset.dx = np.delete(dataset.dx, [0])
1017                    dataset.dx = dataset.dx.astype(np.float64)
1018                if dataset.dxl is not None:
1019                    dataset.dxl = np.delete(dataset.dxl, [0])
1020                    dataset.dxl = dataset.dxl.astype(np.float64)
1021                if dataset.dxw is not None:
1022                    dataset.dxw = np.delete(dataset.dxw, [0])
1023                    dataset.dxw = dataset.dxw.astype(np.float64)
1024                if dataset.dy is not None:
1025                    dataset.dy = np.delete(dataset.dy, [0])
1026                    dataset.dy = dataset.dy.astype(np.float64)
1027                np.trim_zeros(dataset.x)
1028                np.trim_zeros(dataset.y)
1029                np.trim_zeros(dataset.dy)
1030            elif isinstance(dataset, plottable_2D):
1031                dataset.data = dataset.data.astype(np.float64)
1032                dataset.qx_data = dataset.qx_data.astype(np.float64)
1033                dataset.xmin = np.min(dataset.qx_data)
1034                dataset.xmax = np.max(dataset.qx_data)
1035                dataset.qy_data = dataset.qy_data.astype(np.float64)
1036                dataset.ymin = np.min(dataset.qy_data)
1037                dataset.ymax = np.max(dataset.qy_data)
1038                dataset.q_data = np.sqrt(dataset.qx_data * dataset.qx_data
1039                                         + dataset.qy_data * dataset.qy_data)
1040                if dataset.err_data is not None:
1041                    dataset.err_data = dataset.err_data.astype(np.float64)
1042                if dataset.dqx_data is not None:
1043                    dataset.dqx_data = dataset.dqx_data.astype(np.float64)
1044                if dataset.dqy_data is not None:
1045                    dataset.dqy_data = dataset.dqy_data.astype(np.float64)
1046                if dataset.mask is not None:
1047                    dataset.mask = dataset.mask.astype(dtype=bool)
1048
1049                if len(dataset.shape) == 2:
1050                    n_rows, n_cols = dataset.shape
1051                    dataset.y_bins = dataset.qy_data[0::int(n_cols)]
1052                    dataset.x_bins = dataset.qx_data[:int(n_cols)]
1053                    dataset.data = dataset.data.flatten()
1054                else:
1055                    dataset.y_bins = []
1056                    dataset.x_bins = []
1057                    dataset.data = dataset.data.flatten()
1058
1059            final_dataset = combine_data(dataset, self.current_datainfo)
1060            self.output.append(final_dataset)
1061
1062    def _create_unique_key(self, dictionary, name, numb=0):
1063        """
1064        Create a unique key value for any dictionary to prevent overwriting
1065        Recurse until a unique key value is found.
1066
1067        :param dictionary: A dictionary with any number of entries
1068        :param name: The index of the item to be added to dictionary
1069        :param numb: The number to be appended to the name, starts at 0
1070        """
1071        if dictionary.get(name) is not None:
1072            numb += 1
1073            name = name.split("_")[0]
1074            name += "_{0}".format(numb)
1075            name = self._create_unique_key(dictionary, name, numb)
1076        return name
1077
1078    def _get_node_value_from_text(self, node, node_text):
1079        """
1080        Get the value of a node and any applicable units
1081
1082        :param node: The XML node to get the value of
1083        :param tagname: The tagname of the node
1084        """
1085        units = ""
1086        # If the value is a float, compile with units.
1087        if self.ns_list.ns_datatype == "float":
1088            # If an empty value is given, set as zero.
1089            if node_text is None or node_text.isspace() \
1090                    or node_text.lower() == "nan":
1091                node_text = "0.0"
1092            # Convert the value to the base units
1093            tag = node.tag.replace(self.base_ns, "")
1094            node_text, units = self._unit_conversion(node, tag, node_text)
1095
1096        # If the value is a timestamp, convert to a datetime object
1097        elif self.ns_list.ns_datatype == "timestamp":
1098            if node_text is None or node_text.isspace():
1099                pass
1100            else:
1101                try:
1102                    node_text = \
1103                        datetime.datetime.fromtimestamp(node_text)
1104                except ValueError:
1105                    node_text = None
1106        return node_text, units
1107
1108    def _get_node_value(self, node):
1109        """
1110        Get the value of a node and any applicable units
1111
1112        :param node: The XML node to get the value of
1113        :param tagname: The tagname of the node
1114        """
1115        #Get the text from the node and convert all whitespace to spaces
1116        units = ''
1117        node_value = node.text
1118        if node_value is not None:
1119            node_value = ' '.join(node_value.split())
1120        else:
1121            node_value = ""
1122        node_value, units = self._get_node_value_from_text(node, node_value)
1123        return node_value, units
1124
1125    def _unit_conversion(self, node, tagname, node_value):
1126        """
1127        A unit converter method used to convert the data included in the file
1128        to the default units listed in data_info
1129
1130        :param node: XML node
1131        :param tagname: name of the node
1132        :param node_value: The value of the current dom node
1133        """
1134        attr = node.attrib
1135        value_unit = ''
1136        err_msg = None
1137        default_unit = None
1138        if not isinstance(node_value, float):
1139            node_value = float(node_value)
1140        if 'unit' in attr and attr.get('unit') is not None:
1141            try:
1142                local_unit = attr['unit']
1143                unitname = self.ns_list.current_level.get("unit", "")
1144                if "SASdetector" in self.names:
1145                    save_in = "detector"
1146                elif "aperture" in self.names:
1147                    save_in = "aperture"
1148                elif "SAScollimation" in self.names:
1149                    save_in = "collimation"
1150                elif "SAStransmission_spectrum" in self.names:
1151                    save_in = "transspectrum"
1152                elif "SASdata" in self.names:
1153                    x = np.zeros(1)
1154                    y = np.zeros(1)
1155                    self.current_data1d = Data1D(x, y)
1156                    save_in = "current_data1d"
1157                elif "SASsource" in self.names:
1158                    save_in = "current_datainfo.source"
1159                elif "SASsample" in self.names:
1160                    save_in = "current_datainfo.sample"
1161                elif "SASprocess" in self.names:
1162                    save_in = "process"
1163                else:
1164                    save_in = "current_datainfo"
1165                exec "default_unit = self.{0}.{1}".format(save_in, unitname)
1166                if local_unit and default_unit and local_unit.lower() != default_unit.lower() \
1167                        and local_unit.lower() != "none":
1168                    if HAS_CONVERTER == True:
1169                        # Check local units - bad units raise KeyError
1170                        data_conv_q = Converter(local_unit)
1171                        value_unit = default_unit
1172                        node_value = data_conv_q(node_value, units=default_unit)
1173                    else:
1174                        value_unit = local_unit
1175                        err_msg = "Unit converter is not available.\n"
1176                else:
1177                    value_unit = local_unit
1178            except KeyError:
1179                err_msg = "CanSAS reader: unexpected "
1180                err_msg += "\"{0}\" unit [{1}]; "
1181                err_msg = err_msg.format(tagname, local_unit)
1182                err_msg += "expecting [{0}]".format(default_unit)
1183                value_unit = local_unit
1184            except:
1185                err_msg = "CanSAS reader: unknown error converting "
1186                err_msg += "\"{0}\" unit [{1}]"
1187                err_msg = err_msg.format(tagname, local_unit)
1188                value_unit = local_unit
1189        elif 'unit' in attr:
1190            value_unit = attr['unit']
1191        if err_msg:
1192            self.errors.add(err_msg)
1193        return node_value, value_unit
1194
1195    def _check_for_empty_data(self):
1196        """
1197        Creates an empty data set if no data is passed to the reader
1198
1199        :param data1d: presumably a Data1D object
1200        """
1201        if self.current_dataset is None:
1202            x_vals = np.empty(0)
1203            y_vals = np.empty(0)
1204            dx_vals = np.empty(0)
1205            dy_vals = np.empty(0)
1206            dxl = np.empty(0)
1207            dxw = np.empty(0)
1208            self.current_dataset = plottable_1D(x_vals, y_vals, dx_vals, dy_vals)
1209            self.current_dataset.dxl = dxl
1210            self.current_dataset.dxw = dxw
1211
1212    def _check_for_empty_resolution(self):
1213        """
1214        A method to check all resolution data sets are the same size as I and Q
1215        """
1216        if isinstance(self.current_dataset, plottable_1D):
1217            dql_exists = False
1218            dqw_exists = False
1219            dq_exists = False
1220            di_exists = False
1221            if self.current_dataset.dxl is not None:
1222                dql_exists = True
1223            if self.current_dataset.dxw is not None:
1224                dqw_exists = True
1225            if self.current_dataset.dx is not None:
1226                dq_exists = True
1227            if self.current_dataset.dy is not None:
1228                di_exists = True
1229            if dqw_exists and not dql_exists:
1230                array_size = self.current_dataset.dxw.size - 1
1231                self.current_dataset.dxl = np.append(self.current_dataset.dxl,
1232                                                     np.zeros([array_size]))
1233            elif dql_exists and not dqw_exists:
1234                array_size = self.current_dataset.dxl.size - 1
1235                self.current_dataset.dxw = np.append(self.current_dataset.dxw,
1236                                                     np.zeros([array_size]))
1237            elif not dql_exists and not dqw_exists and not dq_exists:
1238                array_size = self.current_dataset.x.size - 1
1239                self.current_dataset.dx = np.append(self.current_dataset.dx,
1240                                                    np.zeros([array_size]))
1241            if not di_exists:
1242                array_size = self.current_dataset.y.size - 1
1243                self.current_dataset.dy = np.append(self.current_dataset.dy,
1244                                                    np.zeros([array_size]))
1245        elif isinstance(self.current_dataset, plottable_2D):
1246            dqx_exists = False
1247            dqy_exists = False
1248            di_exists = False
1249            mask_exists = False
1250            if self.current_dataset.dqx_data is not None:
1251                dqx_exists = True
1252            if self.current_dataset.dqy_data is not None:
1253                dqy_exists = True
1254            if self.current_dataset.err_data is not None:
1255                di_exists = True
1256            if self.current_dataset.mask is not None:
1257                mask_exists = True
1258            if not dqy_exists:
1259                array_size = self.current_dataset.qy_data.size - 1
1260                self.current_dataset.dqy_data = np.append(
1261                    self.current_dataset.dqy_data, np.zeros([array_size]))
1262            if not dqx_exists:
1263                array_size = self.current_dataset.qx_data.size - 1
1264                self.current_dataset.dqx_data = np.append(
1265                    self.current_dataset.dqx_data, np.zeros([array_size]))
1266            if not di_exists:
1267                array_size = self.current_dataset.data.size - 1
1268                self.current_dataset.err_data = np.append(
1269                    self.current_dataset.err_data, np.zeros([array_size]))
1270            if not mask_exists:
1271                array_size = self.current_dataset.data.size - 1
1272                self.current_dataset.mask = np.append(
1273                    self.current_dataset.mask,
1274                    np.ones([array_size] ,dtype=bool))
1275
1276    ####### All methods below are for writing CanSAS XML files #######
1277
1278    def write(self, filename, datainfo):
1279        """
1280        Write the content of a Data1D as a CanSAS XML file
1281
1282        :param filename: name of the file to write
1283        :param datainfo: Data1D object
1284        """
1285        # Create XML document
1286        doc, _ = self._to_xml_doc(datainfo)
1287        # Write the file
1288        file_ref = open(filename, 'w')
1289        if self.encoding is None:
1290            self.encoding = "UTF-8"
1291        doc.write(file_ref, encoding=self.encoding,
1292                  pretty_print=True, xml_declaration=True)
1293        file_ref.close()
1294
1295    def _to_xml_doc(self, datainfo):
1296        """
1297        Create an XML document to contain the content of a Data1D
1298
1299        :param datainfo: Data1D object
1300        """
1301        is_2d = False
1302        if issubclass(datainfo.__class__, Data2D):
1303            is_2d = True
1304
1305        # Get PIs and create root element
1306        pi_string = self._get_pi_string()
1307        # Define namespaces and create SASroot object
1308        main_node = self._create_main_node()
1309        # Create ElementTree, append SASroot and apply processing instructions
1310        base_string = pi_string + self.to_string(main_node)
1311        base_element = self.create_element_from_string(base_string)
1312        doc = self.create_tree(base_element)
1313        # Create SASentry Element
1314        entry_node = self.create_element("SASentry")
1315        root = doc.getroot()
1316        root.append(entry_node)
1317
1318        # Add Title to SASentry
1319        self.write_node(entry_node, "Title", datainfo.title)
1320        # Add Run to SASentry
1321        self._write_run_names(datainfo, entry_node)
1322        # Add Data info to SASEntry
1323        if is_2d:
1324            self._write_data_2d(datainfo, entry_node)
1325        else:
1326            if self._check_root():
1327                self._write_data(datainfo, entry_node)
1328            else:
1329                self._write_data_linearized(datainfo, entry_node)
1330        # Transmission Spectrum Info
1331        # TODO: fix the writer to linearize all data, including T_spectrum
1332        # self._write_trans_spectrum(datainfo, entry_node)
1333        # Sample info
1334        self._write_sample_info(datainfo, entry_node)
1335        # Instrument info
1336        instr = self._write_instrument(datainfo, entry_node)
1337        #   Source
1338        self._write_source(datainfo, instr)
1339        #   Collimation
1340        self._write_collimation(datainfo, instr)
1341        #   Detectors
1342        self._write_detectors(datainfo, instr)
1343        # Processes info
1344        self._write_process_notes(datainfo, entry_node)
1345        # Note info
1346        self._write_notes(datainfo, entry_node)
1347        # Return the document, and the SASentry node associated with
1348        #      the data we just wrote
1349        # If the calling function was not the cansas reader, return a minidom
1350        #      object rather than an lxml object.
1351        self.frm = inspect.stack()[1]
1352        doc, entry_node = self._check_origin(entry_node, doc)
1353        return doc, entry_node
1354
1355    def write_node(self, parent, name, value, attr=None):
1356        """
1357        :param doc: document DOM
1358        :param parent: parent node
1359        :param name: tag of the element
1360        :param value: value of the child text node
1361        :param attr: attribute dictionary
1362
1363        :return: True if something was appended, otherwise False
1364        """
1365        if value is not None:
1366            parent = self.ebuilder(parent, name, value, attr)
1367            return True
1368        return False
1369
1370    def _get_pi_string(self):
1371        """
1372        Creates the processing instructions header for writing to file
1373        """
1374        pis = self.return_processing_instructions()
1375        if len(pis) > 0:
1376            pi_tree = self.create_tree(pis[0])
1377            i = 1
1378            for i in range(1, len(pis) - 1):
1379                pi_tree = self.append(pis[i], pi_tree)
1380            pi_string = self.to_string(pi_tree)
1381        else:
1382            pi_string = ""
1383        return pi_string
1384
1385    def _create_main_node(self):
1386        """
1387        Creates the primary xml header used when writing to file
1388        """
1389        xsi = "http://www.w3.org/2001/XMLSchema-instance"
1390        version = self.cansas_version
1391        n_s = CANSAS_NS.get(version).get("ns")
1392        if version == "1.1":
1393            url = "http://www.cansas.org/formats/1.1/"
1394        else:
1395            url = "http://www.cansas.org/formats/1.0/"
1396        schema_location = "{0} {1}cansas1d.xsd".format(n_s, url)
1397        attrib = {"{" + xsi + "}schemaLocation" : schema_location,
1398                  "version" : version}
1399        nsmap = {'xsi' : xsi, None: n_s}
1400
1401        main_node = self.create_element("{" + n_s + "}SASroot",
1402                                        attrib=attrib, nsmap=nsmap)
1403        return main_node
1404
1405    def _write_run_names(self, datainfo, entry_node):
1406        """
1407        Writes the run names to the XML file
1408
1409        :param datainfo: The Data1D object the information is coming from
1410        :param entry_node: lxml node ElementTree object to be appended to
1411        """
1412        if datainfo.run is None or datainfo.run == []:
1413            datainfo.run.append(RUN_NAME_DEFAULT)
1414            datainfo.run_name[RUN_NAME_DEFAULT] = RUN_NAME_DEFAULT
1415        for item in datainfo.run:
1416            runname = {}
1417            if item in datainfo.run_name and \
1418            len(str(datainfo.run_name[item])) > 1:
1419                runname = {'name': datainfo.run_name[item]}
1420            self.write_node(entry_node, "Run", item, runname)
1421
1422    def _write_data(self, datainfo, entry_node):
1423        """
1424        Writes 1D I and Q data to the XML file
1425
1426        :param datainfo: The Data1D object the information is coming from
1427        :param entry_node: lxml node ElementTree object to be appended to
1428        """
1429        node = self.create_element("SASdata")
1430        self.append(node, entry_node)
1431
1432        for i in range(len(datainfo.x)):
1433            point = self.create_element("Idata")
1434            node.append(point)
1435            self.write_node(point, "Q", datainfo.x[i],
1436                            {'unit': datainfo._xaxis + " | " + datainfo._xunit})
1437            if len(datainfo.y) >= i:
1438                self.write_node(point, "I", datainfo.y[i],
1439                                {'unit': datainfo._yaxis + " | " + datainfo._yunit})
1440            if datainfo.dy is not None and len(datainfo.dy) > i:
1441                self.write_node(point, "Idev", datainfo.dy[i],
1442                                {'unit': datainfo._yaxis + " | " + datainfo._yunit})
1443            if datainfo.dx is not None and len(datainfo.dx) > i:
1444                self.write_node(point, "Qdev", datainfo.dx[i],
1445                                {'unit': datainfo._xaxis + " | " + datainfo._xunit})
1446            if datainfo.dxw is not None and len(datainfo.dxw) > i:
1447                self.write_node(point, "dQw", datainfo.dxw[i],
1448                                {'unit': datainfo._xaxis + " | " + datainfo._xunit})
1449            if datainfo.dxl is not None and len(datainfo.dxl) > i:
1450                self.write_node(point, "dQl", datainfo.dxl[i],
1451                                {'unit': datainfo._xaxis + " | " + datainfo._xunit})
1452        if datainfo.isSesans:
1453            sesans = self.create_element("Sesans")
1454            sesans.text = str(datainfo.isSesans)
1455            node.append(sesans)
1456            self.write_node(node, "yacceptance", datainfo.sample.yacceptance[0],
1457                             {'unit': datainfo.sample.yacceptance[1]})
1458            self.write_node(node, "zacceptance", datainfo.sample.zacceptance[0],
1459                             {'unit': datainfo.sample.zacceptance[1]})
1460
1461
1462    def _write_data_2d(self, datainfo, entry_node):
1463        """
1464        Writes 2D data to the XML file
1465
1466        :param datainfo: The Data2D object the information is coming from
1467        :param entry_node: lxml node ElementTree object to be appended to
1468        """
1469        attr = {}
1470        if datainfo.data.shape:
1471            attr["x_bins"] = str(len(datainfo.x_bins))
1472            attr["y_bins"] = str(len(datainfo.y_bins))
1473        node = self.create_element("SASdata", attr)
1474        self.append(node, entry_node)
1475
1476        point = self.create_element("Idata")
1477        node.append(point)
1478        qx = ','.join([str(datainfo.qx_data[i]) for i in xrange(len(datainfo.qx_data))])
1479        qy = ','.join([str(datainfo.qy_data[i]) for i in xrange(len(datainfo.qy_data))])
1480        intensity = ','.join([str(datainfo.data[i]) for i in xrange(len(datainfo.data))])
1481
1482        self.write_node(point, "Qx", qx,
1483                        {'unit': datainfo._xunit})
1484        self.write_node(point, "Qy", qy,
1485                        {'unit': datainfo._yunit})
1486        self.write_node(point, "I", intensity,
1487                        {'unit': datainfo._zunit})
1488        if datainfo.err_data is not None:
1489            err = ','.join([str(datainfo.err_data[i]) for i in
1490                            xrange(len(datainfo.err_data))])
1491            self.write_node(point, "Idev", err,
1492                            {'unit': datainfo._zunit})
1493        if datainfo.dqy_data is not None:
1494            dqy = ','.join([str(datainfo.dqy_data[i]) for i in
1495                            xrange(len(datainfo.dqy_data))])
1496            self.write_node(point, "Qydev", dqy,
1497                            {'unit': datainfo._yunit})
1498        if datainfo.dqx_data is not None:
1499            dqx = ','.join([str(datainfo.dqx_data[i]) for i in
1500                            xrange(len(datainfo.dqx_data))])
1501            self.write_node(point, "Qxdev", dqx,
1502                            {'unit': datainfo._xunit})
1503        if datainfo.mask is not None:
1504            mask = ','.join(
1505                ["1" if datainfo.mask[i] else "0"
1506                 for i in xrange(len(datainfo.mask))])
1507            self.write_node(point, "Mask", mask)
1508
1509    def _write_trans_spectrum(self, datainfo, entry_node):
1510        """
1511        Writes the transmission spectrum data to the XML file
1512
1513        :param datainfo: The Data1D object the information is coming from
1514        :param entry_node: lxml node ElementTree object to be appended to
1515        """
1516        for i in range(len(datainfo.trans_spectrum)):
1517            spectrum = datainfo.trans_spectrum[i]
1518            node = self.create_element("SAStransmission_spectrum",
1519                                       {"name" : spectrum.name})
1520            self.append(node, entry_node)
1521            if isinstance(spectrum.timestamp, datetime.datetime):
1522                node.setAttribute("timestamp", spectrum.timestamp)
1523            for i in range(len(spectrum.wavelength)):
1524                point = self.create_element("Tdata")
1525                node.append(point)
1526                self.write_node(point, "Lambda", spectrum.wavelength[i],
1527                                {'unit': spectrum.wavelength_unit})
1528                self.write_node(point, "T", spectrum.transmission[i],
1529                                {'unit': spectrum.transmission_unit})
1530                if spectrum.transmission_deviation is not None \
1531                and len(spectrum.transmission_deviation) >= i:
1532                    self.write_node(point, "Tdev",
1533                                    spectrum.transmission_deviation[i],
1534                                    {'unit':
1535                                     spectrum.transmission_deviation_unit})
1536
1537    def _write_sample_info(self, datainfo, entry_node):
1538        """
1539        Writes the sample information to the XML file
1540
1541        :param datainfo: The Data1D object the information is coming from
1542        :param entry_node: lxml node ElementTree object to be appended to
1543        """
1544        sample = self.create_element("SASsample")
1545        if datainfo.sample.name is not None:
1546            self.write_attribute(sample, "name",
1547                                 str(datainfo.sample.name))
1548        self.append(sample, entry_node)
1549        self.write_node(sample, "ID", str(datainfo.sample.ID))
1550        self.write_node(sample, "thickness", datainfo.sample.thickness,
1551                        {"unit": datainfo.sample.thickness_unit})
1552        self.write_node(sample, "transmission", datainfo.sample.transmission)
1553        self.write_node(sample, "temperature", datainfo.sample.temperature,
1554                        {"unit": datainfo.sample.temperature_unit})
1555
1556        pos = self.create_element("position")
1557        written = self.write_node(pos,
1558                                  "x",
1559                                  datainfo.sample.position.x,
1560                                  {"unit": datainfo.sample.position_unit})
1561        written = written | self.write_node( \
1562            pos, "y", datainfo.sample.position.y,
1563            {"unit": datainfo.sample.position_unit})
1564        written = written | self.write_node( \
1565            pos, "z", datainfo.sample.position.z,
1566            {"unit": datainfo.sample.position_unit})
1567        if written == True:
1568            self.append(pos, sample)
1569
1570        ori = self.create_element("orientation")
1571        written = self.write_node(ori, "roll",
1572                                  datainfo.sample.orientation.x,
1573                                  {"unit": datainfo.sample.orientation_unit})
1574        written = written | self.write_node( \
1575            ori, "pitch", datainfo.sample.orientation.y,
1576            {"unit": datainfo.sample.orientation_unit})
1577        written = written | self.write_node( \
1578            ori, "yaw", datainfo.sample.orientation.z,
1579            {"unit": datainfo.sample.orientation_unit})
1580        if written == True:
1581            self.append(ori, sample)
1582
1583        for item in datainfo.sample.details:
1584            self.write_node(sample, "details", item)
1585
1586    def _write_instrument(self, datainfo, entry_node):
1587        """
1588        Writes the instrumental information to the XML file
1589
1590        :param datainfo: The Data1D object the information is coming from
1591        :param entry_node: lxml node ElementTree object to be appended to
1592        """
1593        instr = self.create_element("SASinstrument")
1594        self.append(instr, entry_node)
1595        self.write_node(instr, "name", datainfo.instrument)
1596        return instr
1597
1598    def _write_source(self, datainfo, instr):
1599        """
1600        Writes the source information to the XML file
1601
1602        :param datainfo: The Data1D object the information is coming from
1603        :param instr: instrument node  to be appended to
1604        """
1605        source = self.create_element("SASsource")
1606        if datainfo.source.name is not None:
1607            self.write_attribute(source, "name",
1608                                 str(datainfo.source.name))
1609        self.append(source, instr)
1610        if datainfo.source.radiation is None or datainfo.source.radiation == '':
1611            datainfo.source.radiation = "neutron"
1612        self.write_node(source, "radiation", datainfo.source.radiation)
1613
1614        size = self.create_element("beam_size")
1615        if datainfo.source.beam_size_name is not None:
1616            self.write_attribute(size, "name",
1617                                 str(datainfo.source.beam_size_name))
1618        written = self.write_node( \
1619            size, "x", datainfo.source.beam_size.x,
1620            {"unit": datainfo.source.beam_size_unit})
1621        written = written | self.write_node( \
1622            size, "y", datainfo.source.beam_size.y,
1623            {"unit": datainfo.source.beam_size_unit})
1624        written = written | self.write_node( \
1625            size, "z", datainfo.source.beam_size.z,
1626            {"unit": datainfo.source.beam_size_unit})
1627        if written == True:
1628            self.append(size, source)
1629
1630        self.write_node(source, "beam_shape", datainfo.source.beam_shape)
1631        self.write_node(source, "wavelength",
1632                        datainfo.source.wavelength,
1633                        {"unit": datainfo.source.wavelength_unit})
1634        self.write_node(source, "wavelength_min",
1635                        datainfo.source.wavelength_min,
1636                        {"unit": datainfo.source.wavelength_min_unit})
1637        self.write_node(source, "wavelength_max",
1638                        datainfo.source.wavelength_max,
1639                        {"unit": datainfo.source.wavelength_max_unit})
1640        self.write_node(source, "wavelength_spread",
1641                        datainfo.source.wavelength_spread,
1642                        {"unit": datainfo.source.wavelength_spread_unit})
1643
1644    def _write_collimation(self, datainfo, instr):
1645        """
1646        Writes the collimation information to the XML file
1647
1648        :param datainfo: The Data1D object the information is coming from
1649        :param instr: lxml node ElementTree object to be appended to
1650        """
1651        if datainfo.collimation == [] or datainfo.collimation is None:
1652            coll = Collimation()
1653            datainfo.collimation.append(coll)
1654        for item in datainfo.collimation:
1655            coll = self.create_element("SAScollimation")
1656            if item.name is not None:
1657                self.write_attribute(coll, "name", str(item.name))
1658            self.append(coll, instr)
1659
1660            self.write_node(coll, "length", item.length,
1661                            {"unit": item.length_unit})
1662
1663            for aperture in item.aperture:
1664                apert = self.create_element("aperture")
1665                if aperture.name is not None:
1666                    self.write_attribute(apert, "name", str(aperture.name))
1667                if aperture.type is not None:
1668                    self.write_attribute(apert, "type", str(aperture.type))
1669                self.append(apert, coll)
1670
1671                size = self.create_element("size")
1672                if aperture.size_name is not None:
1673                    self.write_attribute(size, "name",
1674                                         str(aperture.size_name))
1675                written = self.write_node(size, "x", aperture.size.x,
1676                                          {"unit": aperture.size_unit})
1677                written = written | self.write_node( \
1678                    size, "y", aperture.size.y,
1679                    {"unit": aperture.size_unit})
1680                written = written | self.write_node( \
1681                    size, "z", aperture.size.z,
1682                    {"unit": aperture.size_unit})
1683                if written == True:
1684                    self.append(size, apert)
1685
1686                self.write_node(apert, "distance", aperture.distance,
1687                                {"unit": aperture.distance_unit})
1688
1689    def _write_detectors(self, datainfo, instr):
1690        """
1691        Writes the detector information to the XML file
1692
1693        :param datainfo: The Data1D object the information is coming from
1694        :param inst: lxml instrument node to be appended to
1695        """
1696        if datainfo.detector is None or datainfo.detector == []:
1697            det = Detector()
1698            det.name = ""
1699            datainfo.detector.append(det)
1700
1701        for item in datainfo.detector:
1702            det = self.create_element("SASdetector")
1703            written = self.write_node(det, "name", item.name)
1704            written = written | self.write_node(det, "SDD", item.distance,
1705                                                {"unit": item.distance_unit})
1706            if written == True:
1707                self.append(det, instr)
1708
1709            off = self.create_element("offset")
1710            written = self.write_node(off, "x", item.offset.x,
1711                                      {"unit": item.offset_unit})
1712            written = written | self.write_node(off, "y", item.offset.y,
1713                                                {"unit": item.offset_unit})
1714            written = written | self.write_node(off, "z", item.offset.z,
1715                                                {"unit": item.offset_unit})
1716            if written == True:
1717                self.append(off, det)
1718
1719            ori = self.create_element("orientation")
1720            written = self.write_node(ori, "roll", item.orientation.x,
1721                                      {"unit": item.orientation_unit})
1722            written = written | self.write_node(ori, "pitch",
1723                                                item.orientation.y,
1724                                                {"unit": item.orientation_unit})
1725            written = written | self.write_node(ori, "yaw",
1726                                                item.orientation.z,
1727                                                {"unit": item.orientation_unit})
1728            if written == True:
1729                self.append(ori, det)
1730
1731            center = self.create_element("beam_center")
1732            written = self.write_node(center, "x", item.beam_center.x,
1733                                      {"unit": item.beam_center_unit})
1734            written = written | self.write_node(center, "y",
1735                                                item.beam_center.y,
1736                                                {"unit": item.beam_center_unit})
1737            written = written | self.write_node(center, "z",
1738                                                item.beam_center.z,
1739                                                {"unit": item.beam_center_unit})
1740            if written == True:
1741                self.append(center, det)
1742
1743            pix = self.create_element("pixel_size")
1744            written = self.write_node(pix, "x", item.pixel_size.x,
1745                                      {"unit": item.pixel_size_unit})
1746            written = written | self.write_node(pix, "y", item.pixel_size.y,
1747                                                {"unit": item.pixel_size_unit})
1748            written = written | self.write_node(pix, "z", item.pixel_size.z,
1749                                                {"unit": item.pixel_size_unit})
1750            if written == True:
1751                self.append(pix, det)
1752            self.write_node(det, "slit_length", item.slit_length,
1753                {"unit": item.slit_length_unit})
1754
1755    def _write_process_notes(self, datainfo, entry_node):
1756        """
1757        Writes the process notes to the XML file
1758
1759        :param datainfo: The Data1D object the information is coming from
1760        :param entry_node: lxml node ElementTree object to be appended to
1761
1762        """
1763        for item in datainfo.process:
1764            node = self.create_element("SASprocess")
1765            self.append(node, entry_node)
1766            self.write_node(node, "name", item.name)
1767            self.write_node(node, "date", item.date)
1768            self.write_node(node, "description", item.description)
1769            for term in item.term:
1770                if isinstance(term, list):
1771                    value = term['value']
1772                    del term['value']
1773                elif isinstance(term, dict):
1774                    value = term.get("value")
1775                    del term['value']
1776                else:
1777                    value = term
1778                self.write_node(node, "term", value, term)
1779            for note in item.notes:
1780                self.write_node(node, "SASprocessnote", note)
1781            if len(item.notes) == 0:
1782                self.write_node(node, "SASprocessnote", "")
1783
1784    def _write_notes(self, datainfo, entry_node):
1785        """
1786        Writes the notes to the XML file and creates an empty note if none
1787        exist
1788
1789        :param datainfo: The Data1D object the information is coming from
1790        :param entry_node: lxml node ElementTree object to be appended to
1791
1792        """
1793        if len(datainfo.notes) == 0:
1794            node = self.create_element("SASnote")
1795            self.append(node, entry_node)
1796        else:
1797            for item in datainfo.notes:
1798                node = self.create_element("SASnote")
1799                self.write_text(node, item)
1800                self.append(node, entry_node)
1801
1802    def _check_root(self):
1803        """
1804        Return the document, and the SASentry node associated with
1805        the data we just wrote.
1806        If the calling function was not the cansas reader, return a minidom
1807        object rather than an lxml object.
1808
1809        :param entry_node: lxml node ElementTree object to be appended to
1810        :param doc: entire xml tree
1811        """
1812        if not self.frm:
1813            self.frm = inspect.stack()[2]
1814        mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "")
1815        mod_name = mod_name.replace(".py", "")
1816        mod = mod_name.split("sas/")
1817        mod_name = mod[1]
1818        return mod_name == "sascalc/dataloader/readers/cansas_reader"
1819
1820    def _check_origin(self, entry_node, doc):
1821        """
1822        Return the document, and the SASentry node associated with
1823        the data we just wrote.
1824        If the calling function was not the cansas reader, return a minidom
1825        object rather than an lxml object.
1826
1827        :param entry_node: lxml node ElementTree object to be appended to
1828        :param doc: entire xml tree
1829        """
1830        if not self._check_root():
1831            string = self.to_string(doc, pretty_print=False)
1832            doc = parseString(string)
1833            node_name = entry_node.tag
1834            node_list = doc.getElementsByTagName(node_name)
1835            entry_node = node_list.item(0)
1836        return doc, entry_node
1837
1838    # DO NOT REMOVE - used in saving and loading panel states.
1839    def _store_float(self, location, node, variable, storage, optional=True):
1840        """
1841        Get the content of a xpath location and store
1842        the result. Check that the units are compatible
1843        with the destination. The value is expected to
1844        be a float.
1845
1846        The xpath location might or might not exist.
1847        If it does not exist, nothing is done
1848
1849        :param location: xpath location to fetch
1850        :param node: node to read the data from
1851        :param variable: name of the data member to store it in [string]
1852        :param storage: data object that has the 'variable' data member
1853        :param optional: if True, no exception will be raised
1854            if unit conversion can't be done
1855
1856        :raise ValueError: raised when the units are not recognized
1857        """
1858        entry = get_content(location, node)
1859        try:
1860            value = float(entry.text)
1861        except:
1862            value = None
1863
1864        if value is not None:
1865            # If the entry has units, check to see that they are
1866            # compatible with what we currently have in the data object
1867            units = entry.get('unit')
1868            if units is not None:
1869                toks = variable.split('.')
1870                local_unit = None
1871                exec "local_unit = storage.%s_unit" % toks[0]
1872                if local_unit is not None and units.lower() != local_unit.lower():
1873                    if HAS_CONVERTER == True:
1874                        try:
1875                            conv = Converter(units)
1876                            exec "storage.%s = %g" % \
1877                                (variable, conv(value, units=local_unit))
1878                        except:
1879                            _, exc_value, _ = sys.exc_info()
1880                            err_mess = "CanSAS reader: could not convert"
1881                            err_mess += " %s unit [%s]; expecting [%s]\n  %s" \
1882                                % (variable, units, local_unit, exc_value)
1883                            self.errors.add(err_mess)
1884                            if optional:
1885                                logger.info(err_mess)
1886                            else:
1887                                raise ValueError, err_mess
1888                    else:
1889                        err_mess = "CanSAS reader: unrecognized %s unit [%s];"\
1890                        % (variable, units)
1891                        err_mess += " expecting [%s]" % local_unit
1892                        self.errors.add(err_mess)
1893                        if optional:
1894                            logger.info(err_mess)
1895                        else:
1896                            raise ValueError, err_mess
1897                else:
1898                    exec "storage.%s = value" % variable
1899            else:
1900                exec "storage.%s = value" % variable
1901
1902    # DO NOT REMOVE - used in saving and loading panel states.
1903    def _store_content(self, location, node, variable, storage):
1904        """
1905        Get the content of a xpath location and store
1906        the result. The value is treated as a string.
1907
1908        The xpath location might or might not exist.
1909        If it does not exist, nothing is done
1910
1911        :param location: xpath location to fetch
1912        :param node: node to read the data from
1913        :param variable: name of the data member to store it in [string]
1914        :param storage: data object that has the 'variable' data member
1915
1916        :return: return a list of errors
1917        """
1918        entry = get_content(location, node)
1919        if entry is not None and entry.text is not None:
1920            exec "storage.%s = entry.text.strip()" % variable
1921
1922
1923# DO NOT REMOVE Called by outside packages:
1924#    sas.sasgui.perspectives.invariant.invariant_state
1925#    sas.sasgui.perspectives.fitting.pagestate
1926def get_content(location, node):
1927    """
1928    Get the first instance of the content of a xpath location.
1929
1930    :param location: xpath location
1931    :param node: node to start at
1932
1933    :return: Element, or None
1934    """
1935    nodes = node.xpath(location,
1936                       namespaces={'ns': CANSAS_NS.get("1.0").get("ns")})
1937    if len(nodes) > 0:
1938        return nodes[0]
1939    else:
1940        return None
1941
1942# DO NOT REMOVE Called by outside packages:
1943#    sas.sasgui.perspectives.fitting.pagestate
1944def write_node(doc, parent, name, value, attr=None):
1945    """
1946    :param doc: document DOM
1947    :param parent: parent node
1948    :param name: tag of the element
1949    :param value: value of the child text node
1950    :param attr: attribute dictionary
1951
1952    :return: True if something was appended, otherwise False
1953    """
1954    if attr is None:
1955        attr = {}
1956    if value is not None:
1957        node = doc.createElement(name)
1958        node.appendChild(doc.createTextNode(str(value)))
1959        for item in attr:
1960            node.setAttribute(item, attr[item])
1961        parent.appendChild(node)
1962        return True
1963    return False
Note: See TracBrowser for help on using the repository browser.