source: sasview/src/sas/sascalc/dataloader/readers/cansas_reader.py @ 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: 80.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                        setupArray = startArray
632
633                    ## Transmission Spectrum
634                    if setupTagName == "T":
635                        self.transspectrum.transmission = setupArray
636                        self.transspectrum.transmission_unit = transmissionDataUnits
637                    elif setupTagName == "Tdev":
638                        self.transspectrum.transmission_deviation = setupArray
639                        self.transspectrum.transmission_deviation_unit = transmissionDataUnits
640                    elif setupTagName == "Lambda":
641                        self.transspectrum.wavelength = setupArray
642                        self.transspectrum.wavelength_unit = transmissionDataUnits
643
644                # If there's more data present, let's deal with that too
645                for loopIter in range(1, len(sasNode)):
646                    for dataNode in sasNode[loopIter]:
647                        dataTagName = dataNode.tag.replace(self.base_ns, "")
648                        dataArray = np.fromstring(dataNode.text, dtype=float, sep=",")
649
650                    if dataTagName == "T":
651                        self.transspectrum.transmission[loopIter] = setupArray
652                    elif dataTagName == "Tdev":
653                        self.transspectrum.transmission_deviation[loopIter] = setupArray
654                    elif dataTagName == "Lambda":
655                        self.transspectrum.wavelength[loopIter] = setupArray
656
657                self.current_datainfo.trans_spectrum.append(self.transspectrum)
658                self.transspectrum = TransmissionSpectrum()
659
660
661            ## Everything else goes in meta_data
662            else:
663                new_key = self._create_unique_key(self.current_datainfo.meta_data, currentTagName)
664                self.current_datainfo.meta_data[new_key] = sasNode.text
665
666        self.add_intermediate()
667
668        # As before in the code, I guess in case we have to return a tuple for some reason...
669        return self.output, None
670
671    def _is_call_local(self):
672        """
673
674        """
675        if self.frm == "":
676            inter = inspect.stack()
677            self.frm = inter[2]
678        mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "")
679        mod_name = mod_name.replace(".py", "")
680        mod = mod_name.split("sas/")
681        mod_name = mod[1]
682        if mod_name != "sascalc/dataloader/readers/cansas_reader":
683            return False
684        return True
685
686    def is_cansas(self, ext="xml"):
687        """
688        Checks to see if the xml file is a CanSAS file
689
690        :param ext: The file extension of the data file
691        """
692        if self.validate_xml():
693            name = "{http://www.w3.org/2001/XMLSchema-instance}schemaLocation"
694            value = self.xmlroot.get(name)
695            if CANSAS_NS.get(self.cansas_version).get("ns") == \
696                    value.rsplit(" ")[0]:
697                return True
698        if ext == "svs":
699            return True
700        raise RuntimeError
701
702    def load_file_and_schema(self, xml_file, schema_path=""):
703        """
704        Loads the file and associates a schema, if a schema is passed in or if one already exists
705
706        :param xml_file: The xml file path sent to Reader.read
707        :param schema_path: The path to a schema associated with the xml_file, or find one based on the file
708        """
709        base_name = xml_reader.__file__
710        base_name = base_name.replace("\\", "/")
711        base = base_name.split("/sas/")[0]
712
713        # Load in xml file and get the cansas version from the header
714        self.set_xml_file(xml_file)
715        self.cansas_version = self.xmlroot.get("version", "1.0")
716
717        # Generic values for the cansas file based on the version
718        self.cansas_defaults = CANSAS_NS.get(self.cansas_version, "1.0")
719        if schema_path == "":
720            schema_path = "{0}/sas/sascalc/dataloader/readers/schema/{1}".format \
721                (base, self.cansas_defaults.get("schema")).replace("\\", "/")
722
723        # Link a schema to the XML file.
724        self.set_schema(schema_path)
725
726    def add_data_set(self):
727        """
728        Adds the current_dataset to the list of outputs after preforming final processing on the data and then calls a
729        private method to generate a new data set.
730
731        :param key: NeXus group name for current tree level
732        """
733
734        if self.current_datainfo and self.current_dataset:
735            self._final_cleanup()
736        self.data = []
737        self.current_datainfo = DataInfo()
738
739    def _initialize_new_data_set(self, node=None):
740        """
741        A private class method to generate a new 1D data object.
742        Outside methods should call add_data_set() to be sure any existing data is stored properly.
743
744        :param node: XML node to determine if 1D or 2D data
745        """
746        x = np.array(0)
747        y = np.array(0)
748        for child in node:
749            if child.tag.replace(self.base_ns, "") == "Idata":
750                for i_child in child:
751                    if i_child.tag.replace(self.base_ns, "") == "Qx":
752                        self.current_dataset = plottable_2D()
753                        return
754        self.current_dataset = plottable_1D(x, y)
755
756    def add_intermediate(self):
757        """
758        This method stores any intermediate objects within the final data set after fully reading the set.
759
760        :param parent: The NXclass name for the h5py Group object that just finished being processed
761        """
762
763        if self.parent_class == 'SASprocess':
764            self.current_datainfo.process.append(self.process)
765            self.process = Process()
766        elif self.parent_class == 'SASdetector':
767            self.current_datainfo.detector.append(self.detector)
768            self.detector = Detector()
769        elif self.parent_class == 'SAStransmission_spectrum':
770            self.current_datainfo.trans_spectrum.append(self.transspectrum)
771            self.transspectrum = TransmissionSpectrum()
772        elif self.parent_class == 'SAScollimation':
773            self.current_datainfo.collimation.append(self.collimation)
774            self.collimation = Collimation()
775        elif self.parent_class == 'aperture':
776            self.collimation.aperture.append(self.aperture)
777            self.aperture = Aperture()
778        elif self.parent_class == 'SASdata':
779            self._check_for_empty_resolution()
780            self.data.append(self.current_dataset)
781
782    def _final_cleanup(self):
783        """
784        Final cleanup of the Data1D object to be sure it has all the
785        appropriate information needed for perspectives
786        """
787
788        # Append errors to dataset and reset class errors
789        self.current_datainfo.errors = set()
790        for error in self.errors:
791            self.current_datainfo.errors.add(error)
792        self.errors.clear()
793
794        # Combine all plottables with datainfo and append each to output
795        # Type cast data arrays to float64 and find min/max as appropriate
796        for dataset in self.data:
797            if isinstance(dataset, plottable_1D):
798                if dataset.x is not None:
799                    dataset.x = np.delete(dataset.x, [0])
800                    dataset.x = dataset.x.astype(np.float64)
801                    dataset.xmin = np.min(dataset.x)
802                    dataset.xmax = np.max(dataset.x)
803                if dataset.y is not None:
804                    dataset.y = np.delete(dataset.y, [0])
805                    dataset.y = dataset.y.astype(np.float64)
806                    dataset.ymin = np.min(dataset.y)
807                    dataset.ymax = np.max(dataset.y)
808                if dataset.dx is not None:
809                    dataset.dx = np.delete(dataset.dx, [0])
810                    dataset.dx = dataset.dx.astype(np.float64)
811                if dataset.dxl is not None:
812                    dataset.dxl = np.delete(dataset.dxl, [0])
813                    dataset.dxl = dataset.dxl.astype(np.float64)
814                if dataset.dxw is not None:
815                    dataset.dxw = np.delete(dataset.dxw, [0])
816                    dataset.dxw = dataset.dxw.astype(np.float64)
817                if dataset.dy is not None:
818                    dataset.dy = np.delete(dataset.dy, [0])
819                    dataset.dy = dataset.dy.astype(np.float64)
820                np.trim_zeros(dataset.x)
821                np.trim_zeros(dataset.y)
822                np.trim_zeros(dataset.dy)
823            elif isinstance(dataset, plottable_2D):
824                dataset.data = dataset.data.astype(np.float64)
825                dataset.qx_data = dataset.qx_data.astype(np.float64)
826                dataset.xmin = np.min(dataset.qx_data)
827                dataset.xmax = np.max(dataset.qx_data)
828                dataset.qy_data = dataset.qy_data.astype(np.float64)
829                dataset.ymin = np.min(dataset.qy_data)
830                dataset.ymax = np.max(dataset.qy_data)
831                dataset.q_data = np.sqrt(dataset.qx_data * dataset.qx_data
832                                         + dataset.qy_data * dataset.qy_data)
833                if dataset.err_data is not None:
834                    dataset.err_data = dataset.err_data.astype(np.float64)
835                if dataset.dqx_data is not None:
836                    dataset.dqx_data = dataset.dqx_data.astype(np.float64)
837                if dataset.dqy_data is not None:
838                    dataset.dqy_data = dataset.dqy_data.astype(np.float64)
839                if dataset.mask is not None:
840                    dataset.mask = dataset.mask.astype(dtype=bool)
841
842                if len(dataset.shape) == 2:
843                    n_rows, n_cols = dataset.shape
844                    dataset.y_bins = dataset.qy_data[0::int(n_cols)]
845                    dataset.x_bins = dataset.qx_data[:int(n_cols)]
846                    dataset.data = dataset.data.flatten()
847                else:
848                    dataset.y_bins = []
849                    dataset.x_bins = []
850                    dataset.data = dataset.data.flatten()
851
852            final_dataset = combine_data(dataset, self.current_datainfo)
853            self.output.append(final_dataset)
854
855    def _create_unique_key(self, dictionary, name, numb=0):
856        """
857        Create a unique key value for any dictionary to prevent overwriting
858        Recurse until a unique key value is found.
859
860        :param dictionary: A dictionary with any number of entries
861        :param name: The index of the item to be added to dictionary
862        :param numb: The number to be appended to the name, starts at 0
863        """
864        if dictionary.get(name) is not None:
865            numb += 1
866            name = name.split("_")[0]
867            name += "_{0}".format(numb)
868            name = self._create_unique_key(dictionary, name, numb)
869        return name
870
871    def _get_node_value_from_text(self, node, node_text):
872        """
873        Get the value of a node and any applicable units
874
875        :param node: The XML node to get the value of
876        :param tagname: The tagname of the node
877        """
878        units = ""
879        # If the value is a float, compile with units.
880        if self.ns_list.ns_datatype == "float":
881            # If an empty value is given, set as zero.
882            if node_text is None or node_text.isspace() \
883                    or node_text.lower() == "nan":
884                node_text = "0.0"
885            # Convert the value to the base units
886            tag = node.tag.replace(self.base_ns, "")
887            node_text, units = self._unit_conversion(node, tag, node_text)
888
889        # If the value is a timestamp, convert to a datetime object
890        elif self.ns_list.ns_datatype == "timestamp":
891            if node_text is None or node_text.isspace():
892                pass
893            else:
894                try:
895                    node_text = \
896                        datetime.datetime.fromtimestamp(node_text)
897                except ValueError:
898                    node_text = None
899        return node_text, units
900
901    def _get_node_value(self, node):
902        """
903        Get the value of a node and any applicable units
904
905        :param node: The XML node to get the value of
906        :param tagname: The tagname of the node
907        """
908        #Get the text from the node and convert all whitespace to spaces
909        units = ''
910        node_value = node.text
911        if node_value is not None:
912            node_value = ' '.join(node_value.split())
913        else:
914            node_value = ""
915        node_value, units = self._get_node_value_from_text(node, node_value)
916        return node_value, units
917
918    def _unit_conversion(self, node, tagname, node_value):
919        """
920        A unit converter method used to convert the data included in the file
921        to the default units listed in data_info
922
923        :param node: XML node
924        :param tagname: name of the node
925        :param node_value: The value of the current dom node
926        """
927        attr = node.attrib
928        value_unit = ''
929        err_msg = None
930        default_unit = None
931        if not isinstance(node_value, float):
932            node_value = float(node_value)
933        if 'unit' in attr and attr.get('unit') is not None:
934            try:
935                local_unit = attr['unit']
936                unitname = self.ns_list.current_level.get("unit", "")
937                if "SASdetector" in self.names:
938                    save_in = "detector"
939                elif "aperture" in self.names:
940                    save_in = "aperture"
941                elif "SAScollimation" in self.names:
942                    save_in = "collimation"
943                elif "SAStransmission_spectrum" in self.names:
944                    save_in = "transspectrum"
945                elif "SASdata" in self.names:
946                    x = np.zeros(1)
947                    y = np.zeros(1)
948                    self.current_data1d = Data1D(x, y)
949                    save_in = "current_data1d"
950                elif "SASsource" in self.names:
951                    save_in = "current_datainfo.source"
952                elif "SASsample" in self.names:
953                    save_in = "current_datainfo.sample"
954                elif "SASprocess" in self.names:
955                    save_in = "process"
956                else:
957                    save_in = "current_datainfo"
958                exec "default_unit = self.{0}.{1}".format(save_in, unitname)
959                if local_unit and default_unit and local_unit.lower() != default_unit.lower() \
960                        and local_unit.lower() != "none":
961                    if HAS_CONVERTER == True:
962                        # Check local units - bad units raise KeyError
963                        data_conv_q = Converter(local_unit)
964                        value_unit = default_unit
965                        node_value = data_conv_q(node_value, units=default_unit)
966                    else:
967                        value_unit = local_unit
968                        err_msg = "Unit converter is not available.\n"
969                else:
970                    value_unit = local_unit
971            except KeyError:
972                err_msg = "CanSAS reader: unexpected "
973                err_msg += "\"{0}\" unit [{1}]; "
974                err_msg = err_msg.format(tagname, local_unit)
975                err_msg += "expecting [{0}]".format(default_unit)
976                value_unit = local_unit
977            except:
978                err_msg = "CanSAS reader: unknown error converting "
979                err_msg += "\"{0}\" unit [{1}]"
980                err_msg = err_msg.format(tagname, local_unit)
981                value_unit = local_unit
982        elif 'unit' in attr:
983            value_unit = attr['unit']
984        if err_msg:
985            self.errors.add(err_msg)
986        return node_value, value_unit
987
988    def _check_for_empty_data(self):
989        """
990        Creates an empty data set if no data is passed to the reader
991
992        :param data1d: presumably a Data1D object
993        """
994        if self.current_dataset is None:
995            x_vals = np.empty(0)
996            y_vals = np.empty(0)
997            dx_vals = np.empty(0)
998            dy_vals = np.empty(0)
999            dxl = np.empty(0)
1000            dxw = np.empty(0)
1001            self.current_dataset = plottable_1D(x_vals, y_vals, dx_vals, dy_vals)
1002            self.current_dataset.dxl = dxl
1003            self.current_dataset.dxw = dxw
1004
1005    def _check_for_empty_resolution(self):
1006        """
1007        A method to check all resolution data sets are the same size as I and Q
1008        """
1009        if isinstance(self.current_dataset, plottable_1D):
1010            dql_exists = False
1011            dqw_exists = False
1012            dq_exists = False
1013            di_exists = False
1014            if self.current_dataset.dxl is not None:
1015                dql_exists = True
1016            if self.current_dataset.dxw is not None:
1017                dqw_exists = True
1018            if self.current_dataset.dx is not None:
1019                dq_exists = True
1020            if self.current_dataset.dy is not None:
1021                di_exists = True
1022            if dqw_exists and not dql_exists:
1023                array_size = self.current_dataset.dxw.size - 1
1024                self.current_dataset.dxl = np.append(self.current_dataset.dxl,
1025                                                     np.zeros([array_size]))
1026            elif dql_exists and not dqw_exists:
1027                array_size = self.current_dataset.dxl.size - 1
1028                self.current_dataset.dxw = np.append(self.current_dataset.dxw,
1029                                                     np.zeros([array_size]))
1030            elif not dql_exists and not dqw_exists and not dq_exists:
1031                array_size = self.current_dataset.x.size - 1
1032                self.current_dataset.dx = np.append(self.current_dataset.dx,
1033                                                    np.zeros([array_size]))
1034            if not di_exists:
1035                array_size = self.current_dataset.y.size - 1
1036                self.current_dataset.dy = np.append(self.current_dataset.dy,
1037                                                    np.zeros([array_size]))
1038        elif isinstance(self.current_dataset, plottable_2D):
1039            dqx_exists = False
1040            dqy_exists = False
1041            di_exists = False
1042            mask_exists = False
1043            if self.current_dataset.dqx_data is not None:
1044                dqx_exists = True
1045            if self.current_dataset.dqy_data is not None:
1046                dqy_exists = True
1047            if self.current_dataset.err_data is not None:
1048                di_exists = True
1049            if self.current_dataset.mask is not None:
1050                mask_exists = True
1051            if not dqy_exists:
1052                array_size = self.current_dataset.qy_data.size - 1
1053                self.current_dataset.dqy_data = np.append(
1054                    self.current_dataset.dqy_data, np.zeros([array_size]))
1055            if not dqx_exists:
1056                array_size = self.current_dataset.qx_data.size - 1
1057                self.current_dataset.dqx_data = np.append(
1058                    self.current_dataset.dqx_data, np.zeros([array_size]))
1059            if not di_exists:
1060                array_size = self.current_dataset.data.size - 1
1061                self.current_dataset.err_data = np.append(
1062                    self.current_dataset.err_data, np.zeros([array_size]))
1063            if not mask_exists:
1064                array_size = self.current_dataset.data.size - 1
1065                self.current_dataset.mask = np.append(
1066                    self.current_dataset.mask,
1067                    np.ones([array_size] ,dtype=bool))
1068
1069    ####### All methods below are for writing CanSAS XML files #######
1070
1071    def write(self, filename, datainfo):
1072        """
1073        Write the content of a Data1D as a CanSAS XML file
1074
1075        :param filename: name of the file to write
1076        :param datainfo: Data1D object
1077        """
1078        # Create XML document
1079        doc, _ = self._to_xml_doc(datainfo)
1080        # Write the file
1081        file_ref = open(filename, 'w')
1082        if self.encoding is None:
1083            self.encoding = "UTF-8"
1084        doc.write(file_ref, encoding=self.encoding,
1085                  pretty_print=True, xml_declaration=True)
1086        file_ref.close()
1087
1088    def _to_xml_doc(self, datainfo):
1089        """
1090        Create an XML document to contain the content of a Data1D
1091
1092        :param datainfo: Data1D object
1093        """
1094        is_2d = False
1095        if issubclass(datainfo.__class__, Data2D):
1096            is_2d = True
1097
1098        # Get PIs and create root element
1099        pi_string = self._get_pi_string()
1100        # Define namespaces and create SASroot object
1101        main_node = self._create_main_node()
1102        # Create ElementTree, append SASroot and apply processing instructions
1103        base_string = pi_string + self.to_string(main_node)
1104        base_element = self.create_element_from_string(base_string)
1105        doc = self.create_tree(base_element)
1106        # Create SASentry Element
1107        entry_node = self.create_element("SASentry")
1108        root = doc.getroot()
1109        root.append(entry_node)
1110
1111        # Add Title to SASentry
1112        self.write_node(entry_node, "Title", datainfo.title)
1113        # Add Run to SASentry
1114        self._write_run_names(datainfo, entry_node)
1115        # Add Data info to SASEntry
1116        if is_2d:
1117            self._write_data_2d(datainfo, entry_node)
1118        else:
1119            if self._check_root():
1120                self._write_data(datainfo, entry_node)
1121            else:
1122                self._write_data_linearized(datainfo, entry_node)
1123        # Transmission Spectrum Info
1124        # TODO: fix the writer to linearize all data, including T_spectrum
1125        # self._write_trans_spectrum(datainfo, entry_node)
1126        # Sample info
1127        self._write_sample_info(datainfo, entry_node)
1128        # Instrument info
1129        instr = self._write_instrument(datainfo, entry_node)
1130        #   Source
1131        self._write_source(datainfo, instr)
1132        #   Collimation
1133        self._write_collimation(datainfo, instr)
1134        #   Detectors
1135        self._write_detectors(datainfo, instr)
1136        # Processes info
1137        self._write_process_notes(datainfo, entry_node)
1138        # Note info
1139        self._write_notes(datainfo, entry_node)
1140        # Return the document, and the SASentry node associated with
1141        #      the data we just wrote
1142        # If the calling function was not the cansas reader, return a minidom
1143        #      object rather than an lxml object.
1144        self.frm = inspect.stack()[1]
1145        doc, entry_node = self._check_origin(entry_node, doc)
1146        return doc, entry_node
1147
1148    def write_node(self, parent, name, value, attr=None):
1149        """
1150        :param doc: document DOM
1151        :param parent: parent node
1152        :param name: tag of the element
1153        :param value: value of the child text node
1154        :param attr: attribute dictionary
1155
1156        :return: True if something was appended, otherwise False
1157        """
1158        if value is not None:
1159            parent = self.ebuilder(parent, name, value, attr)
1160            return True
1161        return False
1162
1163    def _get_pi_string(self):
1164        """
1165        Creates the processing instructions header for writing to file
1166        """
1167        pis = self.return_processing_instructions()
1168        if len(pis) > 0:
1169            pi_tree = self.create_tree(pis[0])
1170            i = 1
1171            for i in range(1, len(pis) - 1):
1172                pi_tree = self.append(pis[i], pi_tree)
1173            pi_string = self.to_string(pi_tree)
1174        else:
1175            pi_string = ""
1176        return pi_string
1177
1178    def _create_main_node(self):
1179        """
1180        Creates the primary xml header used when writing to file
1181        """
1182        xsi = "http://www.w3.org/2001/XMLSchema-instance"
1183        version = self.cansas_version
1184        n_s = CANSAS_NS.get(version).get("ns")
1185        if version == "1.1":
1186            url = "http://www.cansas.org/formats/1.1/"
1187        else:
1188            url = "http://www.cansas.org/formats/1.0/"
1189        schema_location = "{0} {1}cansas1d.xsd".format(n_s, url)
1190        attrib = {"{" + xsi + "}schemaLocation" : schema_location,
1191                  "version" : version}
1192        nsmap = {'xsi' : xsi, None: n_s}
1193
1194        main_node = self.create_element("{" + n_s + "}SASroot",
1195                                        attrib=attrib, nsmap=nsmap)
1196        return main_node
1197
1198    def _write_run_names(self, datainfo, entry_node):
1199        """
1200        Writes the run names to the XML file
1201
1202        :param datainfo: The Data1D object the information is coming from
1203        :param entry_node: lxml node ElementTree object to be appended to
1204        """
1205        if datainfo.run is None or datainfo.run == []:
1206            datainfo.run.append(RUN_NAME_DEFAULT)
1207            datainfo.run_name[RUN_NAME_DEFAULT] = RUN_NAME_DEFAULT
1208        for item in datainfo.run:
1209            runname = {}
1210            if item in datainfo.run_name and \
1211            len(str(datainfo.run_name[item])) > 1:
1212                runname = {'name': datainfo.run_name[item]}
1213            self.write_node(entry_node, "Run", item, runname)
1214
1215    def _write_data(self, datainfo, entry_node):
1216        """
1217        Writes 1D I and Q data to the XML file
1218
1219        :param datainfo: The Data1D object the information is coming from
1220        :param entry_node: lxml node ElementTree object to be appended to
1221        """
1222        node = self.create_element("SASdata")
1223        self.append(node, entry_node)
1224
1225        for i in range(len(datainfo.x)):
1226            point = self.create_element("Idata")
1227            node.append(point)
1228            self.write_node(point, "Q", datainfo.x[i],
1229                            {'unit': datainfo._xaxis + " | " + datainfo._xunit})
1230            if len(datainfo.y) >= i:
1231                self.write_node(point, "I", datainfo.y[i],
1232                                {'unit': datainfo._yaxis + " | " + datainfo._yunit})
1233            if datainfo.dy is not None and len(datainfo.dy) > i:
1234                self.write_node(point, "Idev", datainfo.dy[i],
1235                                {'unit': datainfo._yaxis + " | " + datainfo._yunit})
1236            if datainfo.dx is not None and len(datainfo.dx) > i:
1237                self.write_node(point, "Qdev", datainfo.dx[i],
1238                                {'unit': datainfo._xaxis + " | " + datainfo._xunit})
1239            if datainfo.dxw is not None and len(datainfo.dxw) > i:
1240                self.write_node(point, "dQw", datainfo.dxw[i],
1241                                {'unit': datainfo._xaxis + " | " + datainfo._xunit})
1242            if datainfo.dxl is not None and len(datainfo.dxl) > i:
1243                self.write_node(point, "dQl", datainfo.dxl[i],
1244                                {'unit': datainfo._xaxis + " | " + datainfo._xunit})
1245        if datainfo.isSesans:
1246            sesans = self.create_element("Sesans")
1247            sesans.text = str(datainfo.isSesans)
1248            node.append(sesans)
1249            self.write_node(node, "yacceptance", datainfo.sample.yacceptance[0],
1250                             {'unit': datainfo.sample.yacceptance[1]})
1251            self.write_node(node, "zacceptance", datainfo.sample.zacceptance[0],
1252                             {'unit': datainfo.sample.zacceptance[1]})
1253
1254
1255    def _write_data_2d(self, datainfo, entry_node):
1256        """
1257        Writes 2D data to the XML file
1258
1259        :param datainfo: The Data2D object the information is coming from
1260        :param entry_node: lxml node ElementTree object to be appended to
1261        """
1262        attr = {}
1263        if datainfo.data.shape:
1264            attr["x_bins"] = str(len(datainfo.x_bins))
1265            attr["y_bins"] = str(len(datainfo.y_bins))
1266        node = self.create_element("SASdata", attr)
1267        self.append(node, entry_node)
1268
1269        point = self.create_element("Idata")
1270        node.append(point)
1271        qx = ','.join([str(datainfo.qx_data[i]) for i in xrange(len(datainfo.qx_data))])
1272        qy = ','.join([str(datainfo.qy_data[i]) for i in xrange(len(datainfo.qy_data))])
1273        intensity = ','.join([str(datainfo.data[i]) for i in xrange(len(datainfo.data))])
1274
1275        self.write_node(point, "Qx", qx,
1276                        {'unit': datainfo._xunit})
1277        self.write_node(point, "Qy", qy,
1278                        {'unit': datainfo._yunit})
1279        self.write_node(point, "I", intensity,
1280                        {'unit': datainfo._zunit})
1281        if datainfo.err_data is not None:
1282            err = ','.join([str(datainfo.err_data[i]) for i in
1283                            xrange(len(datainfo.err_data))])
1284            self.write_node(point, "Idev", err,
1285                            {'unit': datainfo._zunit})
1286        if datainfo.dqy_data is not None:
1287            dqy = ','.join([str(datainfo.dqy_data[i]) for i in
1288                            xrange(len(datainfo.dqy_data))])
1289            self.write_node(point, "Qydev", dqy,
1290                            {'unit': datainfo._yunit})
1291        if datainfo.dqx_data is not None:
1292            dqx = ','.join([str(datainfo.dqx_data[i]) for i in
1293                            xrange(len(datainfo.dqx_data))])
1294            self.write_node(point, "Qxdev", dqx,
1295                            {'unit': datainfo._xunit})
1296        if datainfo.mask is not None:
1297            mask = ','.join(
1298                ["1" if datainfo.mask[i] else "0"
1299                 for i in xrange(len(datainfo.mask))])
1300            self.write_node(point, "Mask", mask)
1301
1302    def _write_trans_spectrum(self, datainfo, entry_node):
1303        """
1304        Writes the transmission spectrum data to the XML file
1305
1306        :param datainfo: The Data1D object the information is coming from
1307        :param entry_node: lxml node ElementTree object to be appended to
1308        """
1309        for i in range(len(datainfo.trans_spectrum)):
1310            spectrum = datainfo.trans_spectrum[i]
1311            node = self.create_element("SAStransmission_spectrum",
1312                                       {"name" : spectrum.name})
1313            self.append(node, entry_node)
1314            if isinstance(spectrum.timestamp, datetime.datetime):
1315                node.setAttribute("timestamp", spectrum.timestamp)
1316            for i in range(len(spectrum.wavelength)):
1317                point = self.create_element("Tdata")
1318                node.append(point)
1319                self.write_node(point, "Lambda", spectrum.wavelength[i],
1320                                {'unit': spectrum.wavelength_unit})
1321                self.write_node(point, "T", spectrum.transmission[i],
1322                                {'unit': spectrum.transmission_unit})
1323                if spectrum.transmission_deviation is not None \
1324                and len(spectrum.transmission_deviation) >= i:
1325                    self.write_node(point, "Tdev",
1326                                    spectrum.transmission_deviation[i],
1327                                    {'unit':
1328                                     spectrum.transmission_deviation_unit})
1329
1330    def _write_sample_info(self, datainfo, entry_node):
1331        """
1332        Writes the sample information to the XML file
1333
1334        :param datainfo: The Data1D object the information is coming from
1335        :param entry_node: lxml node ElementTree object to be appended to
1336        """
1337        sample = self.create_element("SASsample")
1338        if datainfo.sample.name is not None:
1339            self.write_attribute(sample, "name",
1340                                 str(datainfo.sample.name))
1341        self.append(sample, entry_node)
1342        self.write_node(sample, "ID", str(datainfo.sample.ID))
1343        self.write_node(sample, "thickness", datainfo.sample.thickness,
1344                        {"unit": datainfo.sample.thickness_unit})
1345        self.write_node(sample, "transmission", datainfo.sample.transmission)
1346        self.write_node(sample, "temperature", datainfo.sample.temperature,
1347                        {"unit": datainfo.sample.temperature_unit})
1348
1349        pos = self.create_element("position")
1350        written = self.write_node(pos,
1351                                  "x",
1352                                  datainfo.sample.position.x,
1353                                  {"unit": datainfo.sample.position_unit})
1354        written = written | self.write_node( \
1355            pos, "y", datainfo.sample.position.y,
1356            {"unit": datainfo.sample.position_unit})
1357        written = written | self.write_node( \
1358            pos, "z", datainfo.sample.position.z,
1359            {"unit": datainfo.sample.position_unit})
1360        if written == True:
1361            self.append(pos, sample)
1362
1363        ori = self.create_element("orientation")
1364        written = self.write_node(ori, "roll",
1365                                  datainfo.sample.orientation.x,
1366                                  {"unit": datainfo.sample.orientation_unit})
1367        written = written | self.write_node( \
1368            ori, "pitch", datainfo.sample.orientation.y,
1369            {"unit": datainfo.sample.orientation_unit})
1370        written = written | self.write_node( \
1371            ori, "yaw", datainfo.sample.orientation.z,
1372            {"unit": datainfo.sample.orientation_unit})
1373        if written == True:
1374            self.append(ori, sample)
1375
1376        for item in datainfo.sample.details:
1377            self.write_node(sample, "details", item)
1378
1379    def _write_instrument(self, datainfo, entry_node):
1380        """
1381        Writes the instrumental information to the XML file
1382
1383        :param datainfo: The Data1D object the information is coming from
1384        :param entry_node: lxml node ElementTree object to be appended to
1385        """
1386        instr = self.create_element("SASinstrument")
1387        self.append(instr, entry_node)
1388        self.write_node(instr, "name", datainfo.instrument)
1389        return instr
1390
1391    def _write_source(self, datainfo, instr):
1392        """
1393        Writes the source information to the XML file
1394
1395        :param datainfo: The Data1D object the information is coming from
1396        :param instr: instrument node  to be appended to
1397        """
1398        source = self.create_element("SASsource")
1399        if datainfo.source.name is not None:
1400            self.write_attribute(source, "name",
1401                                 str(datainfo.source.name))
1402        self.append(source, instr)
1403        if datainfo.source.radiation is None or datainfo.source.radiation == '':
1404            datainfo.source.radiation = "neutron"
1405        self.write_node(source, "radiation", datainfo.source.radiation)
1406
1407        size = self.create_element("beam_size")
1408        if datainfo.source.beam_size_name is not None:
1409            self.write_attribute(size, "name",
1410                                 str(datainfo.source.beam_size_name))
1411        written = self.write_node( \
1412            size, "x", datainfo.source.beam_size.x,
1413            {"unit": datainfo.source.beam_size_unit})
1414        written = written | self.write_node( \
1415            size, "y", datainfo.source.beam_size.y,
1416            {"unit": datainfo.source.beam_size_unit})
1417        written = written | self.write_node( \
1418            size, "z", datainfo.source.beam_size.z,
1419            {"unit": datainfo.source.beam_size_unit})
1420        if written == True:
1421            self.append(size, source)
1422
1423        self.write_node(source, "beam_shape", datainfo.source.beam_shape)
1424        self.write_node(source, "wavelength",
1425                        datainfo.source.wavelength,
1426                        {"unit": datainfo.source.wavelength_unit})
1427        self.write_node(source, "wavelength_min",
1428                        datainfo.source.wavelength_min,
1429                        {"unit": datainfo.source.wavelength_min_unit})
1430        self.write_node(source, "wavelength_max",
1431                        datainfo.source.wavelength_max,
1432                        {"unit": datainfo.source.wavelength_max_unit})
1433        self.write_node(source, "wavelength_spread",
1434                        datainfo.source.wavelength_spread,
1435                        {"unit": datainfo.source.wavelength_spread_unit})
1436
1437    def _write_collimation(self, datainfo, instr):
1438        """
1439        Writes the collimation information to the XML file
1440
1441        :param datainfo: The Data1D object the information is coming from
1442        :param instr: lxml node ElementTree object to be appended to
1443        """
1444        if datainfo.collimation == [] or datainfo.collimation is None:
1445            coll = Collimation()
1446            datainfo.collimation.append(coll)
1447        for item in datainfo.collimation:
1448            coll = self.create_element("SAScollimation")
1449            if item.name is not None:
1450                self.write_attribute(coll, "name", str(item.name))
1451            self.append(coll, instr)
1452
1453            self.write_node(coll, "length", item.length,
1454                            {"unit": item.length_unit})
1455
1456            for aperture in item.aperture:
1457                apert = self.create_element("aperture")
1458                if aperture.name is not None:
1459                    self.write_attribute(apert, "name", str(aperture.name))
1460                if aperture.type is not None:
1461                    self.write_attribute(apert, "type", str(aperture.type))
1462                self.append(apert, coll)
1463
1464                size = self.create_element("size")
1465                if aperture.size_name is not None:
1466                    self.write_attribute(size, "name",
1467                                         str(aperture.size_name))
1468                written = self.write_node(size, "x", aperture.size.x,
1469                                          {"unit": aperture.size_unit})
1470                written = written | self.write_node( \
1471                    size, "y", aperture.size.y,
1472                    {"unit": aperture.size_unit})
1473                written = written | self.write_node( \
1474                    size, "z", aperture.size.z,
1475                    {"unit": aperture.size_unit})
1476                if written == True:
1477                    self.append(size, apert)
1478
1479                self.write_node(apert, "distance", aperture.distance,
1480                                {"unit": aperture.distance_unit})
1481
1482    def _write_detectors(self, datainfo, instr):
1483        """
1484        Writes the detector information to the XML file
1485
1486        :param datainfo: The Data1D object the information is coming from
1487        :param inst: lxml instrument node to be appended to
1488        """
1489        if datainfo.detector is None or datainfo.detector == []:
1490            det = Detector()
1491            det.name = ""
1492            datainfo.detector.append(det)
1493
1494        for item in datainfo.detector:
1495            det = self.create_element("SASdetector")
1496            written = self.write_node(det, "name", item.name)
1497            written = written | self.write_node(det, "SDD", item.distance,
1498                                                {"unit": item.distance_unit})
1499            if written == True:
1500                self.append(det, instr)
1501
1502            off = self.create_element("offset")
1503            written = self.write_node(off, "x", item.offset.x,
1504                                      {"unit": item.offset_unit})
1505            written = written | self.write_node(off, "y", item.offset.y,
1506                                                {"unit": item.offset_unit})
1507            written = written | self.write_node(off, "z", item.offset.z,
1508                                                {"unit": item.offset_unit})
1509            if written == True:
1510                self.append(off, det)
1511
1512            ori = self.create_element("orientation")
1513            written = self.write_node(ori, "roll", item.orientation.x,
1514                                      {"unit": item.orientation_unit})
1515            written = written | self.write_node(ori, "pitch",
1516                                                item.orientation.y,
1517                                                {"unit": item.orientation_unit})
1518            written = written | self.write_node(ori, "yaw",
1519                                                item.orientation.z,
1520                                                {"unit": item.orientation_unit})
1521            if written == True:
1522                self.append(ori, det)
1523
1524            center = self.create_element("beam_center")
1525            written = self.write_node(center, "x", item.beam_center.x,
1526                                      {"unit": item.beam_center_unit})
1527            written = written | self.write_node(center, "y",
1528                                                item.beam_center.y,
1529                                                {"unit": item.beam_center_unit})
1530            written = written | self.write_node(center, "z",
1531                                                item.beam_center.z,
1532                                                {"unit": item.beam_center_unit})
1533            if written == True:
1534                self.append(center, det)
1535
1536            pix = self.create_element("pixel_size")
1537            written = self.write_node(pix, "x", item.pixel_size.x,
1538                                      {"unit": item.pixel_size_unit})
1539            written = written | self.write_node(pix, "y", item.pixel_size.y,
1540                                                {"unit": item.pixel_size_unit})
1541            written = written | self.write_node(pix, "z", item.pixel_size.z,
1542                                                {"unit": item.pixel_size_unit})
1543            if written == True:
1544                self.append(pix, det)
1545            self.write_node(det, "slit_length", item.slit_length,
1546                {"unit": item.slit_length_unit})
1547
1548    def _write_process_notes(self, datainfo, entry_node):
1549        """
1550        Writes the process notes to the XML file
1551
1552        :param datainfo: The Data1D object the information is coming from
1553        :param entry_node: lxml node ElementTree object to be appended to
1554
1555        """
1556        for item in datainfo.process:
1557            node = self.create_element("SASprocess")
1558            self.append(node, entry_node)
1559            self.write_node(node, "name", item.name)
1560            self.write_node(node, "date", item.date)
1561            self.write_node(node, "description", item.description)
1562            for term in item.term:
1563                if isinstance(term, list):
1564                    value = term['value']
1565                    del term['value']
1566                elif isinstance(term, dict):
1567                    value = term.get("value")
1568                    del term['value']
1569                else:
1570                    value = term
1571                self.write_node(node, "term", value, term)
1572            for note in item.notes:
1573                self.write_node(node, "SASprocessnote", note)
1574            if len(item.notes) == 0:
1575                self.write_node(node, "SASprocessnote", "")
1576
1577    def _write_notes(self, datainfo, entry_node):
1578        """
1579        Writes the notes to the XML file and creates an empty note if none
1580        exist
1581
1582        :param datainfo: The Data1D object the information is coming from
1583        :param entry_node: lxml node ElementTree object to be appended to
1584
1585        """
1586        if len(datainfo.notes) == 0:
1587            node = self.create_element("SASnote")
1588            self.append(node, entry_node)
1589        else:
1590            for item in datainfo.notes:
1591                node = self.create_element("SASnote")
1592                self.write_text(node, item)
1593                self.append(node, entry_node)
1594
1595    def _check_root(self):
1596        """
1597        Return the document, and the SASentry node associated with
1598        the data we just wrote.
1599        If the calling function was not the cansas reader, return a minidom
1600        object rather than an lxml object.
1601
1602        :param entry_node: lxml node ElementTree object to be appended to
1603        :param doc: entire xml tree
1604        """
1605        if not self.frm:
1606            self.frm = inspect.stack()[2]
1607        mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "")
1608        mod_name = mod_name.replace(".py", "")
1609        mod = mod_name.split("sas/")
1610        mod_name = mod[1]
1611        return mod_name == "sascalc/dataloader/readers/cansas_reader"
1612
1613    def _check_origin(self, entry_node, doc):
1614        """
1615        Return the document, and the SASentry node associated with
1616        the data we just wrote.
1617        If the calling function was not the cansas reader, return a minidom
1618        object rather than an lxml object.
1619
1620        :param entry_node: lxml node ElementTree object to be appended to
1621        :param doc: entire xml tree
1622        """
1623        if not self._check_root():
1624            string = self.to_string(doc, pretty_print=False)
1625            doc = parseString(string)
1626            node_name = entry_node.tag
1627            node_list = doc.getElementsByTagName(node_name)
1628            entry_node = node_list.item(0)
1629        return doc, entry_node
1630
1631    # DO NOT REMOVE - used in saving and loading panel states.
1632    def _store_float(self, location, node, variable, storage, optional=True):
1633        """
1634        Get the content of a xpath location and store
1635        the result. Check that the units are compatible
1636        with the destination. The value is expected to
1637        be a float.
1638
1639        The xpath location might or might not exist.
1640        If it does not exist, nothing is done
1641
1642        :param location: xpath location to fetch
1643        :param node: node to read the data from
1644        :param variable: name of the data member to store it in [string]
1645        :param storage: data object that has the 'variable' data member
1646        :param optional: if True, no exception will be raised
1647            if unit conversion can't be done
1648
1649        :raise ValueError: raised when the units are not recognized
1650        """
1651        entry = get_content(location, node)
1652        try:
1653            value = float(entry.text)
1654        except:
1655            value = None
1656
1657        if value is not None:
1658            # If the entry has units, check to see that they are
1659            # compatible with what we currently have in the data object
1660            units = entry.get('unit')
1661            if units is not None:
1662                toks = variable.split('.')
1663                local_unit = None
1664                exec "local_unit = storage.%s_unit" % toks[0]
1665                if local_unit is not None and units.lower() != local_unit.lower():
1666                    if HAS_CONVERTER == True:
1667                        try:
1668                            conv = Converter(units)
1669                            exec "storage.%s = %g" % \
1670                                (variable, conv(value, units=local_unit))
1671                        except:
1672                            _, exc_value, _ = sys.exc_info()
1673                            err_mess = "CanSAS reader: could not convert"
1674                            err_mess += " %s unit [%s]; expecting [%s]\n  %s" \
1675                                % (variable, units, local_unit, exc_value)
1676                            self.errors.add(err_mess)
1677                            if optional:
1678                                logger.info(err_mess)
1679                            else:
1680                                raise ValueError, err_mess
1681                    else:
1682                        err_mess = "CanSAS reader: unrecognized %s unit [%s];"\
1683                        % (variable, units)
1684                        err_mess += " expecting [%s]" % local_unit
1685                        self.errors.add(err_mess)
1686                        if optional:
1687                            logger.info(err_mess)
1688                        else:
1689                            raise ValueError, err_mess
1690                else:
1691                    exec "storage.%s = value" % variable
1692            else:
1693                exec "storage.%s = value" % variable
1694
1695    # DO NOT REMOVE - used in saving and loading panel states.
1696    def _store_content(self, location, node, variable, storage):
1697        """
1698        Get the content of a xpath location and store
1699        the result. The value is treated as a string.
1700
1701        The xpath location might or might not exist.
1702        If it does not exist, nothing is done
1703
1704        :param location: xpath location to fetch
1705        :param node: node to read the data from
1706        :param variable: name of the data member to store it in [string]
1707        :param storage: data object that has the 'variable' data member
1708
1709        :return: return a list of errors
1710        """
1711        entry = get_content(location, node)
1712        if entry is not None and entry.text is not None:
1713            exec "storage.%s = entry.text.strip()" % variable
1714
1715
1716# DO NOT REMOVE Called by outside packages:
1717#    sas.sasgui.perspectives.invariant.invariant_state
1718#    sas.sasgui.perspectives.fitting.pagestate
1719def get_content(location, node):
1720    """
1721    Get the first instance of the content of a xpath location.
1722
1723    :param location: xpath location
1724    :param node: node to start at
1725
1726    :return: Element, or None
1727    """
1728    nodes = node.xpath(location,
1729                       namespaces={'ns': CANSAS_NS.get("1.0").get("ns")})
1730    if len(nodes) > 0:
1731        return nodes[0]
1732    else:
1733        return None
1734
1735# DO NOT REMOVE Called by outside packages:
1736#    sas.sasgui.perspectives.fitting.pagestate
1737def write_node(doc, parent, name, value, attr=None):
1738    """
1739    :param doc: document DOM
1740    :param parent: parent node
1741    :param name: tag of the element
1742    :param value: value of the child text node
1743    :param attr: attribute dictionary
1744
1745    :return: True if something was appended, otherwise False
1746    """
1747    if attr is None:
1748        attr = {}
1749    if value is not None:
1750        node = doc.createElement(name)
1751        node.appendChild(doc.createTextNode(str(value)))
1752        for item in attr:
1753            node.setAttribute(item, attr[item])
1754        parent.appendChild(node)
1755        return True
1756    return False
Note: See TracBrowser for help on using the repository browser.