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

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalcmagnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 6a455cd3 was 6a455cd3, checked in by krzywon, 7 years ago

Merge branch 'master' into 4_1_issues

# Conflicts:
# docs/sphinx-docs/source/conf.py
# src/sas/sascalc/dataloader/readers/cansas_reader.py
# src/sas/sasgui/guiframe/documentation_window.py
# src/sas/sasgui/perspectives/fitting/models.py

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