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