source: sasview/src/sas/sascalc/dataloader/readers/cansas_reader_BACKUP_72072.py @ 3d6c010

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

Merge master into branch

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