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

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

Re-implement 2D CanSAS XML support

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