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

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalcmagnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 574adc7 was 574adc7, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

convert sascalc to python 2/3 syntax

  • Property mode set to 100644
File size: 63.0 KB
Line 
1import logging
2import os
3import sys
4import datetime
5import inspect
6
7import numpy as np
8
9# The following 2 imports *ARE* used. Do not remove either.
10import xml.dom.minidom
11from xml.dom.minidom import parseString
12
13from lxml import etree
14
15from sas.sascalc.data_util.nxsunit import Converter
16
17# For saving individual sections of data
18from ..data_info import Data1D, Data2D, DataInfo, plottable_1D, plottable_2D, \
19    Collimation, TransmissionSpectrum, Detector, Process, Aperture, \
20    combine_data_info_with_plottable as combine_data
21from ..loader_exceptions import FileContentsException, DefaultReaderException, \
22    DataReaderException
23from . import xml_reader
24from .xml_reader import XMLreader
25from .cansas_constants import CansasConstants, CurrentLevel
26
27logger = logging.getLogger(__name__)
28
29PREPROCESS = "xmlpreprocess"
30ENCODING = "encoding"
31RUN_NAME_DEFAULT = "None"
32INVALID_SCHEMA_PATH_1_1 = "{0}/sas/sascalc/dataloader/readers/schema/cansas1d_invalid_v1_1.xsd"
33INVALID_SCHEMA_PATH_1_0 = "{0}/sas/sascalc/dataloader/readers/schema/cansas1d_invalid_v1_0.xsd"
34INVALID_XML = "\n\nThe loaded xml file, {0} does not fully meet the CanSAS v1.x specification. SasView loaded " + \
35              "as much of the data as possible.\n\n"
36HAS_CONVERTER = True
37
38CONSTANTS = CansasConstants()
39CANSAS_FORMAT = CONSTANTS.format
40CANSAS_NS = CONSTANTS.names
41ALLOW_ALL = True
42
43class Reader(XMLreader):
44    cansas_version = "1.0"
45    base_ns = "{cansas1d/1.0}"
46    cansas_defaults = None
47    type_name = "canSAS"
48    invalid = True
49    frm = ""
50    # Log messages and errors
51    logging = None
52    errors = set()
53    # Namespace hierarchy for current xml_file object
54    names = None
55    ns_list = None
56    # Temporary storage location for loading multiple data sets in a single file
57    current_data1d = None
58    data = None
59    # Wildcards
60    type = ["XML files (*.xml)|*.xml", "SasView Save Files (*.svs)|*.svs"]
61    # List of allowed extensions
62    ext = ['.xml', '.XML', '.svs', '.SVS']
63    # Flag to bypass extension check
64    allow_all = True
65
66    def reset_state(self):
67        """
68        Resets the class state to a base case when loading a new data file so previous
69        data files do not appear a second time
70        """
71        self.current_datainfo = None
72        self.current_dataset = None
73        self.current_data1d = None
74        self.data = []
75        self.process = Process()
76        self.transspectrum = TransmissionSpectrum()
77        self.aperture = Aperture()
78        self.collimation = Collimation()
79        self.detector = Detector()
80        self.names = []
81        self.cansas_defaults = {}
82        self.output = []
83        self.ns_list = None
84        self.logging = []
85        self.encoding = None
86
87    def read(self, xml_file, schema_path="", invalid=True):
88        if schema_path != "" or invalid != True:
89            # read has been called from self.get_file_contents because xml file doens't conform to schema
90            _, self.extension = os.path.splitext(os.path.basename(xml_file))
91            return self.get_file_contents(xml_file=xml_file, schema_path=schema_path, invalid=invalid)
92
93        # Otherwise, read has been called by the data loader - file_reader_base_class handles this
94        return super(XMLreader, self).read(xml_file)
95
96    def get_file_contents(self, xml_file=None, schema_path="", invalid=True):
97        # Reset everything since we're loading a new file
98        self.reset_state()
99        self.invalid = invalid
100        if xml_file is None:
101            xml_file = self.f_open.name
102        # We don't sure f_open since lxml handles opnening/closing files
103        if not self.f_open.closed:
104            self.f_open.close()
105
106        basename, _ = os.path.splitext(os.path.basename(xml_file))
107
108        try:
109            # Raises FileContentsException
110            self.load_file_and_schema(xml_file, schema_path)
111            self.current_datainfo = DataInfo()
112            # Raises FileContentsException if file doesn't meet CanSAS schema
113            self.is_cansas(self.extension)
114            self.invalid = False # If we reach this point then file must be valid CanSAS
115
116            # Parse each SASentry
117            entry_list = self.xmlroot.xpath('/ns:SASroot/ns:SASentry', namespaces={
118                'ns': self.cansas_defaults.get("ns")
119            })
120            # Look for a SASentry
121            self.names.append("SASentry")
122            self.set_processing_instructions()
123
124            for entry in entry_list:
125                self.current_datainfo.filename = basename + self.extension
126                self.current_datainfo.meta_data["loader"] = "CanSAS XML 1D"
127                self.current_datainfo.meta_data[PREPROCESS] = self.processing_instructions
128                self._parse_entry(entry)
129                self.data_cleanup()
130        except FileContentsException as fc_exc:
131            # File doesn't meet schema - try loading with a less strict schema
132            base_name = xml_reader.__file__
133            base_name = base_name.replace("\\", "/")
134            base = base_name.split("/sas/")[0]
135            if self.cansas_version == "1.1":
136                invalid_schema = INVALID_SCHEMA_PATH_1_1.format(base, self.cansas_defaults.get("schema"))
137            else:
138                invalid_schema = INVALID_SCHEMA_PATH_1_0.format(base, self.cansas_defaults.get("schema"))
139            self.set_schema(invalid_schema)
140            if self.invalid:
141                try:
142                    # Load data with less strict schema
143                    self.read(xml_file, invalid_schema, False)
144
145                    # File can still be read but doesn't match schema, so raise exception
146                    self.load_file_and_schema(xml_file) # Reload strict schema so we can find where error are in file
147                    invalid_xml = self.find_invalid_xml()
148                    if invalid_xml != "":
149                        invalid_xml = INVALID_XML.format(basename + self.extension) + invalid_xml
150                        raise DataReaderException(invalid_xml) # Handled by base class
151                except FileContentsException as fc_exc:
152                    msg = "CanSAS Reader could not load the file {}".format(xml_file)
153                    if fc_exc.message is not None: # Propagate error messages from earlier
154                        msg = fc_exc.message
155                    if not self.extension in self.ext: # If the file has no associated loader
156                        raise DefaultReaderException(msg)
157                    raise FileContentsException(msg)
158                    pass
159            else:
160                raise fc_exc
161        except Exception as e: # Convert all other exceptions to FileContentsExceptions
162            raise
163            raise FileContentsException(str(e))
164
165
166    def load_file_and_schema(self, xml_file, schema_path=""):
167        base_name = xml_reader.__file__
168        base_name = base_name.replace("\\", "/")
169        base = base_name.split("/sas/")[0]
170
171        # Try and parse the XML file
172        try:
173            self.set_xml_file(xml_file)
174        except etree.XMLSyntaxError: # File isn't valid XML so can't be loaded
175            msg = "SasView cannot load {}.\nInvalid XML syntax".format(xml_file)
176            raise FileContentsException(msg)
177
178        self.cansas_version = self.xmlroot.get("version", "1.0")
179        self.cansas_defaults = CANSAS_NS.get(self.cansas_version, "1.0")
180
181        if schema_path == "":
182            schema_path = "{}/sas/sascalc/dataloader/readers/schema/{}".format(
183                base, self.cansas_defaults.get("schema").replace("\\", "/")
184            )
185        self.set_schema(schema_path)
186
187    def is_cansas(self, ext="xml"):
188        """
189        Checks to see if the XML file is a CanSAS file
190
191        :param ext: The file extension of the data file
192        :raises FileContentsException: Raised if XML file isn't valid CanSAS
193        """
194        if self.validate_xml(): # Check file is valid XML
195            name = "{http://www.w3.org/2001/XMLSchema-instance}schemaLocation"
196            value = self.xmlroot.get(name)
197            # Check schema CanSAS version matches file CanSAS version
198            if CANSAS_NS.get(self.cansas_version).get("ns") == value.rsplit(" ")[0]:
199                return True
200        if ext == "svs":
201            return True # Why is this required?
202        # If we get to this point then file isn't valid CanSAS
203        logger.warning("File doesn't meet CanSAS schema. Trying to load anyway.")
204        raise FileContentsException("The file is not valid CanSAS")
205
206    def _parse_entry(self, dom, recurse=False):
207        if not self._is_call_local() and not recurse:
208            self.reset_state()
209            self.data = []
210            self.current_datainfo = DataInfo()
211            self.names.append("SASentry")
212            self.parent_class = "SASentry"
213        # Create an empty dataset if no data has been passed to the reader
214        if self.current_dataset is None:
215            self.current_dataset = plottable_1D(np.empty(0), np.empty(0),
216                np.empty(0), np.empty(0))
217        self.base_ns = "{" + CANSAS_NS.get(self.cansas_version).get("ns") + "}"
218
219        # Loop through each child in the parent element
220        for node in dom:
221            attr = node.attrib
222            name = attr.get("name", "")
223            type = attr.get("type", "")
224            # Get the element name and set the current names level
225            tagname = node.tag.replace(self.base_ns, "")
226            tagname_original = tagname
227            # Skip this iteration when loading in save state information
228            if tagname == "fitting_plug_in" or tagname == "pr_inversion" or tagname == "invariant":
229                continue
230            # Get where to store content
231            self.names.append(tagname_original)
232            self.ns_list = CONSTANTS.iterate_namespace(self.names)
233            # If the element is a child element, recurse
234            if len(node.getchildren()) > 0:
235                self.parent_class = tagname_original
236                if tagname == 'SASdata':
237                    self._initialize_new_data_set(node)
238                    if isinstance(self.current_dataset, plottable_2D):
239                        x_bins = attr.get("x_bins", "")
240                        y_bins = attr.get("y_bins", "")
241                        if x_bins is not "" and y_bins is not "":
242                            self.current_dataset.shape = (x_bins, y_bins)
243                        else:
244                            self.current_dataset.shape = ()
245                # Recurse to access data within the group
246                self._parse_entry(node, recurse=True)
247                if tagname == "SASsample":
248                    self.current_datainfo.sample.name = name
249                elif tagname == "beam_size":
250                    self.current_datainfo.source.beam_size_name = name
251                elif tagname == "SAScollimation":
252                    self.collimation.name = name
253                elif tagname == "aperture":
254                    self.aperture.name = name
255                    self.aperture.type = type
256                self._add_intermediate()
257            else:
258                if isinstance(self.current_dataset, plottable_2D):
259                    data_point = node.text
260                    unit = attr.get('unit', '')
261                else:
262                    data_point, unit = self._get_node_value(node, tagname)
263
264                # If this is a dataset, store the data appropriately
265                if tagname == 'Run':
266                    self.current_datainfo.run_name[data_point] = name
267                    self.current_datainfo.run.append(data_point)
268                elif tagname == 'Title':
269                    self.current_datainfo.title = data_point
270                elif tagname == 'SASnote':
271                    self.current_datainfo.notes.append(data_point)
272
273                # I and Q points
274                elif tagname == 'I' and isinstance(self.current_dataset, plottable_1D):
275                    self.current_dataset.yaxis("Intensity", unit)
276                    self.current_dataset.y = np.append(self.current_dataset.y, data_point)
277                elif tagname == 'Idev' and isinstance(self.current_dataset, plottable_1D):
278                    self.current_dataset.dy = np.append(self.current_dataset.dy, data_point)
279                elif tagname == 'Q':
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                    self.current_dataset.xaxis(attr.get('x_axis'),
295                                                attr.get('x_unit'))
296                    self.current_dataset.yaxis(attr.get('y_axis'),
297                                                attr.get('y_unit'))
298                elif tagname == 'yacceptance':
299                    self.current_datainfo.sample.yacceptance = (data_point, unit)
300                elif tagname == 'zacceptance':
301                    self.current_datainfo.sample.zacceptance = (data_point, unit)
302
303                # I and Qx, Qy - 2D data
304                elif tagname == 'I' and isinstance(self.current_dataset, plottable_2D):
305                    self.current_dataset.yaxis("Intensity", unit)
306                    self.current_dataset.data = np.fromstring(data_point, dtype=float, sep=",")
307                elif tagname == 'Idev' and isinstance(self.current_dataset, plottable_2D):
308                    self.current_dataset.err_data = np.fromstring(data_point, dtype=float, sep=",")
309                elif tagname == 'Qx':
310                    self.current_dataset.xaxis("Qx", unit)
311                    self.current_dataset.qx_data = np.fromstring(data_point, dtype=float, sep=",")
312                elif tagname == 'Qy':
313                    self.current_dataset.yaxis("Qy", unit)
314                    self.current_dataset.qy_data = np.fromstring(data_point, dtype=float, sep=",")
315                elif tagname == 'Qxdev':
316                    self.current_dataset.xaxis("Qxdev", unit)
317                    self.current_dataset.dqx_data = np.fromstring(data_point, dtype=float, sep=",")
318                elif tagname == 'Qydev':
319                    self.current_dataset.yaxis("Qydev", unit)
320                    self.current_dataset.dqy_data = np.fromstring(data_point, dtype=float, sep=",")
321                elif tagname == 'Mask':
322                    inter = [item == "1" for item in data_point.split(",")]
323                    self.current_dataset.mask = np.asarray(inter, dtype=bool)
324
325                # Sample Information
326                elif tagname == 'ID' and self.parent_class == 'SASsample':
327                    self.current_datainfo.sample.ID = data_point
328                elif tagname == 'Title' and self.parent_class == 'SASsample':
329                    self.current_datainfo.sample.name = data_point
330                elif tagname == 'thickness' and self.parent_class == 'SASsample':
331                    self.current_datainfo.sample.thickness = data_point
332                    self.current_datainfo.sample.thickness_unit = unit
333                elif tagname == 'transmission' and self.parent_class == 'SASsample':
334                    self.current_datainfo.sample.transmission = data_point
335                elif tagname == 'temperature' and self.parent_class == 'SASsample':
336                    self.current_datainfo.sample.temperature = data_point
337                    self.current_datainfo.sample.temperature_unit = unit
338                elif tagname == 'details' and self.parent_class == 'SASsample':
339                    self.current_datainfo.sample.details.append(data_point)
340                elif tagname == 'x' and self.parent_class == 'position':
341                    self.current_datainfo.sample.position.x = data_point
342                    self.current_datainfo.sample.position_unit = unit
343                elif tagname == 'y' and self.parent_class == 'position':
344                    self.current_datainfo.sample.position.y = data_point
345                    self.current_datainfo.sample.position_unit = unit
346                elif tagname == 'z' and self.parent_class == 'position':
347                    self.current_datainfo.sample.position.z = data_point
348                    self.current_datainfo.sample.position_unit = unit
349                elif tagname == 'roll' and self.parent_class == 'orientation' and 'SASsample' in self.names:
350                    self.current_datainfo.sample.orientation.x = data_point
351                    self.current_datainfo.sample.orientation_unit = unit
352                elif tagname == 'pitch' and self.parent_class == 'orientation' and 'SASsample' in self.names:
353                    self.current_datainfo.sample.orientation.y = data_point
354                    self.current_datainfo.sample.orientation_unit = unit
355                elif tagname == 'yaw' and self.parent_class == 'orientation' and 'SASsample' in self.names:
356                    self.current_datainfo.sample.orientation.z = data_point
357                    self.current_datainfo.sample.orientation_unit = unit
358
359                # Instrumental Information
360                elif tagname == 'name' and self.parent_class == 'SASinstrument':
361                    self.current_datainfo.instrument = data_point
362
363                # Detector Information
364                elif tagname == 'name' and self.parent_class == 'SASdetector':
365                    self.detector.name = data_point
366                elif tagname == 'SDD' and self.parent_class == 'SASdetector':
367                    self.detector.distance = data_point
368                    self.detector.distance_unit = unit
369                elif tagname == 'slit_length' and self.parent_class == 'SASdetector':
370                    self.detector.slit_length = data_point
371                    self.detector.slit_length_unit = unit
372                elif tagname == 'x' and self.parent_class == 'offset':
373                    self.detector.offset.x = data_point
374                    self.detector.offset_unit = unit
375                elif tagname == 'y' and self.parent_class == 'offset':
376                    self.detector.offset.y = data_point
377                    self.detector.offset_unit = unit
378                elif tagname == 'z' and self.parent_class == 'offset':
379                    self.detector.offset.z = data_point
380                    self.detector.offset_unit = unit
381                elif tagname == 'x' and self.parent_class == 'beam_center':
382                    self.detector.beam_center.x = data_point
383                    self.detector.beam_center_unit = unit
384                elif tagname == 'y' and self.parent_class == 'beam_center':
385                    self.detector.beam_center.y = data_point
386                    self.detector.beam_center_unit = unit
387                elif tagname == 'z' and self.parent_class == 'beam_center':
388                    self.detector.beam_center.z = data_point
389                    self.detector.beam_center_unit = unit
390                elif tagname == 'x' and self.parent_class == 'pixel_size':
391                    self.detector.pixel_size.x = data_point
392                    self.detector.pixel_size_unit = unit
393                elif tagname == 'y' and self.parent_class == 'pixel_size':
394                    self.detector.pixel_size.y = data_point
395                    self.detector.pixel_size_unit = unit
396                elif tagname == 'z' and self.parent_class == 'pixel_size':
397                    self.detector.pixel_size.z = data_point
398                    self.detector.pixel_size_unit = unit
399                elif tagname == 'roll' and self.parent_class == 'orientation' and 'SASdetector' in self.names:
400                    self.detector.orientation.x = data_point
401                    self.detector.orientation_unit = unit
402                elif tagname == 'pitch' and self.parent_class == 'orientation' and 'SASdetector' in self.names:
403                    self.detector.orientation.y = data_point
404                    self.detector.orientation_unit = unit
405                elif tagname == 'yaw' and self.parent_class == 'orientation' and 'SASdetector' in self.names:
406                    self.detector.orientation.z = data_point
407                    self.detector.orientation_unit = unit
408
409                # Collimation and Aperture
410                elif tagname == 'length' and self.parent_class == 'SAScollimation':
411                    self.collimation.length = data_point
412                    self.collimation.length_unit = unit
413                elif tagname == 'name' and self.parent_class == 'SAScollimation':
414                    self.collimation.name = data_point
415                elif tagname == 'distance' and self.parent_class == 'aperture':
416                    self.aperture.distance = data_point
417                    self.aperture.distance_unit = unit
418                elif tagname == 'x' and self.parent_class == 'size':
419                    self.aperture.size.x = data_point
420                    self.collimation.size_unit = unit
421                elif tagname == 'y' and self.parent_class == 'size':
422                    self.aperture.size.y = data_point
423                    self.collimation.size_unit = unit
424                elif tagname == 'z' and self.parent_class == 'size':
425                    self.aperture.size.z = data_point
426                    self.collimation.size_unit = unit
427
428                # Process Information
429                elif tagname == 'name' and self.parent_class == 'SASprocess':
430                    self.process.name = data_point
431                elif tagname == 'description' and self.parent_class == 'SASprocess':
432                    self.process.description = data_point
433                elif tagname == 'date' and self.parent_class == 'SASprocess':
434                    try:
435                        self.process.date = datetime.datetime.fromtimestamp(data_point)
436                    except:
437                        self.process.date = data_point
438                elif tagname == 'SASprocessnote':
439                    self.process.notes.append(data_point)
440                elif tagname == 'term' and self.parent_class == 'SASprocess':
441                    unit = attr.get("unit", "")
442                    dic = { "name": name, "value": data_point, "unit": unit }
443                    self.process.term.append(dic)
444
445                # Transmission Spectrum
446                elif tagname == 'T' and self.parent_class == 'Tdata':
447                    self.transspectrum.transmission = np.append(self.transspectrum.transmission, data_point)
448                    self.transspectrum.transmission_unit = unit
449                elif tagname == 'Tdev' and self.parent_class == 'Tdata':
450                    self.transspectrum.transmission_deviation = np.append(self.transspectrum.transmission_deviation, data_point)
451                    self.transspectrum.transmission_deviation_unit = unit
452                elif tagname == 'Lambda' and self.parent_class == 'Tdata':
453                    self.transspectrum.wavelength = np.append(self.transspectrum.wavelength, data_point)
454                    self.transspectrum.wavelength_unit = unit
455
456                # Source Information
457                elif tagname == 'wavelength' and (self.parent_class == 'SASsource' or self.parent_class == 'SASData'):
458                    self.current_datainfo.source.wavelength = data_point
459                    self.current_datainfo.source.wavelength_unit = unit
460                elif tagname == 'wavelength_min' and self.parent_class == 'SASsource':
461                    self.current_datainfo.source.wavelength_min = data_point
462                    self.current_datainfo.source.wavelength_min_unit = unit
463                elif tagname == 'wavelength_max' and self.parent_class == 'SASsource':
464                    self.current_datainfo.source.wavelength_max = data_point
465                    self.current_datainfo.source.wavelength_max_unit = unit
466                elif tagname == 'wavelength_spread' and self.parent_class == 'SASsource':
467                    self.current_datainfo.source.wavelength_spread = data_point
468                    self.current_datainfo.source.wavelength_spread_unit = unit
469                elif tagname == 'x' and self.parent_class == 'beam_size':
470                    self.current_datainfo.source.beam_size.x = data_point
471                    self.current_datainfo.source.beam_size_unit = unit
472                elif tagname == 'y' and self.parent_class == 'beam_size':
473                    self.current_datainfo.source.beam_size.y = data_point
474                    self.current_datainfo.source.beam_size_unit = unit
475                elif tagname == 'z' and self.parent_class == 'pixel_size':
476                    self.current_datainfo.source.data_point.z = data_point
477                    self.current_datainfo.source.beam_size_unit = unit
478                elif tagname == 'radiation' and self.parent_class == 'SASsource':
479                    self.current_datainfo.source.radiation = data_point
480                elif tagname == 'beam_shape' and self.parent_class == 'SASsource':
481                    self.current_datainfo.source.beam_shape = data_point
482
483                # Everything else goes in meta_data
484                else:
485                    new_key = self._create_unique_key(self.current_datainfo.meta_data, tagname)
486                    self.current_datainfo.meta_data[new_key] = data_point
487
488            self.names.remove(tagname_original)
489            length = 0
490            if len(self.names) > 1:
491                length = len(self.names) - 1
492            self.parent_class = self.names[length]
493        if not self._is_call_local() and not recurse:
494            self.frm = ""
495            self.current_datainfo.errors = set()
496            for error in self.errors:
497                self.current_datainfo.errors.add(error)
498            self.data_cleanup()
499            self.sort_one_d_data()
500            self.sort_two_d_data()
501            self.reset_data_list()
502            empty = None
503            return self.output[0], empty
504
505    def data_cleanup(self):
506        """
507        Clean up the data sets and refresh everything
508        :return: None
509        """
510        has_error_dx = self.current_dataset.dx is not None
511        has_error_dxl = self.current_dataset.dxl is not None
512        has_error_dxw = self.current_dataset.dxw is not None
513        has_error_dy = self.current_dataset.dy is not None
514        self.remove_empty_q_values(has_error_dx=has_error_dx,
515                                   has_error_dxl=has_error_dxl,
516                                   has_error_dxw=has_error_dxw,
517                                   has_error_dy=has_error_dy)
518        self.send_to_output()  # Combine datasets with DataInfo
519        self.current_datainfo = DataInfo()  # Reset DataInfo
520
521    def _is_call_local(self):
522        if self.frm == "":
523            inter = inspect.stack()
524            self.frm = inter[2]
525        mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "")
526        mod_name = mod_name.replace(".py", "")
527        mod = mod_name.split("sas/")
528        mod_name = mod[1]
529        if mod_name != "sascalc/dataloader/readers/cansas_reader":
530            return False
531        return True
532
533    def _add_intermediate(self):
534        """
535        This method stores any intermediate objects within the final data set after fully reading the set.
536        """
537        if self.parent_class == 'SASprocess':
538            self.current_datainfo.process.append(self.process)
539            self.process = Process()
540        elif self.parent_class == 'SASdetector':
541            self.current_datainfo.detector.append(self.detector)
542            self.detector = Detector()
543        elif self.parent_class == 'SAStransmission_spectrum':
544            self.current_datainfo.trans_spectrum.append(self.transspectrum)
545            self.transspectrum = TransmissionSpectrum()
546        elif self.parent_class == 'SAScollimation':
547            self.current_datainfo.collimation.append(self.collimation)
548            self.collimation = Collimation()
549        elif self.parent_class == 'aperture':
550            self.collimation.aperture.append(self.aperture)
551            self.aperture = Aperture()
552        elif self.parent_class == 'SASdata':
553            self._check_for_empty_resolution()
554            self.data.append(self.current_dataset)
555
556    def _get_node_value(self, node, tagname):
557        """
558        Get the value of a node and any applicable units
559
560        :param node: The XML node to get the value of
561        :param tagname: The tagname of the node
562        """
563        #Get the text from the node and convert all whitespace to spaces
564        units = ''
565        node_value = node.text
566        if node_value is not None:
567            node_value = ' '.join(node_value.split())
568        else:
569            node_value = ""
570
571        # If the value is a float, compile with units.
572        if self.ns_list.ns_datatype == "float":
573            # If an empty value is given, set as zero.
574            if node_value is None or node_value.isspace() \
575                                    or node_value.lower() == "nan":
576                node_value = "0.0"
577            #Convert the value to the base units
578            node_value, units = self._unit_conversion(node, tagname, node_value)
579
580        # If the value is a timestamp, convert to a datetime object
581        elif self.ns_list.ns_datatype == "timestamp":
582            if node_value is None or node_value.isspace():
583                pass
584            else:
585                try:
586                    node_value = \
587                        datetime.datetime.fromtimestamp(node_value)
588                except ValueError:
589                    node_value = None
590        return node_value, units
591
592    def _unit_conversion(self, node, tagname, node_value):
593        """
594        A unit converter method used to convert the data included in the file
595        to the default units listed in data_info
596
597        :param node: XML node
598        :param tagname: name of the node
599        :param node_value: The value of the current dom node
600        """
601        attr = node.attrib
602        value_unit = ''
603        err_msg = None
604        default_unit = None
605        if not isinstance(node_value, float):
606            node_value = float(node_value)
607        if 'unit' in attr and attr.get('unit') is not None:
608            try:
609                local_unit = attr['unit']
610                unitname = self.ns_list.current_level.get("unit", "")
611                if "SASdetector" in self.names:
612                    save_in = "detector"
613                elif "aperture" in self.names:
614                    save_in = "aperture"
615                elif "SAScollimation" in self.names:
616                    save_in = "collimation"
617                elif "SAStransmission_spectrum" in self.names:
618                    save_in = "transspectrum"
619                elif "SASdata" in self.names:
620                    x = np.zeros(1)
621                    y = np.zeros(1)
622                    self.current_data1d = Data1D(x, y)
623                    save_in = "current_data1d"
624                elif "SASsource" in self.names:
625                    save_in = "current_datainfo.source"
626                elif "SASsample" in self.names:
627                    save_in = "current_datainfo.sample"
628                elif "SASprocess" in self.names:
629                    save_in = "process"
630                else:
631                    save_in = "current_datainfo"
632                exec("default_unit = self.{0}.{1}".format(save_in, unitname))
633                if (local_unit and default_unit
634                        and local_unit.lower() != default_unit.lower()
635                        and local_unit.lower() != "none"):
636                    if HAS_CONVERTER:
637                        # Check local units - bad units raise KeyError
638                        data_conv_q = Converter(local_unit)
639                        value_unit = default_unit
640                        node_value = data_conv_q(node_value, units=default_unit)
641                    else:
642                        value_unit = local_unit
643                        err_msg = "Unit converter is not available.\n"
644                else:
645                    value_unit = local_unit
646            except KeyError:
647                # Do not throw an error for loading Sesans data in cansas xml
648                # This is a temporary fix.
649                if local_unit != "A" and local_unit != 'pol':
650                    err_msg = "CanSAS reader: unexpected "
651                    err_msg += "\"{0}\" unit [{1}]; "
652                    err_msg = err_msg.format(tagname, local_unit)
653                    err_msg += "expecting [{0}]".format(default_unit)
654                value_unit = local_unit
655            except Exception:
656                err_msg = "CanSAS reader: unknown error converting "
657                err_msg += "\"{0}\" unit [{1}]"
658                err_msg = err_msg.format(tagname, local_unit)
659                value_unit = local_unit
660        elif 'unit' in attr:
661            value_unit = attr['unit']
662        if err_msg:
663            self.errors.add(err_msg)
664        return node_value, value_unit
665
666    def _check_for_empty_resolution(self):
667        """
668        a method to check all resolution data sets are the same size as I and q
669        """
670        dql_exists = False
671        dqw_exists = False
672        dq_exists = False
673        di_exists = False
674        if self.current_dataset.dxl is not None:
675            dql_exists = True
676        if self.current_dataset.dxw is not None:
677            dqw_exists = True
678        if self.current_dataset.dx is not None:
679            dq_exists = True
680        if self.current_dataset.dy is not None:
681            di_exists = True
682        if dqw_exists and not dql_exists:
683            array_size = self.current_dataset.dxw.size
684            self.current_dataset.dxl = np.zeros(array_size)
685        elif dql_exists and not dqw_exists:
686            array_size = self.current_dataset.dxl.size
687            self.current_dataset.dxw = np.zeros(array_size)
688        elif not dql_exists and not dqw_exists and not dq_exists:
689            array_size = self.current_dataset.x.size
690            self.current_dataset.dx = np.append(self.current_dataset.dx,
691                                                np.zeros([array_size]))
692        if not di_exists:
693            array_size = self.current_dataset.y.size
694            self.current_dataset.dy = np.append(self.current_dataset.dy,
695                                                np.zeros([array_size]))
696
697    def _initialize_new_data_set(self, node=None):
698        if node is not None:
699            for child in node:
700                if child.tag.replace(self.base_ns, "") == "Idata":
701                    for i_child in child:
702                        if i_child.tag.replace(self.base_ns, "") == "Qx":
703                            self.current_dataset = plottable_2D()
704                            return
705        self.current_dataset = plottable_1D(np.array(0), np.array(0))
706
707    ## Writing Methods
708    def write(self, filename, datainfo):
709        """
710        Write the content of a Data1D as a CanSAS XML file
711
712        :param filename: name of the file to write
713        :param datainfo: Data1D object
714        """
715        # Create XML document
716        doc, _ = self._to_xml_doc(datainfo)
717        # Write the file
718        file_ref = open(filename, 'w')
719        if self.encoding is None:
720            self.encoding = "UTF-8"
721        doc.write(file_ref, encoding=self.encoding,
722                  pretty_print=True, xml_declaration=True)
723        file_ref.close()
724
725    def _to_xml_doc(self, datainfo):
726        """
727        Create an XML document to contain the content of a Data1D
728
729        :param datainfo: Data1D object
730        """
731        is_2d = False
732        if issubclass(datainfo.__class__, Data2D):
733            is_2d = True
734
735        # Get PIs and create root element
736        pi_string = self._get_pi_string()
737        # Define namespaces and create SASroot object
738        main_node = self._create_main_node()
739        # Create ElementTree, append SASroot and apply processing instructions
740        base_string = pi_string + self.to_string(main_node)
741        base_element = self.create_element_from_string(base_string)
742        doc = self.create_tree(base_element)
743        # Create SASentry Element
744        entry_node = self.create_element("SASentry")
745        root = doc.getroot()
746        root.append(entry_node)
747
748        # Add Title to SASentry
749        self.write_node(entry_node, "Title", datainfo.title)
750        # Add Run to SASentry
751        self._write_run_names(datainfo, entry_node)
752        # Add Data info to SASEntry
753        if is_2d:
754            self._write_data_2d(datainfo, entry_node)
755        else:
756            self._write_data(datainfo, entry_node)
757        # Transmission Spectrum Info
758        # TODO: fix the writer to linearize all data, including T_spectrum
759        # self._write_trans_spectrum(datainfo, entry_node)
760        # Sample info
761        self._write_sample_info(datainfo, entry_node)
762        # Instrument info
763        instr = self._write_instrument(datainfo, entry_node)
764        #   Source
765        self._write_source(datainfo, instr)
766        #   Collimation
767        self._write_collimation(datainfo, instr)
768        #   Detectors
769        self._write_detectors(datainfo, instr)
770        # Processes info
771        self._write_process_notes(datainfo, entry_node)
772        # Note info
773        self._write_notes(datainfo, entry_node)
774        # Return the document, and the SASentry node associated with
775        #      the data we just wrote
776        # If the calling function was not the cansas reader, return a minidom
777        #      object rather than an lxml object.
778        self.frm = inspect.stack()[1]
779        doc, entry_node = self._check_origin(entry_node, doc)
780        return doc, entry_node
781
782    def write_node(self, parent, name, value, attr=None):
783        """
784        :param doc: document DOM
785        :param parent: parent node
786        :param name: tag of the element
787        :param value: value of the child text node
788        :param attr: attribute dictionary
789
790        :return: True if something was appended, otherwise False
791        """
792        if value is not None:
793            parent = self.ebuilder(parent, name, value, attr)
794            return True
795        return False
796
797    def _get_pi_string(self):
798        """
799        Creates the processing instructions header for writing to file
800        """
801        pis = self.return_processing_instructions()
802        if len(pis) > 0:
803            pi_tree = self.create_tree(pis[0])
804            i = 1
805            for i in range(1, len(pis) - 1):
806                pi_tree = self.append(pis[i], pi_tree)
807            pi_string = self.to_string(pi_tree)
808        else:
809            pi_string = ""
810        return pi_string
811
812    def _create_main_node(self):
813        """
814        Creates the primary xml header used when writing to file
815        """
816        xsi = "http://www.w3.org/2001/XMLSchema-instance"
817        version = self.cansas_version
818        n_s = CANSAS_NS.get(version).get("ns")
819        if version == "1.1":
820            url = "http://www.cansas.org/formats/1.1/"
821        else:
822            url = "http://svn.smallangles.net/svn/canSAS/1dwg/trunk/"
823        schema_location = "{0} {1}cansas1d.xsd".format(n_s, url)
824        attrib = {"{" + xsi + "}schemaLocation" : schema_location,
825                  "version" : version}
826        nsmap = {'xsi' : xsi, None: n_s}
827
828        main_node = self.create_element("{" + n_s + "}SASroot",
829                                        attrib=attrib, nsmap=nsmap)
830        return main_node
831
832    def _write_run_names(self, datainfo, entry_node):
833        """
834        Writes the run names to the XML file
835
836        :param datainfo: The Data1D object the information is coming from
837        :param entry_node: lxml node ElementTree object to be appended to
838        """
839        if datainfo.run is None or datainfo.run == []:
840            datainfo.run.append(RUN_NAME_DEFAULT)
841            datainfo.run_name[RUN_NAME_DEFAULT] = RUN_NAME_DEFAULT
842        for item in datainfo.run:
843            runname = {}
844            if item in datainfo.run_name and \
845            len(str(datainfo.run_name[item])) > 1:
846                runname = {'name': datainfo.run_name[item]}
847            self.write_node(entry_node, "Run", item, runname)
848
849    def _write_data(self, datainfo, entry_node):
850        """
851        Writes 1D I and Q data to the XML file
852
853        :param datainfo: The Data1D object the information is coming from
854        :param entry_node: lxml node ElementTree object to be appended to
855        """
856        node = self.create_element("SASdata")
857        self.append(node, entry_node)
858
859        for i in range(len(datainfo.x)):
860            point = self.create_element("Idata")
861            node.append(point)
862            self.write_node(point, "Q", datainfo.x[i],
863                            {'unit': datainfo.x_unit})
864            if len(datainfo.y) >= i:
865                self.write_node(point, "I", datainfo.y[i],
866                                {'unit': datainfo.y_unit})
867            if datainfo.dy is not None and len(datainfo.dy) > i:
868                self.write_node(point, "Idev", datainfo.dy[i],
869                                {'unit': datainfo.y_unit})
870            if datainfo.dx is not None and len(datainfo.dx) > i:
871                self.write_node(point, "Qdev", datainfo.dx[i],
872                                {'unit': datainfo.x_unit})
873            if datainfo.dxw is not None and len(datainfo.dxw) > i:
874                self.write_node(point, "dQw", datainfo.dxw[i],
875                                {'unit': datainfo.x_unit})
876            if datainfo.dxl is not None and len(datainfo.dxl) > i:
877                self.write_node(point, "dQl", datainfo.dxl[i],
878                                {'unit': datainfo.x_unit})
879        if datainfo.isSesans:
880            sesans_attrib = {'x_axis': datainfo._xaxis,
881                             'y_axis': datainfo._yaxis,
882                             'x_unit': datainfo.x_unit,
883                             'y_unit': datainfo.y_unit}
884            sesans = self.create_element("Sesans", attrib=sesans_attrib)
885            sesans.text = str(datainfo.isSesans)
886            entry_node.append(sesans)
887            self.write_node(entry_node, "yacceptance", datainfo.sample.yacceptance[0],
888                             {'unit': datainfo.sample.yacceptance[1]})
889            self.write_node(entry_node, "zacceptance", datainfo.sample.zacceptance[0],
890                             {'unit': datainfo.sample.zacceptance[1]})
891
892
893    def _write_data_2d(self, datainfo, entry_node):
894        """
895        Writes 2D data to the XML file
896
897        :param datainfo: The Data2D object the information is coming from
898        :param entry_node: lxml node ElementTree object to be appended to
899        """
900        attr = {}
901        if datainfo.data.shape:
902            attr["x_bins"] = str(len(datainfo.x_bins))
903            attr["y_bins"] = str(len(datainfo.y_bins))
904        node = self.create_element("SASdata", attr)
905        self.append(node, entry_node)
906
907        point = self.create_element("Idata")
908        node.append(point)
909        qx = ','.join(str(v) for v in datainfo.qx_data)
910        qy = ','.join(str(v) for v in datainfo.qy_data)
911        intensity = ','.join(str(v) for v in datainfo.data)
912
913        self.write_node(point, "Qx", qx,
914                        {'unit': datainfo._xunit})
915        self.write_node(point, "Qy", qy,
916                        {'unit': datainfo._yunit})
917        self.write_node(point, "I", intensity,
918                        {'unit': datainfo._zunit})
919        if datainfo.err_data is not None:
920            err = ','.join(str(v) for v in datainfo.err_data)
921            self.write_node(point, "Idev", err,
922                            {'unit': datainfo._zunit})
923        if datainfo.dqy_data is not None:
924            dqy = ','.join(str(v) for v in datainfo.dqy_data)
925            self.write_node(point, "Qydev", dqy,
926                            {'unit': datainfo._yunit})
927        if datainfo.dqx_data is not None:
928            dqx = ','.join(str(v) for v in datainfo.dqx_data)
929            self.write_node(point, "Qxdev", dqx,
930                            {'unit': datainfo._xunit})
931        if datainfo.mask is not None:
932            mask = ','.join("1" if v else "0" for v in datainfo.mask)
933            self.write_node(point, "Mask", mask)
934
935    def _write_trans_spectrum(self, datainfo, entry_node):
936        """
937        Writes the transmission spectrum data to the XML file
938
939        :param datainfo: The Data1D object the information is coming from
940        :param entry_node: lxml node ElementTree object to be appended to
941        """
942        for i in range(len(datainfo.trans_spectrum)):
943            spectrum = datainfo.trans_spectrum[i]
944            node = self.create_element("SAStransmission_spectrum",
945                                       {"name" : spectrum.name})
946            self.append(node, entry_node)
947            if isinstance(spectrum.timestamp, datetime.datetime):
948                node.setAttribute("timestamp", spectrum.timestamp)
949            for i in range(len(spectrum.wavelength)):
950                point = self.create_element("Tdata")
951                node.append(point)
952                self.write_node(point, "Lambda", spectrum.wavelength[i],
953                                {'unit': spectrum.wavelength_unit})
954                self.write_node(point, "T", spectrum.transmission[i],
955                                {'unit': spectrum.transmission_unit})
956                if spectrum.transmission_deviation is not None \
957                and len(spectrum.transmission_deviation) >= i:
958                    self.write_node(point, "Tdev",
959                                    spectrum.transmission_deviation[i],
960                                    {'unit':
961                                     spectrum.transmission_deviation_unit})
962
963    def _write_sample_info(self, datainfo, entry_node):
964        """
965        Writes the sample information to the XML file
966
967        :param datainfo: The Data1D object the information is coming from
968        :param entry_node: lxml node ElementTree object to be appended to
969        """
970        sample = self.create_element("SASsample")
971        if datainfo.sample.name is not None:
972            self.write_attribute(sample, "name",
973                                 str(datainfo.sample.name))
974        self.append(sample, entry_node)
975        self.write_node(sample, "ID", str(datainfo.sample.ID))
976        self.write_node(sample, "thickness", datainfo.sample.thickness,
977                        {"unit": datainfo.sample.thickness_unit})
978        self.write_node(sample, "transmission", datainfo.sample.transmission)
979        self.write_node(sample, "temperature", datainfo.sample.temperature,
980                        {"unit": datainfo.sample.temperature_unit})
981
982        pos = self.create_element("position")
983        written = self.write_node(pos,
984                                  "x",
985                                  datainfo.sample.position.x,
986                                  {"unit": datainfo.sample.position_unit})
987        written = written | self.write_node( \
988            pos, "y", datainfo.sample.position.y,
989            {"unit": datainfo.sample.position_unit})
990        written = written | self.write_node( \
991            pos, "z", datainfo.sample.position.z,
992            {"unit": datainfo.sample.position_unit})
993        if written == True:
994            self.append(pos, sample)
995
996        ori = self.create_element("orientation")
997        written = self.write_node(ori, "roll",
998                                  datainfo.sample.orientation.x,
999                                  {"unit": datainfo.sample.orientation_unit})
1000        written = written | self.write_node( \
1001            ori, "pitch", datainfo.sample.orientation.y,
1002            {"unit": datainfo.sample.orientation_unit})
1003        written = written | self.write_node( \
1004            ori, "yaw", datainfo.sample.orientation.z,
1005            {"unit": datainfo.sample.orientation_unit})
1006        if written == True:
1007            self.append(ori, sample)
1008
1009        for item in datainfo.sample.details:
1010            self.write_node(sample, "details", item)
1011
1012    def _write_instrument(self, datainfo, entry_node):
1013        """
1014        Writes the instrumental information to the XML file
1015
1016        :param datainfo: The Data1D object the information is coming from
1017        :param entry_node: lxml node ElementTree object to be appended to
1018        """
1019        instr = self.create_element("SASinstrument")
1020        self.append(instr, entry_node)
1021        self.write_node(instr, "name", datainfo.instrument)
1022        return instr
1023
1024    def _write_source(self, datainfo, instr):
1025        """
1026        Writes the source information to the XML file
1027
1028        :param datainfo: The Data1D object the information is coming from
1029        :param instr: instrument node  to be appended to
1030        """
1031        source = self.create_element("SASsource")
1032        if datainfo.source.name is not None:
1033            self.write_attribute(source, "name",
1034                                 str(datainfo.source.name))
1035        self.append(source, instr)
1036        if datainfo.source.radiation is None or datainfo.source.radiation == '':
1037            datainfo.source.radiation = "neutron"
1038        self.write_node(source, "radiation", datainfo.source.radiation)
1039
1040        size = self.create_element("beam_size")
1041        if datainfo.source.beam_size_name is not None:
1042            self.write_attribute(size, "name",
1043                                 str(datainfo.source.beam_size_name))
1044        written = self.write_node( \
1045            size, "x", datainfo.source.beam_size.x,
1046            {"unit": datainfo.source.beam_size_unit})
1047        written = written | self.write_node( \
1048            size, "y", datainfo.source.beam_size.y,
1049            {"unit": datainfo.source.beam_size_unit})
1050        written = written | self.write_node( \
1051            size, "z", datainfo.source.beam_size.z,
1052            {"unit": datainfo.source.beam_size_unit})
1053        if written == True:
1054            self.append(size, source)
1055
1056        self.write_node(source, "beam_shape", datainfo.source.beam_shape)
1057        self.write_node(source, "wavelength",
1058                        datainfo.source.wavelength,
1059                        {"unit": datainfo.source.wavelength_unit})
1060        self.write_node(source, "wavelength_min",
1061                        datainfo.source.wavelength_min,
1062                        {"unit": datainfo.source.wavelength_min_unit})
1063        self.write_node(source, "wavelength_max",
1064                        datainfo.source.wavelength_max,
1065                        {"unit": datainfo.source.wavelength_max_unit})
1066        self.write_node(source, "wavelength_spread",
1067                        datainfo.source.wavelength_spread,
1068                        {"unit": datainfo.source.wavelength_spread_unit})
1069
1070    def _write_collimation(self, datainfo, instr):
1071        """
1072        Writes the collimation information to the XML file
1073
1074        :param datainfo: The Data1D object the information is coming from
1075        :param instr: lxml node ElementTree object to be appended to
1076        """
1077        if datainfo.collimation == [] or datainfo.collimation is None:
1078            coll = Collimation()
1079            datainfo.collimation.append(coll)
1080        for item in datainfo.collimation:
1081            coll = self.create_element("SAScollimation")
1082            if item.name is not None:
1083                self.write_attribute(coll, "name", str(item.name))
1084            self.append(coll, instr)
1085
1086            self.write_node(coll, "length", item.length,
1087                            {"unit": item.length_unit})
1088
1089            for aperture in item.aperture:
1090                apert = self.create_element("aperture")
1091                if aperture.name is not None:
1092                    self.write_attribute(apert, "name", str(aperture.name))
1093                if aperture.type is not None:
1094                    self.write_attribute(apert, "type", str(aperture.type))
1095                self.append(apert, coll)
1096
1097                size = self.create_element("size")
1098                if aperture.size_name is not None:
1099                    self.write_attribute(size, "name",
1100                                         str(aperture.size_name))
1101                written = self.write_node(size, "x", aperture.size.x,
1102                                          {"unit": aperture.size_unit})
1103                written = written | self.write_node( \
1104                    size, "y", aperture.size.y,
1105                    {"unit": aperture.size_unit})
1106                written = written | self.write_node( \
1107                    size, "z", aperture.size.z,
1108                    {"unit": aperture.size_unit})
1109                if written == True:
1110                    self.append(size, apert)
1111
1112                self.write_node(apert, "distance", aperture.distance,
1113                                {"unit": aperture.distance_unit})
1114
1115    def _write_detectors(self, datainfo, instr):
1116        """
1117        Writes the detector information to the XML file
1118
1119        :param datainfo: The Data1D object the information is coming from
1120        :param inst: lxml instrument node to be appended to
1121        """
1122        if datainfo.detector is None or datainfo.detector == []:
1123            det = Detector()
1124            det.name = ""
1125            datainfo.detector.append(det)
1126
1127        for item in datainfo.detector:
1128            det = self.create_element("SASdetector")
1129            written = self.write_node(det, "name", item.name)
1130            written = written | self.write_node(det, "SDD", item.distance,
1131                                                {"unit": item.distance_unit})
1132            if written == True:
1133                self.append(det, instr)
1134
1135            off = self.create_element("offset")
1136            written = self.write_node(off, "x", item.offset.x,
1137                                      {"unit": item.offset_unit})
1138            written = written | self.write_node(off, "y", item.offset.y,
1139                                                {"unit": item.offset_unit})
1140            written = written | self.write_node(off, "z", item.offset.z,
1141                                                {"unit": item.offset_unit})
1142            if written == True:
1143                self.append(off, det)
1144
1145            ori = self.create_element("orientation")
1146            written = self.write_node(ori, "roll", item.orientation.x,
1147                                      {"unit": item.orientation_unit})
1148            written = written | self.write_node(ori, "pitch",
1149                                                item.orientation.y,
1150                                                {"unit": item.orientation_unit})
1151            written = written | self.write_node(ori, "yaw",
1152                                                item.orientation.z,
1153                                                {"unit": item.orientation_unit})
1154            if written == True:
1155                self.append(ori, det)
1156
1157            center = self.create_element("beam_center")
1158            written = self.write_node(center, "x", item.beam_center.x,
1159                                      {"unit": item.beam_center_unit})
1160            written = written | self.write_node(center, "y",
1161                                                item.beam_center.y,
1162                                                {"unit": item.beam_center_unit})
1163            written = written | self.write_node(center, "z",
1164                                                item.beam_center.z,
1165                                                {"unit": item.beam_center_unit})
1166            if written == True:
1167                self.append(center, det)
1168
1169            pix = self.create_element("pixel_size")
1170            written = self.write_node(pix, "x", item.pixel_size.x,
1171                                      {"unit": item.pixel_size_unit})
1172            written = written | self.write_node(pix, "y", item.pixel_size.y,
1173                                                {"unit": item.pixel_size_unit})
1174            written = written | self.write_node(pix, "z", item.pixel_size.z,
1175                                                {"unit": item.pixel_size_unit})
1176            if written == True:
1177                self.append(pix, det)
1178            self.write_node(det, "slit_length", item.slit_length,
1179                {"unit": item.slit_length_unit})
1180
1181
1182    def _write_process_notes(self, datainfo, entry_node):
1183        """
1184        Writes the process notes to the XML file
1185
1186        :param datainfo: The Data1D object the information is coming from
1187        :param entry_node: lxml node ElementTree object to be appended to
1188
1189        """
1190        for item in datainfo.process:
1191            node = self.create_element("SASprocess")
1192            self.append(node, entry_node)
1193            self.write_node(node, "name", item.name)
1194            self.write_node(node, "date", item.date)
1195            self.write_node(node, "description", item.description)
1196            for term in item.term:
1197                if isinstance(term, list):
1198                    value = term['value']
1199                    del term['value']
1200                elif isinstance(term, dict):
1201                    value = term.get("value")
1202                    del term['value']
1203                else:
1204                    value = term
1205                self.write_node(node, "term", value, term)
1206            for note in item.notes:
1207                self.write_node(node, "SASprocessnote", note)
1208            if len(item.notes) == 0:
1209                self.write_node(node, "SASprocessnote", "")
1210
1211    def _write_notes(self, datainfo, entry_node):
1212        """
1213        Writes the notes to the XML file and creates an empty note if none
1214        exist
1215
1216        :param datainfo: The Data1D object the information is coming from
1217        :param entry_node: lxml node ElementTree object to be appended to
1218
1219        """
1220        if len(datainfo.notes) == 0:
1221            node = self.create_element("SASnote")
1222            self.append(node, entry_node)
1223        else:
1224            for item in datainfo.notes:
1225                node = self.create_element("SASnote")
1226                self.write_text(node, item)
1227                self.append(node, entry_node)
1228
1229    def _check_origin(self, entry_node, doc):
1230        """
1231        Return the document, and the SASentry node associated with
1232        the data we just wrote.
1233        If the calling function was not the cansas reader, return a minidom
1234        object rather than an lxml object.
1235
1236        :param entry_node: lxml node ElementTree object to be appended to
1237        :param doc: entire xml tree
1238        """
1239        if not self.frm:
1240            self.frm = inspect.stack()[1]
1241        mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "")
1242        mod_name = mod_name.replace(".py", "")
1243        mod = mod_name.split("sas/")
1244        mod_name = mod[1]
1245        if mod_name != "sascalc/dataloader/readers/cansas_reader":
1246            string = self.to_string(doc, pretty_print=False)
1247            doc = parseString(string)
1248            node_name = entry_node.tag
1249            node_list = doc.getElementsByTagName(node_name)
1250            entry_node = node_list.item(0)
1251        return doc, entry_node
1252
1253    # DO NOT REMOVE - used in saving and loading panel states.
1254    def _store_float(self, location, node, variable, storage, optional=True):
1255        """
1256        Get the content of a xpath location and store
1257        the result. Check that the units are compatible
1258        with the destination. The value is expected to
1259        be a float.
1260
1261        The xpath location might or might not exist.
1262        If it does not exist, nothing is done
1263
1264        :param location: xpath location to fetch
1265        :param node: node to read the data from
1266        :param variable: name of the data member to store it in [string]
1267        :param storage: data object that has the 'variable' data member
1268        :param optional: if True, no exception will be raised
1269            if unit conversion can't be done
1270
1271        :raise ValueError: raised when the units are not recognized
1272        """
1273        entry = get_content(location, node)
1274        try:
1275            value = float(entry.text)
1276        except ValueError:
1277            value = None
1278
1279        if value is not None:
1280            # If the entry has units, check to see that they are
1281            # compatible with what we currently have in the data object
1282            units = entry.get('unit')
1283            if units is not None:
1284                toks = variable.split('.')
1285                exec("local_unit = storage.%s_unit" % toks[0])
1286                if local_unit is not None and units.lower() != local_unit.lower():
1287                    if HAS_CONVERTER == True:
1288                        try:
1289                            conv = Converter(units)
1290                            exec("storage.%s = %g" %
1291-                                (variable, conv(value, units=local_unit)))
1292                        except Exception:
1293                            _, exc_value, _ = sys.exc_info()
1294                            err_mess = "CanSAS reader: could not convert"
1295                            err_mess += " %s unit [%s]; expecting [%s]\n  %s" \
1296                                % (variable, units, local_unit, exc_value)
1297                            self.errors.add(err_mess)
1298                            if optional:
1299                                logger.info(err_mess)
1300                            else:
1301                                raise ValueError(err_mess)
1302                    else:
1303                        err_mess = "CanSAS reader: unrecognized %s unit [%s];"\
1304                        % (variable, units)
1305                        err_mess += " expecting [%s]" % local_unit
1306                        self.errors.add(err_mess)
1307                        if optional:
1308                            logger.info(err_mess)
1309                        else:
1310                            raise ValueError(err_mess)
1311                else:
1312                    exec("storage.%s = value" % variable)
1313            else:
1314                exec("storage.%s = value" % variable)
1315
1316    # DO NOT REMOVE - used in saving and loading panel states.
1317    def _store_content(self, location, node, variable, storage):
1318        """
1319        Get the content of a xpath location and store
1320        the result. The value is treated as a string.
1321
1322        The xpath location might or might not exist.
1323        If it does not exist, nothing is done
1324
1325        :param location: xpath location to fetch
1326        :param node: node to read the data from
1327        :param variable: name of the data member to store it in [string]
1328        :param storage: data object that has the 'variable' data member
1329
1330        :return: return a list of errors
1331        """
1332        entry = get_content(location, node)
1333        if entry is not None and entry.text is not None:
1334            exec("storage.%s = entry.text.strip()" % variable)
1335
1336# DO NOT REMOVE Called by outside packages:
1337#    sas.sasgui.perspectives.invariant.invariant_state
1338#    sas.sasgui.perspectives.fitting.pagestate
1339def get_content(location, node):
1340    """
1341    Get the first instance of the content of a xpath location.
1342
1343    :param location: xpath location
1344    :param node: node to start at
1345
1346    :return: Element, or None
1347    """
1348    nodes = node.xpath(location,
1349                       namespaces={'ns': CANSAS_NS.get("1.0").get("ns")})
1350    if len(nodes) > 0:
1351        return nodes[0]
1352    else:
1353        return None
1354
1355# DO NOT REMOVE Called by outside packages:
1356#    sas.sasgui.perspectives.fitting.pagestate
1357def write_node(doc, parent, name, value, attr=None):
1358    """
1359    :param doc: document DOM
1360    :param parent: parent node
1361    :param name: tag of the element
1362    :param value: value of the child text node
1363    :param attr: attribute dictionary
1364
1365    :return: True if something was appended, otherwise False
1366    """
1367    if attr is None:
1368        attr = {}
1369    if value is not None:
1370        node = doc.createElement(name)
1371        node.appendChild(doc.createTextNode(str(value)))
1372        for item in attr:
1373            node.setAttribute(item, attr[item])
1374        parent.appendChild(node)
1375        return True
1376    return False
Note: See TracBrowser for help on using the repository browser.