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

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

Merge aftermath

Added y-acceptance term back into the file reader after the merge
overwrote it

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