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

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

Merge branch 'master' into ticket-876

# Conflicts:
# src/sas/sascalc/dataloader/readers/ascii_reader.py
# src/sas/sascalc/dataloader/readers/xml_reader.py

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