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

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

Correctly set error message in CanSAS XML reader

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