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

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 c155a16 was c155a16, checked in by Ricardo Ferraz Leal <ricleal@…>, 7 years ago

Logging is now logger

  • Property mode set to 100644
File size: 70.5 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()
37
38PREPROCESS = "xmlpreprocess"
39ENCODING = "encoding"
40RUN_NAME_DEFAULT = "None"
41INVALID_SCHEMA_PATH_1_1 = "{0}/sas/sascalc/dataloader/readers/schema/cansas1d_invalid_v1_1.xsd"
42INVALID_SCHEMA_PATH_1_0 = "{0}/sas/sascalc/dataloader/readers/schema/cansas1d_invalid_v1_0.xsd"
43INVALID_XML = "\n\nThe loaded xml file, {0} does not fully meet the CanSAS v1.x specification. SasView loaded " + \
44              "as much of the data as possible.\n\n"
45HAS_CONVERTER = True
46try:
47    from sas.sascalc.data_util.nxsunit import Converter
48except ImportError:
49    HAS_CONVERTER = False
50
51CONSTANTS = CansasConstants()
52CANSAS_FORMAT = CONSTANTS.format
53CANSAS_NS = CONSTANTS.names
54ALLOW_ALL = True
55
56class Reader(XMLreader):
57    """
58    Class to load cansas 1D XML files
59
60    :Dependencies:
61        The CanSAS reader requires PyXML 0.8.4 or later.
62    """
63    # CanSAS version - defaults to version 1.0
64    cansas_version = "1.0"
65    base_ns = "{cansas1d/1.0}"
66    cansas_defaults = None
67    type_name = "canSAS"
68    invalid = True
69    frm = ""
70    # Log messages and errors
71    logging = None
72    errors = set()
73    # Namespace hierarchy for current xml_file object
74    names = None
75    ns_list = None
76    # Temporary storage location for loading multiple data sets in a single file
77    current_datainfo = None
78    current_dataset = None
79    current_data1d = None
80    data = None
81    # List of data1D objects to be sent back to SasView
82    output = None
83    # Wildcards
84    type = ["XML files (*.xml)|*.xml", "SasView Save Files (*.svs)|*.svs"]
85    # List of allowed extensions
86    ext = ['.xml', '.XML', '.svs', '.SVS']
87    # Flag to bypass extension check
88    allow_all = True
89
90    def reset_state(self):
91        """
92        Resets the class state to a base case when loading a new data file so previous
93        data files do not appear a second time
94        """
95        self.current_datainfo = None
96        self.current_dataset = None
97        self.current_data1d = None
98        self.data = []
99        self.process = Process()
100        self.transspectrum = TransmissionSpectrum()
101        self.aperture = Aperture()
102        self.collimation = Collimation()
103        self.detector = Detector()
104        self.names = []
105        self.cansas_defaults = {}
106        self.output = []
107        self.ns_list = None
108        self.logging = []
109        self.encoding = None
110
111    def read(self, xml_file, schema_path="", invalid=True):
112        """
113        Validate and read in an xml_file file in the canSAS format.
114
115        :param xml_file: A canSAS file path in proper XML format
116        :param schema_path: A file path to an XML schema to validate the xml_file against
117        """
118        # For every file loaded, reset everything to a base state
119        self.reset_state()
120        self.invalid = invalid
121        # Check that the file exists
122        if os.path.isfile(xml_file):
123            basename, extension = os.path.splitext(os.path.basename(xml_file))
124            # If the file type is not allowed, return nothing
125            if extension in self.ext or self.allow_all:
126                # Get the file location of
127                self.load_file_and_schema(xml_file, schema_path)
128                self.add_data_set()
129                # Try to load the file, but raise an error if unable to.
130                # Check the file matches the XML schema
131                try:
132                    self.is_cansas(extension)
133                    self.invalid = False
134                    # Get each SASentry from XML file and add it to a list.
135                    entry_list = self.xmlroot.xpath(
136                            '/ns:SASroot/ns:SASentry',
137                            namespaces={'ns': self.cansas_defaults.get("ns")})
138                    self.names.append("SASentry")
139
140                    # Get all preprocessing events and encoding
141                    self.set_processing_instructions()
142
143                    # Parse each <SASentry> item
144                    for entry in entry_list:
145                        # Create a new DataInfo object for every <SASentry>
146
147                        # Set the file name and then parse the entry.
148                        self.current_datainfo.filename = basename + extension
149                        self.current_datainfo.meta_data["loader"] = "CanSAS XML 1D"
150                        self.current_datainfo.meta_data[PREPROCESS] = \
151                            self.processing_instructions
152
153                        # Parse the XML SASentry
154                        self._parse_entry(entry)
155                        # Combine datasets with datainfo
156                        self.add_data_set()
157                except RuntimeError:
158                    # If the file does not match the schema, raise this error
159                    invalid_xml = self.find_invalid_xml()
160                    invalid_xml = INVALID_XML.format(basename + extension) + invalid_xml
161                    self.errors.add(invalid_xml)
162                    # Try again with an invalid CanSAS schema, that requires only a data set in each
163                    base_name = xml_reader.__file__
164                    base_name = base_name.replace("\\", "/")
165                    base = base_name.split("/sas/")[0]
166                    if self.cansas_version == "1.1":
167                        invalid_schema = INVALID_SCHEMA_PATH_1_1.format(base, self.cansas_defaults.get("schema"))
168                    else:
169                        invalid_schema = INVALID_SCHEMA_PATH_1_0.format(base, self.cansas_defaults.get("schema"))
170                    self.set_schema(invalid_schema)
171                    try:
172                        if self.invalid:
173                            if self.is_cansas():
174                                self.output = self.read(xml_file, invalid_schema, False)
175                            else:
176                                raise RuntimeError
177                        else:
178                            raise RuntimeError
179                    except RuntimeError:
180                        x = np.zeros(1)
181                        y = np.zeros(1)
182                        self.current_data1d = Data1D(x,y)
183                        self.current_data1d.errors = self.errors
184                        return [self.current_data1d]
185        else:
186            self.output.append("Not a valid file path.")
187        # Return a list of parsed entries that dataloader can manage
188        return self.output
189
190    def _parse_entry(self, dom, recurse=False):
191        """
192        Parse a SASEntry - new recursive method for parsing the dom of
193            the CanSAS data format. This will allow multiple data files
194            and extra nodes to be read in simultaneously.
195
196        :param dom: dom object with a namespace base of names
197        """
198
199        if not self._is_call_local() and not recurse:
200            self.reset_state()
201            self.add_data_set()
202            self.names.append("SASentry")
203            self.parent_class = "SASentry"
204        self._check_for_empty_data()
205        self.base_ns = "{0}{1}{2}".format("{", \
206                            CANSAS_NS.get(self.cansas_version).get("ns"), "}")
207
208        # Go through each child in the parent element
209        for node in dom:
210            attr = node.attrib
211            name = attr.get("name", "")
212            type = attr.get("type", "")
213            # Get the element name and set the current names level
214            tagname = node.tag.replace(self.base_ns, "")
215            tagname_original = tagname
216            # Skip this iteration when loading in save state information
217            if tagname == "fitting_plug_in" or tagname == "pr_inversion" or tagname == "invariant":
218                continue
219
220            # Get where to store content
221            self.names.append(tagname_original)
222            self.ns_list = CONSTANTS.iterate_namespace(self.names)
223            # If the element is a child element, recurse
224            if len(node.getchildren()) > 0:
225                self.parent_class = tagname_original
226                if tagname == 'SASdata':
227                    self._initialize_new_data_set(node)
228                    if isinstance(self.current_dataset, plottable_2D):
229                        x_bins = attr.get("x_bins", "")
230                        y_bins = attr.get("y_bins", "")
231                        if x_bins is not "" and y_bins is not "":
232                            self.current_dataset.shape = (x_bins, y_bins)
233                        else:
234                            self.current_dataset.shape = ()
235                # Recursion step to access data within the group
236                self._parse_entry(node, True)
237                if tagname == "SASsample":
238                    self.current_datainfo.sample.name = name
239                elif tagname == "beam_size":
240                    self.current_datainfo.source.beam_size_name = name
241                elif tagname == "SAScollimation":
242                    self.collimation.name = name
243                elif tagname == "aperture":
244                    self.aperture.name = name
245                    self.aperture.type = type
246                self.add_intermediate()
247            else:
248                if isinstance(self.current_dataset, plottable_2D):
249                    data_point = node.text
250                    unit = attr.get('unit', '')
251                else:
252                    data_point, unit = self._get_node_value(node, tagname)
253
254                # If this is a dataset, store the data appropriately
255                if tagname == 'Run':
256                    self.current_datainfo.run_name[data_point] = name
257                    self.current_datainfo.run.append(data_point)
258                elif tagname == 'Title':
259                    self.current_datainfo.title = data_point
260                elif tagname == 'SASnote':
261                    self.current_datainfo.notes.append(data_point)
262
263                # I and Q - 1D data
264                elif tagname == 'I' and isinstance(self.current_dataset, plottable_1D):
265                    unit_list = unit.split("|")
266                    if len(unit_list) > 1:
267                        self.current_dataset.yaxis(unit_list[0].strip(),
268                                                   unit_list[1].strip())
269                    else:
270                        self.current_dataset.yaxis("Intensity", unit)
271                    self.current_dataset.y = np.append(self.current_dataset.y, data_point)
272                elif tagname == 'Idev' and isinstance(self.current_dataset, plottable_1D):
273                    self.current_dataset.dy = np.append(self.current_dataset.dy, data_point)
274                elif tagname == 'Q':
275                    unit_list = unit.split("|")
276                    if len(unit_list) > 1:
277                        self.current_dataset.xaxis(unit_list[0].strip(),
278                                                   unit_list[1].strip())
279                    else:
280                        self.current_dataset.xaxis("Q", unit)
281                    self.current_dataset.x = np.append(self.current_dataset.x, data_point)
282                elif tagname == 'Qdev':
283                    self.current_dataset.dx = np.append(self.current_dataset.dx, data_point)
284                elif tagname == 'dQw':
285                    self.current_dataset.dxw = np.append(self.current_dataset.dxw, data_point)
286                elif tagname == 'dQl':
287                    self.current_dataset.dxl = np.append(self.current_dataset.dxl, data_point)
288                elif tagname == 'Qmean':
289                    pass
290                elif tagname == 'Shadowfactor':
291                    pass
292                elif tagname == 'Sesans':
293                    self.current_datainfo.isSesans = bool(data_point)
294                elif tagname == 'zacceptance':
295                    self.current_datainfo.sample.zacceptance = (data_point, unit)
296
297                # I and Qx, Qy - 2D data
298                elif tagname == 'I' and isinstance(self.current_dataset, plottable_2D):
299                    self.current_dataset.yaxis("Intensity", unit)
300                    self.current_dataset.data = np.fromstring(data_point, dtype=float, sep=",")
301                elif tagname == 'Idev' and isinstance(self.current_dataset, plottable_2D):
302                    self.current_dataset.err_data = np.fromstring(data_point, dtype=float, sep=",")
303                elif tagname == 'Qx':
304                    self.current_dataset.xaxis("Qx", unit)
305                    self.current_dataset.qx_data = np.fromstring(data_point, dtype=float, sep=",")
306                elif tagname == 'Qy':
307                    self.current_dataset.yaxis("Qy", unit)
308                    self.current_dataset.qy_data = np.fromstring(data_point, dtype=float, sep=",")
309                elif tagname == 'Qxdev':
310                    self.current_dataset.xaxis("Qxdev", unit)
311                    self.current_dataset.dqx_data = np.fromstring(data_point, dtype=float, sep=",")
312                elif tagname == 'Qydev':
313                    self.current_dataset.yaxis("Qydev", unit)
314                    self.current_dataset.dqy_data = np.fromstring(data_point, dtype=float, sep=",")
315                elif tagname == 'Mask':
316                    inter = [item == "1" for item in data_point.split(",")]
317                    self.current_dataset.mask = np.asarray(inter, dtype=bool)
318
319                # Sample Information
320                elif tagname == 'ID' and self.parent_class == 'SASsample':
321                    self.current_datainfo.sample.ID = data_point
322                elif tagname == 'Title' and self.parent_class == 'SASsample':
323                    self.current_datainfo.sample.name = data_point
324                elif tagname == 'thickness' and self.parent_class == 'SASsample':
325                    self.current_datainfo.sample.thickness = data_point
326                    self.current_datainfo.sample.thickness_unit = unit
327                elif tagname == 'transmission' and self.parent_class == 'SASsample':
328                    self.current_datainfo.sample.transmission = data_point
329                elif tagname == 'temperature' and self.parent_class == 'SASsample':
330                    self.current_datainfo.sample.temperature = data_point
331                    self.current_datainfo.sample.temperature_unit = unit
332                elif tagname == 'details' and self.parent_class == 'SASsample':
333                    self.current_datainfo.sample.details.append(data_point)
334                elif tagname == 'x' and self.parent_class == 'position':
335                    self.current_datainfo.sample.position.x = data_point
336                    self.current_datainfo.sample.position_unit = unit
337                elif tagname == 'y' and self.parent_class == 'position':
338                    self.current_datainfo.sample.position.y = data_point
339                    self.current_datainfo.sample.position_unit = unit
340                elif tagname == 'z' and self.parent_class == 'position':
341                    self.current_datainfo.sample.position.z = data_point
342                    self.current_datainfo.sample.position_unit = unit
343                elif tagname == 'roll' and self.parent_class == 'orientation' and 'SASsample' in self.names:
344                    self.current_datainfo.sample.orientation.x = data_point
345                    self.current_datainfo.sample.orientation_unit = unit
346                elif tagname == 'pitch' and self.parent_class == 'orientation' and 'SASsample' in self.names:
347                    self.current_datainfo.sample.orientation.y = data_point
348                    self.current_datainfo.sample.orientation_unit = unit
349                elif tagname == 'yaw' and self.parent_class == 'orientation' and 'SASsample' in self.names:
350                    self.current_datainfo.sample.orientation.z = data_point
351                    self.current_datainfo.sample.orientation_unit = unit
352
353                # Instrumental Information
354                elif tagname == 'name' and self.parent_class == 'SASinstrument':
355                    self.current_datainfo.instrument = data_point
356                # Detector Information
357                elif tagname == 'name' and self.parent_class == 'SASdetector':
358                    self.detector.name = data_point
359                elif tagname == 'SDD' and self.parent_class == 'SASdetector':
360                    self.detector.distance = data_point
361                    self.detector.distance_unit = unit
362                elif tagname == 'slit_length' and self.parent_class == 'SASdetector':
363                    self.detector.slit_length = data_point
364                    self.detector.slit_length_unit = unit
365                elif tagname == 'x' and self.parent_class == 'offset':
366                    self.detector.offset.x = data_point
367                    self.detector.offset_unit = unit
368                elif tagname == 'y' and self.parent_class == 'offset':
369                    self.detector.offset.y = data_point
370                    self.detector.offset_unit = unit
371                elif tagname == 'z' and self.parent_class == 'offset':
372                    self.detector.offset.z = data_point
373                    self.detector.offset_unit = unit
374                elif tagname == 'x' and self.parent_class == 'beam_center':
375                    self.detector.beam_center.x = data_point
376                    self.detector.beam_center_unit = unit
377                elif tagname == 'y' and self.parent_class == 'beam_center':
378                    self.detector.beam_center.y = data_point
379                    self.detector.beam_center_unit = unit
380                elif tagname == 'z' and self.parent_class == 'beam_center':
381                    self.detector.beam_center.z = data_point
382                    self.detector.beam_center_unit = unit
383                elif tagname == 'x' and self.parent_class == 'pixel_size':
384                    self.detector.pixel_size.x = data_point
385                    self.detector.pixel_size_unit = unit
386                elif tagname == 'y' and self.parent_class == 'pixel_size':
387                    self.detector.pixel_size.y = data_point
388                    self.detector.pixel_size_unit = unit
389                elif tagname == 'z' and self.parent_class == 'pixel_size':
390                    self.detector.pixel_size.z = data_point
391                    self.detector.pixel_size_unit = unit
392                elif tagname == 'roll' and self.parent_class == 'orientation' and 'SASdetector' in self.names:
393                    self.detector.orientation.x = data_point
394                    self.detector.orientation_unit = unit
395                elif tagname == 'pitch' and self.parent_class == 'orientation' and 'SASdetector' in self.names:
396                    self.detector.orientation.y = data_point
397                    self.detector.orientation_unit = unit
398                elif tagname == 'yaw' and self.parent_class == 'orientation' and 'SASdetector' in self.names:
399                    self.detector.orientation.z = data_point
400                    self.detector.orientation_unit = unit
401                # Collimation and Aperture
402                elif tagname == 'length' and self.parent_class == 'SAScollimation':
403                    self.collimation.length = data_point
404                    self.collimation.length_unit = unit
405                elif tagname == 'name' and self.parent_class == 'SAScollimation':
406                    self.collimation.name = data_point
407                elif tagname == 'distance' and self.parent_class == 'aperture':
408                    self.aperture.distance = data_point
409                    self.aperture.distance_unit = unit
410                elif tagname == 'x' and self.parent_class == 'size':
411                    self.aperture.size.x = data_point
412                    self.collimation.size_unit = unit
413                elif tagname == 'y' and self.parent_class == 'size':
414                    self.aperture.size.y = data_point
415                    self.collimation.size_unit = unit
416                elif tagname == 'z' and self.parent_class == 'size':
417                    self.aperture.size.z = data_point
418                    self.collimation.size_unit = unit
419
420                # Process Information
421                elif tagname == 'name' and self.parent_class == 'SASprocess':
422                    self.process.name = data_point
423                elif tagname == 'description' and self.parent_class == 'SASprocess':
424                    self.process.description = data_point
425                elif tagname == 'date' and self.parent_class == 'SASprocess':
426                    try:
427                        self.process.date = datetime.datetime.fromtimestamp(data_point)
428                    except:
429                        self.process.date = data_point
430                elif tagname == 'SASprocessnote':
431                    self.process.notes.append(data_point)
432                elif tagname == 'term' and self.parent_class == 'SASprocess':
433                    unit = attr.get("unit", "")
434                    dic = {}
435                    dic["name"] = name
436                    dic["value"] = data_point
437                    dic["unit"] = unit
438                    self.process.term.append(dic)
439
440                # Transmission Spectrum
441                elif tagname == 'T' and self.parent_class == 'Tdata':
442                    self.transspectrum.transmission = np.append(self.transspectrum.transmission, data_point)
443                    self.transspectrum.transmission_unit = unit
444                elif tagname == 'Tdev' and self.parent_class == 'Tdata':
445                    self.transspectrum.transmission_deviation = np.append(self.transspectrum.transmission_deviation, data_point)
446                    self.transspectrum.transmission_deviation_unit = unit
447                elif tagname == 'Lambda' and self.parent_class == 'Tdata':
448                    self.transspectrum.wavelength = np.append(self.transspectrum.wavelength, data_point)
449                    self.transspectrum.wavelength_unit = unit
450
451                # Source Information
452                elif tagname == 'wavelength' and (self.parent_class == 'SASsource' or self.parent_class == 'SASData'):
453                    self.current_datainfo.source.wavelength = data_point
454                    self.current_datainfo.source.wavelength_unit = unit
455                elif tagname == 'wavelength_min' and self.parent_class == 'SASsource':
456                    self.current_datainfo.source.wavelength_min = data_point
457                    self.current_datainfo.source.wavelength_min_unit = unit
458                elif tagname == 'wavelength_max' and self.parent_class == 'SASsource':
459                    self.current_datainfo.source.wavelength_max = data_point
460                    self.current_datainfo.source.wavelength_max_unit = unit
461                elif tagname == 'wavelength_spread' and self.parent_class == 'SASsource':
462                    self.current_datainfo.source.wavelength_spread = data_point
463                    self.current_datainfo.source.wavelength_spread_unit = unit
464                elif tagname == 'x' and self.parent_class == 'beam_size':
465                    self.current_datainfo.source.beam_size.x = data_point
466                    self.current_datainfo.source.beam_size_unit = unit
467                elif tagname == 'y' and self.parent_class == 'beam_size':
468                    self.current_datainfo.source.beam_size.y = data_point
469                    self.current_datainfo.source.beam_size_unit = unit
470                elif tagname == 'z' and self.parent_class == 'pixel_size':
471                    self.current_datainfo.source.data_point.z = data_point
472                    self.current_datainfo.source.beam_size_unit = unit
473                elif tagname == 'radiation' and self.parent_class == 'SASsource':
474                    self.current_datainfo.source.radiation = data_point
475                elif tagname == 'beam_shape' and self.parent_class == 'SASsource':
476                    self.current_datainfo.source.beam_shape = data_point
477
478                # Everything else goes in meta_data
479                else:
480                    new_key = self._create_unique_key(self.current_datainfo.meta_data, tagname)
481                    self.current_datainfo.meta_data[new_key] = data_point
482
483            self.names.remove(tagname_original)
484            length = 0
485            if len(self.names) > 1:
486                length = len(self.names) - 1
487            self.parent_class = self.names[length]
488        if not self._is_call_local() and not recurse:
489            self.frm = ""
490            self.add_data_set()
491            empty = None
492            return self.output[0], empty
493
494
495    def _is_call_local(self):
496        """
497
498        """
499        if self.frm == "":
500            inter = inspect.stack()
501            self.frm = inter[2]
502        mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "")
503        mod_name = mod_name.replace(".py", "")
504        mod = mod_name.split("sas/")
505        mod_name = mod[1]
506        if mod_name != "sascalc/dataloader/readers/cansas_reader":
507            return False
508        return True
509
510    def is_cansas(self, ext="xml"):
511        """
512        Checks to see if the xml file is a CanSAS file
513
514        :param ext: The file extension of the data file
515        """
516        if self.validate_xml():
517            name = "{http://www.w3.org/2001/XMLSchema-instance}schemaLocation"
518            value = self.xmlroot.get(name)
519            if CANSAS_NS.get(self.cansas_version).get("ns") == \
520                    value.rsplit(" ")[0]:
521                return True
522        if ext == "svs":
523            return True
524        raise RuntimeError
525
526    def load_file_and_schema(self, xml_file, schema_path=""):
527        """
528        Loads the file and associates a schema, if a schema is passed in or if one already exists
529
530        :param xml_file: The xml file path sent to Reader.read
531        :param schema_path: The path to a schema associated with the xml_file, or find one based on the file
532        """
533        base_name = xml_reader.__file__
534        base_name = base_name.replace("\\", "/")
535        base = base_name.split("/sas/")[0]
536
537        # Load in xml file and get the cansas version from the header
538        self.set_xml_file(xml_file)
539        self.cansas_version = self.xmlroot.get("version", "1.0")
540
541        # Generic values for the cansas file based on the version
542        self.cansas_defaults = CANSAS_NS.get(self.cansas_version, "1.0")
543        if schema_path == "":
544            schema_path = "{0}/sas/sascalc/dataloader/readers/schema/{1}".format \
545                (base, self.cansas_defaults.get("schema")).replace("\\", "/")
546
547        # Link a schema to the XML file.
548        self.set_schema(schema_path)
549
550    def add_data_set(self):
551        """
552        Adds the current_dataset to the list of outputs after preforming final processing on the data and then calls a
553        private method to generate a new data set.
554
555        :param key: NeXus group name for current tree level
556        """
557
558        if self.current_datainfo and self.current_dataset:
559            self._final_cleanup()
560        self.data = []
561        self.current_datainfo = DataInfo()
562
563    def _initialize_new_data_set(self, node=None):
564        """
565        A private class method to generate a new 1D data object.
566        Outside methods should call add_data_set() to be sure any existing data is stored properly.
567
568        :param node: XML node to determine if 1D or 2D data
569        """
570        x = np.array(0)
571        y = np.array(0)
572        for child in node:
573            if child.tag.replace(self.base_ns, "") == "Idata":
574                for i_child in child:
575                    if i_child.tag.replace(self.base_ns, "") == "Qx":
576                        self.current_dataset = plottable_2D()
577                        return
578        self.current_dataset = plottable_1D(x, y)
579
580    def add_intermediate(self):
581        """
582        This method stores any intermediate objects within the final data set after fully reading the set.
583
584        :param parent: The NXclass name for the h5py Group object that just finished being processed
585        """
586
587        if self.parent_class == 'SASprocess':
588            self.current_datainfo.process.append(self.process)
589            self.process = Process()
590        elif self.parent_class == 'SASdetector':
591            self.current_datainfo.detector.append(self.detector)
592            self.detector = Detector()
593        elif self.parent_class == 'SAStransmission_spectrum':
594            self.current_datainfo.trans_spectrum.append(self.transspectrum)
595            self.transspectrum = TransmissionSpectrum()
596        elif self.parent_class == 'SAScollimation':
597            self.current_datainfo.collimation.append(self.collimation)
598            self.collimation = Collimation()
599        elif self.parent_class == 'aperture':
600            self.collimation.aperture.append(self.aperture)
601            self.aperture = Aperture()
602        elif self.parent_class == 'SASdata':
603            self._check_for_empty_resolution()
604            self.data.append(self.current_dataset)
605
606    def _final_cleanup(self):
607        """
608        Final cleanup of the Data1D object to be sure it has all the
609        appropriate information needed for perspectives
610        """
611
612        # Append errors to dataset and reset class errors
613        self.current_datainfo.errors = set()
614        for error in self.errors:
615            self.current_datainfo.errors.add(error)
616        self.errors.clear()
617
618        # Combine all plottables with datainfo and append each to output
619        # Type cast data arrays to float64 and find min/max as appropriate
620        for dataset in self.data:
621            if isinstance(dataset, plottable_1D):
622                if dataset.x is not None:
623                    dataset.x = np.delete(dataset.x, [0])
624                    dataset.x = dataset.x.astype(np.float64)
625                    dataset.xmin = np.min(dataset.x)
626                    dataset.xmax = np.max(dataset.x)
627                if dataset.y is not None:
628                    dataset.y = np.delete(dataset.y, [0])
629                    dataset.y = dataset.y.astype(np.float64)
630                    dataset.ymin = np.min(dataset.y)
631                    dataset.ymax = np.max(dataset.y)
632                if dataset.dx is not None:
633                    dataset.dx = np.delete(dataset.dx, [0])
634                    dataset.dx = dataset.dx.astype(np.float64)
635                if dataset.dxl is not None:
636                    dataset.dxl = np.delete(dataset.dxl, [0])
637                    dataset.dxl = dataset.dxl.astype(np.float64)
638                if dataset.dxw is not None:
639                    dataset.dxw = np.delete(dataset.dxw, [0])
640                    dataset.dxw = dataset.dxw.astype(np.float64)
641                if dataset.dy is not None:
642                    dataset.dy = np.delete(dataset.dy, [0])
643                    dataset.dy = dataset.dy.astype(np.float64)
644                np.trim_zeros(dataset.x)
645                np.trim_zeros(dataset.y)
646                np.trim_zeros(dataset.dy)
647            elif isinstance(dataset, plottable_2D):
648                dataset.data = dataset.data.astype(np.float64)
649                dataset.qx_data = dataset.qx_data.astype(np.float64)
650                dataset.xmin = np.min(dataset.qx_data)
651                dataset.xmax = np.max(dataset.qx_data)
652                dataset.qy_data = dataset.qy_data.astype(np.float64)
653                dataset.ymin = np.min(dataset.qy_data)
654                dataset.ymax = np.max(dataset.qy_data)
655                dataset.q_data = np.sqrt(dataset.qx_data * dataset.qx_data
656                                         + dataset.qy_data * dataset.qy_data)
657                if dataset.err_data is not None:
658                    dataset.err_data = dataset.err_data.astype(np.float64)
659                if dataset.dqx_data is not None:
660                    dataset.dqx_data = dataset.dqx_data.astype(np.float64)
661                if dataset.dqy_data is not None:
662                    dataset.dqy_data = dataset.dqy_data.astype(np.float64)
663                if dataset.mask is not None:
664                    dataset.mask = dataset.mask.astype(dtype=bool)
665
666                if len(dataset.shape) == 2:
667                    n_rows, n_cols = dataset.shape
668                    dataset.y_bins = dataset.qy_data[0::int(n_cols)]
669                    dataset.x_bins = dataset.qx_data[:int(n_cols)]
670                    dataset.data = dataset.data.flatten()
671                else:
672                    dataset.y_bins = []
673                    dataset.x_bins = []
674                    dataset.data = dataset.data.flatten()
675
676            final_dataset = combine_data(dataset, self.current_datainfo)
677            self.output.append(final_dataset)
678
679    def _create_unique_key(self, dictionary, name, numb=0):
680        """
681        Create a unique key value for any dictionary to prevent overwriting
682        Recurse until a unique key value is found.
683
684        :param dictionary: A dictionary with any number of entries
685        :param name: The index of the item to be added to dictionary
686        :param numb: The number to be appended to the name, starts at 0
687        """
688        if dictionary.get(name) is not None:
689            numb += 1
690            name = name.split("_")[0]
691            name += "_{0}".format(numb)
692            name = self._create_unique_key(dictionary, name, numb)
693        return name
694
695    def _get_node_value(self, node, tagname):
696        """
697        Get the value of a node and any applicable units
698
699        :param node: The XML node to get the value of
700        :param tagname: The tagname of the node
701        """
702        #Get the text from the node and convert all whitespace to spaces
703        units = ''
704        node_value = node.text
705        if node_value is not None:
706            node_value = ' '.join(node_value.split())
707        else:
708            node_value = ""
709
710        # If the value is a float, compile with units.
711        if self.ns_list.ns_datatype == "float":
712            # If an empty value is given, set as zero.
713            if node_value is None or node_value.isspace() \
714                                    or node_value.lower() == "nan":
715                node_value = "0.0"
716            #Convert the value to the base units
717            node_value, units = self._unit_conversion(node, tagname, node_value)
718
719        # If the value is a timestamp, convert to a datetime object
720        elif self.ns_list.ns_datatype == "timestamp":
721            if node_value is None or node_value.isspace():
722                pass
723            else:
724                try:
725                    node_value = \
726                        datetime.datetime.fromtimestamp(node_value)
727                except ValueError:
728                    node_value = None
729        return node_value, units
730
731    def _unit_conversion(self, node, tagname, node_value):
732        """
733        A unit converter method used to convert the data included in the file
734        to the default units listed in data_info
735
736        :param node: XML node
737        :param tagname: name of the node
738        :param node_value: The value of the current dom node
739        """
740        attr = node.attrib
741        value_unit = ''
742        err_msg = None
743        default_unit = None
744        if not isinstance(node_value, float):
745            node_value = float(node_value)
746        if 'unit' in attr and attr.get('unit') is not None:
747            try:
748                local_unit = attr['unit']
749                unitname = self.ns_list.current_level.get("unit", "")
750                if "SASdetector" in self.names:
751                    save_in = "detector"
752                elif "aperture" in self.names:
753                    save_in = "aperture"
754                elif "SAScollimation" in self.names:
755                    save_in = "collimation"
756                elif "SAStransmission_spectrum" in self.names:
757                    save_in = "transspectrum"
758                elif "SASdata" in self.names:
759                    x = np.zeros(1)
760                    y = np.zeros(1)
761                    self.current_data1d = Data1D(x, y)
762                    save_in = "current_data1d"
763                elif "SASsource" in self.names:
764                    save_in = "current_datainfo.source"
765                elif "SASsample" in self.names:
766                    save_in = "current_datainfo.sample"
767                elif "SASprocess" in self.names:
768                    save_in = "process"
769                else:
770                    save_in = "current_datainfo"
771                exec "default_unit = self.{0}.{1}".format(save_in, unitname)
772                if local_unit and default_unit and local_unit.lower() != default_unit.lower() \
773                        and local_unit.lower() != "none":
774                    if HAS_CONVERTER == True:
775                        # Check local units - bad units raise KeyError
776                        data_conv_q = Converter(local_unit)
777                        value_unit = default_unit
778                        node_value = data_conv_q(node_value, units=default_unit)
779                    else:
780                        value_unit = local_unit
781                        err_msg = "Unit converter is not available.\n"
782                else:
783                    value_unit = local_unit
784            except KeyError:
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 == 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 == 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 == 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._xaxis + " | " + datainfo._xunit})
1040            if len(datainfo.y) >= i:
1041                self.write_node(point, "I", datainfo.y[i],
1042                                {'unit': datainfo._yaxis + " | " + datainfo._yunit})
1043            if datainfo.dy is not None and len(datainfo.dy) > i:
1044                self.write_node(point, "Idev", datainfo.dy[i],
1045                                {'unit': datainfo._yaxis + " | " + datainfo._yunit})
1046            if datainfo.dx is not None and len(datainfo.dx) > i:
1047                self.write_node(point, "Qdev", datainfo.dx[i],
1048                                {'unit': datainfo._xaxis + " | " + datainfo._xunit})
1049            if datainfo.dxw is not None and len(datainfo.dxw) > i:
1050                self.write_node(point, "dQw", datainfo.dxw[i],
1051                                {'unit': datainfo._xaxis + " | " + datainfo._xunit})
1052            if datainfo.dxl is not None and len(datainfo.dxl) > i:
1053                self.write_node(point, "dQl", datainfo.dxl[i],
1054                                {'unit': datainfo._xaxis + " | " + datainfo._xunit})
1055        if datainfo.isSesans:
1056            sesans = self.create_element("Sesans")
1057            sesans.text = str(datainfo.isSesans)
1058            node.append(sesans)
1059            self.write_node(node, "zacceptance", datainfo.sample.zacceptance[0],
1060                             {'unit': datainfo.sample.zacceptance[1]})
1061
1062
1063    def _write_data_2d(self, datainfo, entry_node):
1064        """
1065        Writes 2D data to the XML file
1066
1067        :param datainfo: The Data2D object the information is coming from
1068        :param entry_node: lxml node ElementTree object to be appended to
1069        """
1070        attr = {}
1071        if datainfo.data.shape:
1072            attr["x_bins"] = str(len(datainfo.x_bins))
1073            attr["y_bins"] = str(len(datainfo.y_bins))
1074        node = self.create_element("SASdata", attr)
1075        self.append(node, entry_node)
1076
1077        point = self.create_element("Idata")
1078        node.append(point)
1079        qx = ','.join([str(datainfo.qx_data[i]) for i in xrange(len(datainfo.qx_data))])
1080        qy = ','.join([str(datainfo.qy_data[i]) for i in xrange(len(datainfo.qy_data))])
1081        intensity = ','.join([str(datainfo.data[i]) for i in xrange(len(datainfo.data))])
1082
1083        self.write_node(point, "Qx", qx,
1084                        {'unit': datainfo._xunit})
1085        self.write_node(point, "Qy", qy,
1086                        {'unit': datainfo._yunit})
1087        self.write_node(point, "I", intensity,
1088                        {'unit': datainfo._zunit})
1089        if datainfo.err_data is not None:
1090            err = ','.join([str(datainfo.err_data[i]) for i in
1091                            xrange(len(datainfo.err_data))])
1092            self.write_node(point, "Idev", err,
1093                            {'unit': datainfo._zunit})
1094        if datainfo.dqy_data is not None:
1095            dqy = ','.join([str(datainfo.dqy_data[i]) for i in
1096                            xrange(len(datainfo.dqy_data))])
1097            self.write_node(point, "Qydev", dqy,
1098                            {'unit': datainfo._yunit})
1099        if datainfo.dqx_data is not None:
1100            dqx = ','.join([str(datainfo.dqx_data[i]) for i in
1101                            xrange(len(datainfo.dqx_data))])
1102            self.write_node(point, "Qxdev", dqx,
1103                            {'unit': datainfo._xunit})
1104        if datainfo.mask is not None:
1105            mask = ','.join(
1106                ["1" if datainfo.mask[i] else "0"
1107                 for i in xrange(len(datainfo.mask))])
1108            self.write_node(point, "Mask", mask)
1109
1110    def _write_trans_spectrum(self, datainfo, entry_node):
1111        """
1112        Writes the transmission spectrum data to the XML file
1113
1114        :param datainfo: The Data1D object the information is coming from
1115        :param entry_node: lxml node ElementTree object to be appended to
1116        """
1117        for i in range(len(datainfo.trans_spectrum)):
1118            spectrum = datainfo.trans_spectrum[i]
1119            node = self.create_element("SAStransmission_spectrum",
1120                                       {"name" : spectrum.name})
1121            self.append(node, entry_node)
1122            if isinstance(spectrum.timestamp, datetime.datetime):
1123                node.setAttribute("timestamp", spectrum.timestamp)
1124            for i in range(len(spectrum.wavelength)):
1125                point = self.create_element("Tdata")
1126                node.append(point)
1127                self.write_node(point, "Lambda", spectrum.wavelength[i],
1128                                {'unit': spectrum.wavelength_unit})
1129                self.write_node(point, "T", spectrum.transmission[i],
1130                                {'unit': spectrum.transmission_unit})
1131                if spectrum.transmission_deviation != None \
1132                and len(spectrum.transmission_deviation) >= i:
1133                    self.write_node(point, "Tdev",
1134                                    spectrum.transmission_deviation[i],
1135                                    {'unit':
1136                                     spectrum.transmission_deviation_unit})
1137
1138    def _write_sample_info(self, datainfo, entry_node):
1139        """
1140        Writes the sample information to the XML file
1141
1142        :param datainfo: The Data1D object the information is coming from
1143        :param entry_node: lxml node ElementTree object to be appended to
1144        """
1145        sample = self.create_element("SASsample")
1146        if datainfo.sample.name is not None:
1147            self.write_attribute(sample, "name",
1148                                 str(datainfo.sample.name))
1149        self.append(sample, entry_node)
1150        self.write_node(sample, "ID", str(datainfo.sample.ID))
1151        self.write_node(sample, "thickness", datainfo.sample.thickness,
1152                        {"unit": datainfo.sample.thickness_unit})
1153        self.write_node(sample, "transmission", datainfo.sample.transmission)
1154        self.write_node(sample, "temperature", datainfo.sample.temperature,
1155                        {"unit": datainfo.sample.temperature_unit})
1156
1157        pos = self.create_element("position")
1158        written = self.write_node(pos,
1159                                  "x",
1160                                  datainfo.sample.position.x,
1161                                  {"unit": datainfo.sample.position_unit})
1162        written = written | self.write_node( \
1163            pos, "y", datainfo.sample.position.y,
1164            {"unit": datainfo.sample.position_unit})
1165        written = written | self.write_node( \
1166            pos, "z", datainfo.sample.position.z,
1167            {"unit": datainfo.sample.position_unit})
1168        if written == True:
1169            self.append(pos, sample)
1170
1171        ori = self.create_element("orientation")
1172        written = self.write_node(ori, "roll",
1173                                  datainfo.sample.orientation.x,
1174                                  {"unit": datainfo.sample.orientation_unit})
1175        written = written | self.write_node( \
1176            ori, "pitch", datainfo.sample.orientation.y,
1177            {"unit": datainfo.sample.orientation_unit})
1178        written = written | self.write_node( \
1179            ori, "yaw", datainfo.sample.orientation.z,
1180            {"unit": datainfo.sample.orientation_unit})
1181        if written == True:
1182            self.append(ori, sample)
1183
1184        for item in datainfo.sample.details:
1185            self.write_node(sample, "details", item)
1186
1187    def _write_instrument(self, datainfo, entry_node):
1188        """
1189        Writes the instrumental information to the XML file
1190
1191        :param datainfo: The Data1D object the information is coming from
1192        :param entry_node: lxml node ElementTree object to be appended to
1193        """
1194        instr = self.create_element("SASinstrument")
1195        self.append(instr, entry_node)
1196        self.write_node(instr, "name", datainfo.instrument)
1197        return instr
1198
1199    def _write_source(self, datainfo, instr):
1200        """
1201        Writes the source information to the XML file
1202
1203        :param datainfo: The Data1D object the information is coming from
1204        :param instr: instrument node  to be appended to
1205        """
1206        source = self.create_element("SASsource")
1207        if datainfo.source.name is not None:
1208            self.write_attribute(source, "name",
1209                                 str(datainfo.source.name))
1210        self.append(source, instr)
1211        if datainfo.source.radiation == None or datainfo.source.radiation == '':
1212            datainfo.source.radiation = "neutron"
1213        self.write_node(source, "radiation", datainfo.source.radiation)
1214
1215        size = self.create_element("beam_size")
1216        if datainfo.source.beam_size_name is not None:
1217            self.write_attribute(size, "name",
1218                                 str(datainfo.source.beam_size_name))
1219        written = self.write_node( \
1220            size, "x", datainfo.source.beam_size.x,
1221            {"unit": datainfo.source.beam_size_unit})
1222        written = written | self.write_node( \
1223            size, "y", datainfo.source.beam_size.y,
1224            {"unit": datainfo.source.beam_size_unit})
1225        written = written | self.write_node( \
1226            size, "z", datainfo.source.beam_size.z,
1227            {"unit": datainfo.source.beam_size_unit})
1228        if written == True:
1229            self.append(size, source)
1230
1231        self.write_node(source, "beam_shape", datainfo.source.beam_shape)
1232        self.write_node(source, "wavelength",
1233                        datainfo.source.wavelength,
1234                        {"unit": datainfo.source.wavelength_unit})
1235        self.write_node(source, "wavelength_min",
1236                        datainfo.source.wavelength_min,
1237                        {"unit": datainfo.source.wavelength_min_unit})
1238        self.write_node(source, "wavelength_max",
1239                        datainfo.source.wavelength_max,
1240                        {"unit": datainfo.source.wavelength_max_unit})
1241        self.write_node(source, "wavelength_spread",
1242                        datainfo.source.wavelength_spread,
1243                        {"unit": datainfo.source.wavelength_spread_unit})
1244
1245    def _write_collimation(self, datainfo, instr):
1246        """
1247        Writes the collimation information to the XML file
1248
1249        :param datainfo: The Data1D object the information is coming from
1250        :param instr: lxml node ElementTree object to be appended to
1251        """
1252        if datainfo.collimation == [] or datainfo.collimation == None:
1253            coll = Collimation()
1254            datainfo.collimation.append(coll)
1255        for item in datainfo.collimation:
1256            coll = self.create_element("SAScollimation")
1257            if item.name is not None:
1258                self.write_attribute(coll, "name", str(item.name))
1259            self.append(coll, instr)
1260
1261            self.write_node(coll, "length", item.length,
1262                            {"unit": item.length_unit})
1263
1264            for aperture in item.aperture:
1265                apert = self.create_element("aperture")
1266                if aperture.name is not None:
1267                    self.write_attribute(apert, "name", str(aperture.name))
1268                if aperture.type is not None:
1269                    self.write_attribute(apert, "type", str(aperture.type))
1270                self.append(apert, coll)
1271
1272                size = self.create_element("size")
1273                if aperture.size_name is not None:
1274                    self.write_attribute(size, "name",
1275                                         str(aperture.size_name))
1276                written = self.write_node(size, "x", aperture.size.x,
1277                                          {"unit": aperture.size_unit})
1278                written = written | self.write_node( \
1279                    size, "y", aperture.size.y,
1280                    {"unit": aperture.size_unit})
1281                written = written | self.write_node( \
1282                    size, "z", aperture.size.z,
1283                    {"unit": aperture.size_unit})
1284                if written == True:
1285                    self.append(size, apert)
1286
1287                self.write_node(apert, "distance", aperture.distance,
1288                                {"unit": aperture.distance_unit})
1289
1290    def _write_detectors(self, datainfo, instr):
1291        """
1292        Writes the detector information to the XML file
1293
1294        :param datainfo: The Data1D object the information is coming from
1295        :param inst: lxml instrument node to be appended to
1296        """
1297        if datainfo.detector == None or datainfo.detector == []:
1298            det = Detector()
1299            det.name = ""
1300            datainfo.detector.append(det)
1301
1302        for item in datainfo.detector:
1303            det = self.create_element("SASdetector")
1304            written = self.write_node(det, "name", item.name)
1305            written = written | self.write_node(det, "SDD", item.distance,
1306                                                {"unit": item.distance_unit})
1307            if written == True:
1308                self.append(det, instr)
1309
1310            off = self.create_element("offset")
1311            written = self.write_node(off, "x", item.offset.x,
1312                                      {"unit": item.offset_unit})
1313            written = written | self.write_node(off, "y", item.offset.y,
1314                                                {"unit": item.offset_unit})
1315            written = written | self.write_node(off, "z", item.offset.z,
1316                                                {"unit": item.offset_unit})
1317            if written == True:
1318                self.append(off, det)
1319
1320            ori = self.create_element("orientation")
1321            written = self.write_node(ori, "roll", item.orientation.x,
1322                                      {"unit": item.orientation_unit})
1323            written = written | self.write_node(ori, "pitch",
1324                                                item.orientation.y,
1325                                                {"unit": item.orientation_unit})
1326            written = written | self.write_node(ori, "yaw",
1327                                                item.orientation.z,
1328                                                {"unit": item.orientation_unit})
1329            if written == True:
1330                self.append(ori, det)
1331
1332            center = self.create_element("beam_center")
1333            written = self.write_node(center, "x", item.beam_center.x,
1334                                      {"unit": item.beam_center_unit})
1335            written = written | self.write_node(center, "y",
1336                                                item.beam_center.y,
1337                                                {"unit": item.beam_center_unit})
1338            written = written | self.write_node(center, "z",
1339                                                item.beam_center.z,
1340                                                {"unit": item.beam_center_unit})
1341            if written == True:
1342                self.append(center, det)
1343
1344            pix = self.create_element("pixel_size")
1345            written = self.write_node(pix, "x", item.pixel_size.x,
1346                                      {"unit": item.pixel_size_unit})
1347            written = written | self.write_node(pix, "y", item.pixel_size.y,
1348                                                {"unit": item.pixel_size_unit})
1349            written = written | self.write_node(pix, "z", item.pixel_size.z,
1350                                                {"unit": item.pixel_size_unit})
1351            if written == True:
1352                self.append(pix, det)
1353            self.write_node(det, "slit_length", item.slit_length,
1354                {"unit": item.slit_length_unit})
1355
1356
1357    def _write_process_notes(self, datainfo, entry_node):
1358        """
1359        Writes the process notes to the XML file
1360
1361        :param datainfo: The Data1D object the information is coming from
1362        :param entry_node: lxml node ElementTree object to be appended to
1363
1364        """
1365        for item in datainfo.process:
1366            node = self.create_element("SASprocess")
1367            self.append(node, entry_node)
1368            self.write_node(node, "name", item.name)
1369            self.write_node(node, "date", item.date)
1370            self.write_node(node, "description", item.description)
1371            for term in item.term:
1372                if isinstance(term, list):
1373                    value = term['value']
1374                    del term['value']
1375                elif isinstance(term, dict):
1376                    value = term.get("value")
1377                    del term['value']
1378                else:
1379                    value = term
1380                self.write_node(node, "term", value, term)
1381            for note in item.notes:
1382                self.write_node(node, "SASprocessnote", note)
1383            if len(item.notes) == 0:
1384                self.write_node(node, "SASprocessnote", "")
1385
1386    def _write_notes(self, datainfo, entry_node):
1387        """
1388        Writes the notes to the XML file and creates an empty note if none
1389        exist
1390
1391        :param datainfo: The Data1D object the information is coming from
1392        :param entry_node: lxml node ElementTree object to be appended to
1393
1394        """
1395        if len(datainfo.notes) == 0:
1396            node = self.create_element("SASnote")
1397            self.append(node, entry_node)
1398        else:
1399            for item in datainfo.notes:
1400                node = self.create_element("SASnote")
1401                self.write_text(node, item)
1402                self.append(node, entry_node)
1403
1404    def _check_origin(self, entry_node, doc):
1405        """
1406        Return the document, and the SASentry node associated with
1407        the data we just wrote.
1408        If the calling function was not the cansas reader, return a minidom
1409        object rather than an lxml object.
1410
1411        :param entry_node: lxml node ElementTree object to be appended to
1412        :param doc: entire xml tree
1413        """
1414        if not self.frm:
1415            self.frm = inspect.stack()[1]
1416        mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "")
1417        mod_name = mod_name.replace(".py", "")
1418        mod = mod_name.split("sas/")
1419        mod_name = mod[1]
1420        if mod_name != "sascalc/dataloader/readers/cansas_reader":
1421            string = self.to_string(doc, pretty_print=False)
1422            doc = parseString(string)
1423            node_name = entry_node.tag
1424            node_list = doc.getElementsByTagName(node_name)
1425            entry_node = node_list.item(0)
1426        return doc, entry_node
1427
1428    # DO NOT REMOVE - used in saving and loading panel states.
1429    def _store_float(self, location, node, variable, storage, optional=True):
1430        """
1431        Get the content of a xpath location and store
1432        the result. Check that the units are compatible
1433        with the destination. The value is expected to
1434        be a float.
1435
1436        The xpath location might or might not exist.
1437        If it does not exist, nothing is done
1438
1439        :param location: xpath location to fetch
1440        :param node: node to read the data from
1441        :param variable: name of the data member to store it in [string]
1442        :param storage: data object that has the 'variable' data member
1443        :param optional: if True, no exception will be raised
1444            if unit conversion can't be done
1445
1446        :raise ValueError: raised when the units are not recognized
1447        """
1448        entry = get_content(location, node)
1449        try:
1450            value = float(entry.text)
1451        except:
1452            value = None
1453
1454        if value is not None:
1455            # If the entry has units, check to see that they are
1456            # compatible with what we currently have in the data object
1457            units = entry.get('unit')
1458            if units is not None:
1459                toks = variable.split('.')
1460                local_unit = None
1461                exec "local_unit = storage.%s_unit" % toks[0]
1462                if local_unit != None and units.lower() != local_unit.lower():
1463                    if HAS_CONVERTER == True:
1464                        try:
1465                            conv = Converter(units)
1466                            exec "storage.%s = %g" % \
1467                                (variable, conv(value, units=local_unit))
1468                        except:
1469                            _, exc_value, _ = sys.exc_info()
1470                            err_mess = "CanSAS reader: could not convert"
1471                            err_mess += " %s unit [%s]; expecting [%s]\n  %s" \
1472                                % (variable, units, local_unit, exc_value)
1473                            self.errors.add(err_mess)
1474                            if optional:
1475                                logger.info(err_mess)
1476                            else:
1477                                raise ValueError, err_mess
1478                    else:
1479                        err_mess = "CanSAS reader: unrecognized %s unit [%s];"\
1480                        % (variable, units)
1481                        err_mess += " expecting [%s]" % local_unit
1482                        self.errors.add(err_mess)
1483                        if optional:
1484                            logger.info(err_mess)
1485                        else:
1486                            raise ValueError, err_mess
1487                else:
1488                    exec "storage.%s = value" % variable
1489            else:
1490                exec "storage.%s = value" % variable
1491
1492    # DO NOT REMOVE - used in saving and loading panel states.
1493    def _store_content(self, location, node, variable, storage):
1494        """
1495        Get the content of a xpath location and store
1496        the result. The value is treated as a string.
1497
1498        The xpath location might or might not exist.
1499        If it does not exist, nothing is done
1500
1501        :param location: xpath location to fetch
1502        :param node: node to read the data from
1503        :param variable: name of the data member to store it in [string]
1504        :param storage: data object that has the 'variable' data member
1505
1506        :return: return a list of errors
1507        """
1508        entry = get_content(location, node)
1509        if entry is not None and entry.text is not None:
1510            exec "storage.%s = entry.text.strip()" % variable
1511
1512
1513# DO NOT REMOVE Called by outside packages:
1514#    sas.sasgui.perspectives.invariant.invariant_state
1515#    sas.sasgui.perspectives.fitting.pagestate
1516def get_content(location, node):
1517    """
1518    Get the first instance of the content of a xpath location.
1519
1520    :param location: xpath location
1521    :param node: node to start at
1522
1523    :return: Element, or None
1524    """
1525    nodes = node.xpath(location,
1526                       namespaces={'ns': CANSAS_NS.get("1.0").get("ns")})
1527    if len(nodes) > 0:
1528        return nodes[0]
1529    else:
1530        return None
1531
1532# DO NOT REMOVE Called by outside packages:
1533#    sas.sasgui.perspectives.fitting.pagestate
1534def write_node(doc, parent, name, value, attr=None):
1535    """
1536    :param doc: document DOM
1537    :param parent: parent node
1538    :param name: tag of the element
1539    :param value: value of the child text node
1540    :param attr: attribute dictionary
1541
1542    :return: True if something was appended, otherwise False
1543    """
1544    if attr is None:
1545        attr = {}
1546    if value is not None:
1547        node = doc.createElement(name)
1548        node.appendChild(doc.createTextNode(str(value)))
1549        for item in attr:
1550            node.setAttribute(item, attr[item])
1551        parent.appendChild(node)
1552        return True
1553    return False
Note: See TracBrowser for help on using the repository browser.