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

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 3ece5dd was 3ece5dd, checked in by lewis, 7 years ago

Raise and catch correct exceptions in CanSAS XML reader

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