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