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

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

Mid-point commit

We’re loading in the XML file, but for some reason it won’t load into
the GUI. Will investigate.

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